/*
 * Copyright 2010-2019 James Pether Sörling
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *	$Id$
 *  $HeadURL$
*/
package com.hack23.cia.service.component.agent.impl.riksdagen.workgenerator.data;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

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

import com.hack23.cia.model.external.riksdagen.dokumentlista.impl.DocumentElement;
import com.hack23.cia.model.external.riksdagen.dokumentlista.impl.DocumentType;
import com.hack23.cia.model.external.riksdagen.dokumentstatus.impl.DocumentData;
import com.hack23.cia.model.external.riksdagen.dokumentstatus.impl.DocumentData_;
import com.hack23.cia.model.external.riksdagen.dokumentstatus.impl.DocumentStatusContainer;
import com.hack23.cia.model.external.riksdagen.dokumentstatus.impl.DocumentStatusContainer_;
import com.hack23.cia.model.external.riksdagen.votering.impl.VoteDataEmbeddedId;
import com.hack23.cia.model.internal.application.system.impl.ApplicationConfiguration;
import com.hack23.cia.model.internal.application.system.impl.ConfigurationGroup;
import com.hack23.cia.service.data.api.ApplicationConfigurationService;
import com.hack23.cia.service.data.api.CommitteeProposalComponentDataDAO;
import com.hack23.cia.service.data.api.DocumentContentDataDAO;
import com.hack23.cia.service.data.api.DocumentElementDAO;
import com.hack23.cia.service.data.api.DocumentStatusContainerDAO;
import com.hack23.cia.service.data.api.VoteDataDAO;

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

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

	/** The Constant RIKSDAGEN_JAVA_SIMPLE_DATE_FORMAT. */
	private static final String RIKSDAGEN_JAVA_SIMPLE_DATE_FORMAT = "yyyy-MM-dd";

	/** The Constant RIKSDAGEN_JAVA_SIMPLE_DATE_TIME_FORMAT. */
	private static final String RIKSDAGEN_JAVA_SIMPLE_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

	/** The application configuration service. */
	@Autowired
	private ApplicationConfigurationService applicationConfigurationService;

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

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

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

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

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

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

	/**
	 * Creates the map from list.
	 *
	 * @param all
	 *            the all
	 * @return the map
	 */
	private static Map<String, String> createMapFromList(final List<String> all) {
		final Map<String, String> map = new ConcurrentHashMap<>();

		for (final String documentElement : all) {
			map.put(documentElement, documentElement);
		}
		return map;
	}

	/**
	 * Creates the map from list vote.
	 *
	 * @param list
	 *            the list
	 * @return the map
	 */
	private static Map<String, String> createMapFromListVote(final List<VoteDataEmbeddedId> list) {
		final Map<String, String> map = new ConcurrentHashMap<>();

		for (final VoteDataEmbeddedId documentElement : list) {
			map.put(documentElement.getBallotId(), documentElement.getBallotId());
		}
		return map;
	}

	@Override
	public List<String> getAvaibleCommitteeProposal() {
		return documentStatusContainerDAO.getAvaibleCommitteeProposal();
	}

	@Override
	public List<DocumentStatusContainer> getNoneCompletedDocumentStatusCommitteeReports() {
		return documentStatusContainerDAO.findListByEmbeddedProperty(DocumentStatusContainer_.document,DocumentData.class,DocumentData_.documentType,"bet");
	}

	@Override
	public List<String> getAvaibleDocumentContent() {
		return documentElementDAO.getAvaibleDocumentContent();
	}

	@Override
	public Map<String, String> getCommitteeProposalComponentDataMap() {
		return createMapFromList(committeeProposalComponentDataDAO.getIdList());
	}

	@Override
	public Map<String, String> getDocumentContentMap() {
		return createMapFromList(documentContentDataDAO.getIdList());
	}

	@Override
	public Map<String, String> getDocumentElementMap(final Date after, final List<DocumentType> downloadType,
			final boolean onlyWithDocStatus) {
		final List<DocumentElement> all = documentElementDAO.getAll();

		final List<String> documentTypeValues = new ArrayList<>();

		for (final DocumentType docType : downloadType) {
			documentTypeValues.add(docType.value());
		}

		final Map<String, String> map = new ConcurrentHashMap<>();

		for (final DocumentElement documentElement : all) {
			if (checkIncludeDate(after, documentTypeValues, documentElement) && checkIncludeStatus(onlyWithDocStatus, documentElement)) {
				map.put(documentElement.getId(), documentElement.getDocumentType());
			}
		}
		return map;
	}

	/**
	 * Check include status.
	 *
	 * @param onlyWithDocStatus
	 *            the only with doc status
	 * @param documentElement
	 *            the document element
	 * @return true, if successful
	 */
	private static boolean checkIncludeStatus(final boolean onlyWithDocStatus, final DocumentElement documentElement) {
		return !onlyWithDocStatus || documentElement.getDocumentStatusUrlXml() != null;
	}

	/**
	 * Check include date.
	 *
	 * @param after
	 *            the after
	 * @param documentTypeValues
	 *            the document type values
	 * @param documentElement
	 *            the document element
	 * @return true, if successful
	 */
	private static boolean checkIncludeDate(final Date after, final List<String> documentTypeValues,
			final DocumentElement documentElement) {
		try {
			if (documentElement.getMadePublicDate() != null && documentElement.getMadePublicDate().length() > 0) {
				return getDate(documentElement.getMadePublicDate()).after(after)
						&& documentTypeValues.contains(documentElement.getDocumentType());
			} else {
				return getDate(documentElement.getCreatedDate()).after(after)
						&& documentTypeValues.contains(documentElement.getDocumentType());
			}
		} catch (final ParseException e) {
			LOGGER.warn("Problem getting date from{} : exception:{}", documentElement, e);
			return false;
		}
	}

	/**
	 * Gets the date.
	 *
	 * @param date
	 *            the date
	 * @return the date
	 * @throws ParseException
	 *             the parse exception
	 */
	private static Date getDate(final String date) throws ParseException {
		if (RIKSDAGEN_JAVA_SIMPLE_DATE_FORMAT.length() > date.length()) {
			return new SimpleDateFormat(RIKSDAGEN_JAVA_SIMPLE_DATE_TIME_FORMAT, Locale.ENGLISH).parse(date);
		} else {
			return new SimpleDateFormat(RIKSDAGEN_JAVA_SIMPLE_DATE_FORMAT, Locale.ENGLISH).parse(date);
		}
	}

	@Override
	public Map<String, String> getDocumentStatusContainerMap() {
		return createMapFromList(documentStatusContainerDAO.getIdList());
	}

	@Override
	public Map<String, String> getLoadedBallotIdMap() {
		return createMapFromListVote(voteDataDAO.getBallotIdList());
	}

	@Override
	public int getStartYearForDocumentElement() {
		final ApplicationConfiguration registeredUsersGetAdminConfig = applicationConfigurationService
				.checkValueOrLoadDefault("Load Riksdagen documents from year", "Load Riksdagen documents from year",
						ConfigurationGroup.AGENT, RiksdagenImportService.class.getSimpleName(),
						"Riksdagen Import Service", "Responsible import Riksdagen data",
						"agent.riksdagen.documents.loadfromyear", "2000");

		return documentElementDAO
				.getMissingDocumentStartFromYear(Integer.parseInt(registeredUsersGetAdminConfig.getPropertyValue()));
	}

}


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

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

import java.util.ArrayList;
import java.util.List;

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

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

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

