Search in sources :

Example 6 with CoolUserFactoryException

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

the class PrintService method printApplication.

public void printApplication(String nodeRef, final String contextURL, final Locale locale, final boolean email) {
    try {
        LOGGER.info("Start print application width id: " + nodeRef);
        Session cmisSession = cmisService.createAdminSession();
        Folder application = (Folder) cmisSession.getObject(nodeRef);
        Boolean confirmed = isConfirmed(application);
        Folder call = (Folder) cmisSession.getObject(application.getParentId());
        application.refresh();
        CMISUser applicationUser;
        try {
            applicationUser = userService.loadUserForConfirm(application.getPropertyValue(JCONONPropertyIds.APPLICATION_USER.value()));
        } catch (CoolUserFactoryException e) {
            throw new ClientMessageException("User not found of application " + nodeRef, e);
        }
        String nameRicevutaReportModel = getNameRicevutaReportModel(cmisSession, application, locale);
        byte[] stampaByte = getRicevutaReportModel(cmisSession, application, contextURL, nameRicevutaReportModel, false);
        InputStream is = new ByteArrayInputStream(stampaByte);
        archiviaRicevutaReportModel(cmisSession, application, is, nameRicevutaReportModel, confirmed);
        /**
         * Spedisco la mail con la stampa allegata
         */
        if (email) {
            Map<String, Object> mailModel = new HashMap<String, Object>();
            List<String> emailList = new ArrayList<String>();
            emailList.add(applicationUser.getEmail());
            mailModel.put("contextURL", contextURL);
            mailModel.put("folder", application);
            mailModel.put("call", call);
            mailModel.put("message", context.getBean("messageMethod", locale));
            mailModel.put("email_comunicazione", applicationUser.getEmail());
            EmailMessage message = new EmailMessage();
            message.setRecipients(emailList);
            message.setCcRecipients(getCcRecipientsForPrint(confirmed));
            message.setBccRecipients(getBccRecipientsForPrint(confirmed));
            String body;
            if (confirmed) {
                body = Util.processTemplate(mailModel, "/pages/application/application.registration.html.ftl");
                message.setSubject(i18nService.getLabel("subject-info", locale) + i18nService.getLabel("subject-confirm-domanda", locale, call.getProperty(JCONONPropertyIds.CALL_CODICE.value()).getValueAsString()));
                Map<String, Object> properties = new HashMap<String, Object>();
                properties.put(JCONONPropertyIds.APPLICATION_DUMMY.value(), "{\"stampa_archiviata\" : true}");
                application.updateProperties(properties);
            } else {
                body = Util.processTemplate(mailModel, "/pages/application/application.print.html.ftl");
                message.setSubject(i18nService.getLabel("subject-info", locale) + i18nService.getLabel("subject-print-domanda", locale, call.getProperty(JCONONPropertyIds.CALL_CODICE.value()).getValueAsString()));
            }
            message.setBody(body);
            message.setAttachments(Arrays.asList(new AttachmentBean(nameRicevutaReportModel, stampaByte)));
            mailService.send(message);
        }
        if (LOGGER.isInfoEnabled())
            LOGGER.info("End print application width id: " + nodeRef);
    } catch (Exception t) {
        LOGGER.error("Error while print application width id:" + nodeRef, t);
    }
}
Also used : EmailMessage(it.cnr.cool.mail.model.EmailMessage) CMISUser(it.cnr.cool.security.service.impl.alfresco.CMISUser) AttachmentBean(it.cnr.cool.mail.model.AttachmentBean) 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) 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) BindingSession(org.apache.chemistry.opencmis.client.bindings.spi.BindingSession)

Example 7 with CoolUserFactoryException

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

