Search in sources :

Example 1 with CoolUserFactoryException

use of it.cnr.cool.exception.CoolUserFactoryException in project cool-jconon by consiglionazionaledellericerche.

the class PrintService method getRicevutaReportModel.

@SuppressWarnings({ "unchecked", "deprecation" })
public byte[] getRicevutaReportModel(Session cmisSession, Folder application, String contextURL, String nameRicevutaReportModel, boolean immediate) throws CMISApplicationException {
    Folder call = application.getFolderParent();
    Locale locale = Locale.ITALY;
    Properties props = i18nService.loadLabels(locale);
    props.putAll(competitionService.getDynamicLabels(call, cmisSession));
    ApplicationModel applicationModel = new ApplicationModel(application, cmisSession.getDefaultContext(), props, contextURL);
    try {
        CMISUser applicationUser = userService.loadUserForConfirm(application.getPropertyValue(JCONONPropertyIds.APPLICATION_USER.value()));
        applicationModel.getProperties().put("jasperReport:user_matricola", applicationUser.getMatricola());
        applicationModel.getProperties().put("jasperReport:user_email_comunicazione", applicationUser.getEmail());
        applicationModel.getProperties().put("jconon_application:objectId", application.getId());
    } catch (CoolUserFactoryException e) {
        LOGGER.error("User not found", e);
    }
    final Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").excludeFieldsWithoutExposeAnnotation().registerTypeAdapter(GregorianCalendar.class, new JsonSerializer<GregorianCalendar>() {

        @Override
        public JsonElement serialize(GregorianCalendar src, Type typeOfSrc, JsonSerializationContext context) {
            return context.serialize(src.getTime());
        }
    }).create();
    if (call.getPropertyValue(JCONONPropertyIds.CALL_ELENCO_ASSOCIATIONS.value()) != null) {
        applicationModel.getProperties().put("allegati", getAllegati(application, JCONONPolicyType.JCONON_ATTACHMENT_GENERIC_DOCUMENT, cmisSession, applicationModel));
    }
    if (call.getPropertyValue(JCONONPropertyIds.CALL_ELENCO_SEZIONE_CURRICULUM.value()) != null) {
        applicationModel.getProperties().put("curriculum", getCurriculum(call.getPropertyValue(JCONONPropertyIds.CALL_ELENCO_SEZIONE_CURRICULUM.value()), application, cmisSession, applicationModel));
    }
    if (call.getPropertyValue(JCONONPropertyIds.CALL_ELENCO_SEZIONE_CURRICULUM_ULTERIORE.value()) != null) {
        applicationModel.getProperties().put("curriculum_ulteriore", getCurriculum(call.getPropertyValue(JCONONPropertyIds.CALL_ELENCO_SEZIONE_CURRICULUM_ULTERIORE.value()), application, cmisSession, applicationModel));
    }
    if (call.getPropertyValue(JCONONPropertyIds.CALL_ELENCO_SEZIONE_PRODOTTI.value()) != null) {
        applicationModel.getProperties().put("prodotti", getProdotti(call.getPropertyValue(JCONONPropertyIds.CALL_ELENCO_SEZIONE_PRODOTTI.value()), application, JCONONPolicyType.PEOPLE_NO_SELECTED_PRODUCT, cmisSession, applicationModel));
        applicationModel.getProperties().put("prodottiScelti", getProdotti(call.getPropertyValue(JCONONPropertyIds.CALL_ELENCO_SEZIONE_PRODOTTI.value()), application, JCONONPolicyType.PEOPLE_SELECTED_PRODUCT, cmisSession, applicationModel));
    }
    if (call.getPropertyValue(JCONONPropertyIds.CALL_ELENCO_SEZIONE_SCHEDE_ANONIME.value()) != null) {
        applicationModel.getProperties().put("schedeAnonime", getCurriculum(call.getPropertyValue(JCONONPropertyIds.CALL_ELENCO_SEZIONE_SCHEDE_ANONIME.value()), application, cmisSession, applicationModel));
    }
    applicationModel.getProperties().put(Dichiarazioni.dichiarazioni.name(), getDichiarazioni(bulkInfoService.find(application.getType().getId()), application, JCONONPropertyIds.CALL_ELENCO_ASPECTS, applicationModel, Dichiarazioni.dichiarazioni));
    applicationModel.getProperties().put(Dichiarazioni.datiCNR.name(), getDichiarazioni(bulkInfoService.find(application.getType().getId()), application, JCONONPropertyIds.CALL_ELENCO_ASPECTS_SEZIONE_CNR, applicationModel, Dichiarazioni.datiCNR));
    applicationModel.getProperties().put(Dichiarazioni.ulterioriDati.name(), getDichiarazioni(bulkInfoService.find(application.getType().getId()), application, JCONONPropertyIds.CALL_ELENCO_ASPECTS_ULTERIORI_DATI, applicationModel, Dichiarazioni.ulterioriDati));
    String labelSottoscritto = i18nService.getLabel("application.text.sottoscritto.lower." + application.getPropertyValue(JCONONPropertyIds.APPLICATION_SESSO.value()), locale);
    String labelSanzioniPenali = i18nService.getLabel("text.jconon_application_dichiarazione_sanzioni_penali_" + call.getPropertyValue(JCONONPropertyIds.CALL_CODICE.value()), locale);
    if (labelSanzioniPenali == null)
        labelSanzioniPenali = i18nService.getLabel("text.jconon_application_dichiarazione_sanzioni_penali", locale, labelSottoscritto);
    else
        labelSanzioniPenali = i18nService.getLabel("text.jconon_application_dichiarazione_sanzioni_penali_" + call.getPropertyValue(JCONONPropertyIds.CALL_CODICE.value()), locale, labelSottoscritto);
    applicationModel.getProperties().put("label_jconon_application_dichiarazione_sanzioni_penali", labelSanzioniPenali);
    applicationModel.getProperties().put("label_jconon_application_dichiarazione_dati_personali", i18nService.getLabel("text.jconon_application_dichiarazione_dati_personali", locale, labelSottoscritto));
    for (Object key : call.getProperty(JCONONPropertyIds.CALL_ELENCO_SEZIONI_DOMANDA.value()).getValues()) {
        applicationModel.getProperties().put(String.valueOf(key), props.get(key));
    }
    if (immediate) {
        applicationModel.getProperties().put(JCONONPropertyIds.APPLICATION_STATO_DOMANDA.value(), StatoDomanda.CONFERMATA.getValue());
        applicationModel.getProperties().put(JCONONPropertyIds.APPLICATION_DATA_DOMANDA.value(), Calendar.getInstance());
    }
    String json = "{\"properties\":" + gson.toJson(applicationModel.getProperties()) + "}";
    try {
        /**
         * Calcolo il QRCODE del link alla stampa
         */
        ByteArrayOutputStream qrcode = QrCodeUtil.getQrcode(contextURL + "/rest/application/print-download?nodeRef=" + application.getId());
        Map<String, Object> parameters = new HashMap<String, Object>();
        JRDataSource datasource = new JsonDataSource(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)), "properties");
        JRGzipVirtualizer vir = new JRGzipVirtualizer(100);
        final ResourceBundle resourceBundle = ResourceBundle.getBundle("net.sf.jasperreports.view.viewer", locale);
        parameters.put(JRParameter.REPORT_LOCALE, locale);
        parameters.put(JRParameter.REPORT_RESOURCE_BUNDLE, resourceBundle);
        parameters.put(JRParameter.REPORT_DATA_SOURCE, datasource);
        parameters.put(JRParameter.REPORT_VIRTUALIZER, vir);
        parameters.put("DIR_IMAGE", new ClassPathResource(PRINT_RESOURCE_PATH).getPath());
        parameters.put("SUBREPORT_DIR", new ClassPathResource(PRINT_RESOURCE_PATH).getPath());
        if (qrcode != null) {
            parameters.put("QRCODE", new ByteArrayInputStream(qrcode.toByteArray()));
        }
        ClassLoader classLoader = ClassLoader.getSystemClassLoader();
        parameters.put(JRParameter.REPORT_CLASS_LOADER, classLoader);
        JasperReport jasperReport = cacheRepository.jasperReport(PRINT_RESOURCE_PATH + "DomandaConcorso.jrxml", jasperCompileManager());
        JasperPrint jasperPrint = jasperFillManager().fill(jasperReport, parameters);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        JRPdfExporter exporter = new JRPdfExporter();
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, os);
        exporter.setParameter(JRPdfExporterParameter.FORCE_LINEBREAK_POLICY, Boolean.TRUE);
        exporter.exportReport();
        return os.toByteArray();
    } catch (Exception e) {
        throw new CMISApplicationException("Error in JASPER", e);
    }
}
Also used : CMISUser(it.cnr.cool.security.service.impl.alfresco.CMISUser) ApplicationModel(it.cnr.si.cool.jconon.model.ApplicationModel) CMISApplicationException(it.cnr.cool.web.scripts.exception.CMISApplicationException) JRPdfExporter(net.sf.jasperreports.engine.export.JRPdfExporter) JsonDataSource(net.sf.jasperreports.engine.data.JsonDataSource) JRGzipVirtualizer(net.sf.jasperreports.engine.fill.JRGzipVirtualizer) ClassPathResource(org.springframework.core.io.ClassPathResource) JSONException(org.json.JSONException) CmisObjectNotFoundException(org.apache.chemistry.opencmis.commons.exceptions.CmisObjectNotFoundException) WriterException(com.google.zxing.WriterException) ParseException(java.text.ParseException) CMISApplicationException(it.cnr.cool.web.scripts.exception.CMISApplicationException) CoolUserFactoryException(it.cnr.cool.exception.CoolUserFactoryException) NotImplementedException(org.apache.commons.lang3.NotImplementedException) CmisStreamNotSupportedException(org.apache.chemistry.opencmis.commons.exceptions.CmisStreamNotSupportedException) ClientMessageException(it.cnr.cool.web.scripts.exception.ClientMessageException) ACLType(it.cnr.cool.cmis.model.ACLType) Type(java.lang.reflect.Type) PDImageXObject(org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject) JSONObject(org.json.JSONObject) CoolUserFactoryException(it.cnr.cool.exception.CoolUserFactoryException)

