/*
 * 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:49 PM CET
//

package com.hack23.cia.model.external.val.riksdagsvalkrets.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 _Root_QNAME. */
    private static final QName _Root_QNAME = new QName("http://riksdagsvalkrets.val.external.model.cia.hack23.com/impl", "root");

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

    /**
	 * Creates a new Object object.
	 *
	 * @return the sweden parliament electoral region container
	 */
    public SwedenParliamentElectoralRegionContainer createSwedenParliamentElectoralRegionContainer() {
        return new SwedenParliamentElectoralRegionContainer();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the sweden parliament electoral region
	 */
    public SwedenParliamentElectoralRegion createSwedenParliamentElectoralRegion() {
        return new SwedenParliamentElectoralRegion();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @param value the value
	 * @return the JAXB element< sweden parliament electoral region container>
	 */
    @XmlElementDecl(namespace = "http://riksdagsvalkrets.val.external.model.cia.hack23.com/impl", name = "root")
    public JAXBElement<SwedenParliamentElectoralRegionContainer> createRoot(final SwedenParliamentElectoralRegionContainer value) {
        return new JAXBElement<>(_Root_QNAME, SwedenParliamentElectoralRegionContainer.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$
*/
// 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:42 PM CET
//

package com.hack23.cia.model.external.worldbank.indicators.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 _Indicator_QNAME. */
    private static final QName _Indicator_QNAME = new QName("http://indicators.worldbank.external.model.cia.hack23.com/impl", "indicator");

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

    /**
	 * Creates a new Object object.
	 *
	 * @return the indicators element
	 */
    public IndicatorsElement createIndicatorsElement() {
        return new IndicatorsElement();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the indicator element
	 */
    public IndicatorElement createIndicatorElement() {
        return new IndicatorElement();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the source
	 */
    public Source createSource() {
        return new Source();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the topics
	 */
    public Topics createTopics() {
        return new Topics();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the topic
	 */
    public Topic createTopic() {
        return new Topic();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @param value the value
	 * @return the JAXB element< indicator element>
	 */
    @XmlElementDecl(namespace = "http://indicators.worldbank.external.model.cia.hack23.com/impl", name = "indicator")
    public JAXBElement<IndicatorElement> createIndicator(final IndicatorElement value) {
        return new JAXBElement<>(_Indicator_QNAME, IndicatorElement.class, null, value);
    }

}


/*
 * 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.api.action.user;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

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.DocumentStatusContainer;
import com.hack23.cia.service.api.action.common.AbstractResponse;

/**
 * The Class SearchDocumentResponse.
 */
public final class SearchDocumentResponse extends AbstractResponse {

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

	/** The result element. */
	private List<DocumentElement> resultElement = new ArrayList<>();

	/** The status map. */
	private Map<String, DocumentStatusContainer> statusMap;

	/** The data map. */
	private Map<String, DocumentContentData> dataMap;

	/**
	 * Instantiates a new search document response.
	 *
	 * @param result
	 *            the result
	 */
	public SearchDocumentResponse(final ServiceResult result) {
		super(result);
	}

	/**
	 * Gets the result element.
	 *
	 * @return the result element
	 */
	public List<DocumentElement> getResultElement() {
		return resultElement.stream().collect(Collectors.toList());
	}

	/**
	 * Sets the result element.
	 *
	 * @param resultElement
	 *            the new result element
	 */
	public void setResultElement(final List<DocumentElement> resultElement) {
		if (resultElement != null) {
			this.resultElement = resultElement.stream().collect(Collectors.toList());
		}
	}

	/**
	 * Gets the status map.
	 *
	 * @return the status map
	 */
	public Map<String, DocumentStatusContainer> getStatusMap() {
		return statusMap;
	}

	/**
	 * Sets the status map.
	 *
	 * @param statusMap
	 *            the new status map
	 */
	public void setStatusMap(final Map<String, DocumentStatusContainer> statusMap) {
		this.statusMap = statusMap;
	}

	/**
	 * Gets the data map.
	 *
	 * @return the data map
	 */
	public Map<String, DocumentContentData> getDataMap() {
		return dataMap;
	}

	/**
	 * Sets the data map.
	 *
	 * @param dataMap
	 *            the new data map
	 */
	public void setDataMap(final Map<String, DocumentContentData> dataMap) {
		this.dataMap = dataMap;
	}

}


/*
 * 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.rules;

import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.builder.Message;
import org.kie.api.builder.Results;
import org.kie.api.definition.KiePackage;
import org.kie.api.definition.rule.Rule;
import org.kie.api.runtime.KieContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * The Class RulesConfiguration.
 */
@Configuration
public class RulesConfiguration {

	private static final Logger LOGGER = LoggerFactory.getLogger(RulesConfiguration.class);

	/**
	 * Kie container.
	 *
	 * @return the kie container
	 */
	@Bean
	public KieContainer kieContainer() {
		final KieServices kieServices = KieServices.Factory.get();

		final KieContainer kContainer = kieServices.getKieClasspathContainer();
		LOGGER.info("Using classloader {}, parent {}",kContainer.getClassLoader(),kContainer.getClassLoader().getParent());

		final Results verifyResults = kContainer.verify();
		for (final Message m : verifyResults.getMessages()) {
			LOGGER.warn("Kie container message: {}", m);
		}

		final KieBase kieBase = kContainer.getKieBase();
		for (final KiePackage kp : kieBase.getKiePackages()) {
			for (final Rule rule : kp.getRules()) {
				LOGGER.info("Loadded Rule: {} {}", kp, rule.getName());
			}
		}

		return kContainer;
	}
}


/*
 * 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.data.impl;

import java.sql.Connection;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.Session;
import org.hibernate.internal.SessionImpl;
import org.javers.core.Javers;
import org.javers.core.MappingStyle;
import org.javers.hibernate.integration.HibernateUnproxyObjectAccessHook;
import org.javers.repository.sql.ConnectionProvider;
import org.javers.repository.sql.DialectName;
import org.javers.repository.sql.JaversSqlRepository;
import org.javers.repository.sql.SqlRepositoryBuilder;
import org.javers.spring.auditable.AuthorProvider;
import org.javers.spring.auditable.CommitPropertiesProvider;
import org.javers.spring.auditable.aspect.JaversAuditableAspect;
import org.javers.spring.jpa.TransactionalJaversBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.PlatformTransactionManager;

import com.google.common.collect.ImmutableMap;

/**
 * The Class AuditableAspectConfiguration.
 */
@Configuration
public class AuditableAspectConfiguration {

	/** The entity manager. */
	@PersistenceContext
	private EntityManager entityManager;

	/**
	 * Instantiates a new auditable aspect configuration.
	 */
	public AuditableAspectConfiguration() {
		super();
	}

	/**
	 * Gets the javers.
	 *
	 * @param txManager the tx manager
	 * @return the javers
	 */
	@Bean
	public Javers getJavers(final PlatformTransactionManager txManager) {
		final JaversSqlRepository sqlRepository = SqlRepositoryBuilder.sqlRepository()
				.withConnectionProvider(new ConnectionProvider() {

					@Override
					public Connection getConnection() {
						final SessionImpl session = (SessionImpl) entityManager.unwrap(Session.class);

						return session.connection();
					}
				}).withDialect(DialectName.POSTGRES).build();

		return TransactionalJaversBuilder.javers().withTxManager(txManager)
				.withObjectAccessHook(new HibernateUnproxyObjectAccessHook()).registerJaversRepository(sqlRepository)
				.withMappingStyle(MappingStyle.BEAN).build();
	}

	/**
	 * Javers auditable aspect.
	 *
	 * @param javers                   the javers
	 * @param authorProvider           the author provider
	 * @param commitPropertiesProvider the commit properties provider
	 * @return the javers auditable aspect
	 */
	@Bean
	public JaversAuditableAspect javersAuditableAspect(final Javers javers, final AuthorProvider authorProvider,
			final CommitPropertiesProvider commitPropertiesProvider) {
		return new JaversAuditableAspect(javers, authorProvider, commitPropertiesProvider);
	}

	/**
	 * Author provider.
	 *
	 * @return the author provider
	 */
	@Bean
	public AuthorProvider authorProvider() {
		return () -> {
			final SecurityContext context = SecurityContextHolder.getContext();
			if (context != null && context.getAuthentication() != null) {
				return context.getAuthentication().getPrincipal().toString();
			} else {
				return "system";
			}
		};
	}

	/**
	 * Commit properties provider.
	 *
	 * @return the commit properties provider
	 */
	@Bean
	public CommitPropertiesProvider commitPropertiesProvider() {
		return () -> ImmutableMap.of("key", "ok");
	}
}


/*
 * 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.politician.pagemode;

import java.util.List;

import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Component;

import com.hack23.cia.model.external.riksdagen.person.impl.AssignmentData;
import com.hack23.cia.model.external.riksdagen.person.impl.PersonData;
import com.hack23.cia.model.internal.application.data.politician.impl.ViewRiksdagenPolitician;
import com.hack23.cia.web.impl.ui.application.views.common.labelfactory.LabelFactory;
import com.hack23.cia.web.impl.ui.application.views.common.sizing.ContentRatio;
import com.hack23.cia.web.impl.ui.application.views.common.viewnames.PoliticianPageMode;
import com.vaadin.ui.Label;
import com.vaadin.ui.Layout;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.Panel;
import com.vaadin.ui.VerticalLayout;

/**
 * The Class RoleSummaryPageModContentFactoryImpl.
 */
@Component
public final class PoliticianRoleSummaryPageModContentFactoryImpl extends AbstractPoliticianPageModContentFactoryImpl {

	/** The Constant GOVERNMENT_EXPERIENCE. */
	private static final String GOVERNMENT_EXPERIENCE = "Government experience:";

	/** The Constant EU_EXPERIENCE. */
	private static final String EU_EXPERIENCE = "EU experience:";

	/** The Constant TOTAL_ASSIGNMENTS. */
	private static final String TOTAL_ASSIGNMENTS = "Total Assignments:";

	/** The Constant SPEAKER_EXPERIENCE. */
	private static final String SPEAKER_EXPERIENCE = "Speaker experience:";

	/** The Constant PARTY_EXPERIENCE. */
	private static final String PARTY_EXPERIENCE = "Party experience:";

	/** The Constant COMMITTEE_EXPERIENCE. */
	private static final String COMMITTEE_EXPERIENCE = "Committee experience:";

	/** The Constant PARLIAMENT_EXPERIENCE. */
	private static final String PARLIAMENT_EXPERIENCE = "Parliament experience:";

	/**
	 * Instantiates a new politician role summary page mod content factory impl.
	 */
	public PoliticianRoleSummaryPageModContentFactoryImpl() {
		super();
	}

	@Override
	public boolean matches(final String page, final String parameters) {
		return NAME.equals(page) && parameters.contains(PoliticianPageMode.ROLESUMMARY.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();

		final String pageId = getPageId(parameters);
		final ViewRiksdagenPolitician viewRiksdagenPolitician = getItem(parameters);
		getPoliticianMenuItemFactory().createPoliticianMenuBar(menuBar, pageId);

		LabelFactory.createHeader2Label(panelContent, PoliticianPageMode.ROLESUMMARY.toString());

		final PersonData personData = getApplicationManager().getDataContainer(PersonData.class)
				.load(viewRiksdagenPolitician.getPersonId());

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

		createRoleSummary(panelContent, assignmentList, viewRiksdagenPolitician);

		pageCompleted(parameters, panel, pageId, viewRiksdagenPolitician);
		return panelContent;

	}

	/**
	 * Creates the role summary.
	 *
	 * @param roleSummaryLayoutTabsheet the role summary layout tabsheet
	 * @param assignmentList the assignment list
	 * @param viewRiksdagenPolitician the view riksdagen politician
	 */
	private void createRoleSummary(final VerticalLayout roleSummaryLayoutTabsheet,
			final List<AssignmentData> assignmentList, final ViewRiksdagenPolitician viewRiksdagenPolitician) {

		final VerticalLayout layout = new VerticalLayout();
		layout.setSizeFull();

		layout.addComponent(new Label(TOTAL_ASSIGNMENTS + assignmentList.size()));

		if (viewRiksdagenPolitician != null) {

			layout.addComponent(new Label(GOVERNMENT_EXPERIENCE
					+ convertToYearsString(viewRiksdagenPolitician.getTotalDaysServedGovernment())));
			layout.addComponent(new Label(
					SPEAKER_EXPERIENCE + convertToYearsString(viewRiksdagenPolitician.getTotalDaysServedSpeaker())));
			layout.addComponent(new Label(COMMITTEE_EXPERIENCE
					+ convertToYearsString(viewRiksdagenPolitician.getTotalDaysServedCommittee())));
			layout.addComponent(
					new Label(EU_EXPERIENCE + convertToYearsString(viewRiksdagenPolitician.getTotalDaysServedEu())));
			layout.addComponent(new Label(PARLIAMENT_EXPERIENCE
					+ convertToYearsString(viewRiksdagenPolitician.getTotalDaysServedParliament())));
			layout.addComponent(new Label(
					PARTY_EXPERIENCE + convertToYearsString(viewRiksdagenPolitician.getTotalDaysServedParty())));
		}

		roleSummaryLayoutTabsheet.addComponent(layout);
		roleSummaryLayoutTabsheet.setExpandRatio(layout, ContentRatio.GRID);

	}

}


/*
 * 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.external.esv.api;

import java.io.Serializable;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;

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;

/**
 * The Class GovernmentBodyAnnualOutcomeSummary.
 */
public final class GovernmentBodyAnnualOutcomeSummary implements Serializable {

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

	/** The goverment body. */
	private final String govermentBody;

	/** The org number. */
	private final String orgNumber;

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

	/** The year. */
	private final int year;

	/** The year total. */
	private double yearTotal;

	/** The value map. */
	private final Map<Date, Double> valueMap = new HashMap<>();

	/** The description fields. */
	private final Map<String, String> descriptionFields = new HashMap<>();

	/**
	 * Instantiates a new government body annual outcome summary.
	 *
	 * @param govermentBody the goverment body
	 * @param orgNumber     the org number
	 * @param ministry      the ministry
	 * @param year          the year
	 */
	public GovernmentBodyAnnualOutcomeSummary(final String govermentBody, final String orgNumber, final String ministry, final int year) {
		super();
		this.govermentBody = govermentBody;
		this.orgNumber = orgNumber;
		this.ministry = ministry;
		this.year = year;
	}

	/**
	 * Gets the goverment body id.
	 *
	 * @return the goverment body id
	 */
	public String getGovermentBody() {
		return govermentBody;
	}

	/**
	 * Gets the org number.
	 *
	 * @return the org number
	 */
	public String getOrgNumber() {
		return orgNumber;
	}

	/**
	 * Gets the year.
	 *
	 * @return the year
	 */
	public int getYear() {
		return year;
	}

	/**
	 * Gets the ministry.
	 *
	 * @return the ministry
	 */
	public String getMinistry() {
		return ministry;
	}

	/**
	 * Adds the data.
	 *
	 * @param month
	 *            the month
	 * @param value
	 *            the value
	 */
	public void addData(final int month, final Double value) {
		yearTotal = yearTotal + value;
		final Date date = new GregorianCalendar(year, month, 1).getTime();
		valueMap.put(date, value);
	}

	/**
	 * Gets the year total.
	 *
	 * @return the year total
	 */
	public double getYearTotal() {
		return yearTotal;
	}

	/**
	 * Adds the description field.
	 *
	 * @param field
	 *            the field
	 * @param value
	 *            the value
	 */
	public void addDescriptionField(final String field, final String value) {
		descriptionFields.put(field, value);
	}

	/**
	 * Gets the value map.
	 *
	 * @return the value map
	 */
	public Map<Date, Double> getValueMap() {
		return valueMap;
	}

	/**
	 * Gets the description fields.
	 *
	 * @return the description fields
	 */
	public Map<String, String> getDescriptionFields() {
		return descriptionFields;
	}

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

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

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

}


//
// 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.25 at 12:05:09 AM CET
//

package com.hack23.cia.model.internal.application.data.impl;

import java.math.BigDecimal;

import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
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;

/**
 *
Java class for ViewApplicationActionEventPageDailySummary complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="ViewApplicationActionEventPageDailySummary">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="embeddedId" type="{http://data.application.internal.model.cia.hack23.com/impl}ApplicationActionEventPagePeriodSummaryEmbeddedId"/>
 *         <element name="hits" type="{http://www.w3.org/2001/XMLSchema}long"/>
 *         <element name="rank" type="{http://www.w3.org/2001/XMLSchema}long"/>
 *         <element name="rank_percentage" type="{http://www.w3.org/2001/XMLSchema}decimal"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ViewApplicationActionEventPageDailySummary", propOrder = {
    "embeddedId",
    "hits",
    "rank",
    "rankPercentage"
})
@Entity(name = "ViewApplicationActionEventPageDailySummary")
@Table(name = "view_application_action_event_page_daily_summary")
@Inheritance(strategy = InheritanceType.JOINED)
public class ViewApplicationActionEventPageDailySummary
    implements ModelObject
{

    /**
	 *
	 */
	private static final long serialVersionUID = 1L;
	@XmlElement(required = true)
    protected ApplicationActionEventPagePeriodSummaryEmbeddedId embeddedId;
    protected long hits;
    protected long rank;
    @XmlElement(name = "rank_percentage", required = true)
    protected BigDecimal rankPercentage;

    /**
     * Gets the value of the embeddedId property.
     *
     * @return
     *     possible object is
     *     {@link ApplicationActionEventPagePeriodSummaryEmbeddedId }
     *
     */
    @EmbeddedId
    @AttributeOverrides({
        @AttributeOverride(name = "createdDate", column = @Column(name = "EMBEDDED_ID_CREATED_DATE")),
        @AttributeOverride(name = "page", column = @Column(name = "EMBEDDED_ID_PAGE"))
    })
    public ApplicationActionEventPagePeriodSummaryEmbeddedId getEmbeddedId() {
        return embeddedId;
    }

    /**
     * Sets the value of the embeddedId property.
     *
     * @param value
     *     allowed object is
     *     {@link ApplicationActionEventPagePeriodSummaryEmbeddedId }
     *
     */
    public void setEmbeddedId(final ApplicationActionEventPagePeriodSummaryEmbeddedId value) {
        this.embeddedId = value;
    }

    /**
     * Gets the value of the hits property.
     *
     */
    @Basic
    @Column(name = "HITS", precision = 20)
    public long getHits() {
        return hits;
    }

    /**
     * Sets the value of the hits property.
     *
     */
    public void setHits(final long value) {
        this.hits = value;
    }

    /**
     * Gets the value of the rank property.
     *
     */
    @Basic
    @Column(name = "RANK", precision = 20)
    public long getRank() {
        return rank;
    }

    /**
     * Sets the value of the rank property.
     *
     */
    public void setRank(final long value) {
        this.rank = value;
    }

    /**
     * Gets the value of the rankPercentage property.
     *
     * @return
     *     possible object is
     *     {@link BigDecimal }
     *
     */
    @Basic
    @Column(name = "RANK_PERCENTAGE", precision = 20, scale = 10)
    public BigDecimal getRankPercentage() {
        return rankPercentage;
    }

    /**
     * Sets the value of the rankPercentage property.
     *
     * @param value
     *     allowed object is
     *     {@link BigDecimal }
     *
     */
    public void setRankPercentage(final BigDecimal value) {
        this.rankPercentage = value;
    }

    public ViewApplicationActionEventPageDailySummary withEmbeddedId(final ApplicationActionEventPagePeriodSummaryEmbeddedId value) {
        setEmbeddedId(value);
        return this;
    }

    public ViewApplicationActionEventPageDailySummary withHits(final long value) {
        setHits(value);
        return this;
    }

    public ViewApplicationActionEventPageDailySummary withRank(final long value) {
        setRank(value);
        return this;
    }

    public ViewApplicationActionEventPageDailySummary withRankPercentage(final BigDecimal value) {
        setRankPercentage(value);
        return this;
    }

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

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

	@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.service.external.esv.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.hack23.cia.service.external.esv.api.GovernmentBodyAnnualSummary;

/**
 * The Class EsvExcelReaderImpl.
 */
@Component
final class EsvExcelReaderImpl implements EsvExcelReader {

	/** The Constant COMMENT_CELL. */
	private static final int COMMENT_CELL = 9;

	/** The Constant VAT_CELL. */
	private static final int VAT_CELL = 8;

	/** The Constant ANNUAL_HEADCOUNT_CELL. */
	private static final int ANNUAL_HEADCOUNT_CELL = 7;

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

	/** The Constant ORG_NUMBER_CELL. */
	private static final int ORG_NUMBER_CELL = 5;

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

	/** The Constant MCODE_CELL. */
	private static final int MCODE_CELL = 3;

	/** The Constant GOVERNMENT_BODY_ID_CELL. */
	private static final int GOVERNMENT_BODY_ID_CELL = 2;

	/** The Constant CONSECUTIVE_NUMBER_CELL. */
	private static final int CONSECUTIVE_NUMBER_CELL = 1;

	/** The Constant NAME_CELL. */
	private static final int NAME_CELL = 0;

	/** The Constant EXPECTED_COLUMN_LENGTH. */
	private static final int EXPECTED_COLUMN_LENGTH = 10;

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

	/**
	 * Instantiates a new esv excel reader impl.
	 */
	public EsvExcelReaderImpl() {
		super();
	}

	@Override
	public Map<Integer, List<GovernmentBodyAnnualSummary>> getDataPerMinistry(final String name) {
		final Map<Integer, List<GovernmentBodyAnnualSummary>> map = new TreeMap<>();
		try {
			final HSSFWorkbook myWorkBook = createGovermentBodyWorkBook();

			for (int sheetNr = 0; sheetNr < myWorkBook.getNumberOfSheets(); sheetNr++) {
				addMinistryPerYearToMap(name, map, myWorkBook.getSheetAt(sheetNr));
			}

			myWorkBook.close();
		} catch (final IOException e) {
			LOGGER.warn("Problem loading", e);
		}

		return map;
	}

	private static HSSFWorkbook createGovermentBodyWorkBook() throws IOException {
		return new HSSFWorkbook(EsvExcelReaderImpl.class.getResourceAsStream("/Myndighetsinformation.xls"));
	}

	/**
	 * Adds the ministry per year to map.
	 *
	 * @param name
	 *            the name
	 * @param map
	 *            the map
	 * @param mySheet
	 *            the my sheet
	 */
	private static void addMinistryPerYearToMap(final String name,
			final Map<Integer, List<GovernmentBodyAnnualSummary>> map, final HSSFSheet mySheet) {
		if (mySheet.getSheetName().chars().allMatch(Character::isDigit)) {

			final int year = Integer.parseInt(mySheet.getSheetName());

			final List<GovernmentBodyAnnualSummary> yearList = new ArrayList<>();
			final Iterator<Row> rowIterator = mySheet.iterator();

			// Skip header row, ignore first
			rowIterator.next();

			while (rowIterator.hasNext()) {
				addGovernmentBodyAnnualSummaryToList(name, year, yearList, rowIterator.next());
			}
			map.put(year, yearList);
		}
	}

	/**
	 * Adds the government body annual summary to list.
	 *
	 * @param name
	 *            the name
	 * @param year
	 *            the year
	 * @param yearList
	 *            the year list
	 * @param row
	 *            the row
	 */
	private static void addGovernmentBodyAnnualSummaryToList(final String name, final int year,
			final List<GovernmentBodyAnnualSummary> yearList, final Row row) {
		if (row.getLastCellNum() >= EXPECTED_COLUMN_LENGTH) {

			final GovernmentBodyAnnualSummary governmentBodyAnnualSummary = createGovernmentBodyAnnualSummaryFromRow(
					year, row);

			if (name == null || name.equalsIgnoreCase(governmentBodyAnnualSummary.getMinistry())) {
				yearList.add(governmentBodyAnnualSummary);
			}
		}
	}

	/**
	 * Gets the integer.
	 *
	 * @param str
	 *            the str
	 * @return the integer
	 */
	private static int getInteger(final String str) {
		if (str == null || str.trim().length() == 0) {
			return 0;
		} else {
			return Integer.parseInt(str);
		}
	}

	@Override
	public Map<Integer, GovernmentBodyAnnualSummary> getDataPerGovernmentBody(final String name) {
		final Map<Integer, GovernmentBodyAnnualSummary> map = new TreeMap<>();
		try {
			final HSSFWorkbook myWorkBook = createGovermentBodyWorkBook();

			for (int sheetNr = 0; sheetNr < myWorkBook.getNumberOfSheets(); sheetNr++) {
				final HSSFSheet mySheet = myWorkBook.getSheetAt(sheetNr);

				addDataForYearToMap(name, map, mySheet);
			}
			myWorkBook.close();
		} catch (

		final IOException e) {
			LOGGER.warn("Problem loading", e);
		}

		return map;
	}

	/**
	 * Adds the data for year to map.
	 *
	 * @param name
	 *            the name
	 * @param map
	 *            the map
	 * @param mySheet
	 *            the my sheet
	 */
	private static void addDataForYearToMap(final String name, final Map<Integer, GovernmentBodyAnnualSummary> map,
			final HSSFSheet mySheet) {
		if (mySheet.getSheetName().chars().allMatch(Character::isDigit)) {
			final int year = Integer.parseInt(mySheet.getSheetName());
			final Iterator<Row> rowIterator = mySheet.iterator();

			rowIterator.next();

			while (rowIterator.hasNext()) {
				addGovernmentBodyAnnualSummaryToMap(name, map, year, rowIterator.next());
			}
		}
	}

	/**
	 * Adds the government body annual summary to map.
	 *
	 * @param name
	 *            the name
	 * @param map
	 *            the map
	 * @param year
	 *            the year
	 * @param row
	 *            the row
	 */
	private static void addGovernmentBodyAnnualSummaryToMap(final String name, final Map<Integer, GovernmentBodyAnnualSummary> map,
			final int year, final Row row) {
		if (row.getLastCellNum() >= EXPECTED_COLUMN_LENGTH) {

			final GovernmentBodyAnnualSummary governmentBodyAnnualSummary = createGovernmentBodyAnnualSummaryFromRow(
					year, row);
			if (name == null || name.equalsIgnoreCase(governmentBodyAnnualSummary.getName())) {
				map.put(year, governmentBodyAnnualSummary);
			}
		}
	}

	/**
	 * Creates the government body annual summary from row.
	 *
	 * @param year
	 *            the year
	 * @param row
	 *            the row
	 * @return the government body annual summary
	 */
	private static GovernmentBodyAnnualSummary createGovernmentBodyAnnualSummaryFromRow(final int year, final Row row) {
		return new GovernmentBodyAnnualSummary(year, defaultValueIfNull(row.getCell(NAME_CELL)), getInteger(defaultValueIfNull(row.getCell(CONSECUTIVE_NUMBER_CELL))),
				defaultValueIfNull(row.getCell(GOVERNMENT_BODY_ID_CELL)), defaultValueIfNull(row.getCell(MCODE_CELL)), defaultValueIfNull(row.getCell(MINISTRY_CELL)),
				defaultValueIfNull(row.getCell(ORG_NUMBER_CELL)), getInteger(defaultValueIfNull(row.getCell(HEADCOUNT_CELL))), getInteger(defaultValueIfNull(row.getCell(ANNUAL_HEADCOUNT_CELL))),
				defaultValueIfNull(row.getCell(VAT_CELL)), defaultValueIfNull(row.getCell(COMMENT_CELL)));
	}

	/**
	 * Default value if null.
	 *
	 * @param cell
	 *            the cell
	 * @return the string
	 */
	private static String defaultValueIfNull(final Cell cell) {
		if (cell != null) {
			return cell.toString();
		} else {
			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:39:56 PM CET
//

package com.hack23.cia.model.external.riksdagen.person.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 _Personlista_QNAME. */
    private static final QName _Personlista_QNAME = new QName("http://person.riksdagen.external.model.cia.hack23.com/impl", "personlista");

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

    /**
	 * Creates a new Object object.
	 *
	 * @return the person container data
	 */
    public PersonContainerData createPersonContainerData() {
        return new PersonContainerData();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the person data
	 */
    public PersonData createPersonData() {
        return new PersonData();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the person assignment data
	 */
    public PersonAssignmentData createPersonAssignmentData() {
        return new PersonAssignmentData();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the person detail data
	 */
    public PersonDetailData createPersonDetailData() {
        return new PersonDetailData();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the assignment data
	 */
    public AssignmentData createAssignmentData() {
        return new AssignmentData();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the detail data
	 */
    public DetailData createDetailData() {
        return new DetailData();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @param value the value
	 * @return the JAXB element< person container data>
	 */
    @XmlElementDecl(namespace = "http://person.riksdagen.external.model.cia.hack23.com/impl", name = "personlista")
    public JAXBElement<PersonContainerData> createPersonlista(final PersonContainerData value) {
        return new JAXBElement<>(_Personlista_QNAME, PersonContainerData.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$
*/
// 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:56 PM CET
//

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

import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
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.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
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 PersonData.
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PersonData", propOrder = {
    "hangarGuid",
    "id",
    "bornYear",
    "gender",
    "lastName",
    "firstName",
    "place",
    "party",
    "electionRegion",
    "status",
    "imageUrl192",
    "imageUrlMax",
    "imageUrl80",
    "personUrlXml",
    "personAssignmentData",
    "personDetailData"
})
@Entity(name = "PersonData")
@Table(name = "PERSON_DATA")
@Inheritance(strategy = InheritanceType.JOINED)
public class PersonData
    implements ModelObject
{

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

	/** The hangar guid. */
    @XmlElement(name = "hangar_guid", required = true)
    protected String hangarGuid;

    /** The id. */
    @XmlElement(name = "intressent_id", required = true)
    protected String id;

    /** The born year. */
    @XmlElement(name = "fodd_ar")
    protected int bornYear;

    /** The gender. */
    @XmlElement(name = "kon", required = true)
    @XmlSchemaType(name = "string")
    protected SexType gender;

    /** The last name. */
    @XmlElement(name = "efternamn", required = true)
    protected String lastName;

    /** The first name. */
    @XmlElement(name = "tilltalsnamn", required = true)
    protected String firstName;

    /** The place. */
    @XmlElement(name = "iort", required = true)
    protected String place;

    /** The party. */
    @XmlElement(name = "parti", required = true)
    protected String party;

    /** The election region. */
    @XmlElement(name = "valkrets", required = true)
    protected String electionRegion;

    /** The status. */
    @XmlElement(required = true)
    protected String status;

    /** The image url 192. */
    @XmlElement(name = "bild_url_192", required = true)
    @XmlSchemaType(name = "anyURI")
    protected String imageUrl192;

    /** The image url max. */
    @XmlElement(name = "bild_url_max", required = true)
    @XmlSchemaType(name = "anyURI")
    protected String imageUrlMax;

    /** The image url 80. */
    @XmlElement(name = "bild_url_80", required = true)
    @XmlSchemaType(name = "anyURI")
    protected String imageUrl80;

    /** The person url xml. */
    @XmlElement(name = "person_url_xml", required = true)
    @XmlSchemaType(name = "anyURI")
    protected String personUrlXml;

    /** The person assignment data. */
    @XmlElement(name = "personuppdrag", required = true)
    protected PersonAssignmentData personAssignmentData;

    /** The person detail data. */
    @XmlElement(name = "personuppgift", required = true)
    protected PersonDetailData personDetailData;

    /**
	 * Gets the hangar guid.
	 *
	 * @return the hangar guid
	 */
    @Basic
    @Column(name = "HANGAR_GUID")
    public String getHangarGuid() {
        return hangarGuid;
    }

    /**
	 * Sets the hangar guid.
	 *
	 * @param value the new hangar guid
	 */
    public void setHangarGuid(final String value) {
        this.hangarGuid = value;
    }

    /**
	 * Gets the id.
	 *
	 * @return the id
	 */
    @Id
    @Column(name = "ID")
    public String getId() {
        return id;
    }

    /**
	 * Sets the id.
	 *
	 * @param value the new id
	 */
    public void setId(final String value) {
        this.id = value;
    }

    /**
	 * Gets the born year.
	 *
	 * @return the born year
	 */
    @Basic
    @Column(name = "BORN_YEAR", precision = 10, scale = 0)
    public int getBornYear() {
        return bornYear;
    }

    /**
	 * Sets the born year.
	 *
	 * @param value the new born year
	 */
    public void setBornYear(final int value) {
        this.bornYear = value;
    }

    /**
	 * Gets the gender.
	 *
	 * @return the gender
	 */
    @Basic
    @Column(name = "GENDER")
    @Enumerated(EnumType.STRING)
    public SexType getGender() {
        return gender;
    }

    /**
	 * Sets the gender.
	 *
	 * @param value the new gender
	 */
    public void setGender(final SexType value) {
        this.gender = value;
    }

    /**
	 * Gets the last name.
	 *
	 * @return the last name
	 */
    @Basic
    @Column(name = "LAST_NAME")
    public String getLastName() {
        return lastName;
    }

    /**
	 * Sets the last name.
	 *
	 * @param value the new last name
	 */
    public void setLastName(final String value) {
        this.lastName = value;
    }

    /**
	 * Gets the first name.
	 *
	 * @return the first name
	 */
    @Basic
    @Column(name = "FIRST_NAME")
    public String getFirstName() {
        return firstName;
    }

    /**
	 * Sets the first name.
	 *
	 * @param value the new first name
	 */
    public void setFirstName(final String value) {
        this.firstName = value;
    }

    /**
	 * Gets the place.
	 *
	 * @return the place
	 */
    @Basic
    @Column(name = "PLACE")
    public String getPlace() {
        return place;
    }

    /**
	 * Sets the place.
	 *
	 * @param value the new place
	 */
    public void setPlace(final String value) {
        this.place = value;
    }

    /**
	 * Gets the party.
	 *
	 * @return the party
	 */
    @Basic
    @Column(name = "PARTY")
    public String getParty() {
        return party;
    }

    /**
	 * Sets the party.
	 *
	 * @param value the new party
	 */
    public void setParty(final String value) {
        this.party = value;
    }

    /**
	 * Gets the election region.
	 *
	 * @return the election region
	 */
    @Basic
    @Column(name = "ELECTION_REGION")
    public String getElectionRegion() {
        return electionRegion;
    }

    /**
	 * Sets the election region.
	 *
	 * @param value the new election region
	 */
    public void setElectionRegion(final String value) {
        this.electionRegion = value;
    }

    /**
	 * Gets the status.
	 *
	 * @return the status
	 */
    @Basic
    @Column(name = "STATUS")
    public String getStatus() {
        return status;
    }

    /**
	 * Sets the status.
	 *
	 * @param value the new status
	 */
    public void setStatus(final String value) {
        this.status = value;
    }

    /**
	 * Gets the image url 192.
	 *
	 * @return the image url 192
	 */
    @Basic
    @Column(name = "IMAGE_URL_192")
    public String getImageUrl192() {
        return imageUrl192;
    }

    /**
	 * Sets the image url 192.
	 *
	 * @param value the new image url 192
	 */
    public void setImageUrl192(final String value) {
        this.imageUrl192 = value;
    }

    /**
	 * Gets the image url max.
	 *
	 * @return the image url max
	 */
    @Basic
    @Column(name = "IMAGE_URL_MAX")
    public String getImageUrlMax() {
        return imageUrlMax;
    }

    /**
	 * Sets the image url max.
	 *
	 * @param value the new image url max
	 */
    public void setImageUrlMax(final String value) {
        this.imageUrlMax = value;
    }

    /**
	 * Gets the image url 80.
	 *
	 * @return the image url 80
	 */
    @Basic
    @Column(name = "IMAGE_URL_80")
    public String getImageUrl80() {
        return imageUrl80;
    }

    /**
	 * Sets the image url 80.
	 *
	 * @param value the new image url 80
	 */
    public void setImageUrl80(final String value) {
        this.imageUrl80 = value;
    }

    /**
	 * Gets the person url xml.
	 *
	 * @return the person url xml
	 */
    @Basic
    @Column(name = "PERSON_URL_XML")
    public String getPersonUrlXml() {
        return personUrlXml;
    }

    /**
	 * Sets the person url xml.
	 *
	 * @param value the new person url xml
	 */
    public void setPersonUrlXml(final String value) {
        this.personUrlXml = value;
    }

    /**
	 * Gets the person assignment data.
	 *
	 * @return the person assignment data
	 */
    @ManyToOne(targetEntity = PersonAssignmentData.class, cascade = {
        CascadeType.ALL
    })
    @JoinColumn(name = "PERSON_ASSIGNMENT_DATA_PERSO_0")
    public PersonAssignmentData getPersonAssignmentData() {
        return personAssignmentData;
    }

    /**
	 * Sets the person assignment data.
	 *
	 * @param value the new person assignment data
	 */
    public void setPersonAssignmentData(final PersonAssignmentData value) {
        this.personAssignmentData = value;
    }

    /**
	 * Gets the person detail data.
	 *
	 * @return the person detail data
	 */
    @ManyToOne(targetEntity = PersonDetailData.class, cascade = {
        CascadeType.ALL
    })
    @JoinColumn(name = "PERSON_DETAIL_DATA_PERSON_DA_0")
    public PersonDetailData getPersonDetailData() {
        return personDetailData;
    }

    /**
	 * Sets the person detail data.
	 *
	 * @param value the new person detail data
	 */
    public void setPersonDetailData(final PersonDetailData value) {
        this.personDetailData = value;
    }

    /**
	 * With hangar guid.
	 *
	 * @param value the value
	 * @return the person data
	 */
    public PersonData withHangarGuid(final String value) {
        setHangarGuid(value);
        return this;
    }

    /**
	 * With id.
	 *
	 * @param value the value
	 * @return the person data
	 */
    public PersonData withId(final String value) {
        setId(value);
        return this;
    }

    /**
	 * With born year.
	 *
	 * @param value the value
	 * @return the person data
	 */
    public PersonData withBornYear(final int value) {
        setBornYear(value);
        return this;
    }

    /**
	 * With gender.
	 *
	 * @param value the value
	 * @return the person data
	 */
    public PersonData withGender(final SexType value) {
        setGender(value);
        return this;
    }

    /**
	 * With last name.
	 *
	 * @param value the value
	 * @return the person data
	 */
    public PersonData withLastName(final String value) {
        setLastName(value);
        return this;
    }

    /**
	 * With first name.
	 *
	 * @param value the value
	 * @return the person data
	 */
    public PersonData withFirstName(final String value) {
        setFirstName(value);
        return this;
    }

    /**
	 * With place.
	 *
	 * @param value the value
	 * @return the person data
	 */
    public PersonData withPlace(final String value) {
        setPlace(value);
        return this;
    }

    /**
	 * With party.
	 *
	 * @param value the value
	 * @return the person data
	 */
    public PersonData withParty(final String value) {
        setParty(value);
        return this;
    }

    /**
	 * With election region.
	 *
	 * @param value the value
	 * @return the person data
	 */
    public PersonData withElectionRegion(final String value) {
        setElectionRegion(value);
        return this;
    }

    /**
	 * With status.
	 *
	 * @param value the value
	 * @return the person data
	 */
    public PersonData withStatus(final String value) {
        setStatus(value);
        return this;
    }

    /**
	 * With image url 192.
	 *
	 * @param value the value
	 * @return the person data
	 */
    public PersonData withImageUrl192(final String value) {
        setImageUrl192(value);
        return this;
    }

    /**
	 * With image url max.
	 *
	 * @param value the value
	 * @return the person data
	 */
    public PersonData withImageUrlMax(final String value) {
        setImageUrlMax(value);
        return this;
    }

    /**
	 * With image url 80.
	 *
	 * @param value the value
	 * @return the person data
	 */
    public PersonData withImageUrl80(final String value) {
        setImageUrl80(value);
        return this;
    }

    /**
	 * With person url xml.
	 *
	 * @param value the value
	 * @return the person data
	 */
    public PersonData withPersonUrlXml(final String value) {
        setPersonUrlXml(value);
        return this;
    }

    /**
	 * With person assignment data.
	 *
	 * @param value the value
	 * @return the person data
	 */
    public PersonData withPersonAssignmentData(final PersonAssignmentData value) {
        setPersonAssignmentData(value);
        return this;
    }

    /**
	 * With person detail data.
	 *
	 * @param value the value
	 * @return the person data
	 */
    public PersonData withPersonDetailData(final PersonDetailData value) {
        setPersonDetailData(value);
        return this;
    }

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

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

	/* (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.user.politician.pagemode;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Component;

import com.hack23.cia.model.internal.application.system.impl.ApplicationEventGroup;
import com.hack23.cia.web.impl.ui.application.action.ViewAction;
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.vaadin.ui.Layout;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.Panel;
import com.vaadin.ui.TextArea;
import com.vaadin.ui.VerticalLayout;

/**
 * The Class PoliticianRankingOverviewPageModContentFactoryImpl.
 */
@Component
public final class PoliticianRankingOverviewPageModContentFactoryImpl
		extends AbstractPoliticianRankingPageModContentFactoryImpl {

	/** The Constant NAME. */
	public static final String NAME = UserViews.POLITICIAN_RANKING_VIEW_NAME;

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

	/**
	 * Instantiates a new politician ranking overview page mod content factory
	 * impl.
	 */
	public PoliticianRankingOverviewPageModContentFactoryImpl() {
		super();
	}

	@Override
	public boolean matches(final String page, final String parameters) {
		return NAME.equals(page) && (StringUtils.isEmpty(parameters) || parameters.contains(PageMode.OVERVIEW.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();

		getPoliticianRankingMenuItemFactory().createPoliticianRankingMenuBar(menuBar);

		final String pageId = getPageId(parameters);

		panelContent.addComponent(createDescription());

		getPoliticianRankingMenuItemFactory().createOverviewPage(panelContent);

		panel.setCaption(NAME + "::" + OVERVIEW);

		getPageActionEventHelper().createPageEvent(ViewAction.VISIT_POLITICIAN_RANKING_VIEW, ApplicationEventGroup.USER,
				NAME, parameters, pageId);

		return panelContent;

	}

	/**
	 * Creates the description.
	 *
	 * @return the text area
	 */
	private static TextArea createDescription() {
		final TextArea totalpoliticantoplistLabel = new TextArea("Politician Ranking by topic",
				"Time served in Parliament:ALL:CURRENT:*FILTER:Gender,Party,ElectionRegion"
						+ "\nTime served in Committees:ALL:CURRENT:*FILTER:Gender,Party,ElectionRegion"
						+ "\nTime served in Government:ALL:CURRENT:*FILTER:Gender,Party,ElectionRegion"
						+ "\nTop document author NR:ALL:YEAR:CURRENT:*FILTER:DocumnetType,Gender,Party,ElectionRegion"
						+ "\nTop document author SIZE:YEAR:ALL:CURRENT:*FILTER:DocumnetType,Gender,Party,ElectionRegion"

						+ "\nTop votes:ALL:YEAR:CURRENT::*FILTER:Gender,Party,ElectionRegion"
						+ "\nTop vote winner NR/PERCENTAGE :ALL:YEAR:CURRENT::*FILTER:Gender,Party,ElectionRegion"
						+ "\nTop vote party rebel NR/PERCENTAGE :ALL:YEAR:CURRENT::*FILTER:Gender,Party,ElectionRegion"
						+ "\nTop vote presence NR/PERCENTAGE :ALL:YEAR:CURRENT::*FILTER:Gender,Party,ElectionRegion"
						+ "\nSearch by name");
		totalpoliticantoplistLabel.setSizeFull();
		totalpoliticantoplistLabel.setStyleName("Level2Header");
		return totalpoliticantoplistLabel;
	}

}


/*
 * 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.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
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.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.committee.impl.RiksdagenCommitteeDecisionTypeOrgSummaryEmbeddedId;
import com.hack23.cia.model.internal.application.data.committee.impl.RiksdagenCommitteeDecisionTypeSummaryEmbeddedId;
import com.hack23.cia.model.internal.application.data.committee.impl.ViewRiksdagenCommitteeDecisionTypeDailySummary;
import com.hack23.cia.model.internal.application.data.committee.impl.ViewRiksdagenCommitteeDecisionTypeOrgDailySummary;
import com.hack23.cia.service.api.DataContainer;
import com.hack23.cia.web.impl.ui.application.views.common.chartfactory.api.DecisionChartDataManager;
import com.vaadin.ui.AbstractOrderedLayout;

/**
 * The Class DecisionChartDataManagerImpl.
 */
@Service
public final class DecisionChartDataManagerImpl extends AbstractChartDataManagerImpl
		implements DecisionChartDataManager {

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

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

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

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

	/**
	 * Gets the committee decision type map.
	 *
	 * @return the committee decision type map
	 */
	private Map<String, List<ViewRiksdagenCommitteeDecisionTypeDailySummary>> getCommitteeDecisionTypeMap() {
		final DataContainer<ViewRiksdagenCommitteeDecisionTypeDailySummary, RiksdagenCommitteeDecisionTypeSummaryEmbeddedId> committeeBallotDecisionPartyDataContainer = getApplicationManager()
				.getDataContainer(ViewRiksdagenCommitteeDecisionTypeDailySummary.class);

		final Date now = new Date();
		final Date notBefore = new GregorianCalendar(2000, Calendar.JANUARY, 1).getTime();
		return committeeBallotDecisionPartyDataContainer.getAll().parallelStream()
				.filter(t -> t != null && !t.getEmbeddedId().getDecisionDate().after(now)
						&& !notBefore.after(t.getEmbeddedId().getDecisionDate()))
				.collect(Collectors.groupingBy(t -> t.getEmbeddedId().getDecisionType()));
	}

	/**
	 * Gets the committee decision type org map.
	 *
	 * @return the committee decision type org map
	 */
	private Map<String, List<ViewRiksdagenCommitteeDecisionTypeOrgDailySummary>> getCommitteeDecisionTypeOrgMap() {
		final DataContainer<ViewRiksdagenCommitteeDecisionTypeOrgDailySummary, RiksdagenCommitteeDecisionTypeOrgSummaryEmbeddedId> committeeBallotDecisionPartyDataContainer = getApplicationManager()
				.getDataContainer(ViewRiksdagenCommitteeDecisionTypeOrgDailySummary.class);

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

	@Override
	public void createDecisionTypeChart(final AbstractOrderedLayout content) {

		final Map<String, List<ViewRiksdagenCommitteeDecisionTypeDailySummary>> map = getCommitteeDecisionTypeMap();

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

		final DataSeries dataSeries = new DataSeries();

		final Series series = new Series();

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

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

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

		}

		addChart(content, "Decision type daily summary",
				new DCharts().setDataSeries(dataSeries)
						.setOptions(getChartOptions().createOptionsXYDateFloatLegendInsideOneColumn(series)).show(),
				true);
	}

	@Override
	public void createDecisionTypeChart(final AbstractOrderedLayout content, final String org) {

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

		final DataSeries dataSeries = new DataSeries();
		final Series series = new Series();

		final Map<String, List<ViewRiksdagenCommitteeDecisionTypeOrgDailySummary>> allMap = getCommitteeDecisionTypeOrgMap();

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

		if (itemList != null) {

			final Map<String, List<ViewRiksdagenCommitteeDecisionTypeOrgDailySummary>> map = itemList.parallelStream()
					.filter(t -> t != null && t.getEmbeddedId().getDecisionDate() != null)
					.collect(Collectors.groupingBy(t -> t.getEmbeddedId().getDecisionType()));

			addDecisionTypeByOrgData(simpleDateFormat, dataSeries, series, map);
		}

		addChart(content, "Org Decision type daily summary",
				new DCharts().setDataSeries(dataSeries)
						.setOptions(getChartOptions().createOptionsXYDateFloatLegendInsideOneColumn(series)).show(),
				true);
	}

	/**
	 * Adds the decision type by org data.
	 *
	 * @param simpleDateFormat the simple date format
	 * @param dataSeries the data series
	 * @param series the series
	 * @param map the map
	 */
	private static void addDecisionTypeByOrgData(final SimpleDateFormat simpleDateFormat, final DataSeries dataSeries,
			final Series series, final Map<String, List<ViewRiksdagenCommitteeDecisionTypeOrgDailySummary>> map) {
		for (final Entry<String, List<ViewRiksdagenCommitteeDecisionTypeOrgDailySummary>> entry : map.entrySet()) {
			if (!EMPTY_STRING.equals(entry.getKey())) {

				final XYseries label = new XYseries();
				label.setLabel(entry.getKey());

				series.addSeries(label);

				dataSeries.newSeries();
				for (final ViewRiksdagenCommitteeDecisionTypeOrgDailySummary item : entry.getValue()) {
						dataSeries.add(simpleDateFormat.format(item.getEmbeddedId().getDecisionDate()),
								item.getTotal());
				}
			}
		}
	}

}


/*
 * 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:26:40 PM CET
//

package com.hack23.cia.model.external.worldbank.countries.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.XmlRootElement;
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 CountriesElement.
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "country" })
@XmlRootElement(name = "countries")
@Entity(name = "CountriesElement")
@Table(name = "COUNTRIES_ELEMENT")
@Inheritance(strategy = InheritanceType.JOINED)
public class CountriesElement implements ModelObject {

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

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

	/** The page. */
	@XmlAttribute(name = "page", required = true)
	protected BigInteger page;

	/** The pages. */
	@XmlAttribute(name = "pages", required = true)
	protected BigInteger pages;

	/** The per page. */
	@XmlAttribute(name = "per_page", required = true)
	protected BigInteger perPage;

	/** The total. */
	@XmlAttribute(name = "total", required = true)
	protected BigInteger total;

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

	/**
	 * Gets the country.
	 *
	 * @return the country
	 */
	@OneToMany(targetEntity = CountryElement.class, cascade = { CascadeType.ALL })
	@JoinColumn(name = "COUNTRY_COUNTRIES_ELEMENT_HJ_0")
	public List<CountryElement> getCountry() {
		return this.country;
	}

	/**
	 * Sets the country.
	 *
	 * @param country the new country
	 */
	public void setCountry(final List<CountryElement> country) {
		this.country = country;
	}

	/**
	 * Gets the page.
	 *
	 * @return the page
	 */
	@Basic
	@Column(name = "PAGE", precision = 20)
	public BigInteger getPage() {
		return page;
	}

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

	/**
	 * Gets the pages.
	 *
	 * @return the pages
	 */
	@Basic
	@Column(name = "PAGES", precision = 20)
	public BigInteger getPages() {
		return pages;
	}

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

	/**
	 * Gets the per page.
	 *
	 * @return the per page
	 */
	@Basic
	@Column(name = "PER_PAGE", precision = 20)
	public BigInteger getPerPage() {
		return perPage;
	}

	/**
	 * Sets the per page.
	 *
	 * @param value the new per page
	 */
	public void setPerPage(final BigInteger value) {
		this.perPage = value;
	}

	/**
	 * Gets the total.
	 *
	 * @return the total
	 */
	@Basic
	@Column(name = "TOTAL", precision = 20)
	public BigInteger getTotal() {
		return total;
	}

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

	/**
	 * With country.
	 *
	 * @param country the country
	 * @return the countries element
	 */
	public CountriesElement withCountry(final List<CountryElement> country) {
		setCountry(country);
		return this;
	}

	/**
	 * With page.
	 *
	 * @param value the value
	 * @return the countries element
	 */
	public CountriesElement withPage(final BigInteger value) {
		setPage(value);
		return this;
	}

	/**
	 * With pages.
	 *
	 * @param value the value
	 * @return the countries element
	 */
	public CountriesElement withPages(final BigInteger value) {
		setPages(value);
		return this;
	}

	/**
	 * With per page.
	 *
	 * @param value the value
	 * @return the countries element
	 */
	public CountriesElement withPerPage(final BigInteger value) {
		setPerPage(value);
		return this;
	}

	/**
	 * With total.
	 *
	 * @param value the value
	 * @return the countries element
	 */
	public CountriesElement withTotal(final BigInteger value) {
		setTotal(value);
		return this;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public final int hashCode() {
		return HashCodeBuilder.reflectionHashCode(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;
	}

	public boolean equals(final Object obj) {
		if (obj == null) {
			return false;
		}
		if (obj == this) {
			return true;
		}
		if (obj.getClass() != getClass()) {
			return false;
		}
		return new EqualsBuilder().append(getCountry().toArray(), ((CountriesElement) obj).getCountry().toArray()).isEquals();
	}

}


/*
 * 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.document.pagemode;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Component;

import com.hack23.cia.model.external.riksdagen.dokumentstatus.impl.DocumentAttachment;
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.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.labelfactory.LabelFactory;
import com.hack23.cia.web.impl.ui.application.views.common.pagelinks.impl.ExternalAttachmentDownloadLink;
import com.hack23.cia.web.impl.ui.application.views.common.pagelinks.impl.StreamSourceImplementation;
import com.hack23.cia.web.impl.ui.application.views.common.sizing.ContentRatio;
import com.hack23.cia.web.impl.ui.application.views.common.viewnames.DocumentPageMode;
import com.vaadin.server.StreamResource;
import com.vaadin.ui.Layout;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.Panel;
import com.vaadin.ui.VerticalLayout;
import com.whitestein.vaadin.widgets.wtpdfviewer.WTPdfViewer;

/**
 * The Class DocumentAttachementsPageModContentFactoryImpl.
 */
@Component
public final class DocumentAttachementsPageModContentFactoryImpl extends AbstractDocumentPageModContentFactoryImpl {

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

	/** The Constant HIDE_COLUMNS. */
	private static final String[] HIDE_COLUMNS = new String[] { "hjid" };

	/** The Constant COLUMN_ORDER. */
	private static final String[] COLUMN_ORDER = new String[] { "fileName", "fileSize", "fileType", "fileUrl" };

	/** The Constant DOCUMENT_ATTACHMENTS. */
	private static final String DOCUMENT_ATTACHMENTS = "Document Attachments";

	/**
	 * Instantiates a new document attachements page mod content factory impl.
	 */
	public DocumentAttachementsPageModContentFactoryImpl() {
		super();
	}

	@Override
	public boolean matches(final String page, final String parameters) {
		return NAME.equals(page) && StringUtils.contains(parameters, DocumentPageMode.DOCUMENTATTACHMENTS.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();

		final String pageId = getPageId(parameters);

		getDocumentMenuItemFactory().createDocumentMenuBar(menuBar, pageId);

		final DataContainer<DocumentStatusContainer, String> documentStatusContainerDataContainer = getApplicationManager()
				.getDataContainer(DocumentStatusContainer.class);

		final DocumentStatusContainer documentStatusContainer = documentStatusContainerDataContainer
				.findByQueryProperty(DocumentStatusContainer.class, DocumentStatusContainer_.document,
						DocumentData.class, DocumentData_.id, pageId);

		LabelFactory.createHeader2Label(panelContent, DOCUMENT_ATTACHMENTS);

		if (documentStatusContainer != null && documentStatusContainer.getDocumentAttachmentContainer() != null
				&& documentStatusContainer.getDocumentAttachmentContainer().getDocumentAttachmentList() != null) {

			getGridFactory().createBasicBeanItemGrid(panelContent, DocumentAttachment.class,
					documentStatusContainer.getDocumentAttachmentContainer().getDocumentAttachmentList(),
					DOCUMENT_ATTACHMENTS, COLUMN_ORDER, HIDE_COLUMNS, null, null, null);

			displayDocumentAttachements(panelContent,
					documentStatusContainer.getDocumentAttachmentContainer().getDocumentAttachmentList());
		}

		panel.setContent(panelContent);
		getPageActionEventHelper().createPageEvent(ViewAction.VISIT_DOCUMENT_VIEW, ApplicationEventGroup.USER, NAME,
				parameters, pageId);
		return panelContent;

	}

	/**
	 * Display document attachements.
	 *
	 * @param panelContent the panel content
	 * @param documentAttachmentList the document attachment list
	 */
	private static void displayDocumentAttachements(final VerticalLayout panelContent,
			final List<DocumentAttachment> documentAttachmentList) {
		for (final DocumentAttachment documentAttachment : documentAttachmentList) {

			if (PDF.equalsIgnoreCase(documentAttachment.getFileType())) {
				final WTPdfViewer wtPdfViewer = new WTPdfViewer();
				wtPdfViewer.setSizeFull();

				wtPdfViewer.setResource(new StreamResource(new StreamSourceImplementation(documentAttachment.getFileUrl()), documentAttachment.getFileName()));

				panelContent.addComponent(wtPdfViewer);
				panelContent.setExpandRatio(wtPdfViewer, ContentRatio.LARGE);
			} else {
				final VerticalLayout verticalLayout = new VerticalLayout();
				panelContent.addComponent(verticalLayout);
				panelContent.setExpandRatio(verticalLayout, ContentRatio.SMALL);
				final ExternalAttachmentDownloadLink link = new ExternalAttachmentDownloadLink(
						documentAttachment.getFileName(), documentAttachment.getFileType(),
						documentAttachment.getFileUrl());
				verticalLayout.addComponent(link);
			}
		}
	}

}


/*
 * 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.labelfactory;

import com.hack23.cia.web.impl.ui.application.views.common.sizing.ContentRatio;
import com.vaadin.ui.AbstractOrderedLayout;
import com.vaadin.ui.Label;

/**
 * A factory for creating Label objects.
 */
public final class LabelFactory {

	/**
	 * Instantiates a new label factory.
	 */
	private LabelFactory() {
		super();
	}

	/**
	 * Creates a new Label object.
	 *
	 * @param panel
	 *            the panel
	 * @param content
	 *            the content
	 */
	public static void createHeader2Label(final AbstractOrderedLayout panel,final String content) {
		final Label label = new Label(content);
		label.setStyleName("Level2Header");

		panel.addComponent(label);
		panel.setExpandRatio(label,ContentRatio.SMALL);
	}

}


/*
 * 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.application.encryption;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.jcajce.provider.digest.SHA3;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.user.impl.UserAccount;
import com.hack23.cia.service.data.api.EncryptedValueDAO;

/**
 * The Class VaultManagerImpl.
 */
@Service
@Transactional(propagation = Propagation.REQUIRED)
public final class VaultManagerImpl implements VaultManager {

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

	/** The Constant TAG_BIT_LENGTH. */
	private static final int TAG_BIT_LENGTH = 128;

	/** The Constant KEY_SIZE_IN_BYTES. */
	private static final int KEY_SIZE_IN_BYTES = 32;

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

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

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

	/** The Constant AES_GCM_NO_PADDING. */
	private static final String AES_GCM_NO_PADDING = "AES/GCM/NoPadding";

	/** The algorithm. */
	private static final String ALGORITHM = "AES";

	/** The encrypted value DAO. */
	private final EncryptedValueDAO encryptedValueDAO;

	/**
	 * Instantiates a new vault manager impl.
	 *
	 * @param encryptedValueDAO the encrypted value DAO
	 */
	@Autowired
	public VaultManagerImpl(final EncryptedValueDAO encryptedValueDAO) {
		super();
		this.encryptedValueDAO = encryptedValueDAO;
	}

	static {
		Security.setProperty("crypto.policy", "unlimited");
		Security.addProvider(new BouncyCastleProvider());
	}

	@Override
	public String getEncryptedValue(final String password, final UserAccount userExist) {
		if (userExist != null) {
			final EncryptedValue encryptedValue = encryptedValueDAO.findFirstByProperty(EncryptedValue_.userId,
					userExist.getUserId());

			if (encryptedValue != null) {
				return decryptValue(password, userExist.getUserId(), encryptedValue.getStorage());
			}
		}
		return null;
	}

	@Override
	public String encryptValue(final String password, final String userId, final String value) {
		if (password != null && userId != null && value!=null) {

			try {
				final Key buildKey = buildKey(userId, password);
				final SecureRandom secureRandom = new SecureRandom();
				final byte[] iv = new byte[IV_BYTE_SIZE];
				secureRandom.nextBytes(iv);
				final Cipher cipher = Cipher.getInstance(AES_GCM_NO_PADDING);
				final GCMParameterSpec parameterSpec = new GCMParameterSpec(TAG_BIT_LENGTH, iv);
				cipher.init(Cipher.ENCRYPT_MODE, buildKey, parameterSpec);

				final byte[] cipherText = cipher.doFinal(value.getBytes(StandardCharsets.UTF_8));
				final ByteBuffer byteBuffer = ByteBuffer.allocate(4 + iv.length + cipherText.length);
				byteBuffer.putInt(iv.length);
				byteBuffer.put(iv);
				byteBuffer.put(cipherText);
				return Hex.toHexString(byteBuffer.array());
			} catch (final GeneralSecurityException e) {
				LOGGER.error(ENCRYPT_VALUE,e);
				return null;
			}
		} else {
			return null;
		}

	}

	@Override
	public String decryptValue(final String password, final String userId, final String value) {
		if (password != null && userId != null && value!=null) {
			try {
				final Key buildKey = buildKey(userId, password);
				final ByteBuffer byteBuffer = ByteBuffer.wrap(Hex.decode(value.getBytes(StandardCharsets.UTF_8)));
				final int ivLength = byteBuffer.getInt();
				final byte[] iv = new byte[ivLength];
				byteBuffer.get(iv);
				final byte[] cipherText = new byte[byteBuffer.remaining()];
				byteBuffer.get(cipherText);

				final Cipher cipher = Cipher.getInstance(AES_GCM_NO_PADDING);
				cipher.init(Cipher.DECRYPT_MODE, buildKey, new GCMParameterSpec(TAG_BIT_LENGTH, iv));
				return new String(cipher.doFinal(cipherText),StandardCharsets.UTF_8);
			} catch (final GeneralSecurityException e) {
				LOGGER.error(DECRYPT_VALUE,e);
				return null;
			}
		} else {
			return null;
		}

	}

	/**
	 * Builds the key.
	 *
	 * @param userid
	 *            the userid
	 * @param password
	 *            the password
	 * @return the key
	 */
	private static Key buildKey(final String userid, final String password) {
		return new SecretKeySpec(Arrays.copyOf(
				new SHA3.Digest512().digest((userid + ".uuid" + password).getBytes(StandardCharsets.UTF_8)), KEY_SIZE_IN_BYTES),
				ALGORITHM);
	}
}


/*
 * 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:05 PM CET
//

package com.hack23.cia.model.external.riksdagen.documentcontent.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 _Documentcontentdata_QNAME. */
    private static final QName _Documentcontentdata_QNAME = new QName("http://documentcontent.riksdagen.external.model.cia.hack23.com/impl", "documentcontentdata");

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

    /**
	 * Creates a new Object object.
	 *
	 * @return the document content data
	 */
    public DocumentContentData createDocumentContentData() {
        return new DocumentContentData();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @param value the value
	 * @return the JAXB element< document content data>
	 */
    @XmlElementDecl(namespace = "http://documentcontent.riksdagen.external.model.cia.hack23.com/impl", name = "documentcontentdata")
    public JAXBElement<DocumentContentData> createDocumentcontentdata(final DocumentContentData value) {
        return new JAXBElement<>(_Documentcontentdata_QNAME, DocumentContentData.class, null, value);
    }

}


/*
 * 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.Objects;
import java.util.Set;
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.party.impl.ViewRiksdagenPartyBallotSupportAnnualSummary;
import com.hack23.cia.model.internal.application.data.party.impl.ViewRiksdagenPartyBallotSupportAnnualSummaryEmbeddedId;
import com.hack23.cia.model.internal.application.data.party.impl.ViewRiksdagenPartyBallotSupportAnnualSummaryEmbeddedId_;
import com.hack23.cia.model.internal.application.data.party.impl.ViewRiksdagenPartyBallotSupportAnnualSummary_;
import com.hack23.cia.service.api.DataContainer;
import com.hack23.cia.web.impl.ui.application.views.common.chartfactory.api.PartySupportsChartDataManager;
import com.vaadin.ui.AbstractOrderedLayout;

/**
 * The Class PartySupportsChartDataManagerImpl.
 */
@Service
public final class PartySupportsChartDataManagerImpl extends AbstractChartDataManagerImpl
		implements PartySupportsChartDataManager {

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

	@Override
	public void createPartyChart(final AbstractOrderedLayout content, final String partyId) {

		final DataContainer<ViewRiksdagenPartyBallotSupportAnnualSummary, ViewRiksdagenPartyBallotSupportAnnualSummaryEmbeddedId> dataContainer = getApplicationManager()
				.getDataContainer(ViewRiksdagenPartyBallotSupportAnnualSummary.class);

		final List<ViewRiksdagenPartyBallotSupportAnnualSummary> list = dataContainer.findListByEmbeddedProperty(ViewRiksdagenPartyBallotSupportAnnualSummary.class,
				ViewRiksdagenPartyBallotSupportAnnualSummary_.embeddedId,
				ViewRiksdagenPartyBallotSupportAnnualSummaryEmbeddedId.class,
				ViewRiksdagenPartyBallotSupportAnnualSummaryEmbeddedId_.party, partyId);

		final Map<String, List<ViewRiksdagenPartyBallotSupportAnnualSummary>> map = list.parallelStream().filter(Objects::nonNull)
		.collect(Collectors.groupingBy(t -> t.getEmbeddedId().getOtherParty()));

		final Series series = new Series();
		final DataSeries dataSeries = new DataSeries();

		addData(map, series, dataSeries);

		addChart(content,"Party support ballot", new DCharts().setDataSeries(dataSeries).setOptions(getChartOptions().createOptionsPartyLineChart(series)).show(), true);
	}

	/**
	 * Adds the data.
	 *
	 * @param map        the map
	 * @param series     the series
	 * @param dataSeries the data series
	 */
	private static void addData(final Map<String, List<ViewRiksdagenPartyBallotSupportAnnualSummary>> map, final Series series,
			final DataSeries dataSeries) {
		final Set<Entry<String, List<ViewRiksdagenPartyBallotSupportAnnualSummary>>> entryMap = map.entrySet();

		for (final Entry<String, List<ViewRiksdagenPartyBallotSupportAnnualSummary>> entry : entryMap) {
			series.addSeries(new XYseries().setLabel(entry.getKey()));

			dataSeries.newSeries();
			for (final ViewRiksdagenPartyBallotSupportAnnualSummary data : entry.getValue()) {
					dataSeries.add(data.getEmbeddedId().getDate(),
							100 - data.getDisagreePercentage());
			}

		}
	}

}


/*
 * 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.rules;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.service.api.action.kpi.ComplianceCheck;
import com.hack23.cia.service.api.action.kpi.ResourceType;
import com.hack23.cia.service.api.action.kpi.RuleViolation;
import com.hack23.cia.service.api.action.kpi.Status;

/**
 * The Class AbstractComplianceCheckImpl.
 */
public abstract class AbstractComplianceCheckImpl implements ComplianceCheck {

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

	/** The resource type. */
	private final ResourceType resourceType;

	/** The rule violation map. */
	private final Map<String,RuleViolation> ruleViolationMap = new HashMap<>();

	/**
	 * Instantiates a new abstract compliance check impl.
	 *
	 * @param resourceType
	 *            the resource type
	 */
	public AbstractComplianceCheckImpl(final ResourceType resourceType) {
		super();
		this.resourceType = resourceType;
	}

	/**
	 * Gets the resource type.
	 *
	 * @return the resource type
	 */
	@Override
	public ResourceType getResourceType() {
		return resourceType;
	}

	/**
	 * Gets the rule violations.
	 *
	 * @return the rule violations
	 */
	@Override
	public final List<RuleViolation> getRuleViolations() {
		return new ArrayList<>(ruleViolationMap.values());
	}

	/**
	 * Gets the number rule violations.
	 *
	 * @return the number rule violations
	 */
	@Override
	public int getNumberRuleViolations() {
		return ruleViolationMap.size();
	}

	/**
	 * Gets the rule summary.
	 *
	 * @return the rule summary
	 */
	@Override
	public final String getRuleSummary() {
		final Collection<RuleViolation> values = ruleViolationMap.values();
		final StringBuilder builder = new StringBuilder();
		for (final RuleViolation ruleViolation : values) {
			builder.append('[').append(ruleViolation.getRuleName()).append('/').append(ruleViolation.getStatus()) .append(']');
		}
		return builder.toString();
	}

	/**
	 * Adds the violation.
	 *
	 * @param status
	 *            the status
	 * @param ruleName
	 *            the rule name
	 * @param ruleGroup
	 *            the rule group
	 * @param ruleDescription
	 *            the rule description
	 * @param positive
	 *            the positive
	 */
	public final void addViolation(final Status status,final String ruleName,final String ruleGroup,final String ruleDescription,final String positive) {
		final RuleViolation currentRuleViolation = ruleViolationMap.get(ruleName);
		if (currentRuleViolation == null || status.ordinal() > currentRuleViolation.getStatus().ordinal()) {
			ruleViolationMap.put(ruleName, new RuleViolation(getId(),getName(),resourceType,ruleName,ruleDescription,ruleGroup,status,positive));
		}
	}

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

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

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

}


/*
 * 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:13 PM CET
//

package com.hack23.cia.model.external.riksdagen.votering.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 _Votering_QNAME. */
    private static final QName _Votering_QNAME = new QName("http://votering.riksdagen.external.model.cia.hack23.com/impl", "votering");

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

    /**
	 * Creates a new Object object.
	 *
	 * @return the ballot container
	 */
    public BallotContainer createBallotContainer() {
        return new BallotContainer();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the ballot document element
	 */
    public BallotDocumentElement createBallotDocumentElement() {
        return new BallotDocumentElement();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the ballot document data
	 */
    public BallotDocumentData createBallotDocumentData() {
        return new BallotDocumentData();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the vote data dto
	 */
    public VoteDataDto createVoteDataDto() {
        return new VoteDataDto();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the vote data
	 */
    public VoteData createVoteData() {
        return new VoteData();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the vote data embedded id
	 */
    public VoteDataEmbeddedId createVoteDataEmbeddedId() {
        return new VoteDataEmbeddedId();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @param value the value
	 * @return the JAXB element< ballot container>
	 */
    @XmlElementDecl(namespace = "http://votering.riksdagen.external.model.cia.hack23.com/impl", name = "votering")
    public JAXBElement<BallotContainer> createVotering(final BallotContainer value) {
        return new JAXBElement<>(_Votering_QNAME, BallotContainer.class, null, value);
    }

}