<commit_before>/*
 * This file is part of NavalPlan
 *
 * Copyright (C) 2009-2010 Fundación para o Fomento da Calidade Industrial e
 *                         Desenvolvemento Tecnolóxico de Galicia
 * Copyright (C) 2010-2011 Igalia, S.L.
 *
 * 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 org.navalplanner.web.subcontract;

import static org.navalplanner.web.I18nHelper._;

import java.io.StringWriter;
import java.util.Date;
import java.util.List;

import javax.ws.rs.WebApplicationException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.jaxrs.client.WebClient;
import org.navalplanner.business.common.daos.IConfigurationDAO;
import org.navalplanner.business.common.exceptions.InstanceNotFoundException;
import org.navalplanner.business.common.exceptions.ValidationException;
import org.navalplanner.business.externalcompanies.entities.ExternalCompany;
import org.navalplanner.business.orders.daos.IOrderDAO;
import org.navalplanner.business.orders.daos.IOrderElementDAO;
import org.navalplanner.business.orders.entities.OrderElement;
import org.navalplanner.business.planner.daos.ISubcontractedTaskDataDAO;
import org.navalplanner.business.planner.entities.SubcontractState;
import org.navalplanner.business.planner.entities.SubcontractedTaskData;
import org.navalplanner.business.planner.entities.Task;
import org.navalplanner.web.subcontract.exceptions.ConnectionProblemsException;
import org.navalplanner.web.subcontract.exceptions.UnrecoverableErrorServiceException;
import org.navalplanner.ws.cert.NaiveTrustProvider;
import org.navalplanner.ws.common.api.ConstraintViolationDTO;
import org.navalplanner.ws.common.api.InstanceConstraintViolationsDTO;
import org.navalplanner.ws.common.api.InstanceConstraintViolationsListDTO;
import org.navalplanner.ws.common.api.OrderElementDTO;
import org.navalplanner.ws.common.impl.ConfigurationOrderElementConverter;
import org.navalplanner.ws.common.impl.DateConverter;
import org.navalplanner.ws.common.impl.OrderElementConverter;
import org.navalplanner.ws.common.impl.Util;
import org.navalplanner.ws.subcontract.api.SubcontractedTaskDataDTO;
import org.navalplanner.ws.subcontract.impl.SubcontractedTaskDataConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;


/**
 * Model for operations related with subcontracted tasks.
 *
 * @author <NAME> <<EMAIL>>
 */
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class SubcontractedTasksModel implements ISubcontractedTasksModel {

    private static Log LOG = LogFactory.getLog(SubcontractedTasksModel.class);

    @Autowired
    private ISubcontractedTaskDataDAO subcontractedTaskDataDAO;

    @Autowired
    private IOrderElementDAO orderElementDAO;

    @Autowired
    private IOrderDAO orderDAO;

    @Autowired
    private IConfigurationDAO configurationDAO;

    @Override
    @Transactional(readOnly = true)
    public List<SubcontractedTaskData> getSubcontractedTasks() {
        List<SubcontractedTaskData> result = subcontractedTaskDataDAO
                .getAllForMasterScenario();
        for (SubcontractedTaskData subcontractedTaskData : result) {
            forceLoadExternalCompany(subcontractedTaskData);
        }
        return result;
    }

    private void forceLoadExternalCompany(
            SubcontractedTaskData subcontractedTaskData) {
        subcontractedTaskData.getExternalCompany().getName();
    }

    @Override
    @Transactional(readOnly = true)
    public String getOrderCode(SubcontractedTaskData subcontractedTaskData) {
        Task task = subcontractedTaskData.getTask();
        OrderElement orderElement = orderDAO.loadOrderAvoidingProxyFor(task
                .getOrderElement());
        return orderElement.getOrder().getCode();
    }

    @Override
    @Transactional
    public void sendToSubcontractor(SubcontractedTaskData subcontractedTaskData)
            throws ValidationException, ConnectionProblemsException,
            UnrecoverableErrorServiceException {
        subcontractedTaskDataDAO.save(subcontractedTaskData);

        subcontractedTaskData.setState(SubcontractState.FAILED_SENT);

        if (!subcontractedTaskData.isSendable()) {
            throw new RuntimeException("Subcontracted task already sent");
        }

        if (!subcontractedTaskData.getExternalCompany()
                .getInteractsWithApplications()) {
            throw new RuntimeException(
                    "External company has not interaction fields filled");
        }

        makeSubcontractRequestRequest(subcontractedTaskData);

        subcontractedTaskData.setSubcontractCommunicationDate(new Date());
        subcontractedTaskData.setState(SubcontractState.SUCCESS_SENT);
    }

    private void makeSubcontractRequestRequest(
            SubcontractedTaskData subcontractedTaskData)
            throws ConnectionProblemsException, UnrecoverableErrorServiceException {
        SubcontractedTaskDataDTO subcontractedTaskDataDTO = getSubcontractedTaskData(subcontractedTaskData);

        ExternalCompany externalCompany = subcontractedTaskData
                .getExternalCompany();

        NaiveTrustProvider.setAlwaysTrust(true);

        WebClient client = WebClient.create(externalCompany.getAppURI());

        client.path("ws/rest/subcontract");

        Util.addAuthorizationHeader(client, externalCompany
                .getOurCompanyLogin(), externalCompany
                .getOurCompanyPassword());

        try {
            InstanceConstraintViolationsListDTO instanceConstraintViolationsListDTO = client
                    .post(subcontractedTaskDataDTO,
                            InstanceConstraintViolationsListDTO.class);

            List<InstanceConstraintViolationsDTO> instanceConstraintViolationsList = instanceConstraintViolationsListDTO.instanceConstraintViolationsList;
            if ((instanceConstraintViolationsList != null)
                    && (!instanceConstraintViolationsList.isEmpty())) {
                String message = "";

                for (ConstraintViolationDTO constraintViolationDTO :  instanceConstraintViolationsList.get(0).constraintViolations) {
                    message += constraintViolationDTO.toString() + "\n";<commit_msg>[Bug #921] Showing a proper error message if there are problems creating HTTP connection.<commit_after>/*
 * This file is part of NavalPlan
 *
 * Copyright (C) 2009-2010 Fundación para o Fomento da Calidade Industrial e
 *                         Desenvolvemento Tecnolóxico de Galicia
 * Copyright (C) 2010-2011 Igalia, S.L.
 *
 * 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 org.navalplanner.web.subcontract;

import static org.navalplanner.web.I18nHelper._;

import java.io.StringWriter;
import java.util.Date;
import java.util.List;

import javax.ws.rs.WebApplicationException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.jaxrs.client.WebClient;
import org.navalplanner.business.common.daos.IConfigurationDAO;
import org.navalplanner.business.common.exceptions.InstanceNotFoundException;
import org.navalplanner.business.common.exceptions.ValidationException;
import org.navalplanner.business.externalcompanies.entities.ExternalCompany;
import org.navalplanner.business.orders.daos.IOrderDAO;
import org.navalplanner.business.orders.daos.IOrderElementDAO;
import org.navalplanner.business.orders.entities.OrderElement;
import org.navalplanner.business.planner.daos.ISubcontractedTaskDataDAO;
import org.navalplanner.business.planner.entities.SubcontractState;
import org.navalplanner.business.planner.entities.SubcontractedTaskData;
import org.navalplanner.business.planner.entities.Task;
import org.navalplanner.web.subcontract.exceptions.ConnectionProblemsException;
import org.navalplanner.web.subcontract.exceptions.UnrecoverableErrorServiceException;
import org.navalplanner.ws.cert.NaiveTrustProvider;
import org.navalplanner.ws.common.api.ConstraintViolationDTO;
import org.navalplanner.ws.common.api.InstanceConstraintViolationsDTO;
import org.navalplanner.ws.common.api.InstanceConstraintViolationsListDTO;
import org.navalplanner.ws.common.api.OrderElementDTO;
import org.navalplanner.ws.common.impl.ConfigurationOrderElementConverter;
import org.navalplanner.ws.common.impl.DateConverter;
import org.navalplanner.ws.common.impl.OrderElementConverter;
import org.navalplanner.ws.common.impl.Util;
import org.navalplanner.ws.subcontract.api.SubcontractedTaskDataDTO;
import org.navalplanner.ws.subcontract.impl.SubcontractedTaskDataConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;


/**
 * Model for operations related with subcontracted tasks.
 *
 * @author <NAME> <<EMAIL>>
 */
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class SubcontractedTasksModel implements ISubcontractedTasksModel {

    private static Log LOG = LogFactory.getLog(SubcontractedTasksModel.class);

    @Autowired
    private ISubcontractedTaskDataDAO subcontractedTaskDataDAO;

    @Autowired
    private IOrderElementDAO orderElementDAO;

    @Autowired
    private IOrderDAO orderDAO;

    @Autowired
    private IConfigurationDAO configurationDAO;

    @Override
    @Transactional(readOnly = true)
    public List<SubcontractedTaskData> getSubcontractedTasks() {
        List<SubcontractedTaskData> result = subcontractedTaskDataDAO
                .getAllForMasterScenario();
        for (SubcontractedTaskData subcontractedTaskData : result) {
            forceLoadExternalCompany(subcontractedTaskData);
        }
        return result;
    }

    private void forceLoadExternalCompany(
            SubcontractedTaskData subcontractedTaskData) {
        subcontractedTaskData.getExternalCompany().getName();
    }

    @Override
    @Transactional(readOnly = true)
    public String getOrderCode(SubcontractedTaskData subcontractedTaskData) {
        Task task = subcontractedTaskData.getTask();
        OrderElement orderElement = orderDAO.loadOrderAvoidingProxyFor(task
                .getOrderElement());
        return orderElement.getOrder().getCode();
    }

    @Override
    @Transactional
    public void sendToSubcontractor(SubcontractedTaskData subcontractedTaskData)
            throws ValidationException, ConnectionProblemsException,
            UnrecoverableErrorServiceException {
        subcontractedTaskDataDAO.save(subcontractedTaskData);

        subcontractedTaskData.setState(SubcontractState.FAILED_SENT);

        if (!subcontractedTaskData.isSendable()) {
            throw new RuntimeException("Subcontracted task already sent");
        }

        if (!subcontractedTaskData.getExternalCompany()
                .getInteractsWithApplications()) {
            throw new RuntimeException(
                    "External company has not interaction fields filled");
        }

        makeSubcontractRequestRequest(subcontractedTaskData);

        subcontractedTaskData.setSubcontractCommunicationDate(new Date());
        subcontractedTaskData.setState(SubcontractState.SUCCESS_SENT);
    }

    private void makeSubcontractRequestRequest(
            SubcontractedTaskData subcontractedTaskData)
            throws ConnectionProblemsException, UnrecoverableErrorServiceException {
        SubcontractedTaskDataDTO subcontractedTaskDataDTO = getSubcontractedTaskData(subcontractedTaskData);

        ExternalCompany externalCompany = subcontractedTaskData
                .getExternalCompany();

        NaiveTrustProvider.setAlwaysTrust(true);

        try {
            WebClient client = WebClient.create(externalCompany.getAppURI());

            client.path("ws/rest/subcontract");

            Util.addAuthorizationHeader(client, externalCompany
                    .getOurCompanyLogin(), externalCompany
                    .getOurCompanyPassword());

            InstanceConstraintViolationsListDTO instanceConstraintViolationsListDTO = client
                    .post(subcontractedTaskDataDTO,
                            InstanceConstraintViolationsListDTO.class);

            List<InstanceConstraintViolationsDTO> instanceConstraintViolationsList = instanceConstraintViolationsListDTO.instanceConstraintViolationsList;
            if ((instanceConstraintViolationsList != null)
                    && (!instanceConstraintViolationsList.isEmpty())) {
                String message = "";

                for (ConstraintViolationDTO constraintViolationDTO :  instanceConstraintViolationsList.get(0).constraintViolations) {
                    message += constraintViolationDTO.toString() + "\n";
{'fraction_non_alphanumeric': 0.07375571884098156, 'fraction_numerical': 0.0029807292388742547, 'mean_word_length': 4.085301374691576, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 4}, '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': '1798659', 'n_tokens_mistral': 3881, 'n_tokens_neox': 3817, 'n_words': 754}