Example 2 with CoolUserFactoryException

use of it.cnr.cool.exception.CoolUserFactoryException in project cool-jconon by consiglionazionaledellericerche.

the class PrintService method extractionApplicationForPunteggi.

public Map<String, Object> extractionApplicationForPunteggi(Session session, String callId, String contexURL, String userId) throws IOException {
    Map<String, Object> model = new HashMap<String, Object>();
    List<String> columns = new ArrayList<>();
    columns.addAll(headCSVPunteggi);
    int[] idx = { 1 };
    final Map<String, PropertyDefinition<?>> propertyDefinitions = session.getTypeDefinition("P:jconon_call:aspect_punteggi").getPropertyDefinitions();
    Folder call = Optional.ofNullable(session.getObject(callId)).filter(Folder.class::isInstance).map(Folder.class::cast).orElseThrow(() -> new ClientMessageException("Bando non trovato!"));
    addHeaderPunteggi(call, propertyDefinitions, columns, JCONON_CALL_PUNTEGGIO_1);
    addHeaderPunteggi(call, propertyDefinitions, columns, JCONON_CALL_PUNTEGGIO_2);
    addHeaderPunteggi(call, propertyDefinitions, columns, JCONON_CALL_PUNTEGGIO_3);
    addHeaderPunteggi(call, propertyDefinitions, columns, JCONON_CALL_PUNTEGGIO_4);
    addHeaderPunteggi(call, propertyDefinitions, columns, JCONON_CALL_PUNTEGGIO_5);
    addHeaderPunteggi(call, propertyDefinitions, columns, JCONON_CALL_PUNTEGGIO_6);
    columns.add("Totale Punteggi");
    columns.add("Graduatoria");
    columns.add("Esito");
    columns.add("Note");
    columns.add("Data Protocollo Graduatoria");
    columns.add("Numero Protocollo Graduatoria");
    columns.add("Data Protocollo Assunzione Idoneo");
    columns.add("Numero Protocollo Assunzione Idoneo");
    HSSFWorkbook wb = createHSSFWorkbook(columns);
    final HSSFSheet sheet = wb.getSheet(SHEET_DOMANDE);
    sheet.setColumnHidden(0, true);
    List<CmisObject> applications = new ArrayList<>();
    call.getChildren().forEach(cmisObject -> {
        applications.add(cmisObject);
    });
    applications.stream().filter(Folder.class::isInstance).map(Folder.class::cast).filter(folder -> folder.getType().getId().equalsIgnoreCase(JCONONFolderType.JCONON_APPLICATION.value())).filter(folder -> folder.getPropertyValue(JCONONPropertyIds.APPLICATION_STATO_DOMANDA.value()).equals(StatoDomanda.CONFERMATA.getValue())).sorted(Comparator.comparing(folder -> Optional.ofNullable(folder.<BigInteger>getPropertyValue(JCONONPropertyIds.APPLICATION_GRADUATORIA.value())).orElse(BigInteger.valueOf(Integer.MAX_VALUE)))).forEach(folder -> {
        final String userApplicationId = folder.getPropertyValue(JCONONPropertyIds.APPLICATION_USER.value());
        CMISUser user = null;
        try {
            user = userService.loadUserForConfirm(userApplicationId);
        } catch (CoolUserFactoryException _ex) {
            LOGGER.error("USER {} not found", userId, _ex);
            user = new CMISUser(userId);
        }
        getRecordCSVForPunteggi(session, call, folder, user, contexURL, sheet, idx[0]++);
    });
    autoSizeColumns(wb);
    Document doc = createXLSDocument(session, wb, userId);
    model.put("objectId", doc.getId());
    model.put("nameBando", competitionService.getCallName(call));
    return model;
}
Also used : Color(java.awt.Color) Order(it.cnr.si.opencmis.criteria.Order) ApplicationService(it.cnr.si.cool.jconon.service.application.ApplicationService) Autowired(org.springframework.beans.factory.annotation.Autowired) GroupService(it.cnr.cool.security.service.GroupService) PrintDetailBulk(it.cnr.si.cool.jconon.model.PrintDetailBulk) PDType1Font(org.apache.pdfbox.pdmodel.font.PDType1Font) org.apache.poi.ss.usermodel(org.apache.poi.ss.usermodel) BigDecimal(java.math.BigDecimal) JSONException(org.json.JSONException) CriteriaFactory(it.cnr.si.opencmis.criteria.CriteriaFactory) SimpleXlsReportConfiguration(net.sf.jasperreports.export.SimpleXlsReportConfiguration) NumberStyleFormatter(org.springframework.format.number.NumberStyleFormatter) CoolPropertyIds(it.cnr.cool.cmis.model.CoolPropertyIds) BigInteger(java.math.BigInteger) HttpStatus(org.apache.commons.httpclient.HttpStatus) PrintParameterModel(it.cnr.si.cool.jconon.model.PrintParameterModel) ContentStream(org.apache.chemistry.opencmis.commons.data.ContentStream) PropertyDefinition(org.apache.chemistry.opencmis.commons.definitions.PropertyDefinition) CompetitionFolderService(it.cnr.si.cool.jconon.service.cache.CompetitionFolderService) CMISAuthority(it.cnr.cool.security.service.impl.alfresco.CMISAuthority) PDDocument(org.apache.pdfbox.pdmodel.PDDocument) org.apache.chemistry.opencmis.commons.enums(org.apache.chemistry.opencmis.commons.enums) StandardCharsets(java.nio.charset.StandardCharsets) PropertyDecimalDefinition(org.apache.chemistry.opencmis.commons.definitions.PropertyDecimalDefinition) CMISUser(it.cnr.cool.security.service.impl.alfresco.CMISUser) MailService(it.cnr.cool.mail.MailService) IOUtils(org.apache.commons.io.IOUtils) Stream(java.util.stream.Stream) OperationContextImpl(org.apache.chemistry.opencmis.client.runtime.OperationContextImpl) PDPage(org.apache.pdfbox.pdmodel.PDPage) BarcodeFormat(com.google.zxing.BarcodeFormat) FieldProperty(it.cnr.bulkinfo.BulkInfoImpl.FieldProperty) JsonDataSource(net.sf.jasperreports.engine.data.JsonDataSource) JRXlsExporter(net.sf.jasperreports.engine.export.JRXlsExporter) JRPdfExporter(net.sf.jasperreports.engine.export.JRPdfExporter) CMISService(it.cnr.cool.cmis.service.CMISService) java.util(java.util) MimeTypes(it.cnr.cool.util.MimeTypes) InputStreamResource(net.sf.jasperreports.repo.InputStreamResource) SimpleDateFormat(java.text.SimpleDateFormat) SimpleExporterInput(net.sf.jasperreports.export.SimpleExporterInput) NumberFormat(java.text.NumberFormat) PDPageContentStream(org.apache.pdfbox.pdmodel.PDPageContentStream) PDFont(org.apache.pdfbox.pdmodel.font.PDFont) Value(org.springframework.beans.factory.annotation.Value) GroupsEnum(it.cnr.cool.security.GroupsEnum) Resource(net.sf.jasperreports.repo.Resource) Service(org.springframework.stereotype.Service) AttachmentBean(it.cnr.cool.mail.model.AttachmentBean) StatoDomanda(it.cnr.si.cool.jconon.service.application.ApplicationService.StatoDomanda) StreamSupport(java.util.stream.StreamSupport) Restrictions(it.cnr.si.opencmis.criteria.restrictions.Restrictions) RepositoryService(net.sf.jasperreports.repo.RepositoryService) PropertyDateTimeDefinition(org.apache.chemistry.opencmis.commons.definitions.PropertyDateTimeDefinition) UrlBuilder(org.apache.chemistry.opencmis.commons.impl.UrlBuilder) org.apache.chemistry.opencmis.client.api(org.apache.chemistry.opencmis.client.api) org.apache.poi.hssf.usermodel(org.apache.poi.hssf.usermodel) it.cnr.si.cool.jconon.cmis.model(it.cnr.si.cool.jconon.cmis.model) Pair(it.cnr.cool.util.Pair) com.google.gson(com.google.gson) UserService(it.cnr.cool.security.service.UserService) ReportResource(net.sf.jasperreports.repo.ReportResource) LoggerFactory(org.slf4j.LoggerFactory) CmisObjectNotFoundException(org.apache.chemistry.opencmis.commons.exceptions.CmisObjectNotFoundException) SimpleOutputStreamExporterOutput(net.sf.jasperreports.export.SimpleOutputStreamExporterOutput) WriterException(com.google.zxing.WriterException) PDImageXObject(org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject) JcononGroups(it.cnr.si.cool.jconon.util.JcononGroups) JSONObject(org.json.JSONObject) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) JRGzipVirtualizer(net.sf.jasperreports.engine.fill.JRGzipVirtualizer) ParseException(java.text.ParseException) DateFormat(java.text.DateFormat) PDFTextStripper(org.apache.pdfbox.text.PDFTextStripper) JRDocxExporter(net.sf.jasperreports.engine.export.ooxml.JRDocxExporter) Response(org.apache.chemistry.opencmis.client.bindings.spi.http.Response) ACLService(it.cnr.cool.cmis.service.ACLService) CMISApplicationException(it.cnr.cool.web.scripts.exception.CMISApplicationException) QrCodeUtil(it.cnr.si.cool.jconon.util.QrCodeUtil) StringUtil(it.cnr.cool.util.StringUtil) ACLType(it.cnr.cool.cmis.model.ACLType) Collectors(java.util.stream.Collectors) List(java.util.List) PropertyBooleanDefinition(org.apache.chemistry.opencmis.commons.definitions.PropertyBooleanDefinition) Type(java.lang.reflect.Type) PropertyIds(org.apache.chemistry.opencmis.commons.PropertyIds) BitMatrix(com.google.zxing.common.BitMatrix) CoolUserFactoryException(it.cnr.cool.exception.CoolUserFactoryException) NotImplementedException(org.apache.commons.lang3.NotImplementedException) CmisStreamNotSupportedException(org.apache.chemistry.opencmis.commons.exceptions.CmisStreamNotSupportedException) MatrixToImageWriter(com.google.zxing.client.j2se.MatrixToImageWriter) CMISPropertyIds(it.cnr.si.cool.jconon.util.CMISPropertyIds) ClassPathResource(org.springframework.core.io.ClassPathResource) ContentStreamImpl(org.apache.chemistry.opencmis.commons.impl.dataobjects.ContentStreamImpl) ApplicationModel(it.cnr.si.cool.jconon.model.ApplicationModel) NodeVersionService(it.cnr.cool.cmis.service.NodeVersionService) Criteria(it.cnr.si.opencmis.criteria.Criteria) JPEGFactory(org.apache.pdfbox.pdmodel.graphics.image.JPEGFactory) AppendMode(org.apache.pdfbox.pdmodel.PDPageContentStream.AppendMode) Util(it.cnr.cool.rest.util.Util) net.sf.jasperreports.engine(net.sf.jasperreports.engine) CacheRepository(it.cnr.si.cool.jconon.repository.CacheRepository) Logger(org.slf4j.Logger) BindingSession(org.apache.chemistry.opencmis.client.bindings.spi.BindingSession) BulkInfo(it.cnr.bulkinfo.BulkInfo) ClientMessageException(it.cnr.cool.web.scripts.exception.ClientMessageException) Output(org.apache.chemistry.opencmis.client.bindings.spi.http.Output) Code39Writer(com.google.zxing.oned.Code39Writer) ApplicationContext(org.springframework.context.ApplicationContext) JRPdfExporterParameter(net.sf.jasperreports.engine.export.JRPdfExporterParameter) PDRectangle(org.apache.pdfbox.pdmodel.common.PDRectangle) EmailMessage(it.cnr.cool.mail.model.EmailMessage) java.io(java.io) FieldPropertySet(it.cnr.bulkinfo.BulkInfoImpl.FieldPropertySet) BulkInfoCoolService(it.cnr.cool.service.BulkInfoCoolService) SimpleDocxReportConfiguration(net.sf.jasperreports.export.SimpleDocxReportConfiguration) Bean(org.springframework.context.annotation.Bean) I18nService(it.cnr.cool.service.I18nService) StringUtils(org.springframework.util.StringUtils) CMISUser(it.cnr.cool.security.service.impl.alfresco.CMISUser) PDDocument(org.apache.pdfbox.pdmodel.PDDocument) PropertyDefinition(org.apache.chemistry.opencmis.commons.definitions.PropertyDefinition) ClientMessageException(it.cnr.cool.web.scripts.exception.ClientMessageException) PDImageXObject(org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject) JSONObject(org.json.JSONObject) CoolUserFactoryException(it.cnr.cool.exception.CoolUserFactoryException)

