public void testTorrent(AjaxBehaviorEvent event) { // TODO Это точно такая же часть как и в testMessage FacesContext context = FacesContext.getCurrentInstance(); UIComponent component = UIComponent.getCurrentComponent(context); String url = (String) ((UIInput) component.findComponent("filmLinkRutracker")).getValue(); WebBrowser webBrowser = new WebBrowser(LogEnum.WEB.getLog()); // String regexp = (String) ((UIInput) component.findComponent("filmRegexpSerialNumber")).getValue(); FacesMessage message = new FacesMessage(); try { webBrowser.goToUrl(url); filmEdit.setTitle(webBrowser.getTitle()); TorrentFile torrent = webBrowser.downloadTorrentFile(webBrowser.getTorrentUrl()); ByteArrayInputStream bais = new ByteArrayInputStream(torrent.getContent()); TorrentInfo info = new TorrentInfo(new BufferedInputStream(bais)); StringBuilder builder = new StringBuilder(); for (String fileName : info.getInfo()) { builder .append(fileName) .append(" № серии: \"") .append(MessageUtils.parseEpisode(fileName, regexp)) .append("\" "); } message.setSummary(builder.toString()); message.setSeverity(FacesMessage.SEVERITY_INFO); } catch (CoreException e) { message.setSeverity(FacesMessage.SEVERITY_ERROR); message.setSummary(e.getMessage()); } context.addMessage("otherMessageHidden", message); context.renderResponse(); }
/** * finds the component with the given id that is located in the same NamingContainer as a given * component * * @param fc the FacesContext * @param componentId the component id * @param nearComponent a component within the same naming container from which to start the * search (optional) * @return the component or null if no component was found */ public UIComponent findComponent(FacesContext fc, String componentId, UIComponent nearComponent) { if (StringUtils.isEmpty(componentId)) throw new InvalidArgumentException("componentId", componentId); // Begin search near given component (if any) UIComponent component = null; if (nearComponent != null) { // Search below the nearest naming container component = nearComponent.findComponent(componentId); if (component == null) { // Recurse upwards UIComponent nextParent = nearComponent; while (true) { nextParent = nextParent.getParent(); // search NamingContainers only while (nextParent != null && !(nextParent instanceof NamingContainer)) { nextParent = nextParent.getParent(); } if (nextParent == null) { break; } else { component = nextParent.findComponent(componentId); } if (component != null) { break; } } } } // Not found. Search the entire tree if (component == null) component = findChildComponent(fc.getViewRoot(), componentId); // done return component; }
/** Will add the specified type - value metadata as a property to the selected resource. */ public void processAction(ActionEvent actionEvent) throws AbortProcessingException { UIComponent comp = actionEvent.getComponent(); String id = comp.getId(); UIComponent superParent = comp; WebDAVCategories realCategories = null; while (superParent.getParent() != null) { superParent = superParent.getParent(); if (superParent instanceof WebDAVCategories) { realCategories = (WebDAVCategories) superParent; } } if (realCategories == null) { realCategories = (WebDAVCategories) superParent.findComponent(getId()); } if (id.equalsIgnoreCase(getAddButtonId())) { // Add a category to the list of selectable categories // This is input for adding a category HtmlInputText newCategoryInput = (HtmlInputText) comp.getParent().findComponent(getAddCategoryInputId()); String newCategoryName = newCategoryInput.getValue().toString(); CategoryBean.getInstance().addCategory(newCategoryName); if (realCategories != null) { realCategories.reset(); } return; } else if (id.equalsIgnoreCase(getSaveButtonId())) { realCategories.saveCategoriesSettings(); } }
/** * Recursively searches for {@link NamingContainer}s from the given start point looking for the * component with the <code>id</code> specified by <code>forComponent</code>. * * @param startPoint - the starting point in which to begin the search * @param forComponent - the component to search for * @return the component with the the <code>id</code that matches * <code> * forComponent</code> otheriwse null if no match is found. */ private static UIComponent findUIComponentBelow(UIComponent startPoint, String forComponent) { UIComponent retComp = null; if (startPoint.getChildCount() > 0) { List<UIComponent> children = startPoint.getChildren(); for (int i = 0, size = children.size(); i < size; i++) { UIComponent comp = children.get(i); if (comp instanceof NamingContainer) { try { retComp = comp.findComponent(forComponent); } catch (IllegalArgumentException iae) { continue; } } if (retComp == null) { if (comp.getChildCount() > 0) { retComp = findUIComponentBelow(comp, forComponent); } } if (retComp != null) { break; } } } return retComp; }
// 编写处理Action事件的方法 public void processAction(ActionEvent event) { // 获取当前的FacesContext对象 FacesContext context = FacesContext.getCurrentInstance(); // 获取JSF页面中<f:view.../>元素 UIViewRoot viewRoot = context.getViewRoot(); // 通过ID获取<f:view.../>内的<h:form.../>子元素。 UIComponent comp = viewRoot.findComponent("addForm"); // 通过ID获取<h:form.../>内的第一个<h:inputText.../>子元素。 UIInput input = (UIInput) comp.findComponent("name"); // 通过ID获取<h:form.../>内的第二个<h:inputText.../>子元素。 HtmlInputText price = (HtmlInputText) comp.findComponent("price"); if (input.getValue().equals("疯狂Java讲义")) { price.setSize(60); price.setValue("99.0元"); price.setStyle("background-color:#9999ff;" + "font-weight:bold"); } }
public void encodeBegin(FacesContext context) throws IOException { UIComponent component = super.getParent(); Map map = Utils.toMap((String) this.getAttributes().get("exclude")); String targetId = (String) this.getAttributes().get("targetId"); if (Utils.hasContent(targetId)) { UIComponent targetComponent = component.findComponent(targetId); targetId = targetComponent.getClientId(context); } setupElementAndChildren(context, component, targetId, map == null ? null : map.keySet()); }
@SuppressWarnings({"UnusedDeclaration"}) protected UIComponent findReparentedComponent( FaceletContext ctx, UIComponent parent, String tagId) { UIComponent facet = parent.getFacets().get(UIComponent.COMPOSITE_FACET_NAME); if (facet != null) { UIComponent newParent = facet.findComponent((String) parent.getAttributes().get(tagId)); if (newParent != null) return ComponentSupport.findChildByTagId(newParent, tagId); } return null; }
// Returns the resolved (client id) for a particular id. private static String getResolvedId(UIComponent component, String id) { UIComponent resolvedComponent = component.findComponent(id); if (resolvedComponent == null) { if (id.charAt(0) == UINamingContainer.getSeparatorChar(FacesContext.getCurrentInstance())) { return id.substring(1); } return id; } return resolvedComponent.getClientId(); }
public void validate(FacesContext _context, UIComponent _toValidate, Object _value) throws ValidatorException { UIComponent component = _toValidate.findComponent("equal1"); String valeur = (String) component.getAttributes().get("value"); if (!_value.equals(valeur) || valeur.equals("") || _value.equals("")) { FacesMessage message = new FacesMessage(); message.setSeverity(FacesMessage.SEVERITY_ERROR); message.setDetail("Les deux champs ne sont pas identiques"); throw new ValidatorException(message); } }
public void validateGroupMessage(FacesContext context, UIComponent component, Object value) { String strValue = (String) value; if (StringUtils.isEmpty(strValue)) { UIComponent ui = component.findComponent("groupEmailRegexp"); UIInput input = (UIInput) ui; if (!StringUtils.isEmpty((String) input.getValue())) { FacesMessage error = new FacesMessage(); error.setSeverity(FacesMessage.SEVERITY_ERROR); error.setSummary("Поле обязательно для заполнения"); throw new ValidatorException(error); } } }
@Override public String getAsPropertyValue(UIComponent component) { Object value = getAttributeValue(component); if ((null != value) && (!((String) value).isEmpty())) { UIComponent target = component.findComponent((String) value); if (null != target) { return Helper.makeStringVar(target.getClientId()); } // allowed to use non component element id return Helper.makeStringVar(value.toString()); } return null; }
public void testMessage(AjaxBehaviorEvent event) { FacesContext context = FacesContext.getCurrentInstance(); UIComponent component = UIComponent.getCurrentComponent(context); String url = (String) ((UIInput) component.findComponent("filmLinkRutracker")).getValue(); WebBrowser webBrowser = new WebBrowser(LogEnum.WEB.getLog()); FacesMessage message = new FacesMessage(); try { webBrowser.goToUrl(url); String title = webBrowser.getTitle(); filmEdit.setTitle(title); String regexp = (String) ((UIInput) component.findComponent("filmMailRegexp")).getValue(); String mailMessage = (String) ((UIInput) component.findComponent("filmMailMessage")).getValue(); message.setSummary(MessageUtils.createMessage(title, regexp, mailMessage)); message.setSeverity(FacesMessage.SEVERITY_INFO); } catch (CoreException e) { message.setSeverity(FacesMessage.SEVERITY_ERROR); message.setSummary(e.getMessage()); } context.addMessage("otherMessageHidden", message); context.renderResponse(); }
/** * Locates the component identified by <code>forComponent</code> * * @param context the FacesContext for the current request * @param forComponent - the component to search for * @param component - the starting point in which to begin the search * @return the component with the the <code>id</code that matches * <code> * forComponent</code> otheriwse null if no match is found. */ protected UIComponent getForComponent( FacesContext context, String forComponent, UIComponent component) { if (null == forComponent || forComponent.length() == 0) { return null; } UIComponent result = null; UIComponent currentParent = component; try { // Check the naming container of the current // component for component identified by // 'forComponent' while (currentParent != null) { // If the current component is a NamingContainer, // see if it contains what we're looking for. result = currentParent.findComponent(forComponent); if (result != null) { break; } // if not, start checking further up in the view currentParent = currentParent.getParent(); } // no hit from above, scan for a NamingContainer // that contains the component we're looking for from the root. if (result == null) { result = findUIComponentBelow(context.getViewRoot(), forComponent); } } catch (Exception e) { if (logger.isLoggable(Level.FINEST)) { logger.log(Level.FINEST, "Unable to find for component", e); } } // log a message if we were unable to find the specified // component (probably a misconfigured 'for' attribute if (result == null) { if (logger.isLoggable(Level.WARNING)) { logger.warning( MessageUtils.getExceptionMessageString( MessageUtils.COMPONENT_NOT_FOUND_IN_VIEW_WARNING_ID, forComponent)); } } return result; }
/** * finds a child component with the given id that is located below the given parent component * * @param parent the parent * @param componentId the component id * @return the component or null if no component was found */ public static UIComponent findChildComponent(UIComponent parent, String componentId) { UIComponent component = null; if (parent.getChildCount() == 0) return null; Iterator<UIComponent> children = parent.getChildren().iterator(); while (children.hasNext()) { UIComponent nextChild = children.next(); if (nextChild instanceof NamingContainer) { component = nextChild.findComponent(componentId); } if (component == null) { component = findChildComponent(nextChild, componentId); } if (component != null) { break; } } return component; }
public static String findClientIds(String ids, UIComponent component, FacesContext context) throws IOException { if (ids == null) return null; StringBuilder clientIds = new StringBuilder(); String[] idlist = ids.split("[\\s]"); for (String id : idlist) { if (!id.startsWith("@")) { UIComponent found = component.findComponent(id); if (found != null) { if (clientIds.length() > 0) clientIds.append(" "); clientIds.append(found.getClientId(context)); } else { throw new IOException("Cannot find id " + id + " within components NamingContainer"); } } } return clientIds.toString(); }
@Override public void encodeEnd(final FacesContext context, final UIComponent component) throws IOException { final ResponseWriter writer = context.getResponseWriter(); final FilterOnEnter filterOnEnter = (FilterOnEnter) component; String target = ""; if (filterOnEnter.getTarget() != null && !filterOnEnter.getTarget().isEmpty()) { UIComponent targetComponent = component.findComponent(filterOnEnter.getTarget()); if (targetComponent == null) { throw new FacesException( "Cannot find component " + filterOnEnter.getTarget() + " in view."); } else { target = targetComponent.getClientId(context); } } writer.startElement("script", null); writer.writeAttribute("type", "text/javascript", null); writer.write(getScript(target, filterOnEnter)); writer.endElement("script"); }
public void updateAttribute(AjaxBehaviorEvent event) throws AbortProcessingException { UIComponent component = (UIComponent) event.getSource(); String attributeName = (String) component.findComponent("name").getAttributes().get("value"); Object attributeValue = component.findComponent("value").getAttributes().get("value"); component.findComponent("fu").getAttributes().put(attributeName, attributeValue); }
/** * @see ViewHandler#retargetMethodExpressions(javax.faces.context.FacesContext, * javax.faces.component.UIComponent) */ @Override public void retargetMethodExpressions(FacesContext context, UIComponent topLevelComponent) { BeanInfo componentBeanInfo = (BeanInfo) topLevelComponent.getAttributes().get(UIComponent.BEANINFO_KEY); // PENDING(edburns): log error message if componentBeanInfo is null; if (null == componentBeanInfo) { return; } PropertyDescriptor attributes[] = componentBeanInfo.getPropertyDescriptors(); String targets = null, attrName = null, strValue = null, methodSignature = null; UIComponent target = null; ExpressionFactory expressionFactory = null; ValueExpression valueExpression = null; MethodExpression toApply = null; Class expectedReturnType = null; Class expectedParameters[] = null; for (PropertyDescriptor cur : attributes) { // If the current attribute represents a ValueExpression if (null != (valueExpression = (ValueExpression) cur.getValue("type"))) { // take no action on this attribute. continue; } // If the current attribute representes a MethodExpression if (null != (valueExpression = (ValueExpression) cur.getValue("method-signature"))) { methodSignature = (String) valueExpression.getValue(context.getELContext()); if (null != methodSignature) { // This is the name of the attribute on the top level component, // and on the inner component. if (null != (valueExpression = (ValueExpression) cur.getValue("targets"))) { targets = (String) valueExpression.getValue(context.getELContext()); } if (null == targets) { targets = cur.getName(); } if (null == targets || 0 == targets.length()) { // PENDING error message in page? logger.severe("Unable to retarget MethodExpression: " + methodSignature); continue; } String[] targetIds = targets.split(" "); for (String curTarget : targetIds) { attrName = cur.getName(); // Find the attribute on the top level component valueExpression = (ValueExpression) topLevelComponent.getAttributes().get(attrName); if (null == valueExpression) { // PENDING error message in page? logger.severe( "Unable to find attribute with name \"" + attrName + "\" in top level component in consuming page. " + "Page author error."); continue; } // lazily initialize this local variable if (null == expressionFactory) { expressionFactory = context.getApplication().getExpressionFactory(); } // If the attribute is one of the pre-defined // MethodExpression attributes boolean isAction = false, isActionListener = false, isValidator = false, isValueChangeListener = false; if ((isAction = attrName.equals("action")) || (isActionListener = attrName.equals("actionListener")) || (isValidator = attrName.equals("validator")) || (isValueChangeListener = attrName.equals("valueChangeListener"))) { // This is the inner component to which the attribute should // be applied target = topLevelComponent.findComponent(curTarget); if (null == targets) { // PENDING error message in page? logger.severe( "Unable to retarget MethodExpression. " + "Unable to find inner component with id " + targets + "."); continue; } if (isAction) { expectedReturnType = Object.class; expectedParameters = new Class[] {}; toApply = expressionFactory.createMethodExpression( context.getELContext(), valueExpression.getExpressionString(), expectedReturnType, expectedParameters); ((ActionSource2) target).setActionExpression(toApply); } else if (isActionListener) { expectedReturnType = Void.TYPE; expectedParameters = new Class[] {ActionEvent.class}; toApply = expressionFactory.createMethodExpression( context.getELContext(), valueExpression.getExpressionString(), expectedReturnType, expectedParameters); ((ActionSource2) target) .addActionListener(new MethodExpressionActionListener(toApply)); } else if (isValidator) { expectedReturnType = Void.TYPE; expectedParameters = new Class[] {FacesContext.class, UIComponent.class, Object.class}; toApply = expressionFactory.createMethodExpression( context.getELContext(), valueExpression.getExpressionString(), expectedReturnType, expectedParameters); ((EditableValueHolder) target).addValidator(new MethodExpressionValidator(toApply)); } else if (isValueChangeListener) { expectedReturnType = Void.TYPE; expectedParameters = new Class[] {ValueChangeEvent.class}; toApply = expressionFactory.createMethodExpression( context.getELContext(), valueExpression.getExpressionString(), expectedReturnType, expectedParameters); ((EditableValueHolder) target) .addValueChangeListener(new MethodExpressionValueChangeListener(toApply)); } } else { // There is no explicit methodExpression property on // an inner component to which this MethodExpression // should be retargeted. In this case, replace the // ValueExpression with a method expresson. // Pull apart the methodSignature to derive the // expectedReturnType and expectedParameters // PENDING(rlubke,jimdriscoll) bulletproof this assert (null != methodSignature); methodSignature = methodSignature.trim(); // Get expectedReturnType int j, i = methodSignature.indexOf(" "); if (-1 != i) { strValue = methodSignature.substring(0, i); try { expectedReturnType = Util.getTypeFromString(strValue); } catch (ClassNotFoundException cnfe) { logger.log( Level.SEVERE, "Unable to determine expected return type for " + methodSignature, cnfe); continue; } } else { logger.severe("Unable to determine expected return type for " + methodSignature); continue; } // derive the arguments i = methodSignature.indexOf("("); if (-1 != i) { j = methodSignature.indexOf(")", i + 1); if (-1 != j) { strValue = methodSignature.substring(i + 1, j); if (0 < strValue.length()) { String[] params = strValue.split(","); expectedParameters = new Class[params.length]; boolean exceptionThrown = false; for (i = 0; i < params.length; i++) { try { expectedParameters[i] = Util.getTypeFromString(params[i]); } catch (ClassNotFoundException cnfe) { logger.log( Level.SEVERE, "Unable to determine expected return type for " + methodSignature, cnfe); exceptionThrown = true; break; } } if (exceptionThrown) { continue; } } else { expectedParameters = new Class[] {}; } } } assert (null != expectedReturnType); assert (null != expectedParameters); toApply = expressionFactory.createMethodExpression( context.getELContext(), valueExpression.getExpressionString(), expectedReturnType, expectedParameters); topLevelComponent.getAttributes().put(attrName, toApply); } } } } } }
public static String findClientIds(FacesContext context, UIComponent component, String list) { if (list == null) return "@none"; // System.out.println("ComponentUtils.findClientIds() component.clientId: " + // component.getClientId(context) + " list: " + list); String[] ids = list.split("[,\\s]+"); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < ids.length; i++) { if (i != 0) buffer.append(" "); String id = ids[i].trim(); // System.out.println("ComponentUtils.findClientIds() ["+i+"] id: " + id); if (id.equals("@all") || id.equals("@none")) { // System.out.println("ComponentUtils.findClientIds() ["+i+"] " + id); buffer.append(id); } else if (id.equals("@this")) { // System.out.println("ComponentUtils.findClientIds() ["+i+"] @this : " + // component.getClientId(context)); buffer.append(component.getClientId(context)); } else if (id.equals("@parent")) { // System.out.println("ComponentUtils.findClientIds() ["+i+"] @parent: " + // component.getParent().getClientId(context)); buffer.append(component.getParent().getClientId(context)); } else if (id.equals("@form")) { UIComponent form = ComponentUtils.findParentForm(context, component); if (form == null) throw new FacesException( "Component " + component.getClientId(context) + " needs to be enclosed in a form"); buffer.append(form.getClientId(context)); } else { UIComponent comp = component.findComponent(id); // For portlets, if the standard search doesn't work, it may be necessary to do an absolute // search // which requires including the portlet's namespace. So the resulting encoded id looks // something // like portletNamespace:container:componentId. We make the search absolute by pre-pending // a leading colon (:). if (comp == null) { String encodedId = encodeNameSpace(context, id); if (!encodedId.startsWith(":")) { encodedId = ":" + encodedId; } comp = component.findComponent(encodedId); // System.out.println("ComponentUtils.findClientIds() ["+i+"] comp // : " + (comp == null ? "null" : comp.getClientId(context)) + " id: " + encodedId); } if (comp != null) { buffer.append(comp.getClientId(context)); } else { if (context.getApplication().getProjectStage().equals(ProjectStage.Development)) { logger.log(Level.INFO, "Cannot find component with identifier \"{0}\" in view.", id); } buffer.append(id); } } } return buffer.toString(); }
public static void clearSubmittedValues(UIComponent component, String componentName) { UIComponent uiComponent = component.findComponent(componentName); clearSubmittedValues(uiComponent); }