/**
 * The Class SwedenElectionRegion.
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SwedenElectionRegion", propOrder = {
    "countyId",
    "municipalId",
    "regionName",
    "parties"
})
@Entity(name = "SwedenElectionRegion")
@Table(name = "SWEDEN_ELECTION_REGION")
@Inheritance(strategy = InheritanceType.JOINED)
public class SwedenElectionRegion
    implements ModelObject
{

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

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

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

    /** The region name. */
    @XmlElement(name = "namn", required = true)
    protected String regionName;

    /** The parties. */
    @XmlElement(name = "parti", required = true)
    protected List<SwedenPoliticalParty> parties = new ArrayList<>();

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

    /**
	 * Gets the county id.
	 *
	 * @return the county id
	 */
    @Basic
    @Column(name = "COUNTY_ID")
    public String getCountyId() {
        return countyId;
    }

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

    /**
	 * Gets the municipal id.
	 *
	 * @return the municipal id
	 */
    @Basic
    @Column(name = "MUNICIPAL_ID")
    public String getMunicipalId() {
        return municipalId;
    }

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

    /**
	 * Gets the region name.
	 *
	 * @return the region name
	 */
    @Basic
    @Column(name = "REGION_NAME")
    public String getRegionName() {
        return regionName;
    }

    /**
	 * Sets the region name.
	 *
	 * @param value the new region name
	 */
    public void setRegionName(final String value) {
        this.regionName = value;
    }

    /**
	 * Gets the parties.
	 *
	 * @return the parties
	 */
    @OneToMany(targetEntity = SwedenPoliticalParty.class, cascade = {
        CascadeType.ALL
    })
    @JoinColumn(name = "PARTIES_SWEDEN_ELECTION_REGI_0")
    public List<SwedenPoliticalParty> getParties() {
        return this.parties;
    }

    /**
	 * Sets the parties.
	 *
	 * @param parties the new parties
	 */
    public void setParties(final List<SwedenPoliticalParty> parties) {
        this.parties = parties;
    }

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

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

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

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

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

}


/*
 * Copyright 2010-2019 James Pether Sörling
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *	$Id$
 *  $HeadURL$
*/
package com.hack23.cia.service.external.riksdagen.impl;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.xml.bind.JAXBElement;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.oxm.Unmarshaller;
import org.springframework.stereotype.Component;

import com.hack23.cia.model.external.riksdagen.votering.impl.BallotContainer;
import com.hack23.cia.model.external.riksdagen.votering.impl.VoteData;
import com.hack23.cia.model.external.riksdagen.votering.impl.VoteDataDto;
import com.hack23.cia.model.external.riksdagen.votering.impl.VoteDataEmbeddedId;
import com.hack23.cia.model.external.riksdagen.voteringlista.impl.BallotDocumentElement;
import com.hack23.cia.model.external.riksdagen.voteringlista.impl.VoteListContainerElement;
import com.hack23.cia.service.external.common.api.XmlAgent;
import com.hack23.cia.service.external.common.api.XmlAgentException;
import com.hack23.cia.service.external.riksdagen.api.DataFailureException;
import com.hack23.cia.service.external.riksdagen.api.RiksdagenBallotApi;

/**
 * The Class RiksdagenBallotApiImpl.
 */
@Component
final class RiksdagenBallotApiImpl implements RiksdagenBallotApi {

	/** The Constant BALLOT. */
	private static final String BALLOT = "https://data.riksdagen.se/votering/${ID_KEY}/xml";

	/** The Constant BALLOT_LIST. */
	private static final String BALLOT_LIST="https://data.riksdagen.se/voteringlista/?rm=&bet=&punkt=&iid=&parti=&valkrets=&rost=&sz=10000&utformat=xml&gruppering=votering_id";

	/** The Constant HTTP_VOTERING_RIKSDAGEN_EXTERNAL_MODEL_CIA_HACK23_COM_IMPL. */
	private static final String HTTP_VOTERING_RIKSDAGEN_EXTERNAL_MODEL_CIA_HACK23_COM_IMPL = "http://votering.riksdagen.external.model.cia.hack23.com/impl";

	/**
	 * The Constant HTTP_VOTERINGLISTA_RIKSDAGEN_EXTERNAL_MODEL_CIA_HACK23_COM_IMPL.
	 */
	private static final String HTTP_VOTERINGLISTA_RIKSDAGEN_EXTERNAL_MODEL_CIA_HACK23_COM_IMPL = "http://voteringlista.riksdagen.external.model.cia.hack23.com/impl";

	/** The Constant ID_KEY. */
	private static final String ID_KEY = "${ID_KEY}";

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

	/** The Constant PROBLEM_GETTING_BALLOT_ID_S_FROM_DATA_RIKSDAGEN_SE. */
	private static final String PROBLEM_GETTING_BALLOT_ID_S_FROM_DATA_RIKSDAGEN_SE = "Problem getting ballot id:{} from data.riksdagen.se";

	/** The Constant PROBLEM_GETTING_BALLOT_LIST_FROM_DATA_RIKSDAGEN_SE. */
	private static final String PROBLEM_GETTING_BALLOT_LIST_FROM_DATA_RIKSDAGEN_SE = "Problem getting ballot list from data.riksdagen.se";

	/** The riksdagen date util. */
	private final RiksdagenDateUtil riksdagenDateUtil = new RiksdagenDateUtil();

	/** The riksdagen ballot list marshaller. */
	@Autowired
	@Qualifier("riksdagenBallotListMarshaller")
	private Unmarshaller riksdagenBallotListMarshaller;

	/** The riksdagen ballot marshaller. */
	@Autowired
	@Qualifier("riksdagenBallotMarshaller")
	private Unmarshaller riksdagenBallotMarshaller;

	/** The xml agent. */
	private final XmlAgent xmlAgent;

	/**
	 * Instantiates a new riksdagen ballot api impl.
	 *
	 * @param xmlAgent
	 *            the xml agent
	 */
	@Autowired
	public RiksdagenBallotApiImpl(final XmlAgent xmlAgent) {
		super();
		this.xmlAgent = xmlAgent;
	}

	/* (non-Javadoc)
	 * @see com.hack23.cia.service.external.riksdagen.api.RiksdagenBallotApi#getBallot(java.lang.String)
	 */
	@Override
	public List<VoteData> getBallot(final String id) throws DataFailureException {
		final String url = BALLOT.replace(ID_KEY, id);

		try {
			final BallotContainer ballotContainer = ((JAXBElement<BallotContainer>) xmlAgent.unmarshallXml(
					riksdagenBallotMarshaller, url,
					HTTP_VOTERING_RIKSDAGEN_EXTERNAL_MODEL_CIA_HACK23_COM_IMPL,null,null))
					.getValue();

			final List<VoteData> result = new ArrayList<>();
			if (ballotContainer != null && ballotContainer.getBallotDocumentData() != null) {

				final List<VoteDataDto> voteDataList = ballotContainer.getBallotDocumentData().getVoteDataList();
				final Date ballotDate=riksdagenDateUtil.tryToFindValidVoteDate(ballotContainer, voteDataList);

				for (final VoteDataDto voteDataDto: voteDataList) {
					final VoteData voteData= new VoteData().withEmbeddedId(new VoteDataEmbeddedId().withBallotId(voteDataDto.getBallotId()).withIntressentId(voteDataDto.getIntressentId()).withIssue(voteDataDto.getIssue()).withConcern(voteDataDto.getConcern()));

					voteData.setBankNumber(voteDataDto.getBankNumber());
					voteData.setLabel(voteDataDto.getLabel());
					voteData.setLastName(voteDataDto.getLastName());
					voteData.setBornYear(voteDataDto.getBornYear());
					voteData.setFirstName(voteDataDto.getFirstName());
					voteData.setPlace(voteDataDto.getPlace());
					voteData.setGender(voteDataDto.getGender());
					voteData.setFullName(voteDataDto.getFullName());
					voteData.setParty(voteDataDto.getParty().toUpperCase(Locale.ENGLISH));
					voteData.setRm(voteDataDto.getRm());
					voteData.setVote(voteDataDto.getVote());
					voteData.setBallotType(voteDataDto.getBallotType());
					voteData.setElectoralRegionNumber(voteDataDto.getElectoralRegionNumber());
					voteData.setElectoralRegion(voteDataDto.getElectoralRegion());
					voteData.setVoteDate(ballotDate);

					result.add(voteData);
				}
			}

			return result;

		} catch (final XmlAgentException | ParseException e) {
			LOGGER.warn(PROBLEM_GETTING_BALLOT_ID_S_FROM_DATA_RIKSDAGEN_SE,id);
			throw new DataFailureException(e);
		}

	}