Example 3 with CoolUserFactoryException

use of it.cnr.cool.exception.CoolUserFactoryException in project cool-jconon by consiglionazionaledellericerche.

the class ApplicationService method reopenApplication.

public void reopenApplication(Session currentCMISSession, final String applicationSourceId, final String contextURL, Locale locale, String userId) {
    /**
     * Load application source with user session if user cannot access to application
     * throw an exception
     */
    try {
        OperationContext oc = new OperationContextImpl(currentCMISSession.getDefaultContext());
        oc.setFilterString(PropertyIds.OBJECT_ID);
        currentCMISSession.getObject(applicationSourceId, oc);
    } catch (CmisPermissionDeniedException _ex) {
        throw new ClientMessageException("user.cannot.access.to.application", _ex);
    }
    final Folder newApplication = loadApplicationById(currentCMISSession, applicationSourceId, null);
    final Folder call = loadCallById(currentCMISSession, newApplication.getParentId(), null);
    if (newApplication.getPropertyValue(JCONONPropertyIds.APPLICATION_DATA_DOMANDA.value()) == null || !newApplication.getPropertyValue(JCONONPropertyIds.APPLICATION_STATO_DOMANDA.value()).equals(StatoDomanda.CONFERMATA.getValue())) {
        throw new ClientMessageException("message.error.domanda.no.confermata");
    }
    try {
        callService.isBandoInCorso(call, userService.loadUserForConfirm(userId));
    } catch (CoolUserFactoryException e) {
        throw new CMISApplicationException("Error loading user: " + userId, e);
    }
    String link = cmisService.getBaseURL().concat("service/cnr/jconon/manage-application/reopen");
    UrlBuilder url = new UrlBuilder(link);
    Response resp = cmisService.getHttpInvoker(cmisService.getAdminSession()).invokePOST(url, MimeTypes.JSON.mimetype(), new Output() {

        @Override
        public void write(OutputStream out) throws Exception {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("applicationSourceId", newApplication.getProperty(CoolPropertyIds.ALFCMIS_NODEREF.value()).getValueAsString());
            jsonObject.put("groupRdP", "GROUP_" + call.getPropertyValue(JCONONPropertyIds.CALL_RDP.value()));
            jsonObject.put("groupConsumer", JcononGroups.APPLICATION_CONSUMER.group());
            out.write(jsonObject.toString().getBytes());
        }
    }, cmisService.getAdminSession());
    int status = resp.getResponseCode();
    if (status == HttpStatus.SC_NOT_FOUND || status == HttpStatus.SC_BAD_REQUEST || status == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
        throw new CMISApplicationException("Reopen Application error. Exception: " + resp.getErrorContent());
    }
    addToQueueForPrint(applicationSourceId, contextURL, emailOnReopen);
}
Also used : OperationContextImpl(org.apache.chemistry.opencmis.client.runtime.OperationContextImpl) CMISApplicationException(it.cnr.cool.web.scripts.exception.CMISApplicationException) JSONException(org.json.JSONException) CMISApplicationException(it.cnr.cool.web.scripts.exception.CMISApplicationException) CoolUserFactoryException(it.cnr.cool.exception.CoolUserFactoryException) ClientMessageException(it.cnr.cool.web.scripts.exception.ClientMessageException) Response(org.apache.chemistry.opencmis.client.bindings.spi.http.Response) JSONObject(org.json.JSONObject) ClientMessageException(it.cnr.cool.web.scripts.exception.ClientMessageException) Output(org.apache.chemistry.opencmis.client.bindings.spi.http.Output) UrlBuilder(org.apache.chemistry.opencmis.commons.impl.UrlBuilder) CoolUserFactoryException(it.cnr.cool.exception.CoolUserFactoryException)

