View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  
20  package org.apache.myfaces.tobago.internal.renderkit.renderer;
21  
22  import org.apache.myfaces.tobago.internal.component.AbstractUIInput;
23  import org.apache.myfaces.tobago.internal.component.AbstractUISuggest;
24  import org.apache.myfaces.tobago.internal.util.JsonUtils;
25  import org.apache.myfaces.tobago.internal.util.SelectItemUtils;
26  import org.apache.myfaces.tobago.model.AutoSuggestItem;
27  import org.apache.myfaces.tobago.model.AutoSuggestItems;
28  import org.apache.myfaces.tobago.renderkit.RendererBase;
29  import org.apache.myfaces.tobago.renderkit.html.CustomAttributes;
30  import org.apache.myfaces.tobago.renderkit.html.HtmlAttributes;
31  import org.apache.myfaces.tobago.renderkit.html.HtmlElements;
32  import org.apache.myfaces.tobago.renderkit.html.HtmlInputTypes;
33  import org.apache.myfaces.tobago.util.ComponentUtils;
34  import org.apache.myfaces.tobago.webapp.TobagoResponseWriter;
35  import org.slf4j.Logger;
36  import org.slf4j.LoggerFactory;
37  
38  import javax.el.MethodExpression;
39  import javax.faces.context.FacesContext;
40  import javax.faces.model.SelectItem;
41  import java.io.IOException;
42  import java.lang.invoke.MethodHandles;
43  import java.util.ArrayList;
44  import java.util.Collections;
45  import java.util.List;
46  import java.util.Map;
47  
48  public class SuggestRenderer<T extends AbstractUISuggest> extends RendererBase<T> {
49  
50    private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
51  
52    @Override
53    public void decodeInternal(final FacesContext facesContext, final T component) {
54      final String clientId = component.getClientId(facesContext);
55      final Map<String, String> requestParameterMap = facesContext.getExternalContext().getRequestParameterMap();
56      if (requestParameterMap.containsKey(clientId)) {
57        final String query = requestParameterMap.get(clientId);
58        if (LOG.isDebugEnabled()) {
59          LOG.debug("suggest query='{}'", query);
60        }
61        // XXX this is for the old way: for "suggestMethod"
62        final AbstractUIInput input = ComponentUtils.findAncestor(component, AbstractUIInput.class);
63        if (input != null) {
64          input.setSubmittedValue(query);
65        }
66        // this is the new way: for select items
67        component.setQuery(query);
68      }
69    }
70  
71    @Override
72    public void encodeBeginInternal(final FacesContext facesContext, final T component) throws IOException {
73      final AbstractUIInput input = ComponentUtils.findAncestor(component, AbstractUIInput.class);
74      final MethodExpression suggestMethodExpression = component.getSuggestMethodExpression();
75  
76      int totalCount = component.getTotalCount();
77      final String[] array;
78  
79      if (suggestMethodExpression != null && input != null) { // old way (deprecated)
80        final AutoSuggestItems autoSuggestItems
81            = createAutoSuggestItems(suggestMethodExpression.invoke(facesContext.getELContext(), new Object[]{input}));
82        final List<AutoSuggestItem> items = autoSuggestItems.getItems();
83  
84        if (totalCount == -1 || items.size() < totalCount) {
85          totalCount = items.size();
86        }
87  
88        array = new String[totalCount];
89        for (int i = 0; i < totalCount; i++) {
90          array[i] = items.get(i).getLabel();
91        }
92      } else {
93        final List<SelectItem> items = SelectItemUtils.getItemList(facesContext, component);
94  
95        if (totalCount == -1 || items.size() < totalCount) {
96          totalCount = items.size();
97        }
98  
99        array = new String[totalCount];
100       for (int i = 0; i < totalCount; i++) {
101         array[i] = items.get(i).getLabel();
102       }
103     }
104 
105     final TobagoResponseWriter writer = getResponseWriter(facesContext);
106 
107     writer.startElement(HtmlElements.TOBAGO_SUGGEST);
108     final String clientId = component.getClientId(facesContext);
109     writer.writeIdAttribute(clientId);
110     if (input != null) {
111       writer.writeAttribute(HtmlAttributes.FOR, input.getFieldId(facesContext), false);
112     } else {
113       LOG.error("No ancestor with type AbstractUIInput found for suggest id={}", clientId);
114     }
115 
116     writer.writeAttribute(CustomAttributes.MIN_CHARS, component.getMinimumCharacters());
117     writer.writeAttribute(CustomAttributes.DELAY, component.getDelay());
118     writer.writeAttribute(CustomAttributes.MAX_ITEMS, component.getMaximumItems());
119     writer.writeAttribute(CustomAttributes.UPDATE, component.isUpdate());
120     writer.writeAttribute(CustomAttributes.TOTAL_COUNT, totalCount);
121     writer.writeAttribute(CustomAttributes.LOCAL_MENU, component.isLocalMenu());
122     writer.writeAttribute(CustomAttributes.ITEMS, JsonUtils.encode(array), true);
123 
124     if (LOG.isDebugEnabled()) {
125       LOG.debug("suggest list: {}", JsonUtils.encode(array));
126     }
127 
128     writer.startElement(HtmlElements.INPUT);
129     writer.writeAttribute(HtmlAttributes.TYPE, HtmlInputTypes.HIDDEN);
130     writer.writeAttribute(HtmlAttributes.NAME, clientId, false);
131     writer.endElement(HtmlElements.INPUT);
132 
133     writer.endElement(HtmlElements.TOBAGO_SUGGEST);
134   }
135 
136   private AutoSuggestItems createAutoSuggestItems(final Object object) {
137     if (object instanceof AutoSuggestItems) {
138       return (AutoSuggestItems) object;
139     }
140     final AutoSuggestItems autoSuggestItems = new AutoSuggestItems();
141     if (object instanceof List && !((List) object).isEmpty()) {
142       if (((List) object).get(0) instanceof AutoSuggestItem) {
143         //noinspection unchecked
144         autoSuggestItems.setItems((List<AutoSuggestItem>) object);
145       } else if (((List) object).get(0) instanceof String) {
146         final List<AutoSuggestItem> items = new ArrayList<>(((List) object).size());
147         for (int i = 0; i < ((List) object).size(); i++) {
148           final AutoSuggestItem item = new AutoSuggestItem();
149           item.setLabel((String) ((List) object).get(i));
150           item.setValue((String) ((List) object).get(i));
151           items.add(item);
152         }
153         autoSuggestItems.setItems(items);
154       } else {
155         throw new ClassCastException("Can't create AutoSuggestItems from '" + object + "'. "
156             + "Elements needs to be " + String.class.getName() + " or " + AutoSuggestItem.class.getName());
157       }
158     } else {
159       autoSuggestItems.setItems(Collections.emptyList());
160     }
161     return autoSuggestItems;
162   }
163 
164 }