<commit_before>/*
 * AMW - Automated Middleware allows you to manage the configurations of
 * your Java EE applications on an unlimited number of different environments
 * with various versions, including the automated deployment of those apps.
 * Copyright (C) 2013-2016 by Puzzle ITC
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package ch.puzzle.itc.mobiliar.business.deploy.control;

import ch.puzzle.itc.mobiliar.business.generator.control.extracted.ResourceDependencyResolverService;
import ch.puzzle.itc.mobiliar.business.releasing.control.ReleaseMgmtService;
import ch.puzzle.itc.mobiliar.business.usersettings.control.UserSettingsService;
import ch.puzzle.itc.mobiliar.business.resourcerelation.entity.ConsumedResourceRelationEntity;
import ch.puzzle.itc.mobiliar.business.deploy.entity.DeploymentEntity;
import ch.puzzle.itc.mobiliar.business.releasing.entity.ReleaseEntity;
import ch.puzzle.itc.mobiliar.business.resourcegroup.entity.ResourceEntity;
import ch.puzzle.itc.mobiliar.business.utils.notification.NotificationService;
import ch.puzzle.itc.mobiliar.common.util.ConfigurationService;
import ch.puzzle.itc.mobiliar.common.util.ConfigurationService.ConfigKey;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

@Stateless
public class DeploymentNotificationService {

	@Inject
	private NotificationService notificationService;

	@Inject
	private UserSettingsService userSettingsService;

	@Inject
	private ResourceDependencyResolverService resourceDependencyResolverService;

	@Inject
	private ReleaseMgmtService releaseMgmtService;

	@Inject
	private Logger log;

	/**
	 * Creates a notification email for deployment executions and sends them to
	 * the given receipients
	 *
	 * @param deployments
	 *            - the executed deployments
	 * @return the message to be stored with the deployment.
	 * @throws AddressException
	 * @throws MessagingException
	 */
	public String createAndSendMailForDeplyoments(
			final List<DeploymentEntity> deployments) {
		String message = null;

		// do nothing if no deployment is available
		if (deployments != null && !deployments.isEmpty()) {
			String subjectMessage = "AMW-Deploy for tracking id: "
					+ deployments.get(0).getTrackingId();

			try {
				Address[] emailReceipients = getAllReceipients(deployments);

				if (notificationService.createAndSendMail(subjectMessage,
						getMessageContentForDeployments(deployments),
						emailReceipients)) {
					message = getSuccessfulSendMailToReceipientMessage(emailReceipients);
				}
			} catch (MessagingException e) {
				message = getFailureSendMailMessage(e.getMessage());
				log.log(Level.WARNING, "Deployment notification ("
						+ subjectMessage + ") could not be sent", e);
			}
		}

		return message;
	}

	/**
	 * Creation of the e-mail content
	 * 
	 * @param deployments
	 *            - the deployments for which the email shall be generated.
	 * @return the e-mail content to be sent
	 */
	private String getMessageContentForDeployments(
			final List<DeploymentEntity> deployments) {
		final StringBuffer message = new StringBuffer();
		for (final DeploymentEntity deployment : deployments) {

			message.append("AMW-Deployment: ").append(deployment.getId()).append("(").append(deployment.getResourceGroup().getName())
			.append(" on ").append(deployment.getContext().getName()).append(")");
			message.append("\n");
			message.append("Result: ").append(deployment.getDeploymentState().toString());
			message.append("\n");
			message.append(deployment.getStateMessage());
			message.append("\n");
			message.append(getApplicationWithVersionsString(deployment));
			message.append("\n");
		}
		return message.toString();
	}

	private String getApplicationWithVersionsString(DeploymentEntity deploymentEntity){
		StringBuffer result = new StringBuffer();
		if(deploymentEntity != null){
			List<DeploymentEntity.ApplicationWithVersion> applicationsWithVersions = deploymentEntity.getApplicationsWithVersion();<commit_msg>changed mail formatting, see #31<commit_after>/*
 * AMW - Automated Middleware allows you to manage the configurations of
 * your Java EE applications on an unlimited number of different environments
 * with various versions, including the automated deployment of those apps.
 * Copyright (C) 2013-2016 by Puzzle ITC
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package ch.puzzle.itc.mobiliar.business.deploy.control;

import ch.puzzle.itc.mobiliar.business.generator.control.extracted.ResourceDependencyResolverService;
import ch.puzzle.itc.mobiliar.business.releasing.control.ReleaseMgmtService;
import ch.puzzle.itc.mobiliar.business.usersettings.control.UserSettingsService;
import ch.puzzle.itc.mobiliar.business.resourcerelation.entity.ConsumedResourceRelationEntity;
import ch.puzzle.itc.mobiliar.business.deploy.entity.DeploymentEntity;
import ch.puzzle.itc.mobiliar.business.releasing.entity.ReleaseEntity;
import ch.puzzle.itc.mobiliar.business.resourcegroup.entity.ResourceEntity;
import ch.puzzle.itc.mobiliar.business.utils.notification.NotificationService;
import ch.puzzle.itc.mobiliar.common.util.ConfigurationService;
import ch.puzzle.itc.mobiliar.common.util.ConfigurationService.ConfigKey;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

@Stateless
public class DeploymentNotificationService {

	@Inject
	private NotificationService notificationService;

	@Inject
	private UserSettingsService userSettingsService;

	@Inject
	private ResourceDependencyResolverService resourceDependencyResolverService;

	@Inject
	private ReleaseMgmtService releaseMgmtService;

	@Inject
	private Logger log;

	/**
	 * Creates a notification email for deployment executions and sends them to
	 * the given receipients
	 *
	 * @param deployments
	 *            - the executed deployments
	 * @return the message to be stored with the deployment.
	 * @throws AddressException
	 * @throws MessagingException
	 */
	public String createAndSendMailForDeplyoments(
			final List<DeploymentEntity> deployments) {
		String message = null;

		// do nothing if no deployment is available
		if (deployments != null && !deployments.isEmpty()) {
			String subjectMessage = "AMW-Deploy for tracking id: "
					+ deployments.get(0).getTrackingId();

			try {
				Address[] emailReceipients = getAllReceipients(deployments);

				if (notificationService.createAndSendMail(subjectMessage,
						getMessageContentForDeployments(deployments),
						emailReceipients)) {
					message = getSuccessfulSendMailToReceipientMessage(emailReceipients);
				}
			} catch (MessagingException e) {
				message = getFailureSendMailMessage(e.getMessage());
				log.log(Level.WARNING, "Deployment notification ("
						+ subjectMessage + ") could not be sent", e);
			}
		}

		return message;
	}

	/**
	 * Creation of the e-mail content
	 * 
	 * @param deployments
	 *            - the deployments for which the email shall be generated.
	 * @return the e-mail content to be sent
	 */
	private String getMessageContentForDeployments(
			final List<DeploymentEntity> deployments) {
		final StringBuffer message = new StringBuffer();
		for (final DeploymentEntity deployment : deployments) {
			message.append("Application server: ").append(deployment.getResourceGroup().getName());
			message.append(" (").append(deployment.getRelease()).append(")\n");
			message.append("Applications: \n");
			message.append(getApplicationWithVersionsString(deployment));
			message.append("Result: ").append(deployment.getDeploymentState().toString()).append("\n");
			message.append("Environment: ").append(deployment.getContext().getName()).append("\n");
			message.append("Id: ").append(deployment.getId()).append("\n");
			message.append("\n");
			message.append("State message:\n");
			message.append(deployment.getStateMessage()).append("\n");
			message.append("\n\n");
		}
		return message.toString();
	}

	private String getApplicationWithVersionsString(DeploymentEntity deploymentEntity){
		StringBuffer result = new StringBuffer();
		if(deploymentEntity != null){
			List<DeploymentEntity.ApplicationWithVersion> applicationsWithVersions = deploymentEntity.getApplicationsWithVersion();
{'fraction_non_alphanumeric': 0.09565391950215799, 'fraction_numerical': 0.0022081702298504466, 'mean_word_length': 4.930952380952381, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1379686', 'n_tokens_mistral': 2960, 'n_tokens_neox': 2666, 'n_words': 729}