Example 4 with CoolUserFactoryException

use of it.cnr.cool.exception.CoolUserFactoryException in project cool-jconon by consiglionazionaledellericerche.

the class ApplicationService method load.

public Folder load(Session currentCMISSession, String callId, String applicationId, String userId, boolean preview, String contextURL, Locale locale) {
    Map<String, Object> result = new HashMap<String, Object>();
    Folder application = null;
    CMISUser loginUser = userService.loadUserForConfirm(userId), applicationUser = null;
    Folder call = loadCallById(currentCMISSession, callId, result);
    try {
        if (applicationId != null && !applicationId.isEmpty()) {
            application = loadApplicationById(currentCMISSession, applicationId, result);
            // la chiamata con il parametro applicationId deve prevedere sempre l'esistenza della domanda
            if (application == null)
                throw new ClientMessageException("message.error.caller");
            else {
                // coincide con quello della domanda
                if (!loginUser.isAdmin() && !loginUser.getId().equals(application.getPropertyValue(JCONONPropertyIds.APPLICATION_USER.value())))
                    throw new ClientMessageException("message.error.caller.user");
                else if (!application.getParentId().equals(call.getId()))
                    throw new ClientMessageException("message.error.caller");
            }
        } else
            application = loadApplicationByCall(currentCMISSession, callId, result, userId);
        // Carico lo user dell'application
        applicationUser = getApplicationUser(application);
        // essere un dipendente
        if (call.getType().getId().equals(JCONONFolderType.JCONON_CALL_EMPLOYEES.value()) && ((application == null && loginUser.getMatricola() == null) || (applicationUser != null && applicationUser.getMatricola() == null))) {
            if (!isApplicationPreview(preview, loginUser, call) && blockSubmitEmployee)
                throw new ClientMessageException("message.error.bando.tipologia.employees");
        }
        final Optional<String> canSubmitApplicationOnlySPID = Optional.ofNullable(call.<String>getPropertyValue(JCONONPropertyIds.CALL_ONLY_USER_SPID_CAN_SUBMIT_APPLICATION.value()));
        if (canSubmitApplicationOnlySPID.map(Boolean::valueOf).filter(aBoolean -> {
            return aBoolean.booleanValue();
        }).map(aBoolean -> {
            return !Optional.ofNullable(loginUser.getApplication()).filter(s -> !s.isEmpty()).filter(s -> s.equals("SPID")).isPresent();
        }).orElse(Boolean.FALSE) && !isApplicationPreview(preview, loginUser, call)) {
            throw new ClientMessageException(i18nService.getLabel("message.error.bando.cannot.submit.application.spid", locale));
        }
        /**
         * Se nel bando รจ valorizzato il gruppo delle utenze viene controllata la presenza
         * dell'utenza specifica nel gruppo
         */
        final Optional<String> groupCanSubmitApplication = Optional.ofNullable(call.<String>getPropertyValue(JCONONPropertyIds.CALL_GROUP_CAN_SUBMIT_APPLICATION.value()));
        if (groupCanSubmitApplication.map(groupName -> !loginUser.getGroupsArray().contains(groupName)).orElse(Boolean.FALSE)) {
            throw new ClientMessageException(i18nService.getLabel("message.error.bando.cannot.submit.application", locale, groupService.loadGroup(groupCanSubmitApplication.map(s -> s.replaceAll("GROUP_", "")).orElseThrow(() -> new CMISApplicationException("Cannot find GROUP")), cmisService.getAdminSession()).getDisplay_name()));
        }
        // essere un dipendente
        if (JCONONFolderType.isMobilityCall(call.getType().getId()) && ((application == null && loginUser.getMatricola() != null) || (applicationUser != null && applicationUser.getMatricola() != null))) {
            if (!isApplicationPreview(preview, loginUser, call))
                throw new ClientMessageException("message.error.bando.tipologia.mobility");
        }
        // Se presente e validata, entra...... Se presente e non validata il blocco lo ha in fase di invio.
        if (application == null)
            validateMacroCall(call, null, loginUser);
        else if (application.getPropertyValue(JCONONPropertyIds.APPLICATION_STATO_DOMANDA.value()).equals(StatoDomanda.INIZIALE.getValue()))
            validateMacroCall(call, application, applicationUser);
        else if (isDomandaInviata(application, loginUser)) {
            throw new ClientMessageException("message.error.domanda.inviata.accesso");
        }
        if (!isApplicationPreview(preview, loginUser, call))
            callService.isBandoInCorso(call, loginUser);
        if (application != null) {
            /**
             * Controllo di consistenza su nome e cognome dell'utenza
             */
            if (!loginUser.isAdmin() && loginUser.getId().equals(application.getPropertyValue(JCONONPropertyIds.APPLICATION_USER.value()))) {
                Map<String, Object> properties = new HashMap<String, Object>();
                if (!loginUser.getFirstName().equalsIgnoreCase(application.getPropertyValue(JCONONPropertyIds.APPLICATION_NOME.value()))) {
                    properties.put(JCONONPropertyIds.APPLICATION_NOME.value(), loginUser.getFirstName());
                }
                if (!loginUser.getLastName().equalsIgnoreCase(application.getPropertyValue(JCONONPropertyIds.APPLICATION_COGNOME.value()))) {
                    properties.put(JCONONPropertyIds.APPLICATION_COGNOME.value(), loginUser.getLastName());
                }
                if (!properties.isEmpty())
                    cmisService.createAdminSession().getObject(application).updateProperties(properties, true);
            }
            try {
                validateAllegatiLinked(call, application, currentCMISSession);
            } catch (ClientMessageException e) {
                LOGGER.warn("ValidateAllegatiLinked message: {}", e.getMessage());
                result.put("validateAllegatiLinkedEmpty", e.getKeyMessage());
            }
        }
        if (application == null)
            application = createInitialFolder(loginUser, result, cmisService.createAdminSession(), call);
    } catch (CoolUserFactoryException e) {
        throw new CMISApplicationException("Load Application error.", e);
    }
    return application;
}
Also used : JsonObject(com.google.gson.JsonObject) Order(it.cnr.si.opencmis.criteria.Order) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) GroupService(it.cnr.cool.security.service.GroupService) BigDecimal(java.math.BigDecimal) JSONException(org.json.JSONException) CriteriaFactory(it.cnr.si.opencmis.criteria.CriteriaFactory) JSONObject(org.json.JSONObject) OperationContextUtils(org.apache.chemistry.opencmis.client.util.OperationContextUtils) CoolPropertyIds(it.cnr.cool.cmis.model.CoolPropertyIds) BigInteger(java.math.BigInteger) HttpStatus(org.apache.commons.httpclient.HttpStatus) PrintParameterModel(it.cnr.si.cool.jconon.model.PrintParameterModel) ContentStream(org.apache.chemistry.opencmis.commons.data.ContentStream) PropertyDefinition(org.apache.chemistry.opencmis.commons.definitions.PropertyDefinition) it.cnr.cool.util(it.cnr.cool.util) CompetitionFolderService(it.cnr.si.cool.jconon.service.cache.CompetitionFolderService) Response(org.apache.chemistry.opencmis.client.bindings.spi.http.Response) PolicyType(it.cnr.cool.cmis.model.PolicyType) CMISApplicationException(it.cnr.cool.web.scripts.exception.CMISApplicationException) QueueService(it.cnr.si.cool.jconon.service.QueueService) ACLType(it.cnr.cool.cmis.model.ACLType) Collectors(java.util.stream.Collectors) ZoneId(java.time.ZoneId) CMISUser(it.cnr.cool.security.service.impl.alfresco.CMISUser) MailService(it.cnr.cool.mail.MailService) JsonArray(com.google.gson.JsonArray) Choice(org.apache.chemistry.opencmis.commons.definitions.Choice) Stream(java.util.stream.Stream) OperationContextImpl(org.apache.chemistry.opencmis.client.runtime.OperationContextImpl) PropertyIds(org.apache.chemistry.opencmis.commons.PropertyIds) LocalDate(java.time.LocalDate) Entry(java.util.Map.Entry) CoolUserFactoryException(it.cnr.cool.exception.CoolUserFactoryException) FieldProperty(it.cnr.bulkinfo.BulkInfoImpl.FieldProperty) it.cnr.si.cool.jconon.util(it.cnr.si.cool.jconon.util) java.util(java.util) LocalDateTime(java.time.LocalDateTime) ContentStreamImpl(org.apache.chemistry.opencmis.commons.impl.dataobjects.ContentStreamImpl) SimpleDateFormat(java.text.SimpleDateFormat) BaseTypeId(org.apache.chemistry.opencmis.commons.enums.BaseTypeId) Function(java.util.function.Function) InitializingBean(org.springframework.beans.factory.InitializingBean) PrintService(it.cnr.si.cool.jconon.service.PrintService) JsonElement(com.google.gson.JsonElement) Value(org.springframework.beans.factory.annotation.Value) it.cnr.cool.cmis.service(it.cnr.cool.cmis.service) GroupsEnum(it.cnr.cool.security.GroupsEnum) Criteria(it.cnr.si.opencmis.criteria.Criteria) Service(org.springframework.stereotype.Service) SiperService(it.cnr.si.cool.jconon.service.SiperService) StreamSupport(java.util.stream.StreamSupport) Restrictions(it.cnr.si.opencmis.criteria.restrictions.Restrictions) UrlBuilder(org.apache.chemistry.opencmis.commons.impl.UrlBuilder) IncludeRelationships(org.apache.chemistry.opencmis.commons.enums.IncludeRelationships) TypeService(it.cnr.si.cool.jconon.service.TypeService) org.apache.chemistry.opencmis.client.api(org.apache.chemistry.opencmis.client.api) UnfileObject(org.apache.chemistry.opencmis.commons.enums.UnfileObject) VersioningState(org.apache.chemistry.opencmis.commons.enums.VersioningState) org.apache.chemistry.opencmis.commons.exceptions(org.apache.chemistry.opencmis.commons.exceptions) Logger(org.slf4j.Logger) BindingSession(org.apache.chemistry.opencmis.client.bindings.spi.BindingSession) org.apache.poi.hssf.usermodel(org.apache.poi.hssf.usermodel) it.cnr.si.cool.jconon.cmis.model(it.cnr.si.cool.jconon.cmis.model) BulkInfo(it.cnr.bulkinfo.BulkInfo) ClientMessageException(it.cnr.cool.web.scripts.exception.ClientMessageException) Output(org.apache.chemistry.opencmis.client.bindings.spi.http.Output) ApplicationContext(org.springframework.context.ApplicationContext) CallService(it.cnr.si.cool.jconon.service.call.CallService) java.io(java.io) BulkInfoCoolService(it.cnr.cool.service.BulkInfoCoolService) UserService(it.cnr.cool.security.service.UserService) I18nService(it.cnr.cool.service.I18nService) CMISUser(it.cnr.cool.security.service.impl.alfresco.CMISUser) ClientMessageException(it.cnr.cool.web.scripts.exception.ClientMessageException) JsonObject(com.google.gson.JsonObject) JSONObject(org.json.JSONObject) UnfileObject(org.apache.chemistry.opencmis.commons.enums.UnfileObject) CMISApplicationException(it.cnr.cool.web.scripts.exception.CMISApplicationException) CoolUserFactoryException(it.cnr.cool.exception.CoolUserFactoryException)