	/* (non-Javadoc)
	 * @see com.hack23.cia.service.external.riksdagen.api.RiksdagenBallotApi#getBallotList()
	 */
	@Override
	public List<BallotDocumentElement> getBallotList() throws DataFailureException {

		try {
			final String url = BALLOT_LIST;
			return ((JAXBElement<VoteListContainerElement>) xmlAgent.unmarshallXml(riksdagenBallotListMarshaller, url,
							HTTP_VOTERINGLISTA_RIKSDAGEN_EXTERNAL_MODEL_CIA_HACK23_COM_IMPL,null,null))
							.getValue().getVotering();
		} catch (final XmlAgentException e) {
			LOGGER.warn(PROBLEM_GETTING_BALLOT_LIST_FROM_DATA_RIKSDAGEN_SE);
			throw new DataFailureException(e);
		}
	}
}


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

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;

import com.hack23.cia.model.internal.application.system.impl.ApplicationEventGroup;
import com.hack23.cia.service.api.action.user.ChangePasswordRequest;
import com.hack23.cia.service.api.action.user.DisableGoogleAuthenticatorCredentialRequest;
import com.hack23.cia.service.api.action.user.SetGoogleAuthenticatorCredentialRequest;
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.menufactory.api.UserHomeMenuItemFactory;
import com.hack23.cia.web.impl.ui.application.views.common.rows.RowUtil;
import com.hack23.cia.web.impl.ui.application.views.common.sizing.ContentRatio;
import com.hack23.cia.web.impl.ui.application.views.common.viewnames.UserHomePageMode;
import com.hack23.cia.web.impl.ui.application.views.pageclicklistener.ChangePasswordClickListener;
import com.hack23.cia.web.impl.ui.application.views.pageclicklistener.DisableGoogleAuthenticatorCredentialClickListener;
import com.hack23.cia.web.impl.ui.application.views.pageclicklistener.SetGoogleAuthenticatorCredentialClickListener;
import com.jarektoro.responsivelayout.ResponsiveRow;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.Layout;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.Panel;
import com.vaadin.ui.VerticalLayout;

/**
 * The Class UserHomeSecuritySettingsPageModContentFactoryImpl.
 */
@Component
public final class UserHomeSecuritySettingsPageModContentFactoryImpl extends AbstractUserHomePageModContentFactoryImpl {

	/** The Constant ENABLE_GOOGLE_AUTHENTICATOR. */
	private static final String ENABLE_GOOGLE_AUTHENTICATOR = "Enable Google Authenticator";

	/** The Constant DISABLE_GOOGLE_AUTHENTICATOR. */
	private static final String DISABLE_GOOGLE_AUTHENTICATOR = "Disable Google Authenticator";

	/** The Constant AS_LIST. */
	private static final List<String> AS_LIST = Collections.singletonList("userpassword");

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

	/** The Constant SECURITY_SETTINGS. */
	private static final String SECURITY_SETTINGS = "Security Settings";

	/** The user home menu item factory. */
	@Autowired
	private UserHomeMenuItemFactory userHomeMenuItemFactory;

	/**
	 * Instantiates a new user home security settings page mod content factory impl.
	 */
	public UserHomeSecuritySettingsPageModContentFactoryImpl() {
		super();
	}

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

	@Secured({ "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);

		userHomeMenuItemFactory.createUserHomeMenuBar(menuBar, pageId);

		LabelFactory.createHeader2Label(panelContent, SECURITY_SETTINGS);

		final VerticalLayout overviewLayout = new VerticalLayout();
		overviewLayout.setSizeFull();
		panelContent.addComponent(overviewLayout);
		panelContent.setExpandRatio(overviewLayout, ContentRatio.LARGE);

		final ResponsiveRow grid = RowUtil.createGridLayout(overviewLayout);

		RowUtil.createRowComponent(grid, createChangePasswordButton(), "Change password");
		RowUtil.createRowComponent(grid, createEnableGoogleAuthButton(), "Enable MFA using google authenticator");
		RowUtil.createRowComponent(grid, createDisableGoogleAuthButton(), "Disable MFA using google authenticator");

		panel.setCaption(NAME + "::" + USERHOME + SECURITY_SETTINGS);

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

		return panelContent;

	}

	/**
	 * Creates the enable google auth button.
	 *
	 * @return the vertical layout
	 */
	private VerticalLayout createEnableGoogleAuthButton() {
		final VerticalLayout formLayout = new VerticalLayout();
		formLayout.setSizeFull();

		final Panel formPanel = new Panel();
		formPanel.setSizeFull();

		formLayout.addComponent(formPanel);

		final FormLayout formContent = new FormLayout();
		formPanel.setContent(formContent);

		final SetGoogleAuthenticatorCredentialRequest request = new SetGoogleAuthenticatorCredentialRequest();
		request.setSessionId(RequestContextHolder.currentRequestAttributes().getSessionId());
		request.setUserpassword("");
		final ClickListener listener = new SetGoogleAuthenticatorCredentialClickListener(request);
		getFormFactory().addRequestInputFormFields(formContent, request, SetGoogleAuthenticatorCredentialRequest.class,
				AS_LIST, ENABLE_GOOGLE_AUTHENTICATOR, listener);

		return formLayout;
	}

	/**
	 * Creates the disable google auth button.
	 *
	 * @return the vertical layout
	 */
	private VerticalLayout createDisableGoogleAuthButton() {

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

		final Panel formPanel = new Panel();
		formPanel.setSizeFull();

		formLayout.addComponent(formPanel);

		final FormLayout formContent = new FormLayout();
		formPanel.setContent(formContent);

		final DisableGoogleAuthenticatorCredentialRequest request = new DisableGoogleAuthenticatorCredentialRequest();
		request.setSessionId(RequestContextHolder.currentRequestAttributes().getSessionId());
		request.setUserpassword("");
		final ClickListener listener = new DisableGoogleAuthenticatorCredentialClickListener(request);
		getFormFactory().addRequestInputFormFields(formContent, request,
				DisableGoogleAuthenticatorCredentialRequest.class, AS_LIST, DISABLE_GOOGLE_AUTHENTICATOR, listener);

		return formLayout;
	}

	/**
	 * Creates the change password button.
	 *
	 * @return the vertical layout
	 */
	private VerticalLayout createChangePasswordButton() {

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

		final Panel formPanel = new Panel();
		formPanel.setSizeFull();

		formLayout.addComponent(formPanel);

		final FormLayout formContent = new FormLayout();
		formPanel.setContent(formContent);

		final ChangePasswordRequest request = new ChangePasswordRequest();
		request.setSessionId(RequestContextHolder.currentRequestAttributes().getSessionId());
		request.setCurrentPassword("");
		request.setNewPassword("");
		request.setRepeatNewPassword("");

		final ClickListener listener = new ChangePasswordClickListener(request);
		getFormFactory().addRequestInputFormFields(formContent, request,
				ChangePasswordRequest.class, Arrays.asList("currentPassword","newPassword","repeatNewPassword"), "Change password", listener);

		return formLayout;
	}

}


/*
 * Copyright 2010 James Pether Sörling
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *	$Id$
 *  $HeadURL$
*/
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.02.24 at 11:40:07 PM CET
//

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

import java.util.ArrayList;
import java.util.List;

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

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

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

/**
 * The Class DocumentReferenceContainer.
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "DocumentReferenceContainer", propOrder = {
    "documentReferenceList"
})
@Entity(name = "DocumentReferenceContainer")
@Table(name = "DOCUMENT_REFERENCE_CONTAINER")
@Inheritance(strategy = InheritanceType.JOINED)
public class DocumentReferenceContainer
    implements ModelObject
{

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

	/** The document reference list. */
    @XmlElement(name = "referens", required = true)
    protected List<DocumentReferenceData> documentReferenceList = new ArrayList<>();

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