the class CustomKeyCloakAuthSuccessHandler method onAuthenticationSuccess.

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
    LOG.info("get account with authentication {}", authentication);
    final Optional<KeycloakAuthenticationToken> keycloakAuthenticationToken = Optional.ofNullable(authentication).filter(KeycloakAuthenticationToken.class::isInstance).map(KeycloakAuthenticationToken.class::cast);
    if (keycloakAuthenticationToken.isPresent() && keycloakAuthenticationToken.get().isAuthenticated() && Optional.ofNullable(keycloakAuthenticationToken.get().getAccount()).isPresent()) {
        final OidcKeycloakAccount account = keycloakAuthenticationToken.get().getAccount();
        LOG.info("get account with authentication {}", account);
        if (customKeyCloakAuthenticationProvider.isCNRUser(account)) {
            final String ticketForUser = createTicketForUser(customKeyCloakAuthenticationProvider.getUsernameCNR(account));
            response.addCookie(getCookie(ticketForUser, request.isSecure()));
        } else {
            final Principal principal = account.getPrincipal();
            if (principal instanceof KeycloakPrincipal) {
                KeycloakPrincipal kPrincipal = (KeycloakPrincipal) principal;
                IDToken token = kPrincipal.getKeycloakSecurityContext().getIdToken();
                CMISUser cmisUser = new CMISUser();
                cmisUser.setApplication(SSO);
                cmisUser.setFirstName(token.getGivenName());
                cmisUser.setLastName(token.getFamilyName());
                cmisUser.setDataDiNascita(Optional.ofNullable(token.getBirthdate()).filter(s -> !s.isEmpty()).map(date -> {
                    try {
                        return Date.from(LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
                    } catch (DateTimeParseException _ex) {
                        LOG.warn("Cannot format date of birth", _ex);
                        return null;
                    }
                }).orElse(null));
                cmisUser.setCodicefiscale(Optional.ofNullable(token.getPreferredUsername()).map(cf -> cf.substring(6)).map(String::toUpperCase).orElse(null));
                cmisUser.setSesso(token.getGender());
                cmisUser.setEmail(token.getEmail());
                String userName = normalize(Optional.ofNullable(cmisUser.getFirstName()).map(String::trim).filter(s -> !s.isEmpty()).orElseThrow(() -> new AuthenticationServiceException("First Name cannot be empty"))).toLowerCase().concat("-").concat(normalize(Optional.ofNullable(cmisUser.getLastName()).map(String::trim).filter(s -> !s.isEmpty()).orElseThrow(() -> new AuthenticationServiceException("Last Name cannot be empty"))).toLowerCase());
                Optional<CMISUser> userByCodiceFiscale = Optional.ofNullable(userService.findUserByCodiceFiscale(cmisUser.getCodicefiscale(), cmisService.getAdminSession(), userName));
                if (userByCodiceFiscale.isPresent()) {
                    if (!Optional.ofNullable(userByCodiceFiscale.get().getEmail()).equals(Optional.ofNullable(cmisUser.getEmail())) && Optional.ofNullable(userByCodiceFiscale.get().getApplication()).filter(s -> !s.isEmpty()).isPresent()) {
                        cmisUser.setUserName(userByCodiceFiscale.get().getUserName());
                        userByCodiceFiscale = Optional.ofNullable(userService.updateUser(cmisUser));
                    }
                    response.addCookie(getCookie(createTicketForUser(userByCodiceFiscale.get().getUserName()), request.isSecure()));
                } else {
                    // Verifico se l'utenza ha lo stesso codice fiscale
                    try {
                        Optional<CMISUser> cmisUser2 = Optional.ofNullable(userService.loadUserForConfirm(userName)).filter(cmisUser1 -> cmisUser1.getCodicefiscale().equalsIgnoreCase(cmisUser.getCodicefiscale()));
                        if (cmisUser2.isPresent()) {
                            if (!Optional.ofNullable(cmisUser2.get().getEmail()).equals(Optional.ofNullable(cmisUser.getEmail())) && Optional.ofNullable(cmisUser2.get().getApplication()).filter(s -> !s.isEmpty()).isPresent()) {
                                cmisUser.setUserName(cmisUser2.get().getUserName());
                                cmisUser2 = Optional.ofNullable(userService.updateUser(cmisUser));
                            }
                            response.addCookie(getCookie(createTicketForUser(cmisUser2.get().getUserName()), request.isSecure()));
                        }
                    } catch (CoolUserFactoryException _ex) {
                        LOG.trace("SPID Username {} not found", userName);
                    }
                    if (!userService.isUserExists(userName)) {
                        cmisUser.setUserName(userName);
                    } else {
                        for (int i = 1; i < 20; i++) {
                            final String concatUsername = userName.concat("0").concat(String.valueOf(i));
                            if (!userService.isUserExists(concatUsername)) {
                                cmisUser.setUserName(concatUsername);
                                break;
                            }
                        }
                    }
                    final CMISUser user = userService.createUser(cmisUser);
                    userService.enableAccount(user.getUserName());
                    response.addCookie(getCookie(createTicketForUser(user.getUserName()), request.isSecure()));
                }
            }
        }
    }
    String location = KeycloakCookieBasedRedirect.getRedirectUrlFromCookie(request);
    if (location == null) {
        if (fallback != null) {
            fallback.onAuthenticationSuccess(request, response, authentication);
        }
    } else {
        try {
            location = UriUtils.decode(location, Charset.defaultCharset());
            response.addCookie(KeycloakCookieBasedRedirect.createCookieFromRedirectUrl(null));
            response.sendRedirect(location);
        } catch (IOException e) {
            LOG.warn("Unable to redirect user after login", e);
        }
    }
}
Also used : CMISService(it.cnr.cool.cmis.service.CMISService) KeycloakAuthenticationSuccessHandler(org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationSuccessHandler) ServletException(javax.servlet.ServletException) Date(java.util.Date) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) AuthenticationSuccessHandler(org.springframework.security.web.authentication.AuthenticationSuccessHandler) Value(org.springframework.beans.factory.annotation.Value) HttpServletRequest(javax.servlet.http.HttpServletRequest) OidcKeycloakAccount(org.keycloak.adapters.OidcKeycloakAccount) Charset(java.nio.charset.Charset) Map(java.util.Map) AuthenticationException(org.springframework.security.core.AuthenticationException) UrlBuilder(org.apache.chemistry.opencmis.commons.impl.UrlBuilder) HttpStatus(org.apache.commons.httpclient.HttpStatus) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) Cookie(javax.servlet.http.Cookie) CmisBindingsHelper(org.apache.chemistry.opencmis.client.bindings.impl.CmisBindingsHelper) KeycloakAuthenticationToken(org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken) KeycloakPrincipal(org.keycloak.KeycloakPrincipal) Logger(org.slf4j.Logger) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) IDToken(org.keycloak.representations.IDToken) ZoneId(java.time.ZoneId) Normalizer(java.text.Normalizer) CMISUser(it.cnr.cool.security.service.impl.alfresco.CMISUser) DateTimeParseException(java.time.format.DateTimeParseException) Principal(java.security.Principal) LocalDate(java.time.LocalDate) DateTimeFormatter(java.time.format.DateTimeFormatter) KeycloakCookieBasedRedirect(org.keycloak.adapters.springsecurity.authentication.KeycloakCookieBasedRedirect) UriUtils(org.springframework.web.util.UriUtils) Optional(java.util.Optional) CoolUserFactoryException(it.cnr.cool.exception.CoolUserFactoryException) Authentication(org.springframework.security.core.Authentication) UserService(it.cnr.cool.security.service.UserService) KeycloakAuthenticationToken(org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken) OidcKeycloakAccount(org.keycloak.adapters.OidcKeycloakAccount) CMISUser(it.cnr.cool.security.service.impl.alfresco.CMISUser) IOException(java.io.IOException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) DateTimeParseException(java.time.format.DateTimeParseException) IDToken(org.keycloak.representations.IDToken) KeycloakPrincipal(org.keycloak.KeycloakPrincipal) Principal(java.security.Principal) CoolUserFactoryException(it.cnr.cool.exception.CoolUserFactoryException) KeycloakPrincipal(org.keycloak.KeycloakPrincipal)