Example 5 with CoolUserFactoryException

use of it.cnr.cool.exception.CoolUserFactoryException in project cool-jconon by consiglionazionaledellericerche.

the class ApplicationService method paste.

public String paste(Session currentCMISSession, final String applicationSourceId, final String callTargetId, String userId) {
    /**
     * Load application source with user session if user cannot access to application
     * throw an exception
     */
    try {
        OperationContext oc = new OperationContextImpl(currentCMISSession.getDefaultContext());
        oc.setFilterString(PropertyIds.OBJECT_ID);
        currentCMISSession.getObject(applicationSourceId, oc);
    } catch (CmisPermissionDeniedException _ex) {
        throw new ClientMessageException("user.cannot.access.to.application", _ex);
    }
    final Folder application = loadApplicationById(currentCMISSession, applicationSourceId, null);
    final Folder call = loadCallById(currentCMISSession, callTargetId, null);
    try {
        callService.isBandoInCorso(call, userService.loadUserForConfirm(userId));
    } catch (CoolUserFactoryException e) {
        throw new CMISApplicationException("Error loading user: " + userId, e);
    }
    String link = cmisService.getBaseURL().concat("service/cnr/jconon/manage-application/paste");
    UrlBuilder url = new UrlBuilder(link);
    Response resp = cmisService.getHttpInvoker(cmisService.getAdminSession()).invokePOST(url, MimeTypes.JSON.mimetype(), new Output() {

        @Override
        public void write(OutputStream out) throws Exception {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("applicationSourceId", application.getProperty(CoolPropertyIds.ALFCMIS_NODEREF.value()).getValueAsString());
            jsonObject.put("callTargetId", call.getProperty(CoolPropertyIds.ALFCMIS_NODEREF.value()).getValueAsString());
            out.write(jsonObject.toString().getBytes());
        }
    }, cmisService.getAdminSession());
    int stato = resp.getResponseCode();
    if (stato == HttpStatus.SC_BAD_REQUEST || stato == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
        try {
            JSONObject jsonObject = new JSONObject(resp.getErrorContent());
            throw new ClientMessageException(jsonObject.getString("message"));
        } catch (JSONException e) {
            throw new ClientMessageException("message.application.for.copy.alredy.exists", e);
        }
    }
    if (stato == HttpStatus.SC_NOT_FOUND) {
        throw new ClientMessageException("Paste Application error. Exception: " + resp.getErrorContent());
    }
    try {
        JSONObject jsonObject = new JSONObject(StringUtil.convertStreamToString(resp.getStream()));
        return jsonObject.getString("cmis:objectId");
    } catch (JSONException e) {
        throw new ClientMessageException("Paste Application error. Exception: " + resp.getErrorContent(), e);
    }
}
Also used : OperationContextImpl(org.apache.chemistry.opencmis.client.runtime.OperationContextImpl) JSONException(org.json.JSONException) CMISApplicationException(it.cnr.cool.web.scripts.exception.CMISApplicationException) JSONException(org.json.JSONException) CMISApplicationException(it.cnr.cool.web.scripts.exception.CMISApplicationException) CoolUserFactoryException(it.cnr.cool.exception.CoolUserFactoryException) ClientMessageException(it.cnr.cool.web.scripts.exception.ClientMessageException) Response(org.apache.chemistry.opencmis.client.bindings.spi.http.Response) JSONObject(org.json.JSONObject) ClientMessageException(it.cnr.cool.web.scripts.exception.ClientMessageException) Output(org.apache.chemistry.opencmis.client.bindings.spi.http.Output) UrlBuilder(org.apache.chemistry.opencmis.commons.impl.UrlBuilder) CoolUserFactoryException(it.cnr.cool.exception.CoolUserFactoryException)