    /**
	 * Gets the document reference list.
	 *
	 * @return the document reference list
	 */
    @OneToMany(targetEntity = DocumentReferenceData.class, cascade = {
        CascadeType.ALL
    })
    @JoinColumn(name = "DOCUMENT_REFERENCE_LIST_DOCU_0")
    public List<DocumentReferenceData> getDocumentReferenceList() {
        return this.documentReferenceList;
    }

    /**
	 * Sets the document reference list.
	 *
	 * @param documentReferenceList the new document reference list
	 */
    public void setDocumentReferenceList(final List<DocumentReferenceData> documentReferenceList) {
        this.documentReferenceList = documentReferenceList;
    }

    /**
	 * With document reference list.
	 *
	 * @param documentReferenceList the document reference list
	 * @return the document reference container
	 */
    public DocumentReferenceContainer withDocumentReferenceList(final List<DocumentReferenceData> documentReferenceList) {
        setDocumentReferenceList(documentReferenceList);
        return this;
    }

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

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

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

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

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

}


/*
 * Copyright 2010-2019 James Pether Sörling
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *	$Id$
 *  $HeadURL$
*/
package com.hack23.cia.service.external.riksdagen.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import com.hack23.cia.model.external.riksdagen.votering.impl.BallotContainer;
import com.hack23.cia.model.external.riksdagen.votering.impl.VoteDataDto;

/**
 * The Class RiksdagenDateUtil.
 */
final class RiksdagenDateUtil {

	/** The Constant YYYY_MM_DD. */
	public static final String YYYY_MM_DD = "yyyy-MM-dd";

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

	/**
	 * Instantiates a new riksdagen date util.
	 */
	public RiksdagenDateUtil() {
		super();
	}

	/**
	 * Best guess vote date.
	 *
	 * @param ballotContainer
	 *            the ballot container
	 * @return the date
	 * @throws ParseException
	 *             the parse exception
	 */
	private static Date bestGuessVoteDate(final BallotContainer ballotContainer) throws ParseException {
		final com.hack23.cia.model.external.riksdagen.votering.impl.BallotDocumentElement ballotDocumentElement = ballotContainer.getBallotDocumentElement();
		Date result;

		final String createdDate=ballotContainer.getBallotDocumentElement().getCreatedDate();

		if(createdDate!= null && createdDate.length()>= YYYY_MM_DD.length()) {
			result=new SimpleDateFormat(YYYY_MM_DD,Locale.ENGLISH).parse(createdDate);
		} else {
			final String systemDate = ballotDocumentElement.getSystemDate();

			if(systemDate!= null && systemDate.length()>= YYYY_MM_DD.length()) {
				result=new SimpleDateFormat(YYYY_MM_DD,Locale.ENGLISH).parse(systemDate);
			} else {
				result=new SimpleDateFormat(YYYY_MM_DD,Locale.ENGLISH).parse(ballotDocumentElement.getMadePublicDate());
			}
		}
		return result;
	}

	/**
	 * Check same date.
	 *
	 * @param voteList
	 *            the vote list
	 * @return the date
	 * @throws ParseException
	 *             the parse exception
	 */
	private static Date checkSameDate(final List<VoteDataDto> voteList) throws ParseException {
		final Set<String> set = new HashSet<>();
		Date result=null;

		for (final VoteDataDto voteData : voteList) {
			final String voteDate = voteData.getVoteDate();
			if (voteDate !=null && voteDate.length() >= YYYY_MM_DD.length()) {
				set.add(voteData.getVoteDate());
			}
		}

		if (set.size() ==CONTAINS_ONE) {
			final String dateString = set.iterator().next();
			result=new SimpleDateFormat(YYYY_MM_DD,Locale.ENGLISH).parse(dateString);
		}
		return result;
	}

	/**
	 * Try to find valid vote date.
	 *
	 * @param ballotContainer
	 *            the ballot container
	 * @param voteDataList
	 *            the vote data list
	 * @return the date
	 * @throws ParseException
	 *             the parse exception
	 */
	public Date tryToFindValidVoteDate(final BallotContainer ballotContainer, final List<VoteDataDto> voteDataList)
					throws ParseException {
		Date ballotDate;
		final Date sameDate = checkSameDate(voteDataList);

		if (sameDate != null) {
			ballotDate = sameDate;
		} else {
			ballotDate = bestGuessVoteDate(ballotContainer);
		}
		return ballotDate;
	}

}


/*
 * Copyright 2010-2019 James Pether Sörling
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *	$Id$
 *  $HeadURL$
*/
package com.hack23.cia.web.impl.ui.application.util;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.vaadin.server.WebBrowser;

import nl.basjes.parse.useragent.UserAgent;
import nl.basjes.parse.useragent.UserAgentAnalyzer;

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

	/** The Constant USER_AGENT_ANALYZER. */
	private static final UserAgentAnalyzer USER_AGENT_ANALYZER = UserAgentAnalyzer
            .newBuilder()
            .hideMatcherLoadStats()
            .withCache(10000)
            .build();

	/** The Constant X_FORWARDED_FOR. */
	public static final String X_FORWARDED_FOR = "X-Forwarded-For";

	/**
	 * Gets the ip information.
	 *
	 * @param webBrowser
	 *            the web browser
	 * @return the ip information
	 */
	public static String getIpInformation(final WebBrowser webBrowser) {
		String ipInformation=webBrowser.getAddress();

		final HttpServletRequest httpRequest=((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest();
		final String xForwardedForHeader = httpRequest.getHeader(X_FORWARDED_FOR);
		if (xForwardedForHeader != null) {
			final String[] split = xForwardedForHeader.split(",");
			if (split.length != 0) {
				ipInformation = split[0];
			}
		}
		return ipInformation;
	}

	/**
	 * Gets the operating system.
	 *
	 * @param webBrowser
	 *            the web browser
	 * @return the operating system
	 */
	public static String getOperatingSystem(final WebBrowser webBrowser) {
		synchronized (USER_AGENT_ANALYZER) {
			final UserAgent userAgent = USER_AGENT_ANALYZER.parse(webBrowser.getBrowserApplication());
			return userAgent.getValue(UserAgent.DEVICE_CLASS) + "." +userAgent.getValue(UserAgent.OPERATING_SYSTEM_NAME) +"." + userAgent.getValue(UserAgent.OPERATING_SYSTEM_VERSION);
		}
	}

}


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

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

import java.util.ArrayList;
import java.util.List;

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

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

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

/**
 * The Class CommitteeProposalContainer.
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CommitteeProposalContainer", propOrder = {
    "committeeProposalList"
})
@Entity(name = "CommitteeProposalContainer")
@Table(name = "COMMITTEE_PROPOSAL_CONTAINER")
@Inheritance(strategy = InheritanceType.JOINED)
public class CommitteeProposalContainer
    implements ModelObject
{

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

	/** The committee proposal list. */
    @XmlElement(name = "utskottsforslag", required = true)
    protected List<CommitteeProposalData> committeeProposalList = new ArrayList<>();

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

    /**
	 * Gets the committee proposal list.
	 *
	 * @return the committee proposal list
	 */
    @OneToMany(targetEntity = CommitteeProposalData.class, cascade = {
        CascadeType.ALL
    })
    @JoinColumn(name = "COMMITTEE_PROPOSAL_LIST_COMM_0")
    public List<CommitteeProposalData> getCommitteeProposalList() {
        return this.committeeProposalList;
    }

    /**
	 * Sets the committee proposal list.
	 *
	 * @param committeeProposalList the new committee proposal list
	 */
    public void setCommitteeProposalList(final List<CommitteeProposalData> committeeProposalList) {
        this.committeeProposalList = committeeProposalList;
    }

    /**
	 * With committee proposal list.
	 *
	 * @param committeeProposalList the committee proposal list
	 * @return the committee proposal container
	 */
    public CommitteeProposalContainer withCommitteeProposalList(final List<CommitteeProposalData> committeeProposalList) {
        setCommitteeProposalList(committeeProposalList);
        return this;
    }

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

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

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

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

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

}