Example 8 with CoolUserFactoryException

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

the class CacheRepository method getCompetitionFolder.

@Cacheable(COMPETITION)
public CmisObjectCache getCompetitionFolder() {
    LOGGER.info("Try to connect to repository base url: {}", baseURL);
    Folder competition = null;
    Session session = cmisService.createAdminSession();
    Criteria criteria = CriteriaFactory.createCriteria(JCONONFolderType.JCONON_COMPETITION.queryName());
    ItemIterable<QueryResult> results = criteria.executeQuery(session, false, session.getDefaultContext());
    if (results.getTotalNumItems() == 0) {
        competition = (Folder) session.getObject(session.createFolder(Collections.unmodifiableMap(Stream.of(new AbstractMap.SimpleEntry<>(PropertyIds.OBJECT_TYPE_ID, JCONONFolderType.JCONON_COMPETITION.value()), new AbstractMap.SimpleEntry<>(PropertyIds.NAME, Optional.ofNullable(i18NService.getLabel("app.name", Locale.ITALIAN)).orElse("Selezioni on-line"))).collect(Collectors.toMap((e) -> e.getKey(), (e) -> e.getValue()))), session.getRootFolder()));
        /**
         * Creo le folder per i documenti
         */
        final ObjectId documents = session.createFolder(Collections.unmodifiableMap(Stream.of(new AbstractMap.SimpleEntry<>(PropertyIds.OBJECT_TYPE_ID, BaseTypeId.CMIS_FOLDER.value()), new AbstractMap.SimpleEntry<>(PropertyIds.NAME, "documents")).collect(Collectors.toMap((e) -> e.getKey(), (e) -> e.getValue()))), competition);
        session.createFolder(Collections.unmodifiableMap(Stream.of(new AbstractMap.SimpleEntry<>(PropertyIds.OBJECT_TYPE_ID, BaseTypeId.CMIS_FOLDER.value()), new AbstractMap.SimpleEntry<>(PropertyIds.NAME, "manuali")).collect(Collectors.toMap((e) -> e.getKey(), (e) -> e.getValue()))), documents);
        session.createFolder(Collections.unmodifiableMap(Stream.of(new AbstractMap.SimpleEntry<>(PropertyIds.OBJECT_TYPE_ID, BaseTypeId.CMIS_FOLDER.value()), new AbstractMap.SimpleEntry<>(PropertyIds.NAME, "graduatorie")).collect(Collectors.toMap((e) -> e.getKey(), (e) -> e.getValue()))), documents);
        /**
         * Creo anche i gruppi necessari al funzionamento
         */
        createGroup(null, JcononGroups.CONCORSI.name(), JcononGroups.CONCORSI.label());
        createGroup(null, JcononGroups.COMMISSIONI_CONCORSO.name(), JcononGroups.COMMISSIONI_CONCORSO.label());
        createGroup(null, JcononGroups.RDP_CONCORSO.name(), JcononGroups.RDP_CONCORSO.label());
        createGroup(null, JcononGroups.APPLICATION_CONSUMER.name(), JcononGroups.APPLICATION_CONSUMER.label());
        createGroup(null, JcononGroups.GESTORI_BANDI.name(), JcononGroups.GESTORI_BANDI.label(), "[\"APP.DEFAULT\", \"AUTH.EXT.gestori\"]");
        for (ObjectType objectType : session.getTypeChildren(JCONONFolderType.JCONON_CALL.value(), false)) {
            createGroup("GROUP_GESTORI_BANDI", "GESTORI_" + objectType.getId().replace(":", "_").toUpperCase(), "GESTORI " + objectType.getDisplayName(), "[\"APP.DEFAULT\", \"AUTH.EXT.gestori\"]", "{\"jconon_group_gestori:call_type\": \"" + objectType.getId() + "\"}");
        }
        Map<String, ACLType> aces = new HashMap<String, ACLType>();
        aces.put(GroupsEnum.CONCORSI.value(), ACLType.Contributor);
        aces.put("GROUP_GESTORI_BANDI", ACLType.Contributor);
        aclService.addAcl(cmisService.getAdminSession(), competition.getProperty(CoolPropertyIds.ALFCMIS_NODEREF.value()).getValueAsString(), aces);
        try {
            CMISUser user = new CMISUser();
            user.setFirstName(guestUserName);
            user.setLastName(guestUserName);
            user.setUserName(guestUserName);
            user.setPassword(guestPassword);
            user.setEmail("anonymus@anonymus.it");
            userService.createUser(user);
            userService.enableAccount(user.getUserName());
        } catch (CoolUserFactoryException _ex) {
            LOGGER.error("Cannot create guest user in repository", _ex);
        }
    } else {
        for (QueryResult queryResult : results) {
            ObjectId objectId = session.createObjectId((String) queryResult.getPropertyById(PropertyIds.OBJECT_ID).getFirstValue());
            competition = (Folder) session.getObject(objectId);
        }
    }
    return new CmisObjectCache().id(competition.getId()).path(competition.getPath());
}
Also used : ObjectTypeCache(it.cnr.si.cool.jconon.repository.dto.ObjectTypeCache) Cacheable(org.springframework.cache.annotation.Cacheable) LoggerFactory(org.slf4j.LoggerFactory) CmisObjectNotFoundException(org.apache.chemistry.opencmis.commons.exceptions.CmisObjectNotFoundException) Autowired(org.springframework.beans.factory.annotation.Autowired) CacheEvict(org.springframework.cache.annotation.CacheEvict) BulkInfoCool(it.cnr.bulkinfo.cool.BulkInfoCool) JcononGroups(it.cnr.si.cool.jconon.util.JcononGroups) CriteriaFactory(it.cnr.si.opencmis.criteria.CriteriaFactory) CoolPropertyIds(it.cnr.cool.cmis.model.CoolPropertyIds) Repository(org.springframework.stereotype.Repository) PropertyDefinition(org.apache.chemistry.opencmis.commons.definitions.PropertyDefinition) CmisBindingsHelper(org.apache.chemistry.opencmis.client.bindings.impl.CmisBindingsHelper) Response(org.apache.chemistry.opencmis.client.bindings.spi.http.Response) ACLService(it.cnr.cool.cmis.service.ACLService) JCONONPolicyType(it.cnr.si.cool.jconon.cmis.model.JCONONPolicyType) ACLType(it.cnr.cool.cmis.model.ACLType) Collectors(java.util.stream.Collectors) CMISUser(it.cnr.cool.security.service.impl.alfresco.CMISUser) IOUtils(org.apache.commons.io.IOUtils) Stream(java.util.stream.Stream) PropertyIds(org.apache.chemistry.opencmis.commons.PropertyIds) CoolUserFactoryException(it.cnr.cool.exception.CoolUserFactoryException) CMISService(it.cnr.cool.cmis.service.CMISService) JasperCompileManager(net.sf.jasperreports.engine.JasperCompileManager) JasperReport(net.sf.jasperreports.engine.JasperReport) java.util(java.util) MimeTypes(it.cnr.cool.util.MimeTypes) ByteArrayOutputStream(java.io.ByteArrayOutputStream) JRException(net.sf.jasperreports.engine.JRException) ClassPathResource(org.springframework.core.io.ClassPathResource) BaseTypeId(org.apache.chemistry.opencmis.commons.enums.BaseTypeId) CmisObjectCache(it.cnr.si.cool.jconon.repository.dto.CmisObjectCache) Value(org.springframework.beans.factory.annotation.Value) GroupsEnum(it.cnr.cool.security.GroupsEnum) Charset(java.nio.charset.Charset) Criteria(it.cnr.si.opencmis.criteria.Criteria) CacheManager(org.springframework.cache.CacheManager) SiperService(it.cnr.si.cool.jconon.service.SiperService) UrlBuilder(org.apache.chemistry.opencmis.commons.impl.UrlBuilder) JCONONDocumentType(it.cnr.si.cool.jconon.cmis.model.JCONONDocumentType) TypeService(it.cnr.si.cool.jconon.service.TypeService) org.apache.chemistry.opencmis.client.api(org.apache.chemistry.opencmis.client.api) OutputStream(java.io.OutputStream) Logger(org.slf4j.Logger) BulkInfoRepository(it.cnr.cool.BulkInfoRepository) Output(org.apache.chemistry.opencmis.client.bindings.spi.http.Output) JCONONFolderType(it.cnr.si.cool.jconon.cmis.model.JCONONFolderType) BulkInfoCoolService(it.cnr.cool.service.BulkInfoCoolService) UserService(it.cnr.cool.security.service.UserService) I18nService(it.cnr.cool.service.I18nService) InputStream(java.io.InputStream) ACLType(it.cnr.cool.cmis.model.ACLType) CMISUser(it.cnr.cool.security.service.impl.alfresco.CMISUser) Criteria(it.cnr.si.opencmis.criteria.Criteria) CmisObjectCache(it.cnr.si.cool.jconon.repository.dto.CmisObjectCache) CoolUserFactoryException(it.cnr.cool.exception.CoolUserFactoryException) Cacheable(org.springframework.cache.annotation.Cacheable)

