protected IDatabaseManager.DatabaseType getType(DataSource dataSource) throws ApsSystemException { String typeString = null; try { String driverClassName = this.invokeGetMethod("getDriverClassName", dataSource); Iterator<Object> typesIter = this.getDatabaseTypeDrivers().keySet().iterator(); while (typesIter.hasNext()) { String typeCode = (String) typesIter.next(); List<String> driverClassNames = (List<String>) this.getDatabaseTypeDrivers().get(typeCode); if (null != driverClassNames && driverClassNames.contains(driverClassName)) { typeString = typeCode; break; } } if (null == typeString) { ApsSystemUtils.getLogger() .severe( "Type not recognized for Driver '" + driverClassName + "' - " + "Recognized types '" + IDatabaseManager.DatabaseType.values() + "'"); return IDatabaseManager.DatabaseType.UNKNOWN; } return Enum.valueOf(IDatabaseManager.DatabaseType.class, typeString.toUpperCase()); } catch (Throwable t) { ApsSystemUtils.getLogger() .severe("Invalid type for db - '" + typeString + "' - " + t.getMessage()); throw new ApsSystemException("Invalid type for db - '" + typeString + "'", t); } }
/** * Verify the validity of the Authority. * * @param authority The authority to verify. * @return True if the authority is valid, else false. */ protected boolean checkAuthority(IApsAuthority authority) { if (null == authority) { ApsSystemUtils.getLogger().severe("Invalid authority detected"); // "Required Users by null authority"; return false; } IApsAuthority authForCheck = this.getAuthority(authority.getAuthority()); if (null == authForCheck) { ApsSystemUtils.getLogger() .severe("The authority with code " + authority.getAuthority() + " does not exist"); // "Required Users by not existing authority : code " + authority.getAuthority()); return false; } if (!authForCheck.getClass().equals(authority.getClass())) { ApsSystemUtils.getLogger() .severe( "Mismatching authority classes detected; code " + authority.getAuthority() + " - Class " + authority.getClass() + " is different by " + authForCheck.getClass()); // "Required Users by invalid authority: code " + authority.getAuthority() + " - Class " + // authority.getClass()); return false; } return true; }
protected boolean checkNode(String nodeCode, Collection<String> groupCodes) { if (!this.isNodeAllowed(nodeCode, groupCodes)) { ApsSystemUtils.getLogger().severe("Node '" + nodeCode + "' not allowed "); return false; } ITreeNode treeNode = this.getTreeNode(nodeCode); if (null == treeNode) { ApsSystemUtils.getLogger().severe("Node '" + nodeCode + "' null "); return false; } return true; }
public Map<String, ApiMethod> getRelatedShowletMethods() throws ApsSystemException { Map<String, ApiMethod> mapping = new HashMap<String, ApiMethod>(); try { List<ApiMethod> masterMethods = this.getMasterMethods(ApiMethod.HttpMethod.GET); for (int i = 0; i < masterMethods.size(); i++) { ApiMethod apiMethod = masterMethods.get(i); ApiMethodRelatedShowlet relatedShowlet = apiMethod.getRelatedShowlet(); if (null != relatedShowlet) { String showletCode = relatedShowlet.getShowletCode(); if (mapping.containsKey(showletCode)) { ApiMethod alreadyMapped = mapping.get(showletCode); String alertMessage = "There is more than one method related whith showlet '" + showletCode + "' - " + "Actual mapped '" + alreadyMapped.getResourceName() + "'; other method '" + apiMethod.getResourceName() + "'"; ApsSystemUtils.getLogger().severe(alertMessage); } else { mapping.put(showletCode, apiMethod.clone()); } } } } catch (Throwable t) { ApsSystemUtils.logThrowable( t, this, "getRelatedShowletMethods", "Error loading related showlet methods"); throw new ApsSystemException("Error loading related showlet methods", t); } return mapping; }
protected String extractTemplate(ApiMethod apiMethod) throws Exception { String template = null; InputStream is = null; try { StringBuffer path = new StringBuffer("classpath*:/api/"); if (null != apiMethod.getPluginCode()) { path.append("plugins/" + apiMethod.getPluginCode() + "/"); } else if (!apiMethod.getSource().equalsIgnoreCase("core")) { path.append(apiMethod.getSource() + "/"); } path.append("aps/get/" + apiMethod.getResourceName() + "/description-item.vm"); Resource[] resources = ApsWebApplicationUtils.getResources(path.toString(), this.getServletContext()); if (null != resources && resources.length == 1) { Resource resource = resources[0]; is = resource.getInputStream(); } if (null == is) { ApsSystemUtils.getLogger() .info("Null Input Stream - template file path " + path.toString()); return null; } template = FileTextReader.getText(is); } catch (Throwable t) { String message = "Error extracting template - " + this.buildApiSignature(apiMethod); ApsSystemUtils.logThrowable(t, this, "extractTemplate", message); } finally { if (null != is) { is.close(); } } return template; }
/** * Invia i contenuti dati agli utenti registrati alla newsletter discriminando, per ogni utente, i * contenuti a lui visibili e per i quali ha fatto implicita richiesta nel proprio profilo. * * @param contents La lista dei contenuti da inviare tramite newsletter. * @throws ApsSystemException In caso di errore. */ protected void sendNewsletterToUsers(List<Content> contents) throws ApsSystemException { try { Map<String, List<String>> profileAttributes = this.prepareProfileAttributesForContents(contents); NewsletterReport newsletterReport = this.prepareNewsletterReport(contents); Set<String> usernames = this.extractUsernames(); if (null != usernames && usernames.size() > 0) { Iterator<String> userIter = usernames.iterator(); while (userIter.hasNext()) { String username = (String) userIter.next(); UserDetails user = this.getUserManager().getUser(username); if (null != user && !user.isDisabled()) { this.sendNewsletterToUser(username, contents, profileAttributes, newsletterReport); } } } else { ApsSystemUtils.getLogger().severe("Newsletter: no receivers to send newsletter to!"); } this.sendNewsletterToSubscribers(contents, newsletterReport); this.addNewsletterReport(newsletterReport); } catch (Throwable t) { ApsSystemUtils.logThrowable(t, this, "sendNewsletterToUsers"); throw new ApsSystemException("Error sending Newsletter To Users ", t); } }
private String prepareSubscribersMailBody( List<Content> userContents, NewsletterReport newsletterReport, boolean isHtml, String mailAddress) { NewsletterConfig config = this.getConfig(); String unsubscriptionLink = isHtml ? config.getSubscribersHtmlFooter() : config.getSubscribersTextFooter(); if (unsubscriptionLink != null) { StringBuffer body = this.prepareMailCommonBody(userContents, newsletterReport, isHtml); String link = this.createUnsubscriptionLink(mailAddress); Map<String, String> footerParams = new HashMap<String, String>(); footerParams.put("unsubscribeLink", link); String unlink = this.parseText(unsubscriptionLink, footerParams); body.append(unlink); return body.toString(); } else { ApsSystemUtils.getLogger() .warning( "Incomplete configuration for newsletter subscribers! CHECK " + JpnewsletterSystemConstants.NEWSLETTER_CONFIG_ITEM + " item!!"); return this.prepareMailBody(userContents, newsletterReport, isHtml); } }
protected NewsletterReport prepareNewsletterReport(List<Content> contents) { NewsletterConfig config = this.getConfig(); NewsletterReport newsletterReport = new NewsletterReport(); newsletterReport.setSubject(config.getSubject()); newsletterReport.setSendDate(new Date()); String defaultLang = this.getLangManager().getDefaultLang().getCode(); boolean alsoHtml = config.isAlsoHtml(); for (Content content : contents) { boolean isConfiguredWithModels = false; ContentReport contentReport = new ContentReport(); contentReport.setContentId(content.getId()); String textBodyPart = this.prepareMailBodyContentPart(content, defaultLang, false); if (null != textBodyPart) { isConfiguredWithModels = true; contentReport.setTextBody(textBodyPart); } if (alsoHtml) { String htmlBodyPart = this.prepareMailBodyContentPart(content, defaultLang, true); contentReport.setHtmlBody(htmlBodyPart); } if (isConfiguredWithModels) { newsletterReport.addContentReport(contentReport); } else { ApsSystemUtils.getLogger() .info( " Newsletter content " + content.getId() + " not added, because has not model in config."); } } return newsletterReport; }
@Override public List<Shortcut> getAllowedShortcuts(UserDetails user) throws ApsSystemException { List<Shortcut> allowedShortcuts = new ArrayList<Shortcut>(); if (null == user) { ApsSystemUtils.getLogger().info("Required allowed shortcut for null user"); return allowedShortcuts; } try { Iterator<Shortcut> shorCutIter = this.getShortcuts().values().iterator(); while (shorCutIter.hasNext()) { Shortcut shortcut = shorCutIter.next(); String permissionName = shortcut.getRequiredPermission(); if (null == permissionName || this.getAuthorizationManager().isAuthOnPermission(user, permissionName)) { allowedShortcuts.add(shortcut.clone()); } } } catch (Throwable t) { ApsSystemUtils.logThrowable(t, this, "getAllowedShortcuts"); throw new ApsSystemException( "Error extracting allowed shortcuts by user " + user.getUsername(), t); } BeanComparator comparator = new BeanComparator("source"); Collections.sort(allowedShortcuts, comparator); return allowedShortcuts; }
@Override public boolean isAuth(UserDetails user, Content content) throws ApsSystemException { if (null == content) { ApsSystemUtils.getLogger().severe("Null content"); return false; } Set<String> groupCodes = this.getContentGroups(content); return this.isAuth(user, groupCodes); }
private boolean isAuthToEdit(UserDetails user, String mainGroupName) throws ApsSystemException { if (null == user) { ApsSystemUtils.getLogger().severe("Null user"); return false; } return (this.getAuthorizationManager() .isAuthOnPermission(user, JacmsSystemConstants.PERMISSION_EDIT_CONTENTS) && this.getAuthorizationManager().isAuthOnGroup(user, mainGroupName)); }
@Override public boolean isAuthToEdit(UserDetails user, Content content) throws ApsSystemException { if (null == content) { ApsSystemUtils.getLogger().severe("Null content"); return false; } String mainGroupName = content.getMainGroup(); return this.isAuthToEdit(user, mainGroupName); }
protected Object extractBean(ApiMethod api) throws ApsSystemException, ApiException { Object bean = this.getBeanFactory().getBean(api.getSpringBean()); if (null == bean) { ApsSystemUtils.getLogger() .severe("Null bean '" + api.getSpringBean() + "' for api " + this.buildApiSignature(api)); throw new ApiException( IApiErrorCodes.SERVER_ERROR, this.buildApiSignature(api) + " is not supported"); } return bean; }
@Override public UserConfigBean saveUserConfigBean(UserDetails user, UserConfigBean userConfig) throws ApsSystemException { if (null == user || null == userConfig || userConfig.getUsername().equals(user.getUsername())) { ApsSystemUtils.getLogger().info("Required operation for null user or invalid user config"); return null; } String[] config = this.saveUserConfig(user, userConfig.getConfig()); return new UserConfigBean(user.getUsername(), config); }
private void decodeDOM(String xml) throws ApsSystemException { SAXBuilder builder = new SAXBuilder(); builder.setValidation(false); StringReader reader = new StringReader(xml); try { this._doc = builder.build(reader); } catch (Throwable t) { ApsSystemUtils.getLogger().error("Error while parsing: " + t.getMessage()); throw new ApsSystemException("Error detected while parsing the XML", t); } }
/** * Costruttore dello scheduler * * @param task Task da eseguire. * @param start Data di partenza dello scheduler * @param delay Intervallo di schedulazione in millisecondi */ public Scheduler(Task task, Date start, long delay) { this._timer = new Timer(); this._task = task; this._timer.schedule(this, start, delay); ApsSystemUtils.getLogger() .trace( "jpcontentworkflow: Scheduler - StartTime: " + DateConverter.getFormattedDate(start, "dd/MM/yyyy HH:mm:ss") + " - Delay: " + delay); }
@Override public void updateNewsletterConfig(NewsletterConfig config) throws ApsSystemException { Date originalStartDate = null; try { originalStartDate = this.getConfig().getStartScheduler(); String xml = new NewsletterConfigDOM().createConfigXml(config); this.getConfigManager() .updateConfigItem(JpnewsletterSystemConstants.NEWSLETTER_CONFIG_ITEM, xml); this.setConfig(config); // restart the scheduler if necessary if (originalStartDate.getTime() != config.getStartScheduler().getTime()) { ApsSystemUtils.getLogger().info("Newsletter: scheduler restart issued"); stopScheduler(); restartScheduler(config); ApsSystemUtils.getLogger().info("Newsletter: scheduler restart completed"); } } catch (Throwable t) { ApsSystemUtils.logThrowable(t, this, "updateNewsletterConfig"); throw new ApsSystemException("Errore in fase di aggiornamento configurazione newsletter", t); } }
protected void sendNewsletterFromThread() throws ApsSystemException { synchronized (this) { if (this.isSendingNewsletter()) { return; } else { this.setSendingNewsletter(true); } } try { ApsSystemUtils.getLogger().info("Newletter: delivery process initiated"); if (!this.getConfig().isActive()) return; List<String> contentIds = this.getContentQueue(); if (contentIds.size() > 0) { List<Content> contents = new ArrayList<Content>(contentIds.size()); for (int i = 0; i < contentIds.size(); i++) { String id = contentIds.get(i); Content content = this.getContentManager().loadContent(id, true); if (content != null) { contents.add(content); } } if (contents.size() > 0) { this.sendNewsletterToUsers(contents); } else { ApsSystemUtils.getLogger() .info( "Newletter: had some contents ids selected, corresponding to no actual content: this is quite strange!"); } this.getNewsletterDAO().cleanContentQueue(contentIds); } else { ApsSystemUtils.getLogger().info("Newletter: no contents found for delivery"); } ApsSystemUtils.getLogger().info("Newletter: delivery process completed"); } catch (Throwable t) { ApsSystemUtils.getLogger().info("Newletter: delivery process ended abnormally"); ApsSystemUtils.logThrowable(t, this, "sendNewsletterFromThread"); } finally { this.setSendingNewsletter(false); } }
/** * Returns the Xml element from a given text. * * @param xmlText The text containing an Xml. * @return The Xml element from a given text. * @throws ApsSystemException In case of parsing exceptions. */ private Element getRootElement(String xmlText) throws ApsSystemException { SAXBuilder builder = new SAXBuilder(); builder.setValidation(false); StringReader reader = new StringReader(xmlText); Element root = null; try { Document doc = builder.build(reader); root = doc.getRootElement(); } catch (Throwable t) { ApsSystemUtils.getLogger().severe("Error parsing xml: " + t.getMessage()); throw new ApsSystemException("Error parsing xml", t); } return root; }
protected void loadResources() throws ApsSystemException { try { ApiResourceLoader loader = new ApiResourceLoader(this.getLocationPatterns(), this.getServletContext()); Map<String, ApiResource> resources = loader.getResources(); this.setMasterResources(resources); ApsSystemUtils.getLogger().config(this.getClass().getName() + ": initialized Api Methods"); this.getApiCatalogDAO().loadApiStatus(resources); } catch (Throwable t) { ApsSystemUtils.logThrowable( t, this, "loadResources", "Error loading Api Resources definitions"); throw new ApsSystemException("Error loading Api Resources definitions", t); } }
protected boolean isAuth(UserDetails user, Set<String> groupCodes) throws ApsSystemException { if (null == user) { ApsSystemUtils.getLogger().severe("Null user"); return false; } if (groupCodes.contains(Group.FREE_GROUP_NAME)) return true; List<Group> userGroups = this.getAuthorizationManager().getGroupsOfUser(user); if (null != userGroups) { for (int i = 0; i < userGroups.size(); i++) { Group group = userGroups.get(i); if (groupCodes.contains(group.getName())) return true; } } return false; }
@Override public String[] saveUserConfig(UserDetails user, String[] config) throws ApsSystemException { if (null == user) { ApsSystemUtils.getLogger().info("Required operation for null user"); return null; } try { config = this.checkShortcutConfig(user, config); String xml = UserShortcutConfigDOM.createUserConfigXml(config); this.getUserShortcutDAO().saveUserConfig(user.getUsername(), xml); } catch (Throwable t) { ApsSystemUtils.logThrowable(t, this, "saveUserConfig"); throw new ApsSystemException("Error saving user config by user " + user.getUsername(), t); } return config; }
@Override public void setUserAuthorizations(String username, List<IApsAuthority> authorities) throws ApsSystemException { for (int i = 0; i < authorities.size(); i++) { IApsAuthority authorityToVerify = authorities.get(i); if (!this.checkAuthority(authorityToVerify)) { ApsSystemUtils.getLogger().severe("Attempt to set invalid authority to user " + username); return; } } try { this.getAuthorizatorDAO().setUserAuthorizations(username, authorities); } catch (Throwable t) { ApsSystemUtils.logThrowable(t, this, "setUserAuthorizations"); throw new ApsSystemException("Error detected while granting user authorizations", t); } }
@Override public String[] getUserConfig(UserDetails user) throws ApsSystemException { String[] config = null; if (null == user) { ApsSystemUtils.getLogger().info("Required shortcut config for null user"); return null; } try { String xml = this.getUserShortcutDAO().loadUserConfig(user.getUsername()); config = UserShortcutConfigDOM.extractUserConfig(xml, this.getUserShortcutsMaxNumber()); config = this.checkShortcutConfig(user, config); } catch (Throwable t) { ApsSystemUtils.logThrowable(t, this, "getUserConfig"); throw new ApsSystemException("Error loading user config", t); } return config; }
public String joinContentLink() { ContentRecordVO contentVo = this.getContentVo(this.getContentId()); if (null == contentVo || !contentVo.isOnLine()) { ApsSystemUtils.getLogger() .severe("Contenuto '" + this.getContentId() + "' INESISTENTE O NON PUBBLICO"); return FAILURE; } if (this.isContentOnPageType()) { // Fa il forward alla scelta pagina di destinazione return "configContentOnPageLink"; } else { String[] destinations = {null, this.getContentId(), null}; this.buildEntryContentAnchorDest(); this.getLinkAttributeHelper() .joinLink(destinations, SymbolicLink.CONTENT_TYPE, this.getRequest()); return SUCCESS; } }
protected void sendSubscriptionFormThread(String mailAddress, String token) throws ApsSystemException { try { NewsletterConfig config = this.getConfig(); String senderCode = config.getSenderCode(); String subject = config.getSubscriptionSubject(); if (subject != null) { Map<String, String> bodyParams = new HashMap<String, String>(); String link = this.createLink(mailAddress, token); bodyParams.put("subscribeLink", link); String textBody = this.parseText(config.getSubscriptionTextBody(), bodyParams); String[] recipientsTo = new String[] {mailAddress}; if (config.isAlsoHtml()) { String htmlBody = this.parseText(config.getSubscriptionHtmlBody(), bodyParams); this.getMailManager() .sendMixedMail( textBody, htmlBody, subject, null, recipientsTo, null, null, senderCode); } else { this.getMailManager() .sendMail( textBody, subject, recipientsTo, null, null, senderCode, IMailManager.CONTENTTYPE_TEXT_PLAIN); } } else { ApsSystemUtils.getLogger() .warning( "Incomplete configuration for newsletter subscribers! CHECK " + JpnewsletterSystemConstants.NEWSLETTER_CONFIG_ITEM + " item!!"); } } catch (Throwable t) { ApsSystemUtils.logThrowable(t, this, "sendMail"); throw new ApsSystemException( "Error sending email for subscription confirmation request to address " + mailAddress, t); } }
protected void loadShortcuts() { try { ShortcutLoader loader = new ShortcutLoader(this.getLocationPatterns(), this.getServletContext()); this.setMenuSections(loader.getManuSections()); this.setShortcuts(loader.getShortcuts()); ApsSystemUtils.getLogger() .config( this.getClass().getName() + ": initialized - " + "Sections menu " + this.getMenuSections().size() + " - Shortcuts " + this.getShortcuts().size()); } catch (Throwable t) { this.setMenuSections(new HashMap<String, MenuSection>()); this.setShortcuts(new HashMap<String, Shortcut>()); ApsSystemUtils.logThrowable(t, this, "loadShortcuts", "Error loading Shortcut definitions"); } }
@Override public TreeNodeWrapper getShowableTree( Set<String> treeNodesToOpen, ITreeNode fullTree, Collection<String> groupCodes) throws ApsSystemException { if (null == treeNodesToOpen || treeNodesToOpen.isEmpty()) { ApsSystemUtils.getLogger().info("No selected nodes"); return new TreeNodeWrapper(fullTree); } TreeNodeWrapper root = null; try { Set<String> checkNodes = new HashSet<String>(); this.buildCheckNodes(treeNodesToOpen, checkNodes, groupCodes); root = new TreeNodeWrapper(fullTree); root.setParent(root); this.builShowableTree(root, null, fullTree, checkNodes); } catch (Throwable t) { ApsSystemUtils.logThrowable(t, this, "getShowableTree"); throw new ApsSystemException("Error creating showalble tree", t); } return root; }
@Override public String resolveLink(SymbolicLink symbolicLink, RequestContext reqCtx) { if (null == symbolicLink) { ApsSystemUtils.getLogger().severe("Null Symbolic Link"); return ""; } String url = null; try { if (symbolicLink.getDestType() == SymbolicLink.URL_TYPE) { url = symbolicLink.getUrlDest(); } else if (symbolicLink.getDestType() == SymbolicLink.PAGE_TYPE) { PageURL pageUrl = this.getUrlManager().createURL(reqCtx); pageUrl.setPageCode(symbolicLink.getPageDest()); url = pageUrl.getURL(); } else if (symbolicLink.getDestType() == SymbolicLink.CONTENT_ON_PAGE_TYPE) { PageURL pageUrl = this.getUrlManager().createURL(reqCtx); pageUrl.setPageCode(symbolicLink.getPageDest()); pageUrl.addParam(SystemConstants.K_CONTENT_ID_PARAM, symbolicLink.getContentDest()); url = pageUrl.getURL(); } else if (symbolicLink.getDestType() == SymbolicLink.CONTENT_TYPE) { PageURL pageUrl = this.getUrlManager().createURL(reqCtx); String contentId = symbolicLink.getContentDest(); String pageCode = this.getContentPageMapperManager().getPageCode(contentId); boolean forwardToDefaultPage = !this.isPageAllowed(reqCtx, pageCode); if (forwardToDefaultPage) { String viewPageCode = this.getContentManager().getViewPage(contentId); pageUrl.setPageCode(viewPageCode); pageUrl.addParam(SystemConstants.K_CONTENT_ID_PARAM, contentId); } else { pageUrl.setPageCode(pageCode); } url = pageUrl.getURL(); } } catch (Throwable t) { ApsSystemUtils.logThrowable(t, this, "resolveLink", "Error resolve link from SymbolicLink"); throw new RuntimeException("Error resolve link from SymbolicLink", t); } return url; }
public InputStream getInputStream() { InputStream documentInputStream = null; try { String resourceId = this.getResourceId(); if (null == resourceId || resourceId.length() == 0) { return null; } ResourceInterface resource = this.getTrashedResourceManager().loadTrashedResource(resourceId); String mainGroup = resource.getMainGroup(); UserDetails currentUser = this.getCurrentUser(); if (!this.getAuthManager().isAuthOnGroup(currentUser, mainGroup)) { return null; } int size = Integer.parseInt(this.getSize()); ResourceInstance instance = null; String path = null; if (resource.isMultiInstance()) { instance = ((AbstractMultiInstanceResource) resource).getInstance(size, getLangCode()); Map<String, String> trashPathsForInstances = getTrashedResourceManager().resourceInstancesTrashFilePaths(resource); path = trashPathsForInstances.get(this.getSize()); } else { instance = ((AbstractMonoInstanceResource) resource).getInstance(); Map<String, String> trashPathsForInstances = getTrashedResourceManager().resourceInstancesTrashFilePaths(resource); path = trashPathsForInstances.get("0"); } this.setContentType(instance.getMimeType()); this.setNameFile(instance.getFileName()); File fileTemp = new File(path); ApsSystemUtils.getLogger().info(" path " + fileTemp); if (fileTemp.exists()) { documentInputStream = new FileInputStream(fileTemp); } } catch (Throwable t) { ApsSystemUtils.logThrowable(t, this, "getInputStream"); } return documentInputStream; }