/*
 * Copyright 2010 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 java.util.ArrayList;
import java.util.List;

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

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

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

/**
 * The Class SwedenParliamentElectoralRegionContainer.
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SwedenParliamentElectoralRegionContainer", propOrder = {
    "parliamentElectoralRegions"
})
@Entity(name = "SwedenParliamentElectoralRegionContainer")
@Table(name = "SWEDEN_PARLIAMENT_ELECTORAL__0")
@Inheritance(strategy = InheritanceType.JOINED)
public class SwedenParliamentElectoralRegionContainer
    implements ModelObject
{

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

	/** The parliament electoral regions. */
    @XmlElement(name = "riksdagsvalkrets", required = true)
    protected List<SwedenParliamentElectoralRegion> parliamentElectoralRegions = new ArrayList<>();

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

    /**
	 * Gets the parliament electoral regions.
	 *
	 * @return the parliament electoral regions
	 */
    @OneToMany(targetEntity = SwedenParliamentElectoralRegion.class, cascade = {
        CascadeType.ALL
    })
    @JoinColumn(name = "PARLIAMENT_ELECTORAL_REGIONS_0")
    public List<SwedenParliamentElectoralRegion> getParliamentElectoralRegions() {
        return this.parliamentElectoralRegions;
    }

    /**
	 * Sets the parliament electoral regions.
	 *
	 * @param parliamentElectoralRegions the new parliament electoral regions
	 */
    public void setParliamentElectoralRegions(final List<SwedenParliamentElectoralRegion> parliamentElectoralRegions) {
        this.parliamentElectoralRegions = parliamentElectoralRegions;
    }

    /**
	 * 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(getParliamentElectoralRegions().toArray(), ((SwedenParliamentElectoralRegionContainer) obj).getParliamentElectoralRegions().toArray()).isEquals();
	}

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

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Collections;
import java.util.List;

import com.hack23.cia.model.internal.application.data.committee.impl.ViewRiksdagenCommitteeBallotDecisionPoliticianSummary;
import com.hack23.cia.model.internal.application.data.committee.impl.ViewRiksdagenVoteDataBallotPoliticianSummaryAnnual;
import com.hack23.cia.model.internal.application.data.committee.impl.ViewRiksdagenVoteDataBallotPoliticianSummaryDaily;
import com.hack23.cia.model.internal.application.data.committee.impl.ViewRiksdagenVoteDataBallotPoliticianSummaryMonthly;
import com.hack23.cia.model.internal.application.data.politician.impl.ViewRiksdagenPolitician;
import com.hack23.cia.service.api.action.kpi.ResourceType;

/**
 * The Class PoliticianComplianceCheckImpl.
 */
public final class PoliticianComplianceCheckImpl extends AbstractComplianceCheckImpl {

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

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

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

	/** The politician. */
	private final ViewRiksdagenPolitician politician;

	/** The ballot decisions. */
	private final List<ViewRiksdagenCommitteeBallotDecisionPoliticianSummary> ballotDecisions;

	/** The daily summary. */
	private final ViewRiksdagenVoteDataBallotPoliticianSummaryDaily dailySummary;

	/** The monthly summary. */
	private final ViewRiksdagenVoteDataBallotPoliticianSummaryMonthly monthlySummary;

	/** The annual summary. */
	private final ViewRiksdagenVoteDataBallotPoliticianSummaryAnnual annualSummary;

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

	/**
	 * Instantiates a new politician compliance check impl.
	 *
	 * @param politician     the politician
	 * @param dailySummary   the daily summary
	 * @param monthlySummary the monthly summary
	 * @param annualSummary  the annual summary
	 * @param decisionList   the decision list
	 */
	public PoliticianComplianceCheckImpl(final ViewRiksdagenPolitician politician,final ViewRiksdagenVoteDataBallotPoliticianSummaryDaily dailySummary, final ViewRiksdagenVoteDataBallotPoliticianSummaryMonthly monthlySummary,final ViewRiksdagenVoteDataBallotPoliticianSummaryAnnual annualSummary, final List<ViewRiksdagenCommitteeBallotDecisionPoliticianSummary> decisionList) {
		super(ResourceType.POLITICIAN);
		this.politician = politician;
		this.dailySummary = dailySummary;
		this.monthlySummary = monthlySummary;
		this.annualSummary = annualSummary;
		this.ballotDecisions = Collections.unmodifiableList(decisionList);
		this.name = politician.getFirstName() + " " + politician.getLastName() + " (" +politician.getParty() +")";
	}

	/**
	 * Gets the politician.
	 *
	 * @return the politician
	 */
	public ViewRiksdagenPolitician getPolitician() {
		return politician;
	}

	@Override
	public String getName() {
		return name;
	}

	@Override
	public String getId() {
		return politician.getPersonId();
	}

	/**
	 * Supports.
	 *
	 * @param committeeReport the committee report
	 * @param rm              the rm
	 * @return true, if successful
	 */
	public boolean supports(final String committeeReport,final String rm) {
		for (final ViewRiksdagenCommitteeBallotDecisionPoliticianSummary summary : ballotDecisions) {
			if (summary.getRm().equalsIgnoreCase(rm) && summary.getCommitteeReport().equalsIgnoreCase(committeeReport)) {
				return YES.equalsIgnoreCase(summary.getVote());
			}
		}
		return false;
	}

	/**
	 * Against.
	 *
	 * @param committeeReport the committee report
	 * @param rm              the rm
	 * @return true, if successful
	 */
	public boolean against(final String committeeReport,final String rm) {
		for (final ViewRiksdagenCommitteeBallotDecisionPoliticianSummary summary : ballotDecisions) {
			if (summary.getRm().equalsIgnoreCase(rm) && summary.getCommitteeReport().equalsIgnoreCase(committeeReport)) {
				return NO.equalsIgnoreCase(summary.getVote());
			}
		}
		return false;
	}

	/**
	 * Gets the daily summary.
	 *
	 * @return the daily summary
	 */
	public ViewRiksdagenVoteDataBallotPoliticianSummaryDaily getDailySummary() {
		return dailySummary;
	}

	/**
	 * Gets the monthly summary.
	 *
	 * @return the monthly summary
	 */
	public ViewRiksdagenVoteDataBallotPoliticianSummaryMonthly getMonthlySummary() {
		return monthlySummary;
	}

	/**
	 * Gets the annual summary.
	 *
	 * @return the annual summary
	 */
	public ViewRiksdagenVoteDataBallotPoliticianSummaryAnnual getAnnualSummary() {
		return annualSummary;
	}

	/**
	 * Gets the year.
	 *
	 * @return the year
	 */
	public int getYear() {
		return LocalDate.now(ZoneId.of("UTC")).getYear();
	}

	/**
	 * Gets the age.
	 *
	 * @return the age
	 */
	public int getAge() {
		return getYear() - politician.getBornYear();
	}

}


/*
 * 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.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.stream.Collectors;

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

import com.hack23.cia.model.internal.application.data.document.impl.RiksdagenDocumentOrgSummaryEmbeddedId;
import com.hack23.cia.model.internal.application.data.document.impl.ViewRiksdagenOrgDocumentDailySummary;
import com.hack23.cia.service.api.DataContainer;
import com.hack23.cia.web.impl.ui.application.views.common.chartfactory.api.OrgDocumentChartDataManager;
import com.vaadin.ui.AbstractOrderedLayout;

/**
 * The Class OrgDocumentChartDataManagerImpl.
 */