Aggregations

CoolUserFactoryException (it.cnr.cool.exception.CoolUserFactoryException)12 CMISUser (it.cnr.cool.security.service.impl.alfresco.CMISUser)10 CMISApplicationException (it.cnr.cool.web.scripts.exception.CMISApplicationException)9 ClientMessageException (it.cnr.cool.web.scripts.exception.ClientMessageException)9 JSONException (org.json.JSONException)9 JSONObject (org.json.JSONObject)9 UrlBuilder (org.apache.chemistry.opencmis.commons.impl.UrlBuilder)8 ACLType (it.cnr.cool.cmis.model.ACLType)6 UserService (it.cnr.cool.security.service.UserService)6 CmisObjectNotFoundException (org.apache.chemistry.opencmis.commons.exceptions.CmisObjectNotFoundException)6 Logger (org.slf4j.Logger)6 LoggerFactory (org.slf4j.LoggerFactory)6 Autowired (org.springframework.beans.factory.annotation.Autowired)6 WriterException (com.google.zxing.WriterException)5 CMISService (it.cnr.cool.cmis.service.CMISService)5 I18nService (it.cnr.cool.service.I18nService)5 ParseException (java.text.ParseException)5 CoolPropertyIds (it.cnr.cool.cmis.model.CoolPropertyIds)4 GroupsEnum (it.cnr.cool.security.GroupsEnum)4 BulkInfoCoolService (it.cnr.cool.service.BulkInfoCoolService)4