Example 9 with CoolUserFactoryException

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

the class SPIDIntegrationService method idpResponse.

public String idpResponse(String samlResponse) throws SAMLException, AuthenticationException {
    Response response = decodeAndValidateSamlResponse(samlResponse);
    final Map<String, String> collect = response.getAssertions().stream().map(Assertion::getAttributeStatements).flatMap(List<AttributeStatement>::stream).map(AttributeStatement::getAttributes).flatMap(List<Attribute>::stream).collect(HashMap::new, (m, attribute) -> m.put(attribute.getName(), getValue(attribute)), HashMap::putAll);
    CMISUser cmisUser = new CMISUser();
    cmisUser.setApplication(SPID);
    cmisUser.setFirstName(collect.getOrDefault(idpConfiguration.getSpidProperties().getAttribute().getName(), null));
    cmisUser.setLastName(collect.getOrDefault(idpConfiguration.getSpidProperties().getAttribute().getFamilyName(), null));
    cmisUser.setDataDiNascita(Optional.ofNullable(collect.getOrDefault(idpConfiguration.getSpidProperties().getAttribute().getDateOfBirth(), null)).filter(s -> !s.isEmpty()).map(date -> {
        try {
            return Date.from(LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
        } catch (DateTimeParseException _ex) {
            LOGGER.warn("Cannot format date of birth", _ex);
            return null;
        }
    }).orElse(null));
    cmisUser.setCodicefiscale(Optional.ofNullable(collect.getOrDefault(idpConfiguration.getSpidProperties().getAttribute().getFiscalNumber(), null)).map(cf -> cf.replaceAll("TINIT-", "")).orElse(null));
    cmisUser.setSesso(collect.getOrDefault(idpConfiguration.getSpidProperties().getAttribute().getGender(), Optional.ofNullable(cmisUser.getCodicefiscale()).map(s -> Integer.valueOf(s.substring(9, 11)) > 40 ? "F" : "M").orElse(null)));
    cmisUser.setEmail(collect.getOrDefault(idpConfiguration.getSpidProperties().getAttribute().getEmail(), " "));
    String userName = normalize(Optional.ofNullable(cmisUser.getFirstName()).map(String::trim).filter(s -> !s.isEmpty()).orElseThrow(() -> new SAMLException("First Name cannot be empty"))).toLowerCase().concat("-").concat(normalize(Optional.ofNullable(cmisUser.getLastName()).map(String::trim).filter(s -> !s.isEmpty()).orElseThrow(() -> new SAMLException("Last Name cannot be empty"))).toLowerCase());
    Optional<CMISUser> userByCodiceFiscale = Optional.ofNullable(userService.findUserByCodiceFiscale(cmisUser.getCodicefiscale(), cmisService.getAdminSession(), userName));
    if (userByCodiceFiscale.isPresent()) {
        if (!Optional.ofNullable(userByCodiceFiscale.get().getEmail()).equals(Optional.ofNullable(cmisUser.getEmail())) && Optional.ofNullable(userByCodiceFiscale.get().getApplication()).filter(s -> s.equalsIgnoreCase(SPID)).isPresent()) {
            cmisUser.setUserName(userByCodiceFiscale.get().getUserName());
            userByCodiceFiscale = Optional.ofNullable(userService.updateUser(cmisUser));
        }
        return createTicketForUser(userByCodiceFiscale.get());
    } else {
        // Verifico se l'utenza ha lo stesso codice fiscale
        try {
            Optional<CMISUser> cmisUser2 = Optional.ofNullable(userService.loadUserForConfirm(userName)).filter(cmisUser1 -> cmisUser1.getCodicefiscale().equalsIgnoreCase(cmisUser.getCodicefiscale()));
            if (cmisUser2.isPresent()) {
                if (!Optional.ofNullable(cmisUser2.get().getEmail()).equals(Optional.ofNullable(cmisUser.getEmail())) && Optional.ofNullable(cmisUser2.get().getApplication()).filter(s -> s.equalsIgnoreCase(SPID)).isPresent()) {
                    cmisUser.setUserName(cmisUser2.get().getUserName());
                    cmisUser2 = Optional.ofNullable(userService.updateUser(cmisUser));
                }
                return createTicketForUser(cmisUser2.get());
            }
        } catch (CoolUserFactoryException _ex) {
            LOGGER.trace("SPID Username {} not found", userName);
        }
        if (!userService.isUserExists(userName)) {
            cmisUser.setUserName(userName);
        } else {
            for (int i = 1; i < 20; i++) {
                final String concatUsername = userName.concat("0").concat(String.valueOf(i));
                if (!userService.isUserExists(concatUsername)) {
                    cmisUser.setUserName(concatUsername);
                    break;
                }
            }
        }
        final CMISUser user = userService.createUser(cmisUser);
        userService.enableAccount(user.getUserName());
        return createTicketForUser(user);
    }
}
Also used : XSString(org.opensaml.xml.schema.XSString) org.opensaml.saml2.core.impl(org.opensaml.saml2.core.impl) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) SPIDRequest(it.cnr.si.cool.jconon.spid.model.SPIDRequest) org.opensaml.xml.signature(org.opensaml.xml.signature) DefaultBootstrap(org.opensaml.DefaultBootstrap) IdpConfiguration(it.cnr.si.cool.jconon.spid.config.IdpConfiguration) BasicSecurityConfiguration(org.opensaml.xml.security.BasicSecurityConfiguration) HttpStatus(org.apache.commons.httpclient.HttpStatus) ValidationException(org.opensaml.xml.validation.ValidationException) Resource(org.springframework.core.io.Resource) CmisBindingsHelper(org.apache.chemistry.opencmis.client.bindings.impl.CmisBindingsHelper) MarshallingException(org.opensaml.xml.io.MarshallingException) java.security(java.security) ResourceBackedMetadataProvider(org.opensaml.saml2.metadata.provider.ResourceBackedMetadataProvider) SignatureException(java.security.SignatureException) ResourceException(org.opensaml.util.resource.ResourceException) Deflater(java.util.zip.Deflater) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) ZoneId(java.time.ZoneId) CMISUser(it.cnr.cool.security.service.impl.alfresco.CMISUser) Signature(org.opensaml.xml.signature.Signature) X509Credential(org.opensaml.xml.security.x509.X509Credential) DateTimeParseException(java.time.format.DateTimeParseException) Stream(java.util.stream.Stream) SecurityException(org.opensaml.xml.security.SecurityException) SPIDRepository(it.cnr.si.cool.jconon.spid.repository.SPIDRepository) Environment(org.springframework.core.env.Environment) SAXException(org.xml.sax.SAXException) LocalDate(java.time.LocalDate) AbstractReloadingMetadataProvider(org.opensaml.saml2.metadata.provider.AbstractReloadingMetadataProvider) CoolUserFactoryException(it.cnr.cool.exception.CoolUserFactoryException) SecurityHelper(org.opensaml.xml.security.SecurityHelper) CMISService(it.cnr.cool.cmis.service.CMISService) java.util(java.util) KeyDescriptor(org.opensaml.saml2.metadata.KeyDescriptor) BasicX509Credential(org.opensaml.xml.security.x509.BasicX509Credential) Scheduled(org.springframework.scheduling.annotation.Scheduled) DeflaterOutputStream(java.util.zip.DeflaterOutputStream) InitializingBean(org.springframework.beans.factory.InitializingBean) Base64(org.opensaml.xml.util.Base64) Credential(org.opensaml.xml.security.credential.Credential) Inject(javax.inject.Inject) Service(org.springframework.stereotype.Service) PageService(it.cnr.cool.service.PageService) UrlBuilder(org.apache.chemistry.opencmis.commons.impl.UrlBuilder) XMLObjectBuilderFactory(org.opensaml.xml.XMLObjectBuilderFactory) SAMLException(org.opensaml.common.SAMLException) InputSource(org.xml.sax.InputSource) org.opensaml.saml2.core(org.opensaml.saml2.core) Logger(org.slf4j.Logger) EntityDescriptor(org.opensaml.saml2.metadata.EntityDescriptor) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) DateTime(org.joda.time.DateTime) AuthenticationException(it.cnr.si.cool.jconon.spid.config.AuthenticationException) CertificateException(java.security.cert.CertificateException) PageModel(it.cnr.cool.service.PageModel) SAMLVersion(org.opensaml.common.SAMLVersion) ApplicationContext(org.springframework.context.ApplicationContext) IdpEntry(it.cnr.si.cool.jconon.spid.model.IdpEntry) XSAny(org.opensaml.xml.schema.XSAny) Normalizer(java.text.Normalizer) KeyInfoHelper(org.opensaml.xml.security.keyinfo.KeyInfoHelper) DOMParser(com.sun.org.apache.xerces.internal.parsers.DOMParser) Element(org.w3c.dom.Element) Marshaller(org.opensaml.xml.io.Marshaller) java.io(java.io) UnmarshallingException(org.opensaml.xml.io.UnmarshallingException) BasicParserPool(org.opensaml.xml.parse.BasicParserPool) IDPSSODescriptor(org.opensaml.saml2.metadata.IDPSSODescriptor) DateTimeFormatter(java.time.format.DateTimeFormatter) Configuration(org.opensaml.xml.Configuration) ResponseSchemaValidator(org.opensaml.saml2.core.validator.ResponseSchemaValidator) MetadataProviderException(org.opensaml.saml2.metadata.provider.MetadataProviderException) UserService(it.cnr.cool.security.service.UserService) XMLHelper(org.opensaml.xml.util.XMLHelper) I18nService(it.cnr.cool.service.I18nService) ConfigurationException(org.opensaml.xml.ConfigurationException) CMISUser(it.cnr.cool.security.service.impl.alfresco.CMISUser) XSString(org.opensaml.xml.schema.XSString) SAMLException(org.opensaml.common.SAMLException) DateTimeParseException(java.time.format.DateTimeParseException) CoolUserFactoryException(it.cnr.cool.exception.CoolUserFactoryException)