@Service
public final class OrgDocumentChartDataManagerImpl extends AbstractChartDataManagerImpl
		implements OrgDocumentChartDataManager {

	private static final String DOCUMENT_HISTORY_BY_ORG = "Document History by Org";

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

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

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

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

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

	private static final String DD_MMM_YYYY = "dd-MMM-yyyy";

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

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

	/**
	 * Gets the view riksdagen org document daily summary map.
	 *
	 * @return the view riksdagen org document daily summary map
	 */
	private Map<String, List<ViewRiksdagenOrgDocumentDailySummary>> getViewRiksdagenOrgDocumentDailySummaryMap() {
		final DataContainer<ViewRiksdagenOrgDocumentDailySummary, RiksdagenDocumentOrgSummaryEmbeddedId> politicianBallotSummaryDailyDataContainer = getApplicationManager()
				.getDataContainer(ViewRiksdagenOrgDocumentDailySummary.class);

		return politicianBallotSummaryDailyDataContainer.getAll().parallelStream()
				.filter(t -> t != null && !t.getEmbeddedId().getPublicDate().startsWith(YEAR_PREFIX))
				.collect(Collectors.groupingBy(
						t -> StringEscapeUtils.unescapeHtml4(t.getEmbeddedId().getOrg()).toUpperCase(Locale.ENGLISH)
								.replace(UNDER_SCORE, EMPTY_STRING).replace(MINUS_SIGN, EMPTY_STRING).trim()));
	}

	@Override
	public void createDocumentHistoryChartByOrg(final AbstractOrderedLayout content, final String org) {
		final String searchOrg = org.toUpperCase(Locale.ENGLISH).replace(UNDER_SCORE, EMPTY_STRING)
				.replace(MINUS_SIGN, EMPTY_STRING).trim();

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

		final Map<String, List<ViewRiksdagenOrgDocumentDailySummary>> allMap = getViewRiksdagenOrgDocumentDailySummaryMap();

		final List<ViewRiksdagenOrgDocumentDailySummary> itemList = allMap.get(searchOrg);

		if (itemList != null) {
			addDocumentHistoryByOrgData(dataSeries, series, itemList);
		}

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

	/**
	 * Adds the document history by org data.
	 *
	 * @param dataSeries
	 *            the data series
	 * @param series
	 *            the series
	 * @param itemList
	 *            the item list
	 */
	private static void addDocumentHistoryByOrgData(final DataSeries dataSeries, final Series series,
			final List<ViewRiksdagenOrgDocumentDailySummary> itemList) {
		final Map<String, List<ViewRiksdagenOrgDocumentDailySummary>> map = itemList.parallelStream()
				.filter(Objects::nonNull)
				.collect(Collectors.groupingBy(t -> StringUtils.defaultIfBlank(t.getDocumentType(), NO_INFO)));
		final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DD_MMM_YYYY, Locale.ENGLISH);
		final SimpleDateFormat parseIncomingDateFormat = new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH);

		for (final Entry<String, List<ViewRiksdagenOrgDocumentDailySummary>> entry : map.entrySet()) {
			addNewDataSerie(dataSeries, series, simpleDateFormat, parseIncomingDateFormat, entry);
		}
	}

	/**
	 * Adds the new data serie.
	 *
	 * @param dataSeries              the data series
	 * @param series                  the series
	 * @param simpleDateFormat        the simple date format
	 * @param parseIncomingDateFormat the parse incoming date format
	 * @param entry                   the entry
	 */
	private static void addNewDataSerie(final DataSeries dataSeries, final Series series,
			final SimpleDateFormat simpleDateFormat, final SimpleDateFormat parseIncomingDateFormat,
			final Entry<String, List<ViewRiksdagenOrgDocumentDailySummary>> entry) {

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

		if (entry.getValue() != null) {
			for (final ViewRiksdagenOrgDocumentDailySummary item : entry.getValue()) {
				addDataItem(dataSeries, simpleDateFormat, parseIncomingDateFormat, item);
			}
		}
	}

	/**
	 * Adds the data item.
	 *
	 * @param dataSeries              the data series
	 * @param simpleDateFormat        the simple date format
	 * @param parseIncomingDateFormat the parse incoming date format
	 * @param item                    the item
	 */
	private static void addDataItem(final DataSeries dataSeries, final SimpleDateFormat simpleDateFormat,
			final SimpleDateFormat parseIncomingDateFormat, final ViewRiksdagenOrgDocumentDailySummary item) {
		if (item != null && item.getEmbeddedId().getPublicDate().length() > 0) {

			try {
				dataSeries.add(
						simpleDateFormat
								.format(parseIncomingDateFormat.parse(item.getEmbeddedId().getPublicDate())),
						item.getTotal());
			} catch (final ParseException e) {
				LOGGER.warn("Problem parsing date:{}", item.getEmbeddedId().getPublicDate());
			}
		}
	}

}


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

import java.util.EnumMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.hack23.cia.model.internal.application.system.impl.ApplicationEventGroup;
import com.hack23.cia.model.internal.application.system.impl.ApplicationOperationType;
import com.hack23.cia.model.internal.application.user.impl.UserAccount;
import com.hack23.cia.model.internal.application.user.impl.UserAccount_;
import com.hack23.cia.model.internal.application.user.impl.UserLockStatus;
import com.hack23.cia.service.api.action.admin.ManageUserAccountRequest;
import com.hack23.cia.service.api.action.admin.ManageUserAccountResponse;
import com.hack23.cia.service.api.action.application.CreateApplicationEventRequest;
import com.hack23.cia.service.api.action.common.ServiceResponse.ServiceResult;
import com.hack23.cia.service.data.api.RemoveDataManager;
import com.hack23.cia.service.impl.action.common.AbstractBusinessServiceImpl;
import com.hack23.cia.service.impl.action.common.BusinessService;

/**
 * The Class ManageUserAccountService.
 */
@Service
@Transactional(propagation = Propagation.REQUIRED)
public final class ManageUserAccountService
		extends AbstractBusinessServiceImpl<ManageUserAccountRequest, ManageUserAccountResponse>
		implements BusinessService<ManageUserAccountRequest, ManageUserAccountResponse> {

	/** The remove data manager. */
	@Autowired
	private RemoveDataManager removeDataManager;

	/** The user command map. */
	private final Map<ManageUserAccountRequest.AccountOperation,UserCommand> userCommandMap = new EnumMap<>(ManageUserAccountRequest.AccountOperation.class);

	/**
	 * Instantiates a new update application configuration service.
	 */
	public ManageUserAccountService() {
		super(ManageUserAccountRequest.class);
	}

	/**
	 * Inits the user command map.
	 */
	@PostConstruct
	public void initUserCommandMap() {
		userCommandMap.put(ManageUserAccountRequest.AccountOperation.DELETE, account -> {
			removeDataManager.removeUserAccountApplicationHistory(account.getUserId());
			getUserDAO().delete(account);
			return new ManageUserAccountResponse(ServiceResult.SUCCESS);
		});

		userCommandMap.put(ManageUserAccountRequest.AccountOperation.UNLOCK, account -> {
			account.setUserLockStatus(UserLockStatus.UNLOCKED);
			getUserDAO().persist(account);
			return new ManageUserAccountResponse(ServiceResult.SUCCESS);
		});

		userCommandMap.put(ManageUserAccountRequest.AccountOperation.LOCK, account -> {
			account.setUserLockStatus(UserLockStatus.LOCKED);
			getUserDAO().persist(account);
			return new ManageUserAccountResponse(ServiceResult.SUCCESS);
		});

	}

	@Override
	@Secured({ "ROLE_ADMIN" })
	public ManageUserAccountResponse processService(final ManageUserAccountRequest serviceRequest) {
		final ManageUserAccountResponse inputValidation = inputValidation(serviceRequest);
		if (inputValidation != null) {
			return inputValidation;
		}

		final CreateApplicationEventRequest eventRequest = createApplicationEventForService(serviceRequest);

		final ManageUserAccountResponse response = performOperation(serviceRequest, eventRequest);
		createApplicationEventService.processService(eventRequest);

		return response;

	}

	/**
	 * Perform operation.
	 *
	 * @param serviceRequest
	 *            the service request
	 * @param eventRequest
	 *            the event request
	 * @return the manage user account response
	 */
	private ManageUserAccountResponse performOperation(final ManageUserAccountRequest serviceRequest,
			final CreateApplicationEventRequest eventRequest) {
		ManageUserAccountResponse response;
		eventRequest.setElementId(serviceRequest.getUserAcountId());
		eventRequest.setApplicationMessage(serviceRequest.getAccountOperation().toString());

		final UserAccount accountToModify = getUserDAO().findFirstByProperty(UserAccount_.userId,
				serviceRequest.getUserAcountId());

		final UserCommand userCommand = userCommandMap.get(serviceRequest.getAccountOperation());
		if (accountToModify != null && userCommand != null) {
			response = userCommand.execute(accountToModify);
		} else {
			response = new ManageUserAccountResponse(ServiceResult.FAILURE);
		}

		eventRequest.setApplicationMessage(response.getResult().toString());
		return response;
	}

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

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

	/**
	 * The Interface UserCommand.
	 */
	interface UserCommand {

		/**
		 * Execute.
		 *
		 * @param account
		 *            the account
		 * @return the manage user account response
		 */
		ManageUserAccountResponse execute(UserAccount account);
	}

}


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

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

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

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

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

