List of usage examples for org.springframework.web.jsf FacesContextUtils getRequiredWebApplicationContext
public static WebApplicationContext getRequiredWebApplicationContext(FacesContext fc) throws IllegalStateException
From source file:org.alfresco.web.bean.wcm.DeployWebsiteDialog.java
@SuppressWarnings("unchecked") @Override/*from w ww .j av a 2 s .co m*/ protected String finishImpl(FacesContext context, String outcome) throws Exception { if (logger.isDebugEnabled()) logger.debug("Requesting deployment of: " + this.websiteRef.toString()); if (this.deployTo != null && this.deployTo.length > 0) { // get the unprotected NodeService and PermissionService for this dialog otherwise // 'AddChildren' permission would be required on the web project node for all users WebApplicationContext wac = FacesContextUtils.getRequiredWebApplicationContext(context); NodeService unprotectedNodeService = (NodeService) wac.getBean("nodeService"); PermissionService unprotectedPermissionService = (PermissionService) wac.getBean("permissionService"); List<String> selectedDeployToNames = new ArrayList<String>(); // create a deploymentattempt node to represent this deployment String attemptId = GUID.generate(); Map<QName, Serializable> props = new HashMap<QName, Serializable>(8, 1.0f); props.put(WCMAppModel.PROP_DEPLOYATTEMPTID, attemptId); props.put(WCMAppModel.PROP_DEPLOYATTEMPTTYPE, this.deployMode); props.put(WCMAppModel.PROP_DEPLOYATTEMPTSTORE, this.store); props.put(WCMAppModel.PROP_DEPLOYATTEMPTVERSION, this.versionToDeploy); props.put(WCMAppModel.PROP_DEPLOYATTEMPTTIME, new Date()); NodeRef attempt = unprotectedNodeService .createNode(this.webProjectRef, WCMAppModel.ASSOC_DEPLOYMENTATTEMPT, WCMAppModel.ASSOC_DEPLOYMENTATTEMPT, WCMAppModel.TYPE_DEPLOYMENTATTEMPT, props) .getChildRef(); // allow anyone to add child nodes to the deploymentattempt node unprotectedPermissionService.setPermission(attempt, PermissionService.ALL_AUTHORITIES, PermissionService.ADD_CHILDREN, true); // execute a deploy action for each of the selected remote servers asynchronously for (String targetServer : this.deployTo) { if (targetServer.length() > 0) { NodeRef serverRef = new NodeRef(targetServer); if (unprotectedNodeService.exists(serverRef)) { // get all properties of the target server Map<QName, Serializable> serverProps = unprotectedNodeService.getProperties(serverRef); String url = (String) serverProps.get(WCMAppModel.PROP_DEPLOYSERVERURL); String serverUri = AVMDeployWebsiteAction.calculateServerUri(serverProps); String serverName = (String) serverProps.get(WCMAppModel.PROP_DEPLOYSERVERNAME); if (serverName == null || serverName.length() == 0) { serverName = serverUri; } // if this is a test server deployment we need to allocate the // test server to the current sandbox so it can re-use it and // more importantly, no one else can. Before doing that however, // we need to make sure no one else has taken the server since // we selected it. if (WCMAppModel.CONSTRAINT_TESTSERVER.equals(this.deployMode) && this.updateTestServer == false) { String allocatedTo = (String) serverProps.get(WCMAppModel.PROP_DEPLOYSERVERALLOCATEDTO); if (allocatedTo != null) { throw new AlfrescoRuntimeException("testserver.taken", new Object[] { serverName }); } else { unprotectedNodeService.setProperty(serverRef, WCMAppModel.PROP_DEPLOYSERVERALLOCATEDTO, this.store); } } if (logger.isDebugEnabled()) logger.debug("Issuing deployment request for: " + serverName); // remember the servers deployed to selectedDeployToNames.add(serverName); // create a deployment monitor object, store in the session, // add to avm browse bean and pass to action DeploymentMonitor monitor = new DeploymentMonitor(this.websiteRef, serverRef, versionToDeploy, serverName, attemptId, url); context.getExternalContext().getSessionMap().put(monitor.getId(), monitor); this.avmBrowseBean.getDeploymentMonitorIds().add(monitor.getId()); // create and execute the action asynchronously Map<String, Serializable> args = new HashMap<String, Serializable>(1, 1.0f); args.put(AVMDeployWebsiteAction.PARAM_WEBPROJECT, webProjectRef); args.put(AVMDeployWebsiteAction.PARAM_SERVER, serverRef); args.put(AVMDeployWebsiteAction.PARAM_ATTEMPT, attempt); args.put(AVMDeployWebsiteAction.PARAM_CALLBACK, monitor); Action action = getActionService().createAction(AVMDeployWebsiteAction.NAME, args); getActionService().executeAction(action, this.websiteRef, false, true); } else if (logger.isWarnEnabled()) { logger.warn("target server '" + targetServer + "' was ignored as it no longer exists!"); } } } // now we know the list of selected servers set the property on the attempt node unprotectedNodeService.setProperty(attempt, WCMAppModel.PROP_DEPLOYATTEMPTSERVERS, (Serializable) selectedDeployToNames); // set the deploymentattempid property on the store this deployment was for getAvmService().deleteStoreProperty(this.store, SandboxConstants.PROP_LAST_DEPLOYMENT_ID); getAvmService().setStoreProperty(this.store, SandboxConstants.PROP_LAST_DEPLOYMENT_ID, new PropertyValue(DataTypeDefinition.TEXT, attemptId)); // close this dialog and immediately open the monitorDeployment dialog Map<String, String> params = new HashMap<String, String>(2); params.put("webproject", this.webProjectRef.toString()); params.put("calledFromTaskDialog", this.calledFromTaskDialog); Application.getDialogManager().setupParameters(params); return "dialog:monitorDeployment"; } else { if (logger.isWarnEnabled()) logger.warn( "Deployment of '" + this.websiteRef.toString() + "' skipped as no servers were selected"); return outcome; } }
From source file:org.alfresco.web.bean.wcm.ReleaseTestServerDialog.java
@SuppressWarnings("unchecked") @Override//from w w w. j a v a 2 s. c o m protected String finishImpl(FacesContext context, String outcome) throws Exception { WebApplicationContext wac = FacesContextUtils.getRequiredWebApplicationContext(context); NodeService unprotectedNodeService = (NodeService) wac.getBean("nodeService"); List<NodeRef> testServers = DeploymentUtil.findAllocatedTestServers(this.store); for (NodeRef testServer : testServers) { unprotectedNodeService.setProperty(testServer, WCMAppModel.PROP_DEPLOYSERVERALLOCATEDTO, null); if (logger.isDebugEnabled()) logger.debug("Released test server '" + testServer + "' from store: " + this.store); } // close dialog and refresh website view // return AlfrescoNavigationHandler.CLOSE_DIALOG_OUTCOME + // AlfrescoNavigationHandler.OUTCOME_SEPARATOR + "browseWebsite"; return (outcome); }
From source file:org.alfresco.web.forms.RenderingEngineTemplateImpl.java
protected static FormDataFunctions getFormDataFunctions() { final FacesContext fc = FacesContext.getCurrentInstance(); final WebApplicationContext wac = FacesContextUtils.getRequiredWebApplicationContext(fc); return new FormDataFunctions((AVMRemote) wac.getBean("avmRemote")); }
From source file:org.alfresco.web.ui.common.Utils.java
/** * Generates a URL for the given usage for the given node. If the URL cannot be generated * then null is returned./*from w ww .j av a 2 s.c o m*/ * * The supported values for the usage parameter are of URLMode enum type * @see URLMode * * @param context Faces context * @param node The node to generate the URL for * @param name Name to use for the download file part of the link if any * @param usage What the URL is going to be used for * * @return The URL for the requested usage without the context path */ public static String generateURL(FacesContext context, Node node, String name, URLMode usage) { String url = null; switch (usage) { case WEBDAV: { // calculate a WebDAV URL for the given node FileFolderService fileFolderService = Repository.getServiceRegistry(context).getFileFolderService(); try { NodeRef rootNode = WebDAVServlet.getWebdavRootNode(); if (rootNode != null) { // build up the webdav url StringBuilder path = new StringBuilder("/").append(WebDAVServlet.WEBDAV_PREFIX); if (!rootNode.equals(node.getNodeRef())) { List<FileInfo> paths = fileFolderService.getNamePath(rootNode, node.getNodeRef()); // build up the path skipping the first path as it is the root folder for (int x = 0; x < paths.size(); x++) { path.append("/") .append(WebDAVHelper.encodeURL(paths.get(x).getName(), getUserAgent(context))); } } url = path.toString(); } } catch (AccessDeniedException e) { // cannot build path if user don't have access all the way up } catch (FileNotFoundException nodeErr) { // cannot build path if file no longer exists } catch (InvalidTypeException e) { // primary path does not translate to a file/folder path. } break; } case CIFS: { // calculate a CIFS path for the given node // get hold of the node service, cifsServer and navigation bean ServiceRegistry serviceRegistry = Repository.getServiceRegistry(context); NodeService nodeService = serviceRegistry.getNodeService(); FileFolderService fileFolderService = serviceRegistry.getFileFolderService(); NavigationBean navBean = (NavigationBean) context.getExternalContext().getSessionMap() .get(NavigationBean.BEAN_NAME); ServerConfigurationAccessor serverConfiguration = (ServerConfigurationAccessor) FacesContextUtils .getRequiredWebApplicationContext(context).getBean("fileServerConfiguration"); if (nodeService != null && fileFolderService != null && navBean != null && serverConfiguration != null) { // Resolve CIFS network folder location for this node FilesystemsConfigSection filesysConfig = (FilesystemsConfigSection) serverConfiguration .getConfigSection(FilesystemsConfigSection.SectionName); DiskSharedDevice diskShare = null; SharedDeviceList shares = filesysConfig.getShares(); Enumeration<SharedDevice> shareEnum = shares.enumerateShares(); while (shareEnum.hasMoreElements() && diskShare == null) { SharedDevice curShare = shareEnum.nextElement(); if (curShare.getContext() instanceof ContentContext) { // ALF-6863: Check if the node has a path beneath contentContext.getRootNode() ContentContext contentContext = (ContentContext) curShare.getContext(); NodeRef rootNode = contentContext.getRootNode(); if (node.getNodeRef().equals(rootNode)) { diskShare = (DiskSharedDevice) curShare; break; } try { fileFolderService.getNamePath(rootNode, node.getNodeRef()); if (logger.isDebugEnabled()) { logger.debug(" Node " + node.getName() + " HAS been found on " + contentContext.getDeviceName()); } diskShare = (DiskSharedDevice) curShare; break; } catch (FileNotFoundException ex) { if (logger.isDebugEnabled()) { logger.debug(" Node " + node.getName() + " HAS NOT been found on " + contentContext.getDeviceName()); } // There is no such node on this SharedDevice, continue continue; } catch (InvalidTypeException e) { if (logger.isDebugEnabled()) { logger.debug(" Node " + node.getName() + " HAS NOT been found on " + contentContext.getDeviceName()); } // primary path does not translate to a file/folder path. } } } if (diskShare != null) { ContentContext contentCtx = (ContentContext) diskShare.getContext(); NodeRef rootNode = contentCtx.getRootNode(); try { if (!EqualsHelper.nullSafeEquals(rootNode, node.getNodeRef())) { String userAgent = Utils.getUserAgent(context); final boolean isIE = Utils.USER_AGENT_MSIE.equals(userAgent); if (isIE) { url = Repository.getNamePathEx(context, node.getNodePath(), rootNode, "\\", "file:///" + navBean.getCIFSServerPath(diskShare)); } else { // build up the CIFS url StringBuilder path = new StringBuilder("file:///") .append(navBean.getCIFSServerPath(diskShare)); List<FileInfo> paths = fileFolderService.getNamePath(rootNode, node.getNodeRef()); // build up the path skipping the first path as it is the root folder for (int x = 0; x < paths.size(); x++) { path.append("\\") .append(WebDAVHelper.encodeURL(paths.get(x).getName(), userAgent)); } url = path.toString(); } } } catch (AccessDeniedException e) { // cannot build path if user don't have access all the way up } catch (FileNotFoundException nodeErr) { // cannot build path if file no longer exists } catch (InvalidNodeRefException nodeErr) { // cannot build path if node no longer exists } } } break; } case HTTP_DOWNLOAD: { url = DownloadContentServlet.generateDownloadURL(node.getNodeRef(), name); break; } case HTTP_INLINE: { url = DownloadContentServlet.generateBrowserURL(node.getNodeRef(), name); break; } case SHOW_DETAILS: { DictionaryService dd = Repository.getServiceRegistry(context).getDictionaryService(); // default to showing details of content String outcome = ExternalAccessServlet.OUTCOME_DOCDETAILS; // if the node is a type of folder then make the outcome to show space details if ((dd.isSubClass(node.getType(), ContentModel.TYPE_FOLDER)) || (dd.isSubClass(node.getType(), ApplicationModel.TYPE_FOLDERLINK))) { outcome = ExternalAccessServlet.OUTCOME_SPACEDETAILS; } // build the url url = ExternalAccessServlet.generateExternalURL(outcome, Repository.getStoreRef().getProtocol() + "/" + Repository.getStoreRef().getIdentifier() + "/" + node.getId()); break; } case BROWSE: { url = ExternalAccessServlet.generateExternalURL(ExternalAccessServlet.OUTCOME_BROWSE, Repository.getStoreRef().getProtocol() + "/" + Repository.getStoreRef().getIdentifier() + "/" + node.getId()); } case FTP: { // not implemented yet! break; } } return url; }
From source file:org.alfresco.web.ui.repo.component.property.BaseAssociationEditor.java
/** * Retrieves the AssociationDefinition for the association we are representing * //from w w w. j a va2 s .c om * @param context Faces Context * @return The AssociationDefinition for the association, null if a definition does not exist */ protected AssociationDefinition getAssociationDefinition(FacesContext context) { // get some metadata about the association from the data dictionary DataDictionary dd = (DataDictionary) FacesContextUtils.getRequiredWebApplicationContext(context) .getBean(Application.BEAN_DATA_DICTIONARY); return dd.getAssociationDefinition((Node) getValue(), this.associationName); }
From source file:org.alfresco.web.ui.repo.component.property.BaseAssociationEditor.java
/** * Retrieves the available options for the current association * //ww w. jav a2 s . c om * @param context Faces Context * @param contains The contains part of the query */ protected void getAvailableOptions(FacesContext context, String contains) { AssociationDefinition assocDef = getAssociationDefinition(context); if (assocDef != null) { // find and show all the available options for the current association String type = assocDef.getTargetClass().getName().toString(); if (type.equals(ContentModel.TYPE_AUTHORITY_CONTAINER.toString())) { UserTransaction tx = null; try { tx = Repository.getUserTransaction(context, true); tx.begin(); String safeContains = null; if (contains != null && contains.length() > 0) { safeContains = Utils.remove(contains.trim(), "\""); safeContains = safeContains.toLowerCase(); } // get all available groups AuthorityService authorityService = Repository.getServiceRegistry(context) .getAuthorityService(); Set<String> groups = authorityService.getAllAuthoritiesInZone(AuthorityService.ZONE_APP_DEFAULT, AuthorityType.GROUP); this.availableOptions = new ArrayList<NodeRef>(groups.size()); // get the NodeRef for each matching group AuthorityDAO authorityDAO = (AuthorityDAO) FacesContextUtils .getRequiredWebApplicationContext(context).getBean("authorityDAO"); if (authorityDAO != null) { List<String> matchingGroups = new ArrayList<String>(); String groupDisplayName; for (String group : groups) { // get display name, if not present strip prefix from group id groupDisplayName = authorityService.getAuthorityDisplayName(group); if (groupDisplayName == null || groupDisplayName.length() == 0) { groupDisplayName = group.substring(PermissionService.GROUP_PREFIX.length()); } // if a search string is present make sure the group matches // otherwise just add the group name to the sorted set if (safeContains != null) { if (groupDisplayName.toLowerCase().indexOf(safeContains) != -1) { matchingGroups.add(group); } } else { matchingGroups.add(group); } } // sort the group names Collections.sort(matchingGroups, new SimpleStringComparator()); // go through the sorted set and get the NodeRef for each group for (String groupName : matchingGroups) { NodeRef groupRef = authorityDAO.getAuthorityNodeRefOrNull(groupName); if (groupRef != null) { this.availableOptions.add(groupRef); } } } // commit the transaction tx.commit(); } catch (Throwable err) { Utils.addErrorMessage(MessageFormat.format( Application.getMessage(context, Repository.ERROR_GENERIC), err.getMessage()), err); this.availableOptions = Collections.<NodeRef>emptyList(); try { if (tx != null) { tx.rollback(); } } catch (Exception tex) { } } } else if (type.equals(ContentModel.TYPE_PERSON.toString())) { List<Pair<QName, String>> filter = (contains != null && contains.trim().length() > 0) ? Utils.generatePersonFilter(contains.trim()) : null; // Always sort by last name, then first name List<Pair<QName, Boolean>> sort = new ArrayList<Pair<QName, Boolean>>(); sort.add(new Pair<QName, Boolean>(ContentModel.PROP_LASTNAME, true)); sort.add(new Pair<QName, Boolean>(ContentModel.PROP_FIRSTNAME, true)); // Log the filtering if (logger.isDebugEnabled()) logger.debug("Query filter: " + filter); // How many to limit too? int maxResults = Application.getClientConfig(context).getSelectorsSearchMaxResults(); if (maxResults <= 0) { maxResults = Utils.getPersonMaxResults(); } List<PersonInfo> persons = Repository.getServiceRegistry(context).getPersonService() .getPeople(filter, true, sort, new PagingRequest(maxResults, null)).getPage(); // Save the results List<NodeRef> nodes = new ArrayList<NodeRef>(persons.size()); for (PersonInfo person : persons) { nodes.add(person.getNodeRef()); } this.availableOptions = nodes; } else { // for all other types/aspects perform a lucene search StringBuilder query = new StringBuilder("+TYPE:\""); if (assocDef.getTargetClass().isAspect()) { query = new StringBuilder("+ASPECT:\""); } else { query = new StringBuilder("+TYPE:\""); } query.append(type); query.append("\""); if (contains != null && contains.trim().length() != 0) { String safeContains = null; if (contains != null && contains.length() > 0) { safeContains = Utils.remove(contains.trim(), "\""); safeContains = safeContains.toLowerCase(); } query.append(" AND +@"); String nameAttr = Repository .escapeQName(QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "name")); query.append(nameAttr); query.append(":\"*" + safeContains + "*\""); } int maxResults = Application.getClientConfig(context).getSelectorsSearchMaxResults(); if (logger.isDebugEnabled()) { logger.debug("Query: " + query.toString()); logger.debug("Max results size: " + maxResults); } SearchParameters searchParams = new SearchParameters(); searchParams.addStore(Repository.getStoreRef()); searchParams.setLanguage(SearchService.LANGUAGE_LUCENE); searchParams.setQuery(query.toString()); if (maxResults > 0) { searchParams.setLimit(maxResults); searchParams.setLimitBy(LimitBy.FINAL_SIZE); } ResultSet results = null; try { results = Repository.getServiceRegistry(context).getSearchService().query(searchParams); this.availableOptions = results.getNodeRefs(); } catch (SearcherException se) { logger.info("Search failed for: " + query, se); Utils.addErrorMessage( Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_QUERY)); } finally { if (results != null) { results.close(); } } } if (logger.isDebugEnabled()) logger.debug("Found " + this.availableOptions.size() + " available options"); } }
From source file:org.alfresco.web.ui.repo.component.property.UIAssociation.java
protected void generateItem(FacesContext context, UIPropertySheet propSheet) throws IOException { String associationName = (String) getName(); // get details of the association DataDictionary dd = (DataDictionary) FacesContextUtils.getRequiredWebApplicationContext(context) .getBean(Application.BEAN_DATA_DICTIONARY); AssociationDefinition assocDef = dd.getAssociationDefinition(propSheet.getNode(), associationName); if (assocDef == null) { logger.warn("Failed to find association definition for association '" + associationName + "'"); } else {//from w w w . j av a 2 s. c om // we've found the association definition but we also need to check // that the association is not a parent child one if (assocDef.isChild()) { logger.warn("The association named '" + associationName + "' is not an association"); } else { String displayLabel = (String) getDisplayLabel(); if (displayLabel == null) { // try and get the repository assigned label displayLabel = assocDef.getTitle(dd.getDictionaryService()); // if the label is still null default to the local name of the property if (displayLabel == null) { displayLabel = assocDef.getName().getLocalName(); } } // generate the label and type specific control generateLabel(context, propSheet, displayLabel); generateControl(context, propSheet, assocDef); } } }
From source file:org.alfresco.web.ui.repo.component.property.UIChildAssociation.java
protected void generateItem(FacesContext context, UIPropertySheet propSheet) throws IOException { String associationName = (String) getName(); // get details of the association DataDictionary dd = (DataDictionary) FacesContextUtils.getRequiredWebApplicationContext(context) .getBean(Application.BEAN_DATA_DICTIONARY); AssociationDefinition assocDef = dd.getAssociationDefinition(propSheet.getNode(), associationName); if (assocDef == null) { logger.warn("Failed to find child association definition for association '" + associationName + "'"); } else {// ww w. j av a 2s .c om // we've found the association definition but we also need to check // that the association is a parent child one if (assocDef.isChild() == false) { logger.warn("The association named '" + associationName + "' is not a child association"); } else { String displayLabel = (String) getDisplayLabel(); if (displayLabel == null) { // try and get the repository assigned label displayLabel = assocDef.getTitle(dd.getDictionaryService()); // if the label is still null default to the local name of the property if (displayLabel == null) { displayLabel = assocDef.getName().getLocalName(); } } // generate the label and type specific control generateLabel(context, propSheet, displayLabel); generateControl(context, propSheet, assocDef); } } }
From source file:org.alfresco.web.ui.repo.component.property.UIProperty.java
protected void generateItem(FacesContext context, UIPropertySheet propSheet) throws IOException { Node node = propSheet.getNode(); String propertyName = (String) getName(); DataDictionary dd = (DataDictionary) FacesContextUtils.getRequiredWebApplicationContext(context) .getBean(Application.BEAN_DATA_DICTIONARY); PropertyDefinition propDef = dd.getPropertyDefinition(node, propertyName); if (propDef == null) { // there is no definition for the node, so it may have been added to // the node as an additional property, so look for it in the node itself. // Or, if the ignoreIfMissing flag is set to false, show the property if (node.hasProperty(propertyName) || getIgnoreIfMissing() == false) { String displayLabel = (String) getDisplayLabel(); if (displayLabel == null) { displayLabel = propertyName; }// w w w.jav a2s . co m // generate the label and generic control generateLabel(context, propSheet, displayLabel); generateControl(context, propSheet, propertyName); } else { // warn the user that the property was not found anywhere if (missingPropsLogger.isWarnEnabled()) missingPropsLogger.warn("Failed to find property '" + propertyName + "' for node: " + node.getNodeRef().toString()); } } else { String displayLabel = (String) getDisplayLabel(); if (displayLabel == null) { // try and get the repository assigned label displayLabel = propDef.getTitle(dd.getDictionaryService()); // if the label is still null default to the local name of the property if (displayLabel == null) { displayLabel = propDef.getName().getLocalName(); } } // generate the label and type specific control generateLabel(context, propSheet, displayLabel); generateControl(context, propSheet, propDef); } }
From source file:org.alfresco.web.ui.wcm.component.UISandboxSnapshots.java
private AVMService getAVMService(FacesContext fc) { return (AVMService) FacesContextUtils.getRequiredWebApplicationContext(fc) .getBean("AVMLockingAwareService"); }