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);
}
}
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);
}
}
}
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());
}
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);
}
}
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);
}
}
Aggregations