Example 10 with CoolUserFactoryException

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

the class PrintService method getCurriculumStrutturatoReportModel.

public byte[] getCurriculumStrutturatoReportModel(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());
    } 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_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));
    }
    String labelSottoscritto = i18nService.getLabel("application.text.sottoscritto.lower." + application.getPropertyValue(JCONONPropertyIds.APPLICATION_SESSO.value()), locale);
    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 {
        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());
        ClassLoader classLoader = ClassLoader.getSystemClassLoader();
        parameters.put(JRParameter.REPORT_CLASS_LOADER, classLoader);
        JasperReport jasperReport = cacheRepository.jasperReport(PRINT_RESOURCE_PATH + "CurriculumStrutturato.jrxml", jasperCompileManager());
        JasperPrint jasperPrint = jasperFillManager().fill(jasperReport, parameters);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        JRDocxExporter export = new JRDocxExporter();
        export.setExporterInput(new SimpleExporterInput(jasperPrint));
        export.setExporterOutput(new SimpleOutputStreamExporterOutput(os));
        SimpleDocxReportConfiguration config = new SimpleDocxReportConfiguration();
        // Set desired configuration
        config.setFlexibleRowHeight(false);
        config.setFramesAsNestedTables(false);
        export.setConfiguration(config);
        export.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) SimpleOutputStreamExporterOutput(net.sf.jasperreports.export.SimpleOutputStreamExporterOutput) ApplicationModel(it.cnr.si.cool.jconon.model.ApplicationModel) CMISApplicationException(it.cnr.cool.web.scripts.exception.CMISApplicationException) SimpleDocxReportConfiguration(net.sf.jasperreports.export.SimpleDocxReportConfiguration) JRDocxExporter(net.sf.jasperreports.engine.export.ooxml.JRDocxExporter) JsonDataSource(net.sf.jasperreports.engine.data.JsonDataSource) JRGzipVirtualizer(net.sf.jasperreports.engine.fill.JRGzipVirtualizer) SimpleExporterInput(net.sf.jasperreports.export.SimpleExporterInput) 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)

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