/**
 * The Class SwedenElectionType.
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SwedenElectionType", propOrder = {
    "electionType",
    "region",
    "electionCode"
})
@Entity(name = "SwedenElectionType")
@Table(name = "SWEDEN_ELECTION_TYPE")
@Inheritance(strategy = InheritanceType.JOINED)
public class SwedenElectionType
    implements ModelObject
{

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

	/** The election type. */
    @XmlElement(name = "valtyp", required = true)
    protected String electionType;

    /** The region. */
    @XmlElement(required = true)
    protected SwedenElectionRegion region;

    /** The election code. */
    @XmlElement(name = "valbeteckning", required = true)
    protected String electionCode;

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

    /**
	 * Gets the election type.
	 *
	 * @return the election type
	 */
    @Basic
    @Column(name = "ELECTION_TYPE")
    public String getElectionType() {
        return electionType;
    }

    /**
	 * Sets the election type.
	 *
	 * @param value the new election type
	 */
    public void setElectionType(final String value) {
        this.electionType = value;
    }

    /**
	 * Gets the region.
	 *
	 * @return the region
	 */
    @ManyToOne(targetEntity = SwedenElectionRegion.class, cascade = {
        CascadeType.ALL
    })
    @JoinColumn(name = "REGION_SWEDEN_ELECTION_TYPE__0")
    public SwedenElectionRegion getRegion() {
        return region;
    }

    /**
	 * Sets the region.
	 *
	 * @param value the new region
	 */
    public void setRegion(final SwedenElectionRegion value) {
        this.region = value;
    }

    /**
	 * Gets the election code.
	 *
	 * @return the election code
	 */
    @Basic
    @Column(name = "ELECTION_CODE")
    public String getElectionCode() {
        return electionCode;
    }

    /**
	 * Sets the election code.
	 *
	 * @param value the new election code
	 */
    public void setElectionCode(final String value) {
        this.electionCode = value;
    }

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

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

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

	@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 java.util.ArrayList;
import java.util.List;

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

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

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

/**
 * The Class BallotDocumentData.
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "BallotDocumentData", propOrder = {
    "voteDataList"
})
@Entity(name = "BallotDocumentData")
@Table(name = "BALLOT_DOCUMENT_DATA")
@Inheritance(strategy = InheritanceType.JOINED)
public class BallotDocumentData
    implements ModelObject
{

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

	/** The vote data list. */
    @XmlElement(name = "votering", required = true)
    protected List<VoteDataDto> voteDataList = new ArrayList<>();

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

    /**
	 * Gets the vote data list.
	 *
	 * @return the vote data list
	 */
    @OneToMany(targetEntity = VoteDataDto.class, cascade = {
        CascadeType.ALL
    })
    @JoinColumn(name = "VOTE_DATA_LIST_BALLOT_DOCUME_0")
    public List<VoteDataDto> getVoteDataList() {
        return this.voteDataList;
    }

    /**
	 * Sets the vote data list.
	 *
	 * @param voteDataList the new vote data list
	 */
    public void setVoteDataList(final List<VoteDataDto> voteDataList) {
        this.voteDataList = voteDataList;
    }

    /**
	 * With vote data list.
	 *
	 * @param voteDataList the vote data list
	 * @return the ballot document data
	 */
    public BallotDocumentData withVoteDataList(final List<VoteDataDto> voteDataList) {
        setVoteDataList(voteDataList);
        return this;
    }

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

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

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

	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(getVoteDataList().toArray(), ((BallotDocumentData) obj).getVoteDataList().toArray()).isEquals();
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#hashCode()
	 */
	@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:39:59 PM CET
//

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

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

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

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

/**
 * The Class PersonDetailElement.
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PersonDetailElement", propOrder = {
    "detailList"
})
@Entity(name = "PersonDetailElement")
@Table(name = "PERSON_DETAIL_ELEMENT")
@Inheritance(strategy = InheritanceType.JOINED)
public class PersonDetailElement
    implements ModelObject
{

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

	/** The detail list. */
    @XmlElement(name = "uppgift", required = true)
    protected DetailElement detailList;

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

    /**
	 * Gets the detail list.
	 *
	 * @return the detail list
	 */
    @ManyToOne(targetEntity = DetailElement.class, cascade = {
        CascadeType.ALL
    })
    @JoinColumn(name = "DETAIL_LIST_PERSON_DETAIL_EL_0")
    public DetailElement getDetailList() {
        return detailList;
    }

    /**
	 * Sets the detail list.
	 *
	 * @param value the new detail list
	 */
    public void setDetailList(final DetailElement value) {
        this.detailList = value;
    }

    /**
	 * With detail list.
	 *
	 * @param value the value
	 * @return the person detail element
	 */
    public PersonDetailElement withDetailList(final DetailElement value) {
        setDetailList(value);
        return this;
    }

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

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

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

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

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

}


/*
 * Copyright 2010 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 java.util.ArrayList;
import java.util.List;

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

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

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

/**
 * The Class PersonAssignmentData.
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PersonAssignmentData", propOrder = {
    "assignmentList"
})
@Entity(name = "PersonAssignmentData")
@Table(name = "PERSON_ASSIGNMENT_DATA")
@Inheritance(strategy = InheritanceType.JOINED)
public class PersonAssignmentData
    implements ModelObject
{

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

	/** The assignment list. */
    @XmlElement(name = "uppdrag", required = true)
    protected List<AssignmentData> assignmentList = new ArrayList<>();

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

    /**
	 * Gets the assignment list.
	 *
	 * @return the assignment list
	 */
    @OneToMany(targetEntity = AssignmentData.class, cascade = {
        CascadeType.ALL
    })
    @JoinColumn(name = "ASSIGNMENT_LIST_PERSON_ASSIG_0")
    public List<AssignmentData> getAssignmentList() {
        return this.assignmentList;
    }

    /**
	 * Sets the assignment list.
	 *
	 * @param assignmentList the new assignment list
	 */
    public void setAssignmentList(final List<AssignmentData> assignmentList) {
        this.assignmentList = assignmentList;
    }

    /**
	 * With assignment list.
	 *
	 * @param assignmentList the assignment list
	 * @return the person assignment data
	 */
    public PersonAssignmentData withAssignmentList(final List<AssignmentData> assignmentList) {
        setAssignmentList(assignmentList);
        return this;
    }

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

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

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

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

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

}


/*
 * Copyright 2010-2019 James Pether Sörling
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *	$Id$
 *  $HeadURL$
*/
package com.hack23.cia.web.impl.ui.application.views.user.party.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 PartyRankingOverviewPageModContentFactoryImpl.
 */
@Component
public final class PartyRankingOverviewPageModContentFactoryImpl extends AbstractPartyRankingPageModContentFactoryImpl {

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

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

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

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

		getPartyRankingMenuItemFactory().createPartyRankingMenuBar(menuBar);

		final String pageId = getPageId(parameters);

		panelContent.addComponent(createDescription());

		getPartyRankingMenuItemFactory().createOverviewPage(panelContent);

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

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

		return panelContent;

	}

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

						+ "\nTop votes NR/PERCENTAGE :ALL:YEAR:CURRENT::#Views:List,Timeline,BarChart,PieChart"
						+ "\nTop vote winner NR/PERCENTAGE :ALL:YEAR:CURRENT::#Views:List,Timeline,BarChart,PieChart"
						+ "\nTop vote party rebel NR/PERCENTAGE :ALL:YEAR:CURRENT::#Views:List,Timeline,BarChart,PieChart"
						+ "\nTop vote presence NR/PERCENTAGE :ALL:YEAR:CURRENT::#Views:List,Timeline,BarChart,PieChart"
						+ "\nSearch by name");
		totalpartytoplistLabel.setSizeFull();
		totalpartytoplistLabel.setStyleName("Level2Header");
		return totalpartytoplistLabel;
	}

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

}


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

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.WordUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.vaadin.gridutil.cell.GridCellFilter;

import com.hack23.cia.web.impl.ui.application.views.common.converters.ListPropertyConverter;
import com.hack23.cia.web.impl.ui.application.views.common.gridfactory.api.GridFactory;
import com.hack23.cia.web.impl.ui.application.views.common.sizing.ContentRatio;
import com.hack23.cia.web.impl.ui.application.views.pageclicklistener.PageItemRendererClickListener;
import com.vaadin.data.BeanPropertySet;
import com.vaadin.data.ValueProvider;
import com.vaadin.event.selection.SelectionListener;
import com.vaadin.ui.AbstractOrderedLayout;
import com.vaadin.ui.Grid;
import com.vaadin.ui.Grid.Column;
import com.vaadin.ui.Grid.SelectionMode;

/**
 * The Class GridFactoryImpl.
 */
@Service
public final class GridFactoryImpl implements GridFactory {

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

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

	/**
	 * Instantiates a new grid factory impl.
	 */
	public GridFactoryImpl() {
		super();
	}

	@Override
	public <T extends Serializable> void createBasicBeanItemGrid(final AbstractOrderedLayout panelContent,
			final Class<T> dataType, final List<T> datasource, final String caption, final String[] columnOrder,
			final String[] hideColumns, final PageItemRendererClickListener<?> listener, final String actionId,
			final ListPropertyConverter[] collectionPropertyConverters) {
		createBasicBeanItemNestedPropertiesGrid(panelContent, dataType, datasource, caption, null, columnOrder,
				hideColumns, listener, actionId, collectionPropertyConverters);

	}

	@Override
	public <T extends Serializable> void createBasicBeanItemNestedPropertiesGrid(
			final AbstractOrderedLayout panelContent, final Class<T> dataType, final List<T> datasource,
			final String caption, final String[] nestedProperties, final String[] columnOrder,
			final String[] hideColumns, final PageItemRendererClickListener<?> listener, final String actionId,
			final ListPropertyConverter[] collectionPropertyConverters) {

		final Grid<T> grid = Grid.withPropertySet(BeanPropertySet.get(dataType));
		grid.setCaption(caption);

		grid.setItems(datasource.stream().filter(Objects::nonNull).collect(Collectors.toList()));

		grid.setSelectionMode(SelectionMode.SINGLE);

		createNestedProperties(grid, nestedProperties);

		setColumnConverters(collectionPropertyConverters, grid);

		configureColumnOrdersAndHiddenFields(columnOrder, hideColumns, grid);

		configureListeners(listener, grid);

		grid.setSizeFull();

		grid.setStyleName("Level2Header");

		createGridCellFilter(columnOrder, grid, dataType);

		grid.setResponsive(true);

		panelContent.addComponent(grid);
		panelContent.setExpandRatio(grid, ContentRatio.GRID);
	}

	private static <T extends Serializable> void createNestedProperties(final Grid<T> grid,
			final String[] nestedProperties) {
		if (nestedProperties != null) {
			for (final String property : nestedProperties) {
				final Column<T, ?> addColumn = grid.addColumn(new BeanNestedPropertyValueProvider<T>(property));
				addColumn.setId(property);
			}
		}
	}

	/**
	 * Configure column orders and hidden fields.
	 *
	 * @param columnOrder
	 *            the column order
	 * @param hideColumns
	 *            the hide columns
	 * @param grid
	 *            the grid
	 */
	private static void configureColumnOrdersAndHiddenFields(final String[] columnOrder, final String[] hideColumns,
			final Grid grid) {
		if (columnOrder != null) {
			grid.setColumnOrder(columnOrder);
		}

		if (hideColumns != null) {
			for (final String o : hideColumns) {
				grid.removeColumn(o);
			}
		}
	}

	/**
	 * Configure listeners.
	 *
	 * @param listener
	 *            the listener
	 * @param grid
	 *            the grid
	 */
	private static void configureListeners(final SelectionListener listener, final Grid grid) {

		if (listener != null) {
			grid.addSelectionListener(listener);
		}
	}

	/**
	 * Creates the grid cell filter.
	 *
	 * @param columnOrder
	 *            the column order
	 * @param grid
	 *            the grid
	 * @param dataType
	 *            the data type
	 */
	private static void createGridCellFilter(final String[] columnOrder, final Grid grid, final Class dataType) {
		if (columnOrder != null) {
			final GridCellFilter filter = new GridCellFilter(grid, dataType);
			for (final String column : columnOrder) {
				if (grid.getColumn(column) != null) {
					filter.setTextFilter(column, true, true);
				}
			}
		}
	}

	/**
	 * Sets the column converters.
	 *
	 * @param collectionPropertyConverter
	 *            the collection property converter
	 * @param grid
	 *            the grid
	 */
	private static void setColumnConverters(final ListPropertyConverter[] collectionPropertyConverter,
			final Grid grid) {
		if (collectionPropertyConverter != null) {
			for (final ListPropertyConverter converter : collectionPropertyConverter) {
				grid.removeColumn(converter.getColumn());
				final Column column = grid.addColumn(converter);
				column.setCaption(WordUtils.capitalize(converter.getColumn()));
				column.setId(converter.getColumn());
			}
		}
	}

	/**
	 * The Class BeanNestedPropertyValueProvider.
	 *
	 * @param <T>
	 *            the generic type
	 */
	public static final class BeanNestedPropertyValueProvider<T> implements ValueProvider<T, String> {

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

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

		/**
		 * Instantiates a new bean nested property value provider.
		 *
		 * @param property
		 *            the property
		 */
		public BeanNestedPropertyValueProvider(final String property) {
			super();
			this.property = property;
		}

		@Override
		public String apply(final T source) {
			try {
				return BeanUtils.getProperty(source, property);
			} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
				LOGGER.warn("Problem getting property : {} from source : {} , exception: {}", property, source, e);
				return "";
			}
		}

	}

}


/*
 * Copyright 2010 James Pether Sörling
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *	$Id$
 *  $HeadURL$
*/
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.02.24 at 11:39:59 PM CET
//

package com.hack23.cia.model.external.riksdagen.personlista.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://personlista.riksdagen.external.model.cia.hack23.com/impl", "personlista");

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

    /**
	 * Creates a new Object object.
	 *
	 * @return the person container element
	 */
    public PersonContainerElement createPersonContainerElement() {
        return new PersonContainerElement();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the person element
	 */
    public PersonElement createPersonElement() {
        return new PersonElement();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the person assignment element
	 */
    public PersonAssignmentElement createPersonAssignmentElement() {
        return new PersonAssignmentElement();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the assignment element
	 */
    public AssignmentElement createAssignmentElement() {
        return new AssignmentElement();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the person detail element
	 */
    public PersonDetailElement createPersonDetailElement() {
        return new PersonDetailElement();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the detail element
	 */
    public DetailElement createDetailElement() {
        return new DetailElement();
    }

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

}