diff --git a/impl/src/main/java/com/sun/faces/application/ApplicationImpl.java b/impl/src/main/java/com/sun/faces/application/ApplicationImpl.java index 4d7af14f85..ac6e9062b3 100644 --- a/impl/src/main/java/com/sun/faces/application/ApplicationImpl.java +++ b/impl/src/main/java/com/sun/faces/application/ApplicationImpl.java @@ -479,7 +479,7 @@ public Converter createConverter(String converterId) { * @see jakarta.faces.application.Application#createConverter(Class) */ @Override - public Converter createConverter(Class targetClass) { + public Converter createConverter(Class targetClass) { return instanceFactory.createConverter(targetClass); } diff --git a/impl/src/main/java/com/sun/faces/application/JavaFlowLoaderHelper.java b/impl/src/main/java/com/sun/faces/application/JavaFlowLoaderHelper.java index 99d95114de..ad77144802 100644 --- a/impl/src/main/java/com/sun/faces/application/JavaFlowLoaderHelper.java +++ b/impl/src/main/java/com/sun/faces/application/JavaFlowLoaderHelper.java @@ -60,7 +60,7 @@ synchronized void loadFlows(FacesContext context, FlowHandler flowHandler) throw WebConfiguration config = WebConfiguration.getInstance(); for (Producer flowProducer : flowProducers) { - Flow toAdd = flowProducer.produce(beanManager.createCreationalContext(null)); + Flow toAdd = flowProducer.produce(beanManager.createCreationalContext(null)); if (toAdd == null) { LOGGER.log(SEVERE, "Flow producer method {0}() returned null. Ignoring.", flowProducer.toString()); } else { diff --git a/impl/src/main/java/com/sun/faces/application/NamedEventManager.java b/impl/src/main/java/com/sun/faces/application/NamedEventManager.java index 1dea5a5230..ce7b4d974a 100644 --- a/impl/src/main/java/com/sun/faces/application/NamedEventManager.java +++ b/impl/src/main/java/com/sun/faces/application/NamedEventManager.java @@ -38,8 +38,8 @@ */ public class NamedEventManager { - private Map> namedEvents = new ConcurrentHashMap<>(); - private Map>> duplicateNames = new ConcurrentHashMap<>(); + private final Map> namedEvents = new ConcurrentHashMap<>(); + private final Map>> duplicateNames = new ConcurrentHashMap<>(); public NamedEventManager() { namedEvents.put("jakarta.faces.event.PreRenderComponent", PreRenderComponentEvent.class); @@ -66,7 +66,7 @@ public Class getNamedEvent(String name) { if (namedEvent == null) { try { - namedEvent = loadClass(name, this); + namedEvent = (Class) loadClass(name, this); } catch (ClassNotFoundException ex) { throw new FacesException("An unknown event type was specified: " + name, ex); } @@ -81,12 +81,8 @@ public Class getNamedEvent(String name) { public void addDuplicateName(String name, Class event) { Class registeredEvent = namedEvents.remove(name); - Set> events = duplicateNames.get(name); + Set> events = duplicateNames.computeIfAbsent(name, k -> new HashSet<>()); - if (events == null) { - events = new HashSet<>(); - duplicateNames.put(name, events); - } events.add(event); if (registeredEvent != null) { diff --git a/impl/src/main/java/com/sun/faces/application/NavigationHandlerImpl.java b/impl/src/main/java/com/sun/faces/application/NavigationHandlerImpl.java index 106ae7f8ad..71a4218d7f 100644 --- a/impl/src/main/java/com/sun/faces/application/NavigationHandlerImpl.java +++ b/impl/src/main/java/com/sun/faces/application/NavigationHandlerImpl.java @@ -91,7 +91,7 @@ public class NavigationHandlerImpl extends ConfigurableNavigationHandler { public static boolean isResetFlowHandlerState(FacesContext facesContext) { - Boolean obtainingNavigationCase = (Boolean) FacesContext.getCurrentInstance().getAttributes().get(RESET_FLOW_HANDLER_STATE_KEY); + Boolean obtainingNavigationCase = (Boolean) facesContext.getAttributes().get(RESET_FLOW_HANDLER_STATE_KEY); return obtainingNavigationCase != null && obtainingNavigationCase; } @@ -256,8 +256,8 @@ public void handleNavigation(FacesContext context, String fromAction, String out // If we are exiting all flows if (caseStruct.newFlow == null) { // NOPMD - parameters.put(TO_FLOW_DOCUMENT_ID_REQUEST_PARAM_NAME, asList(NULL_FLOW)); - parameters.put(FLOW_ID_REQUEST_PARAM_NAME, asList("")); + parameters.put(TO_FLOW_DOCUMENT_ID_REQUEST_PARAM_NAME, List.of(NULL_FLOW)); + parameters.put(FLOW_ID_REQUEST_PARAM_NAME, List.of("")); FlowHandler flowHandler = context.getApplication().getFlowHandler(); if (flowHandler instanceof FlowHandlerImpl) { @@ -272,10 +272,10 @@ public void handleNavigation(FacesContext context, String fromAction, String out if (!parameters.containsKey(TO_FLOW_DOCUMENT_ID_REQUEST_PARAM_NAME) || !parameters.containsKey(FLOW_ID_REQUEST_PARAM_NAME)) { // Overwrite both of them. - List toFlowDocumentIdParam = asList(caseStruct.navCase.getToFlowDocumentId()); + List toFlowDocumentIdParam = Collections.singletonList(caseStruct.navCase.getToFlowDocumentId()); parameters.put(TO_FLOW_DOCUMENT_ID_REQUEST_PARAM_NAME, toFlowDocumentIdParam); - List flowIdParam = asList(caseStruct.newFlow.getId()); + List flowIdParam = Collections.singletonList(caseStruct.newFlow.getId()); parameters.put(FLOW_ID_REQUEST_PARAM_NAME, flowIdParam); } } @@ -475,9 +475,7 @@ private void initializeNavigationFromFlowNonThreadSafe(Flow toInspect) { NavigationInfo info = new NavigationInfo(); if (!switches.isEmpty()) { info.switches = new ConcurrentHashMap<>(); - for (Map.Entry cur : switches.entrySet()) { - info.switches.put(cur.getKey(), cur.getValue()); - } + info.switches.putAll(switches); } if (!navRules.isEmpty()) { info.ruleSet = new NavigationMap(); @@ -544,7 +542,7 @@ private CaseStruct getViewId(FacesContext ctx, String fromAction, String outcome // if viewIdToTest is not null, use its value to find // a navigation match, otherwise look for a match - // based soley on the fromAction and outcome + // based solely on the fromAction and outcome CaseStruct caseStruct = null; Map> navMap = getNavigationMap(ctx); @@ -866,8 +864,8 @@ private CaseStruct findImplicitMatch(FacesContext context, String viewId, String Map appMap = context.getExternalContext().getApplicationMap(); String[] queryElements = Util.split(appMap, queryString, "&|&"); - for (int i = 0, len = queryElements.length; i < len; i++) { - String[] elements = Util.split(appMap, queryElements[i], "=", 2); + for (String queryElement : queryElements) { + String[] elements = Util.split(appMap, queryElement, "=", 2); if (elements.length == 2) { String rightHandSide = elements[1]; String sanitized = null != rightHandSide && 2 < rightHandSide.length() ? rightHandSide.trim() : ""; @@ -877,19 +875,12 @@ private CaseStruct findImplicitMatch(FacesContext context, String viewId, String } rightHandSide = ""; } + if (parameters == null) { - parameters = new LinkedHashMap<>(len / 2, 1.0f); - List values = new ArrayList<>(2); - values.add(rightHandSide); - parameters.put(elements[0], values); - } else { - List values = parameters.get(elements[0]); - if (values == null) { - values = new ArrayList<>(2); - parameters.put(elements[0], values); - } - values.add(rightHandSide); + parameters = new LinkedHashMap<>(queryElements.length / 2, 1.0f); } + + parameters.computeIfAbsent(elements[0], k -> new ArrayList<>(2)).add(rightHandSide); } } } diff --git a/impl/src/main/java/com/sun/faces/application/PropertyEditorHelper.java b/impl/src/main/java/com/sun/faces/application/PropertyEditorHelper.java index 588dfd2b5b..f432f0de4d 100644 --- a/impl/src/main/java/com/sun/faces/application/PropertyEditorHelper.java +++ b/impl/src/main/java/com/sun/faces/application/PropertyEditorHelper.java @@ -35,7 +35,7 @@ */ public class PropertyEditorHelper { - private Application app; + private final Application app; public PropertyEditorHelper(Application app) { this.app = app; @@ -49,7 +49,7 @@ public PropertyEditorHelper(Application app) { */ public Object convertToObject(Class targetClass, String textValue) { UIComponent component = getComponent(); - Converter converter = app.createConverter(targetClass); + Converter converter = app.createConverter(targetClass); if (null == converter) { // PENDING(edburns): I18N FacesException e = new FacesException( diff --git a/impl/src/main/java/com/sun/faces/application/applicationimpl/InstanceFactory.java b/impl/src/main/java/com/sun/faces/application/applicationimpl/InstanceFactory.java index 7617eec378..c7ffdee0d6 100644 --- a/impl/src/main/java/com/sun/faces/application/applicationimpl/InstanceFactory.java +++ b/impl/src/main/java/com/sun/faces/application/applicationimpl/InstanceFactory.java @@ -435,9 +435,9 @@ public Converter createConverter(String converterId) { /* * @see jakarta.faces.application.Application#createConverter(Class) */ - public Converter createConverter(Class targetClass) { + public Converter createConverter(Class targetClass) { notNull("targetClass", targetClass); - Converter returnVal = null; + Converter returnVal = null; BeanManager beanManager = getBeanManager(); returnVal = CdiUtils.createConverter(beanManager, targetClass); diff --git a/impl/src/main/java/com/sun/faces/application/applicationimpl/events/ComponentSystemEventHelper.java b/impl/src/main/java/com/sun/faces/application/applicationimpl/events/ComponentSystemEventHelper.java index 46fe5f1ad9..1b857ead67 100644 --- a/impl/src/main/java/com/sun/faces/application/applicationimpl/events/ComponentSystemEventHelper.java +++ b/impl/src/main/java/com/sun/faces/application/applicationimpl/events/ComponentSystemEventHelper.java @@ -17,16 +17,18 @@ package com.sun.faces.application.applicationimpl.events; import com.sun.faces.util.Cache; -import com.sun.faces.util.Cache.Factory; + import jakarta.faces.event.SystemEvent; +import java.util.function.Function; + /** * Utility class for dealing with {@link jakarta.faces.component.UIComponent} events. */ public class ComponentSystemEventHelper { - private Cache, Cache, EventInfo>> sourceCache; + private final Cache, Cache, EventInfo>> sourceCache; // -------------------------------------------------------- Constructors @@ -34,8 +36,8 @@ public ComponentSystemEventHelper() { // Initialize the 'sources' cache for, ahem, readability... // ~generics++ - Factory, Cache, EventInfo>> eventCacheFactory = sourceClass -> { - Factory, EventInfo> eventInfoFactory = systemEventClass -> new EventInfo(systemEventClass, sourceClass); + Cache.Factory, Cache, EventInfo>> eventCacheFactory = sourceClass -> { + Cache.Factory, EventInfo> eventInfoFactory = systemEventClass -> new EventInfo(systemEventClass, sourceClass); return new Cache<>(eventInfoFactory); }; sourceCache = new Cache<>(eventCacheFactory); diff --git a/impl/src/main/java/com/sun/faces/application/resource/ResourceCache.java b/impl/src/main/java/com/sun/faces/application/resource/ResourceCache.java index c722cbb5e0..7f104f2d52 100644 --- a/impl/src/main/java/com/sun/faces/application/resource/ResourceCache.java +++ b/impl/src/main/java/com/sun/faces/application/resource/ResourceCache.java @@ -51,12 +51,12 @@ public class ResourceCache { /** * The ResourceInfo cache. */ - private MultiKeyConcurrentHashMap resourceCache; + private final MultiKeyConcurrentHashMap resourceCache; /** * Resource check period in minutes. */ - private long checkPeriod; + private final long checkPeriod; // ------------------------------------------------------------ Constructors @@ -99,7 +99,7 @@ public ResourceInfo add(ResourceInfo info, List contracts) { if (LOGGER.isLoggable(FINE)) { LOGGER.log(FINE, "Caching ResourceInfo: {0}", info.toString()); } - ResourceInfoCheckPeriodProxy proxy = resourceCache.putIfAbsent(info.name, info.libraryName, info.localePrefix, new ArrayList(contracts), + ResourceInfoCheckPeriodProxy proxy = resourceCache.putIfAbsent(info.name, info.libraryName, info.localePrefix, new ArrayList<>(contracts), new ResourceInfoCheckPeriodProxy(info, checkPeriod)); return proxy != null ? proxy.getResourceInfo() : null; @@ -153,7 +153,7 @@ private static String getServletContextIdentifier(ServletContext context) { private static final class ResourceInfoCheckPeriodProxy { - private ResourceInfo resourceInfo; + private final ResourceInfo resourceInfo; private Long checkTime; // -------------------------------------------------------- Constructors diff --git a/impl/src/main/java/com/sun/faces/application/view/FaceletFullStateManagementStrategy.java b/impl/src/main/java/com/sun/faces/application/view/FaceletFullStateManagementStrategy.java index 96b7b8be92..655a32b090 100644 --- a/impl/src/main/java/com/sun/faces/application/view/FaceletFullStateManagementStrategy.java +++ b/impl/src/main/java/com/sun/faces/application/view/FaceletFullStateManagementStrategy.java @@ -87,12 +87,12 @@ public class FaceletFullStateManagementStrategy extends StateManagementStrategy /** * Stores the class map. */ - private Map> classMap; + private final Map> classMap; /** * Are we in development mode. */ - private boolean isDevelopmentMode; + private final boolean isDevelopmentMode; /** * Constructor. @@ -348,10 +348,10 @@ private void restoreComponentState(final FacesContext context, final HashMap state) { + private void restoreDynamicActions(FacesContext context, StateContext stateContext, Map state) { if (LOGGER.isLoggable(FINEST)) { LOGGER.finest("FaceletFullStateManagementStrategy.restoreDynamicActions"); } @@ -602,7 +602,7 @@ private Object saveComponentState(FacesContext context) { Object stateObj; if (!component.isTransient()) { if (stateContext.componentAddedDynamically(component)) { - component.getAttributes().put(DYNAMIC_COMPONENT, new Integer(getProperChildIndex(component))); + component.getAttributes().put(DYNAMIC_COMPONENT, getProperChildIndex(component)); stateObj = new StateHolderSaver(finalContext, component); } else { stateObj = component.saveState(finalContext); @@ -628,7 +628,7 @@ private Object saveComponentState(FacesContext context) { * * @param context the Faces context. * @param stateContext the state context. - * @param stateMap the state. + * */ private void saveDynamicActions(FacesContext context, StateContext stateContext, UIViewRoot viewRoot) { if (LOGGER.isLoggable(FINEST)) { @@ -636,7 +636,7 @@ private void saveDynamicActions(FacesContext context, StateContext stateContext, } List actions = stateContext.getDynamicActions(); - HashMap componentMap = stateContext.getDynamicComponents(); + Map componentMap = stateContext.getDynamicComponents(); if (actions != null) { List savedActions = new ArrayList<>(actions.size()); @@ -673,7 +673,7 @@ public Object saveView(FacesContext context) { */ Util.checkIdUniqueness(context, viewRoot, new HashSet<>(viewRoot.getChildCount() << 1)); - /** + /* * Save the dynamic actions. */ StateContext stateContext = StateContext.getStateContext(context); diff --git a/impl/src/main/java/com/sun/faces/application/view/FaceletPartialStateManagementStrategy.java b/impl/src/main/java/com/sun/faces/application/view/FaceletPartialStateManagementStrategy.java index 29e763978f..2cd49b6c09 100644 --- a/impl/src/main/java/com/sun/faces/application/view/FaceletPartialStateManagementStrategy.java +++ b/impl/src/main/java/com/sun/faces/application/view/FaceletPartialStateManagementStrategy.java @@ -392,7 +392,7 @@ private void saveDynamicActions(FacesContext context, StateContext stateContext, } List actions = stateContext.getDynamicActions(); - HashMap componentMap = stateContext.getDynamicComponents(); + Map componentMap = stateContext.getDynamicComponents(); if (actions != null) { List savedActions = new ArrayList<>(actions.size()); diff --git a/impl/src/main/java/com/sun/faces/application/view/FaceletViewHandlingStrategy.java b/impl/src/main/java/com/sun/faces/application/view/FaceletViewHandlingStrategy.java index 2324424349..3401c0187a 100644 --- a/impl/src/main/java/com/sun/faces/application/view/FaceletViewHandlingStrategy.java +++ b/impl/src/main/java/com/sun/faces/application/view/FaceletViewHandlingStrategy.java @@ -930,7 +930,7 @@ protected void handleRenderException(FacesContext context, Exception e) throws I // Always log if (LOGGER.isLoggable(SEVERE)) { UIViewRoot root = context.getViewRoot(); - StringBuffer sb = new StringBuffer(64); + StringBuilder sb = new StringBuilder(64); sb.append("Error Rendering View"); if (root != null) { sb.append('['); @@ -1148,7 +1148,7 @@ private boolean handlesByPrefixOrSuffix(String viewId) { // If there's no extensions array or prefixes array, then assume defaults. // .xhtml extension is handled by the FaceletViewHandler if (extensionsArray == null && prefixesArray == null) { - return isMatchedWithFaceletsSuffix(viewId) ? true : viewId.endsWith(DEFAULT_FACELETS_SUFFIX); + return isMatchedWithFaceletsSuffix(viewId) || viewId.endsWith(DEFAULT_FACELETS_SUFFIX); } if (extensionsArray != null) { @@ -1231,7 +1231,7 @@ private void retargetHandler(FacesContext context, AttachedObjectHandler handler private static final class MethodMetadataIterator implements Iterable, Iterator { private final PropertyDescriptor[] descriptors; - private FacesContext context; + private final FacesContext context; private int curIndex = -1; // -------------------------------------------------------- Constructors @@ -1364,7 +1364,7 @@ public String getTargetAttributeName(FacesContext ctx) { public boolean isRequired(FacesContext ctx) { ValueExpression rd = (ValueExpression) propertyDescriptor.getValue("required"); - return rd != null ? Boolean.valueOf(rd.getValue(ctx.getELContext()).toString()) : false; + return rd != null && Boolean.parseBoolean(rd.getValue(ctx.getELContext()).toString()); } @@ -1400,8 +1400,8 @@ public String getName() { */ private static final class MethodRetargetHandlerManager { - private Map handlerMap = new HashMap<>(4, 1.0f); - private MethodRetargetHandler arbitraryHandler = new ArbitraryMethodRegargetHandler(); + private final Map handlerMap = new HashMap<>(4, 1.0f); + private final MethodRetargetHandler arbitraryHandler = new ArbitraryMethodRegargetHandler(); // -------------------------------------------------------- Constructors @@ -1914,11 +1914,11 @@ private Stream mapIfNeeded(Stream views, ViewVisitOption... opti return views; } - return views.map(view -> toImplicitOutcome(view)); + return views.map(this::toImplicitOutcome); } private boolean returnAsImplicitOutCome(ViewVisitOption... options) { - return stream(options).filter(option -> option == RETURN_AS_MINIMAL_IMPLICIT_OUTCOME).findAny().isPresent(); + return stream(options).anyMatch(option -> option == RETURN_AS_MINIMAL_IMPLICIT_OUTCOME); } private String toImplicitOutcome(String viewId) { diff --git a/impl/src/main/java/com/sun/faces/cdi/CdiConverter.java b/impl/src/main/java/com/sun/faces/cdi/CdiConverter.java index 43695f8be4..ffb07cb9fb 100644 --- a/impl/src/main/java/com/sun/faces/cdi/CdiConverter.java +++ b/impl/src/main/java/com/sun/faces/cdi/CdiConverter.java @@ -24,7 +24,7 @@ /** * A delegate to the CDI managed converter. */ -public class CdiConverter implements Converter, StateHolder { +public class CdiConverter implements Converter, StateHolder { /** * Stores the converter-id (if any). @@ -34,12 +34,12 @@ public class CdiConverter implements Converter, StateHolder { /** * Stores a transient reference to the CDI managed converter. */ - private transient Converter delegate; + private transient Converter delegate; /** * Stores the for-class (if any). */ - private Class forClass; + private Class forClass; /** * Constructor. @@ -54,7 +54,7 @@ public CdiConverter() { * @param forClass the for class. * @param delegate the delegate. */ - public CdiConverter(String converterId, Class forClass, Converter delegate) { + public CdiConverter(String converterId, Class forClass, Converter delegate) { this.converterId = converterId; this.forClass = forClass; this.delegate = delegate; @@ -69,8 +69,8 @@ public CdiConverter(String converterId, Class forClass, Converter delegate) { * @return the object. */ @Override - public Object getAsObject(FacesContext facesContext, UIComponent component, String value) { - return getDelegate(facesContext).getAsObject(facesContext, component, value); + public T getAsObject(FacesContext facesContext, UIComponent component, String value) { + return (T) getDelegate(facesContext).getAsObject(facesContext, component, value); } /** @@ -82,8 +82,8 @@ public Object getAsObject(FacesContext facesContext, UIComponent component, Stri * @return the string. */ @Override - public String getAsString(FacesContext facesContext, UIComponent component, Object value) { - return getDelegate(facesContext).getAsString(facesContext, component, value); + public String getAsString(FacesContext facesContext, UIComponent component, T value) { + return ((Converter)getDelegate(facesContext)).getAsString(facesContext, component, value); } /** @@ -107,7 +107,7 @@ public Object saveState(FacesContext facesContext) { public void restoreState(FacesContext facesContext, Object state) { Object[] stateArray = (Object[]) state; converterId = (String) stateArray[0]; - forClass = (Class) stateArray[1]; + forClass = (Class) stateArray[1]; } /** @@ -139,9 +139,9 @@ public void setTransient(boolean transientValue) { * @param facesContext the Faces context. * @return the delegate. */ - private Converter getDelegate(FacesContext facesContext) { + private Converter getDelegate(FacesContext facesContext) { if (delegate == null) { - if (!converterId.equals("")) { + if (!"".equals(converterId)) { delegate = facesContext.getApplication().createConverter(converterId); } else { delegate = facesContext.getApplication().createConverter(forClass); diff --git a/impl/src/main/java/com/sun/faces/cdi/CdiUtils.java b/impl/src/main/java/com/sun/faces/cdi/CdiUtils.java index a79cd59eb9..4436182c96 100644 --- a/impl/src/main/java/com/sun/faces/cdi/CdiUtils.java +++ b/impl/src/main/java/com/sun/faces/cdi/CdiUtils.java @@ -106,19 +106,19 @@ public static Converter createConverter(BeanManager beanManager, String value * @param forClass the for class. * @return the converter, or null if we could not match one. */ - public static Converter createConverter(BeanManager beanManager, Class forClass) { - Converter managedConverter = null; + public static Converter createConverter(BeanManager beanManager, Class forClass) { + Converter managedConverter = null; for (Class forClassOrSuperclass = forClass; managedConverter == null && forClassOrSuperclass != null && forClassOrSuperclass != Object.class; forClassOrSuperclass = forClassOrSuperclass.getSuperclass()) { - managedConverter = createConverter(beanManager, FacesConverter.Literal.of("", forClassOrSuperclass, true)); + managedConverter = (Converter) createConverter(beanManager, FacesConverter.Literal.of("", forClassOrSuperclass, true)); } if (managedConverter != null) { ApplicationAssociate associate = ApplicationAssociate.getCurrentInstance(); associate.getAnnotationManager().applyConverterAnnotations(FacesContext.getCurrentInstance(), managedConverter); // #4913 - return new CdiConverter("", forClass, managedConverter); + return new CdiConverter<>("", forClass, managedConverter); } return null; @@ -261,10 +261,7 @@ private static String getBeanName(Bean bean) { String className = bean.getBeanClass().getSimpleName(); - return new StringBuilder() - .append(Character.toLowerCase(className.charAt(0))) - .append(className.substring(1)) - .toString(); + return Character.toLowerCase(className.charAt(0)) + className.substring(1); } /** diff --git a/impl/src/main/java/com/sun/faces/component/CompositeComponentStackManager.java b/impl/src/main/java/com/sun/faces/component/CompositeComponentStackManager.java index 203382e111..8e440e0b5b 100644 --- a/impl/src/main/java/com/sun/faces/component/CompositeComponentStackManager.java +++ b/impl/src/main/java/com/sun/faces/component/CompositeComponentStackManager.java @@ -371,7 +371,7 @@ private final class TreeCreationStackHandler extends BaseStackHandler { @Override public void pop() { - Stack s = getStack(false); + Stack s = getStack(false); if (s != null && !stack.isEmpty()) { stack.pop(); if (stack.isEmpty()) { diff --git a/impl/src/main/java/com/sun/faces/component/PassthroughElement.java b/impl/src/main/java/com/sun/faces/component/PassthroughElement.java index 98ef132021..004f7f8cec 100644 --- a/impl/src/main/java/com/sun/faces/component/PassthroughElement.java +++ b/impl/src/main/java/com/sun/faces/component/PassthroughElement.java @@ -376,7 +376,7 @@ private void handleAttribute(String name, Object value) { List setAttributes = (List) getAttributes().get("jakarta.faces.component.UIComponentBase.attributesThatAreSet"); if (setAttributes == null) { String cname = this.getClass().getName(); - if (cname != null && cname.startsWith(OPTIMIZED_PACKAGE)) { + if (cname.startsWith(OPTIMIZED_PACKAGE)) { setAttributes = new ArrayList<>(6); getAttributes().put("jakarta.faces.component.UIComponentBase.attributesThatAreSet", setAttributes); } diff --git a/impl/src/main/java/com/sun/faces/component/search/CompositeSearchKeywordResolver.java b/impl/src/main/java/com/sun/faces/component/search/CompositeSearchKeywordResolver.java index 9f8deb680f..c1c86e2a13 100644 --- a/impl/src/main/java/com/sun/faces/component/search/CompositeSearchKeywordResolver.java +++ b/impl/src/main/java/com/sun/faces/component/search/CompositeSearchKeywordResolver.java @@ -46,8 +46,7 @@ public void add(SearchKeywordResolver searchKeywordResolver) { public void resolve(SearchKeywordContext context, UIComponent current, String keyword) { context.setKeywordResolved(false); - for (int i = 0; i < resolvers.size(); i++) { - SearchKeywordResolver resolver = resolvers.get(i); + for (SearchKeywordResolver resolver : resolvers) { if (resolver.isResolverForKeyword(context.getSearchExpressionContext(), keyword)) { resolver.resolve(context, current, keyword); if (context.isKeywordResolved()) { @@ -59,8 +58,7 @@ public void resolve(SearchKeywordContext context, UIComponent current, String ke @Override public boolean isResolverForKeyword(SearchExpressionContext searchExpressionContext, String keyword) { - for (int i = 0; i < resolvers.size(); i++) { - SearchKeywordResolver resolver = resolvers.get(i); + for (SearchKeywordResolver resolver : resolvers) { if (resolver.isResolverForKeyword(searchExpressionContext, keyword)) { return true; } @@ -71,8 +69,7 @@ public boolean isResolverForKeyword(SearchExpressionContext searchExpressionCont @Override public boolean isPassthrough(SearchExpressionContext searchExpressionContext, String keyword) { - for (int i = 0; i < resolvers.size(); i++) { - SearchKeywordResolver resolver = resolvers.get(i); + for (SearchKeywordResolver resolver : resolvers) { if (resolver.isResolverForKeyword(searchExpressionContext, keyword)) { return resolver.isPassthrough(searchExpressionContext, keyword); } @@ -83,8 +80,7 @@ public boolean isPassthrough(SearchExpressionContext searchExpressionContext, St @Override public boolean isLeaf(SearchExpressionContext searchExpressionContext, String keyword) { - for (int i = 0; i < resolvers.size(); i++) { - SearchKeywordResolver resolver = resolvers.get(i); + for (SearchKeywordResolver resolver : resolvers) { if (resolver.isResolverForKeyword(searchExpressionContext, keyword)) { return resolver.isLeaf(searchExpressionContext, keyword); } diff --git a/impl/src/main/java/com/sun/faces/component/search/SearchExpressionHandlerImpl.java b/impl/src/main/java/com/sun/faces/component/search/SearchExpressionHandlerImpl.java index f12fb58297..5950fa0e4e 100644 --- a/impl/src/main/java/com/sun/faces/component/search/SearchExpressionHandlerImpl.java +++ b/impl/src/main/java/com/sun/faces/component/search/SearchExpressionHandlerImpl.java @@ -35,9 +35,7 @@ public class SearchExpressionHandlerImpl extends SearchExpressionHandler { protected void addHint(SearchExpressionContext searchExpressionContext, SearchExpressionHint hint) { // It is a Set already - if (!searchExpressionContext.getExpressionHints().contains(hint)) { - searchExpressionContext.getExpressionHints().add(hint); - } + searchExpressionContext.getExpressionHints().add(hint); } @Override @@ -340,6 +338,7 @@ public String[] splitExpressions(FacesContext context, String expressions) { for (char separator : separators) { if (c == separator) { isSeparator = true; + break; } } @@ -362,7 +361,7 @@ public String[] splitExpressions(FacesContext context, String expressions) { // lets not forget about part after the separator tokens.add(buffer.toString()); - return tokens.toArray(new String[tokens.size()]); + return tokens.toArray(new String[0]); } @Override diff --git a/impl/src/main/java/com/sun/faces/component/validator/ComponentValidators.java b/impl/src/main/java/com/sun/faces/component/validator/ComponentValidators.java index dc897b7186..ef5b6bca4c 100644 --- a/impl/src/main/java/com/sun/faces/component/validator/ComponentValidators.java +++ b/impl/src/main/java/com/sun/faces/component/validator/ComponentValidators.java @@ -16,12 +16,7 @@ package com.sun.faces.component.validator; -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; import com.sun.faces.facelets.tag.faces.ComponentSupport; import com.sun.faces.util.RequestStateManager; @@ -137,23 +132,17 @@ public void addValidators(FacesContext ctx, EditableValueHolder editableValueHol Map defaultValidatorInfo = application.getDefaultValidatorInfo(); Set keySet = defaultValidatorInfo.keySet(); - List validatorIds = new ArrayList<>(keySet.size()); - for (String key : keySet) { - validatorIds.add(key); - } + // the same order of keySet ... defaultValidatorInfo is a LinkedHashMap ... + Collection validatorIds = new LinkedHashSet<>(keySet); Set disabledIds = (Set) RequestStateManager.remove(ctx, RequestStateManager.DISABLED_VALIDATORS); int count = validatorStack.size(); for (int i = count - 1; i >= 0; i--) { ValidatorInfo info = validatorStack.get(i); if (!info.isEnabled() || disabledIds != null && disabledIds.contains(info.getValidatorId())) { - if (validatorIds.contains(info.getValidatorId())) { - validatorIds.remove(info.getValidatorId()); - } + validatorIds.remove(info.getValidatorId()); } else { - if (!validatorIds.contains(info.getValidatorId())) { - validatorIds.add(info.getValidatorId()); - } + validatorIds.add(info.getValidatorId()); } } @@ -209,11 +198,11 @@ private static void addValidatorsToComponent(FacesContext ctx, Collection defaultValidatorInfo = application.getDefaultValidatorInfo(); - Validator[] validators = editableValueHolder.getValidators(); + Validator[] validators = editableValueHolder.getValidators(); // check to make sure that Validator instances haven't already // been added. for (Map.Entry defaultValidator : defaultValidatorInfo.entrySet()) { - for (Validator validator : validators) { + for (Validator validator : validators) { if (defaultValidator.getValue().equals(validator.getClass().getName())) { validatorIds.remove(defaultValidator.getKey()); break; @@ -222,9 +211,9 @@ private static void addValidatorsToComponent(FacesContext ctx, Collection v = application.createValidator(id); // work backwards up the stack of ValidatorInfo to find the // nearest matching ValidatorInfo to apply attributes if (validatorStack != null) { @@ -248,10 +237,10 @@ private static void addValidatorsToComponent(FacesContext ctx, Collection v) { owner.setAttributes(ctx, v); diff --git a/impl/src/main/java/com/sun/faces/component/visit/FullVisitContext.java b/impl/src/main/java/com/sun/faces/component/visit/FullVisitContext.java index 34880854bb..00b2b522ec 100644 --- a/impl/src/main/java/com/sun/faces/component/visit/FullVisitContext.java +++ b/impl/src/main/java/com/sun/faces/component/visit/FullVisitContext.java @@ -126,8 +126,8 @@ public VisitResult invokeVisitCallback(UIComponent component, VisitCallback call } // The FacesContext for this request - private FacesContext facesContext; + private final FacesContext facesContext; // Our visit hints - private Set hints; + private final Set hints; } diff --git a/impl/src/main/java/com/sun/faces/component/visit/PartialVisitContext.java b/impl/src/main/java/com/sun/faces/component/visit/PartialVisitContext.java index ff6e7d9386..94fcfdf9b7 100644 --- a/impl/src/main/java/com/sun/faces/component/visit/PartialVisitContext.java +++ b/impl/src/main/java/com/sun/faces/component/visit/PartialVisitContext.java @@ -309,12 +309,7 @@ private void addSubtreeClientId(String clientId) { // NamingContainer client id. If not, create the // Collection for this NamingContainer client id and // stash it away in our map - Collection c = subtreeClientIds.get(namingContainerClientId); - - if (c == null) { - c = new ArrayList<>(); - subtreeClientIds.put(namingContainerClientId, c); - } + Collection c = subtreeClientIds.computeIfAbsent(namingContainerClientId, k -> new ArrayList<>()); // Stash away the client id c.add(clientId); @@ -373,7 +368,7 @@ public boolean add(E o) { return added; } - private Collection wrapped; + private final Collection wrapped; } // Little proxy iterator implementation used by CollectionProxy @@ -405,7 +400,7 @@ public void remove() { wrapped.remove(); } - private Iterator wrapped; + private final Iterator wrapped; private E current = null; } @@ -426,8 +421,8 @@ public void remove() { private Map> subtreeClientIds; // The FacesContext for this request - private FacesContext facesContext; + private final FacesContext facesContext; // Our visit hints - private Set hints; + private final Set hints; } diff --git a/impl/src/main/java/com/sun/faces/component/visit/VisitContextFactoryImpl.java b/impl/src/main/java/com/sun/faces/component/visit/VisitContextFactoryImpl.java index 614c8e0ee8..753633cb01 100644 --- a/impl/src/main/java/com/sun/faces/component/visit/VisitContextFactoryImpl.java +++ b/impl/src/main/java/com/sun/faces/component/visit/VisitContextFactoryImpl.java @@ -37,7 +37,7 @@ public VisitContextFactoryImpl() { @Override public VisitContext getVisitContext(FacesContext context, Collection ids, Set hints) { - VisitContext result = null; + VisitContext result; // If ids null (not empty), we create a FullVisitContext. // Otherwise, we create a PartialVisitContext. Note that diff --git a/impl/src/main/java/com/sun/faces/config/ConfigManager.java b/impl/src/main/java/com/sun/faces/config/ConfigManager.java index 99591b0bb5..93a1d2e584 100644 --- a/impl/src/main/java/com/sun/faces/config/ConfigManager.java +++ b/impl/src/main/java/com/sun/faces/config/ConfigManager.java @@ -128,10 +128,9 @@ public class ConfigManager { * when the application is destroyed. *

*/ - private List initializedContexts = new CopyOnWriteArrayList<>(); + private final List initializedContexts = new CopyOnWriteArrayList<>(); - private final List configProcessors = unmodifiableList( - asList( + private final List configProcessors = List.of( new FactoryConfigProcessor(), new LifecycleConfigProcessor(), new ApplicationConfigProcessor(), @@ -144,7 +143,7 @@ public class ConfigManager { new FacesConfigExtensionProcessor(), new ProtectedViewsConfigProcessor(), new FacesFlowDefinitionConfigProcessor(), - new ResourceLibraryContractsConfigProcessor())); + new ResourceLibraryContractsConfigProcessor()); /** *

@@ -152,8 +151,8 @@ public class ConfigManager { * Mojarra, and two other providers to satisfy the requirements of the specification. *

*/ - private final List facesConfigProviders = unmodifiableList( - asList(new MetaInfFacesConfigResourceProvider(), new WebAppFlowConfigResourceProvider(), new WebFacesConfigResourceProvider())); + private final List facesConfigProviders = List.of( + new MetaInfFacesConfigResourceProvider(), new WebAppFlowConfigResourceProvider(), new WebFacesConfigResourceProvider()); /** *

@@ -161,8 +160,8 @@ public class ConfigManager { * Mojarra, and one other providers to satisfy the requirements of the specification. *

*/ - private final List facesletsTagLibConfigProviders = unmodifiableList( - asList(new MetaInfFaceletTaglibraryConfigProvider(), new WebFaceletTaglibResourceProvider())); + private final List facesletsTagLibConfigProviders = List.of( + new MetaInfFaceletTaglibraryConfigProvider(), new WebFaceletTaglibResourceProvider()); /** *

@@ -260,7 +259,7 @@ public void initialize(ServletContext servletContext, InitFacesContext facesCont // from each document. DocumentInfo[] facesDocuments2 = facesDocuments; - configProcessors.subList(0, 3).stream().forEach(e -> { + configProcessors.subList(0, 3).forEach(e -> { try { e.process(servletContext, facesContext, facesDocuments2); } catch (Exception e2) { @@ -275,7 +274,7 @@ public void initialize(ServletContext servletContext, InitFacesContext facesCont ThreadContext threadContext = getThreadContext(containerConnector); Object parentWebContext = threadContext != null ? threadContext.getParentWebContext() : null; - configProcessors.subList(3, configProcessors.size()).stream().forEach(e -> { + configProcessors.subList(3, configProcessors.size()).forEach(e -> { long currentThreadId = Thread.currentThread().getId(); @@ -403,7 +402,7 @@ private List getConfigPopulators() { configPopulators.add(new MojarraRuntimePopulator()); - ServiceLoader.load(ApplicationConfigurationPopulator.class).forEach(e -> configPopulators.add(e)); + ServiceLoader.load(ApplicationConfigurationPopulator.class).forEach(configPopulators::add); return configPopulators; } @@ -477,7 +476,7 @@ private void releaseFactories() { * @param servletContext the ServletContext for the application that needs to be removed */ public void destroy(ServletContext servletContext, FacesContext facesContext) { - configProcessors.stream().forEach(e -> e.destroy(servletContext, facesContext)); + configProcessors.forEach(e -> e.destroy(servletContext, facesContext)); initializedContexts.remove(servletContext); } diff --git a/impl/src/main/java/com/sun/faces/config/ConfigureListener.java b/impl/src/main/java/com/sun/faces/config/ConfigureListener.java index fa975e1f73..545f2f36d6 100644 --- a/impl/src/main/java/com/sun/faces/config/ConfigureListener.java +++ b/impl/src/main/java/com/sun/faces/config/ConfigureListener.java @@ -702,7 +702,7 @@ public WebConfigResourceMonitor(ServletContext servletContext, Collection u monitors.add(new Monitor(uri)); } catch (IOException ioe) { LOGGER.log(SEVERE, () -> "Unable to setup resource monitor for " + uri.toString() + ". Resource will not be monitored for changes."); - LOGGER.log(FINE, ioe, () -> ioe.toString()); + LOGGER.log(FINE, ioe, ioe::toString); } } diff --git a/impl/src/main/java/com/sun/faces/config/FaceletsConfiguration.java b/impl/src/main/java/com/sun/faces/config/FaceletsConfiguration.java index bd7b289636..ddb6fc793a 100644 --- a/impl/src/main/java/com/sun/faces/config/FaceletsConfiguration.java +++ b/impl/src/main/java/com/sun/faces/config/FaceletsConfiguration.java @@ -36,11 +36,11 @@ public class FaceletsConfiguration { // private static final String CONSUME_COMMENTS_ATTRIBUTE_NAME = "com.sun.faces.config.ConsumeComments"; - private static Pattern EXTENSION_PATTERN = Pattern.compile("\\.[^/]+$"); + private static final Pattern EXTENSION_PATTERN = Pattern.compile("\\.[^/]+$"); - private WebConfiguration config; + private final WebConfiguration config; - private Map faceletsProcessingMappings; + private final Map faceletsProcessingMappings; public FaceletsConfiguration(WebConfiguration config) { this.config = config; diff --git a/impl/src/main/java/com/sun/faces/config/InitFacesContext.java b/impl/src/main/java/com/sun/faces/config/InitFacesContext.java index 96c3312dec..d2f88c00c5 100644 --- a/impl/src/main/java/com/sun/faces/config/InitFacesContext.java +++ b/impl/src/main/java/com/sun/faces/config/InitFacesContext.java @@ -51,7 +51,7 @@ */ public class InitFacesContext extends NoOpFacesContext { - private static Logger LOGGER = FacesLogger.CONFIG.getLogger(); + private static final Logger LOGGER = FacesLogger.CONFIG.getLogger(); private static final String INIT_FACES_CONTEXT_ATTR_NAME = RIConstants.FACES_PREFIX + "InitFacesContext"; private ServletContextAdapter servletContextAdapter; diff --git a/impl/src/main/java/com/sun/faces/config/Verifier.java b/impl/src/main/java/com/sun/faces/config/Verifier.java index dc35d7a28c..8afdd89ec1 100644 --- a/impl/src/main/java/com/sun/faces/config/Verifier.java +++ b/impl/src/main/java/com/sun/faces/config/Verifier.java @@ -46,7 +46,7 @@ public enum ObjectType { /** * Container for any messages that may be queued. */ - private List messages; + private final List messages; // ------------------------------------------------------- Constructors @@ -126,7 +126,7 @@ public void validateObject(ObjectType type, String className, Class assignabl if (c != null) { try { - Constructor ctor = c.getConstructor(RIConstants.EMPTY_CLASS_ARGS); + Constructor ctor = c.getConstructor(RIConstants.EMPTY_CLASS_ARGS); if (!Modifier.isPublic(ctor.getModifiers())) { messages.add(MessageUtils.getExceptionMessageString(MessageUtils.VERIFIER_CTOR_NOT_PUBLIC_ID, type, className)); } diff --git a/impl/src/main/java/com/sun/faces/config/WebConfiguration.java b/impl/src/main/java/com/sun/faces/config/WebConfiguration.java index 012bb5cd16..ae798b3ed4 100644 --- a/impl/src/main/java/com/sun/faces/config/WebConfiguration.java +++ b/impl/src/main/java/com/sun/faces/config/WebConfiguration.java @@ -95,19 +95,19 @@ public class WebConfiguration { // Logging level. Defaults to FINE private Level loggingLevel = Level.FINE; - private Map booleanContextParameters = new EnumMap<>(BooleanWebContextInitParameter.class); + private final Map booleanContextParameters = new EnumMap<>(BooleanWebContextInitParameter.class); - private Map contextParameters = new EnumMap<>(WebContextInitParameter.class); + private final Map contextParameters = new EnumMap<>(WebContextInitParameter.class); - private Map> facesConfigParameters = new EnumMap<>(WebContextInitParameter.class); + private final Map> facesConfigParameters = new EnumMap<>(WebContextInitParameter.class); - private Map envEntries = new EnumMap<>(WebEnvironmentEntry.class); + private final Map envEntries = new EnumMap<>(WebEnvironmentEntry.class); - private Map cachedListParams; + private final Map cachedListParams; - private Set setParams = new HashSet<>(); + private final Set setParams = new HashSet<>(); - private ServletContext servletContext; + private final ServletContext servletContext; private ArrayList deferredLoggingActions; @@ -315,7 +315,7 @@ public void overrideContextInitParameter(BooleanWebContextInitParameter param, b return; } - boolean oldVal = booleanContextParameters.put(param, value); + boolean oldVal = Boolean.TRUE.equals(booleanContextParameters.put(param, value)); if (LOGGER.isLoggable(FINE) && oldVal != value) { LOGGER.log(FINE, "Overriding init parameter {0}. Changing from {1} to {2}.", new Object[] { param.getQualifiedName(), oldVal, value }); } @@ -462,8 +462,7 @@ private void discoverResourceLibraryContracts() { } } } else { - contractsToExpose = new ArrayList<>(); - contractsToExpose.addAll(foundContracts); + contractsToExpose = new ArrayList<>(foundContracts); contractMappings.put("*", contractsToExpose); } extContex.getApplicationMap().put(FaceletViewHandlingStrategy.RESOURCE_LIBRARY_CONTRACT_DATA_STRUCTURE_KEY, contractMappings); @@ -513,7 +512,7 @@ private boolean isValueValid(BooleanWebContextInitParameter param, String value) */ private void processBooleanParameters(ServletContext servletContext, String contextName) { - // process boolean contxt parameters + // process boolean context parameters for (BooleanWebContextInitParameter param : BooleanWebContextInitParameter.values()) { String strValue = servletContext.getInitParameter(param.getQualifiedName()); boolean value; @@ -534,12 +533,12 @@ private void processBooleanParameters(ServletContext servletContext, String cont if (alternate != null) { if (isValueValid(param, strValue)) { - value = Boolean.valueOf(strValue); + value = Boolean.parseBoolean(strValue); } else { value = param.getDefaultValue(); } - if (LOGGER.isLoggable(Level.INFO) && alternate != null) { + if (LOGGER.isLoggable(Level.INFO)) { queueLoggingAction(new DeferredBooleanParameterLoggingAction(param, Level.INFO, value ? "faces.config.webconfig.configinfo.reset.enabled" : "faces.config.webconfig.configinfo.reset.disabled", new Object[] { contextName, alternate.getQualifiedName() })); @@ -555,7 +554,7 @@ private void processBooleanParameters(ServletContext servletContext, String cont value = param.getDefaultValue(); } else { if (isValueValid(param, strValue)) { - value = Boolean.valueOf(strValue); + value = Boolean.parseBoolean(strValue); } else { value = param.getDefaultValue(); } @@ -586,8 +585,8 @@ private void processBooleanParameters(ServletContext servletContext, String cont * @param servletContext the ServletContext of interest */ private void initSetList(ServletContext servletContext) { - for (Enumeration e = servletContext.getInitParameterNames(); e.hasMoreElements();) { - String name = e.nextElement().toString(); + for (Enumeration e = servletContext.getInitParameterNames(); e.hasMoreElements();) { + String name = e.nextElement(); if (name.startsWith("com.sun.faces") || name.startsWith("jakarta.faces")) { setParams.add(name); } @@ -677,9 +676,9 @@ private void processJndiEntries(String contextName) { initialContext = new InitialContext(); } catch (NoClassDefFoundError nde) { // On google app engine InitialContext is forbidden to use and GAE throws NoClassDefFoundError - LOGGER.log(FINE, nde, () -> nde.toString()); + LOGGER.log(FINE, nde, nde::toString); } catch (NamingException ne) { - LOGGER.log(Level.WARNING, ne, () -> ne.toString()); + LOGGER.log(Level.WARNING, ne, ne::toString); } if (initialContext != null) { @@ -691,7 +690,7 @@ private void processJndiEntries(String contextName) { try { value = (String) initialContext.lookup(entryName); } catch (NamingException root) { - LOGGER.log(Level.FINE, () -> root.toString()); + LOGGER.log(Level.FINE, root::toString); } if (value != null) { @@ -778,11 +777,11 @@ public enum WebContextInitParameter { WebAppContractsDirectory(ResourceHandler.WEBAPP_CONTRACTS_DIRECTORY_PARAM_NAME, "/contracts"), ; - private String defaultValue; - private String qualifiedName; - private WebContextInitParameter alternate; - private boolean deprecated; - private DeprecationLoggingStrategy loggingStrategy; + private final String defaultValue; + private final String qualifiedName; + private final WebContextInitParameter alternate; + private final boolean deprecated; + private final DeprecationLoggingStrategy loggingStrategy; // ---------------------------------------------------------- Public Methods @@ -888,12 +887,12 @@ public enum BooleanWebContextInitParameter { UseFaceletsID("com.sun.faces.useFaceletsID",false), ; - private BooleanWebContextInitParameter alternate; + private final BooleanWebContextInitParameter alternate; - private String qualifiedName; - private boolean defaultValue; - private boolean deprecated; - private DeprecationLoggingStrategy loggingStrategy; + private final String qualifiedName; + private final boolean defaultValue; + private final boolean deprecated; + private final DeprecationLoggingStrategy loggingStrategy; // ---------------------------------------------------------- Public Methods @@ -952,7 +951,7 @@ public enum WebEnvironmentEntry { ProjectStage(jakarta.faces.application.ProjectStage.PROJECT_STAGE_JNDI_NAME); private static final String JNDI_PREFIX = "java:comp/env/"; - private String qualifiedName; + private final String qualifiedName; // ---------------------------------------------------------- Public Methods @@ -1017,10 +1016,10 @@ private interface DeferredLoggingAction { private class DeferredParameterLoggingAction implements DeferredLoggingAction { - private WebContextInitParameter parameter; - private Level loggingLevel; - private String logKey; - private Object[] params; + private final WebContextInitParameter parameter; + private final Level loggingLevel; + private final String logKey; + private final Object[] params; DeferredParameterLoggingAction(WebContextInitParameter parameter, Level loggingLevel, String logKey, Object[] params) { @@ -1047,10 +1046,10 @@ public void log() { private class DeferredBooleanParameterLoggingAction implements DeferredLoggingAction { - private BooleanWebContextInitParameter parameter; - private Level loggingLevel; - private String logKey; - private Object[] params; + private final BooleanWebContextInitParameter parameter; + private final Level loggingLevel; + private final String logKey; + private final Object[] params; DeferredBooleanParameterLoggingAction(BooleanWebContextInitParameter parameter, Level loggingLevel, String logKey, Object[] params) { this.parameter = parameter; diff --git a/impl/src/main/java/com/sun/faces/config/configprovider/BaseWebConfigResourceProvider.java b/impl/src/main/java/com/sun/faces/config/configprovider/BaseWebConfigResourceProvider.java index 3d11fb7eda..70615c9edc 100644 --- a/impl/src/main/java/com/sun/faces/config/configprovider/BaseWebConfigResourceProvider.java +++ b/impl/src/main/java/com/sun/faces/config/configprovider/BaseWebConfigResourceProvider.java @@ -86,7 +86,7 @@ protected URI getContextURLForPath(ServletContext context, String path) { try { URL url = context.getResource(path); if (url != null) { - return new URI(url.toExternalForm().replaceAll(" ", "%20")); + return new URI(url.toExternalForm().replace(" ", "%20")); } } catch (MalformedURLException | URISyntaxException mue) { throw new FacesException(mue); diff --git a/impl/src/main/java/com/sun/faces/config/configprovider/MetaInfFaceletTaglibraryConfigProvider.java b/impl/src/main/java/com/sun/faces/config/configprovider/MetaInfFaceletTaglibraryConfigProvider.java index 2900ef7e95..abd9739a79 100644 --- a/impl/src/main/java/com/sun/faces/config/configprovider/MetaInfFaceletTaglibraryConfigProvider.java +++ b/impl/src/main/java/com/sun/faces/config/configprovider/MetaInfFaceletTaglibraryConfigProvider.java @@ -64,7 +64,7 @@ public Collection getResources(ServletContext context) { } return resourceURLs.stream() - .map(url -> transformToURI(url)) + .map(this::transformToURI) .collect(toList()); } catch (IOException ioe) { @@ -76,7 +76,7 @@ public Collection getResources(ServletContext context) { private URI transformToURI(URL url) { try { - return new URI(url.toExternalForm().replaceAll(" ", "%20")); + return new URI(url.toExternalForm().replace(" ", "%20")); } catch (URISyntaxException ex) { throw new FacesException(ex); } diff --git a/impl/src/main/java/com/sun/faces/config/configprovider/MetaInfFacesConfigResourceProvider.java b/impl/src/main/java/com/sun/faces/config/configprovider/MetaInfFacesConfigResourceProvider.java index 40501e2257..e0c0504b89 100644 --- a/impl/src/main/java/com/sun/faces/config/configprovider/MetaInfFacesConfigResourceProvider.java +++ b/impl/src/main/java/com/sun/faces/config/configprovider/MetaInfFacesConfigResourceProvider.java @@ -98,11 +98,7 @@ public Collection getResources(ServletContext context) { } } - Set uris = sortedJarMap.get(jarName); - if (uris == null) { - uris = new HashSet<>(); - sortedJarMap.put(jarName, uris); - } + Set uris = sortedJarMap.computeIfAbsent(jarName, k -> new HashSet<>()); uris.add(uri); } else { unsortedResourceList.add(0, uri); @@ -131,7 +127,7 @@ private Collection loadURLs(ServletContext context) throws IOException { try { for (Enumeration e = Util.getCurrentLoader(this).getResources(META_INF_RESOURCES); e.hasMoreElements();) { String urlString = e.nextElement().toExternalForm(); - urlString = urlString.replaceAll(" ", "%20"); + urlString = urlString.replace(" ", "%20"); urls.add(new URI(urlString)); } URL[] urlArray = Classpath.search("META-INF/", FACES_CONFIG_EXTENSION); @@ -141,7 +137,7 @@ private Collection loadURLs(ServletContext context) throws IOException { urls.add(new URI(urlString)); } // special case for finding taglib files in WEB-INF/classes/META-INF - Set paths = context.getResourcePaths(WEB_INF_CLASSES); + Set paths = context.getResourcePaths(WEB_INF_CLASSES); if (paths != null) { for (Object path : paths) { String p = path.toString(); diff --git a/impl/src/main/java/com/sun/faces/config/configprovider/WebAppFlowConfigResourceProvider.java b/impl/src/main/java/com/sun/faces/config/configprovider/WebAppFlowConfigResourceProvider.java index 8a6a6c349d..1c5d9864bd 100644 --- a/impl/src/main/java/com/sun/faces/config/configprovider/WebAppFlowConfigResourceProvider.java +++ b/impl/src/main/java/com/sun/faces/config/configprovider/WebAppFlowConfigResourceProvider.java @@ -74,7 +74,7 @@ public Collection getResources(ServletContext context) { } } - return null == list ? Collections.EMPTY_LIST : list; + return null == list ? Collections.emptyList() : list; } diff --git a/impl/src/main/java/com/sun/faces/config/initfacescontext/NoOpFacesContext.java b/impl/src/main/java/com/sun/faces/config/initfacescontext/NoOpFacesContext.java index 01e7ca954c..0dec948301 100644 --- a/impl/src/main/java/com/sun/faces/config/initfacescontext/NoOpFacesContext.java +++ b/impl/src/main/java/com/sun/faces/config/initfacescontext/NoOpFacesContext.java @@ -16,8 +16,10 @@ package com.sun.faces.config.initfacescontext; +import static java.util.Collections.emptyIterator; import static java.util.Collections.emptyList; +import java.util.Collections; import java.util.Iterator; import java.util.List; @@ -38,8 +40,7 @@ public Lifecycle getLifecycle() { @Override public Iterator getClientIdsWithMessages() { - List list = emptyList(); - return list.iterator(); + return emptyIterator(); } @Override @@ -49,8 +50,7 @@ public FacesMessage.Severity getMaximumSeverity() { @Override public Iterator getMessages() { - List list = emptyList(); - return list.iterator(); + return emptyIterator(); } @Override diff --git a/impl/src/main/java/com/sun/faces/config/initfacescontext/ServletContextAdapter.java b/impl/src/main/java/com/sun/faces/config/initfacescontext/ServletContextAdapter.java index b8bd6de4b9..7d5185908c 100644 --- a/impl/src/main/java/com/sun/faces/config/initfacescontext/ServletContextAdapter.java +++ b/impl/src/main/java/com/sun/faces/config/initfacescontext/ServletContextAdapter.java @@ -165,17 +165,17 @@ public String getRequestContextPath() { @Override public Map getRequestCookieMap() { - return unmodifiableMap(emptyMap()); + return emptyMap(); } @Override public Map getRequestHeaderMap() { - return unmodifiableMap(emptyMap()); + return emptyMap(); } @Override public Map getRequestHeaderValuesMap() { - return unmodifiableMap(emptyMap()); + return emptyMap(); } @Override @@ -195,17 +195,17 @@ public Map getRequestMap() { @Override public Map getRequestParameterMap() { - return unmodifiableMap(emptyMap()); + return emptyMap(); } @Override public Iterator getRequestParameterNames() { - return Collections.emptyList().iterator(); + return Collections.emptyIterator(); } @Override public Map getRequestParameterValuesMap() { - return unmodifiableMap(emptyMap()); + return emptyMap(); } @Override diff --git a/impl/src/main/java/com/sun/faces/config/manager/DbfFactory.java b/impl/src/main/java/com/sun/faces/config/manager/DbfFactory.java index 4e9011d019..be7249ae93 100644 --- a/impl/src/main/java/com/sun/faces/config/manager/DbfFactory.java +++ b/impl/src/main/java/com/sun/faces/config/manager/DbfFactory.java @@ -103,7 +103,7 @@ private static class FacesEntityResolver extends DefaultHandler implements LSRes * Contains mapping between grammar name and the local URL to the * physical resource. */ - private HashMap entities = new HashMap<>(12, 1.0f); + private final HashMap entities = new HashMap<>(12, 1.0f); // -------------------------------------------------------- Constructors @@ -129,7 +129,7 @@ public FacesEntityResolver() { try { schemaUrl = schemaFile.toURI().toURL(); } catch (MalformedURLException mue) { - LOGGER.log(SEVERE, mue, () -> mue.toString()); + LOGGER.log(SEVERE, mue, mue::toString); } if (schemaUrl == null) { @@ -353,7 +353,7 @@ private static Map getSchemaMap(ServletContext servletConte if (schemaMap == null) { synchronized (servletContext) { - schemaMap = synchronizedMap(new EnumMap(FacesSchema.class)); + schemaMap = synchronizedMap(new EnumMap<>(FacesSchema.class)); servletContext.setAttribute(SCHEMA_MAP, schemaMap); } } diff --git a/impl/src/main/java/com/sun/faces/config/manager/Documents.java b/impl/src/main/java/com/sun/faces/config/manager/Documents.java index 1c946b6ad7..450972de58 100644 --- a/impl/src/main/java/com/sun/faces/config/manager/Documents.java +++ b/impl/src/main/java/com/sun/faces/config/manager/Documents.java @@ -117,7 +117,7 @@ public static DocumentInfo[] getXMLDocuments(ServletContext servletContext, List } } - return docs.toArray(new DocumentInfo[docs.size()]); + return docs.toArray(new DocumentInfo[0]); } public static List getProgrammaticDocuments(List configPopulators) throws ParserConfigurationException { @@ -192,7 +192,7 @@ public static DocumentInfo[] sortDocuments(DocumentInfo[] facesDocuments, FacesC list.add(new DocumentOrderingWrapper(facesDocuments[i])); } - DocumentOrderingWrapper[] ordering = list.toArray(new DocumentOrderingWrapper[list.size()]); + DocumentOrderingWrapper[] ordering = list.toArray(new DocumentOrderingWrapper[0]); if (absoluteOrdering == null) { DocumentOrderingWrapper.sort(ordering); diff --git a/impl/src/main/java/com/sun/faces/config/manager/FacesConfigInfo.java b/impl/src/main/java/com/sun/faces/config/manager/FacesConfigInfo.java index 8686434fe3..cc04c296bb 100644 --- a/impl/src/main/java/com/sun/faces/config/manager/FacesConfigInfo.java +++ b/impl/src/main/java/com/sun/faces/config/manager/FacesConfigInfo.java @@ -48,8 +48,8 @@ public class FacesConfigInfo { private static final String OTHERS = "others"; private double version = 2.0; - private boolean isWebInfFacesConfig; - private boolean metadataComplete; + private final boolean isWebInfFacesConfig; + private final boolean metadataComplete; private List absoluteOrdering; // -------------------------------------------------------- Constructors @@ -141,7 +141,7 @@ private boolean isMetadataComplete(Document document) { if (isVersionGreaterOrEqual(2.0)) { String metadataComplete = document.getDocumentElement().getAttributeNS(document.getNamespaceURI(), "metadata-complete"); - return metadataComplete != null ? Boolean.valueOf(metadataComplete) : false; + return metadataComplete != null && Boolean.parseBoolean(metadataComplete); } // not a 2.0 application, so annotation processing will not occur diff --git a/impl/src/main/java/com/sun/faces/context/AjaxNoAjaxExceptionHandler.java b/impl/src/main/java/com/sun/faces/context/AjaxNoAjaxExceptionHandler.java index c397d3a113..b1690966ac 100644 --- a/impl/src/main/java/com/sun/faces/context/AjaxNoAjaxExceptionHandler.java +++ b/impl/src/main/java/com/sun/faces/context/AjaxNoAjaxExceptionHandler.java @@ -22,7 +22,7 @@ public class AjaxNoAjaxExceptionHandler extends ExceptionHandlerWrapper { - private AjaxExceptionHandlerImpl ajaxExceptionHandlerImpl; + private final AjaxExceptionHandlerImpl ajaxExceptionHandlerImpl; public AjaxNoAjaxExceptionHandler(AjaxExceptionHandlerImpl ajaxExceptionHandlerImpl, ExceptionHandlerImpl exceptionHandlerImpl) { super(exceptionHandlerImpl); diff --git a/impl/src/main/java/com/sun/faces/context/ApplicationMap.java b/impl/src/main/java/com/sun/faces/context/ApplicationMap.java index aa18cc0ecb..eda242697e 100644 --- a/impl/src/main/java/com/sun/faces/context/ApplicationMap.java +++ b/impl/src/main/java/com/sun/faces/context/ApplicationMap.java @@ -45,18 +45,15 @@ public Object getContext() { @Override public void clear() { - for (Enumeration e = servletContext.getAttributeNames(); e.hasMoreElements();) { - servletContext.removeAttribute((String) e.nextElement()); + for (Enumeration e = servletContext.getAttributeNames(); e.hasMoreElements();) { + servletContext.removeAttribute(e.nextElement()); } } // Supported by maps if overridden @Override - public void putAll(Map t) { - for (Iterator i = t.entrySet().iterator(); i.hasNext();) { - Map.Entry entry = (Map.Entry) i.next(); - servletContext.setAttribute((String) entry.getKey(), entry.getValue()); - } + public void putAll(Map map) { + map.forEach(servletContext::setAttribute); } @Override @@ -91,14 +88,14 @@ public boolean containsKey(Object key) { @Override public boolean equals(Object obj) { - return !(obj == null || !(obj instanceof ApplicationMap)) && super.equals(obj); + return obj instanceof ApplicationMap && super.equals(obj); } @Override public int hashCode() { int hashCode = 7 * servletContext.hashCode(); - for (Iterator i = entrySet().iterator(); i.hasNext();) { - hashCode += i.next().hashCode(); + for (Map.Entry stringObjectEntry : entrySet()) { + hashCode += stringObjectEntry.hashCode(); } return hashCode; } diff --git a/impl/src/main/java/com/sun/faces/context/BaseContextMap.java b/impl/src/main/java/com/sun/faces/context/BaseContextMap.java index 972ffce797..c17bf21eb3 100644 --- a/impl/src/main/java/com/sun/faces/context/BaseContextMap.java +++ b/impl/src/main/java/com/sun/faces/context/BaseContextMap.java @@ -16,14 +16,7 @@ package com.sun.faces.context; -import java.util.AbstractCollection; -import java.util.AbstractMap; -import java.util.AbstractSet; -import java.util.Collection; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; +import java.util.*; /** *

@@ -46,7 +39,7 @@ public void clear() { // Supported by maps if overridden @Override - public void putAll(Map t) { + public void putAll(Map map) { throw new UnsupportedOperationException(); } @@ -95,8 +88,8 @@ protected boolean removeValue(Object value) { return false; } if (containsValue(value)) { - for (Iterator i = entrySet().iterator(); i.hasNext();) { - Map.Entry e = (Map.Entry) i.next(); + for (Iterator> i = entrySet().iterator(); i.hasNext();) { + Map.Entry e = i.next(); if (value.equals(e.getValue())) { valueRemoved = remove(e.getKey()) != null; } @@ -135,7 +128,7 @@ public Iterator> iterator() { @Override public boolean remove(Object o) { - return o instanceof Map.Entry && removeKey(((Map.Entry) o).getKey()); + return o instanceof Map.Entry && removeKey(((Map.Entry) o).getKey()); } } @@ -163,7 +156,7 @@ class ValueCollection extends AbstractCollection { @Override public int size() { int size = 0; - for (Iterator i = iterator(); i.hasNext(); size++) { + for (Iterator i = iterator(); i.hasNext(); size++) { i.next(); } return size; @@ -180,7 +173,7 @@ public boolean remove(Object o) { } } - abstract class BaseIterator implements Iterator { + abstract static class BaseIterator implements Iterator { protected Enumeration e; protected String currentKey; @@ -304,7 +297,7 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (obj == null || !(obj instanceof Map.Entry)) { + if ( !(obj instanceof Map.Entry) ) { return false; } @@ -312,12 +305,7 @@ public boolean equals(Object obj) { Object inputKey = input.getKey(); Object inputValue = input.getValue(); - if (inputKey == key || inputKey != null && inputKey.equals(key)) { - if (inputValue == value || inputValue != null && inputValue.equals(value)) { - return true; - } - } - return false; + return Objects.equals(inputKey, key) && Objects.equals(inputValue, value); } } diff --git a/impl/src/main/java/com/sun/faces/context/ContextParam.java b/impl/src/main/java/com/sun/faces/context/ContextParam.java index e4cd1830f8..ae787f3b7b 100644 --- a/impl/src/main/java/com/sun/faces/context/ContextParam.java +++ b/impl/src/main/java/com/sun/faces/context/ContextParam.java @@ -54,7 +54,7 @@ public enum ContextParam { /** * Constructor. */ - ContextParam(String name, Class type, Object defaultValue) { + ContextParam(String name, Class type, Object defaultValue) { this.name = name; this.type = type; this.defaultValue = defaultValue; @@ -76,7 +76,7 @@ public Object getDefaultValue() { * @param clazz the class. * @return the default value. */ - public T getDefaultValue(Class clazz) { + public T getDefaultValue(Class clazz) { return clazz.cast(defaultValue); } @@ -94,7 +94,7 @@ public String getName() { * * @return the type. */ - public Class getType() { + public Class getType() { return type; } } diff --git a/impl/src/main/java/com/sun/faces/context/ContextParamUtils.java b/impl/src/main/java/com/sun/faces/context/ContextParamUtils.java index 96bba227c4..15043b4d93 100644 --- a/impl/src/main/java/com/sun/faces/context/ContextParamUtils.java +++ b/impl/src/main/java/com/sun/faces/context/ContextParamUtils.java @@ -58,7 +58,7 @@ public static Object getValue(ServletContext servletContext, ContextParam contex * @param clazz the class. * @return the value. */ - public static T getValue(ServletContext servletContext, ContextParam contextParam, Class clazz) { + public static T getValue(ServletContext servletContext, ContextParam contextParam, Class clazz) { return clazz.cast(getValue(servletContext, contextParam)); } } diff --git a/impl/src/main/java/com/sun/faces/context/ExceptionHandlerImpl.java b/impl/src/main/java/com/sun/faces/context/ExceptionHandlerImpl.java index 708ef57385..551c6b9961 100644 --- a/impl/src/main/java/com/sun/faces/context/ExceptionHandlerImpl.java +++ b/impl/src/main/java/com/sun/faces/context/ExceptionHandlerImpl.java @@ -56,7 +56,7 @@ public class ExceptionHandlerImpl extends ExceptionHandler { private LinkedList unhandledExceptions; private LinkedList handledExceptions; private ExceptionQueuedEvent handled; - private boolean errorPagePresent; + private final boolean errorPagePresent; // ------------------------------------------------------------ Constructors @@ -209,7 +209,7 @@ private void throwIt(FacesContext ctx, FacesException fe) { LOGGER.log(Level.INFO, "Exception when handling error trying to reset the response.", wrapped); } } - if (null != wrapped && wrapped instanceof FacesFileNotFoundException) { + if (wrapped instanceof FacesFileNotFoundException) { extContext.setResponseStatus(404); } else { extContext.setResponseStatus(500); @@ -225,7 +225,7 @@ private void throwIt(FacesContext ctx, FacesException fe) { if (isDevelopment) { // store the view root where the exception occurred into the // request scope so that the error page can display that component - // tree and not the one rendering the errorpage + // tree and not the one rendering the error page ctx.getExternalContext().getRequestMap().put("com.sun.faces.error.view", ctx.getViewRoot()); } throw fe; diff --git a/impl/src/main/java/com/sun/faces/context/ExternalContextFactoryImpl.java b/impl/src/main/java/com/sun/faces/context/ExternalContextFactoryImpl.java index 511b092984..d694c35c10 100644 --- a/impl/src/main/java/com/sun/faces/context/ExternalContextFactoryImpl.java +++ b/impl/src/main/java/com/sun/faces/context/ExternalContextFactoryImpl.java @@ -46,9 +46,7 @@ public ExternalContext getExternalContext(Object servletContext, Object request, ExternalContext extContext = new ExternalContextImpl((ServletContext) servletContext, (ServletRequest) request, (ServletResponse) response); - if (request instanceof ServletRequest) { - ((ServletRequest) request).setAttribute(DEFAULT_EXTERNAL_CONTEXT_KEY, extContext); - } + ((ServletRequest) request).setAttribute(DEFAULT_EXTERNAL_CONTEXT_KEY, extContext); return extContext; diff --git a/impl/src/main/java/com/sun/faces/context/ExternalContextImpl.java b/impl/src/main/java/com/sun/faces/context/ExternalContextImpl.java index 9e1ae9910b..8e6470166e 100644 --- a/impl/src/main/java/com/sun/faces/context/ExternalContextImpl.java +++ b/impl/src/main/java/com/sun/faces/context/ExternalContextImpl.java @@ -97,7 +97,7 @@ public class ExternalContextImpl extends ExternalContext { private Map initParameterMap = null; private Map fallbackContentTypeMap = null; private Flash flash; - private boolean distributable; + private final boolean distributable; private enum PREDEFINED_COOKIE_PROPERTIES { domain, maxAge, path, secure, httpOnly, attribute; @@ -112,7 +112,7 @@ static PREDEFINED_COOKIE_PROPERTIES of(String key) { } } - static final Class theUnmodifiableMapClass = Collections.unmodifiableMap(new HashMap<>()).getClass(); + static final Class theUnmodifiableMapClass = Collections.unmodifiableMap(new HashMap<>()).getClass(); // ------------------------------------------------------------ Constructors @@ -130,15 +130,16 @@ public ExternalContextImpl(ServletContext sc, ServletRequest request, ServletRes boolean enabled = ContextParamUtils.getValue(servletContext, SendPoweredByHeader, Boolean.class); if (enabled) { - ((HttpServletResponse) response).addHeader("X-Powered-By", "Faces/3.0"); + ((HttpServletResponse) response).addHeader("X-Powered-By", "Faces/4.0"); } distributable = ContextParamUtils.getValue(servletContext, ContextParam.EnableDistributable, Boolean.class); - fallbackContentTypeMap = new HashMap<>(3, 1.0f); - fallbackContentTypeMap.put("js", ScriptRenderer.DEFAULT_CONTENT_TYPE); - fallbackContentTypeMap.put("css", StylesheetRenderer.DEFAULT_CONTENT_TYPE); - fallbackContentTypeMap.put("properties", "text/plain"); + fallbackContentTypeMap = Map.of( + "js", ScriptRenderer.DEFAULT_CONTENT_TYPE, + "css", StylesheetRenderer.DEFAULT_CONTENT_TYPE, + "properties", "text/plain" + ); } @@ -154,10 +155,9 @@ public Object getSession(boolean create) { @Override public String getSessionId(boolean create) { - HttpSession session = null; String id = null; - session = (HttpSession) getSession(create); + HttpSession session = (HttpSession) getSession(create); if (session != null) { id = session.getId(); } @@ -198,7 +198,6 @@ public void setRequest(Object request) { this.request = (ServletRequest) request; requestHeaderMap = null; requestHeaderValuesMap = null; - requestHeaderValuesMap = null; requestMap = null; requestParameterMap = null; requestParameterValuesMap = null; @@ -362,9 +361,9 @@ public Map getRequestParameterValuesMap() { */ @Override public Iterator getRequestParameterNames() { - final Enumeration namEnum = request.getParameterNames(); + final Enumeration namEnum = request.getParameterNames(); - return new Iterator() { + return new Iterator<>() { @Override public boolean hasNext() { return namEnum.hasMoreElements(); @@ -372,7 +371,7 @@ public boolean hasNext() { @Override public String next() { - return (String) namEnum.nextElement(); + return namEnum.nextElement(); } @Override @@ -535,7 +534,7 @@ public String encodeActionURL(String url) { if (null != cw) { appendClientWindow = cw.isClientWindowRenderModeEnabled(context); } - if (appendClientWindow && -1 == url.indexOf(ResponseStateManager.CLIENT_WINDOW_URL_PARAM)) { + if (appendClientWindow && !url.contains(ResponseStateManager.CLIENT_WINDOW_URL_PARAM)) { if (null != cw) { String clientWindowId = cw.getId(); StringBuilder builder = new StringBuilder(url); @@ -1042,7 +1041,6 @@ public void release() { request = null; response = null; clientWindow = null; - applicationMap = null; sessionMap = null; requestMap = null; @@ -1126,11 +1124,11 @@ public String getFallbackMimeType(String file) { private static class LocalesIterator implements Iterator { - public LocalesIterator(Enumeration locales) { + public LocalesIterator(Enumeration locales) { this.locales = locales; } - private Enumeration locales; + private final Enumeration locales; @Override public boolean hasNext() { @@ -1139,7 +1137,7 @@ public boolean hasNext() { @Override public Locale next() { - return (Locale) locales.nextElement(); + return locales.nextElement(); } @Override diff --git a/impl/src/main/java/com/sun/faces/context/FacesContextFactoryImpl.java b/impl/src/main/java/com/sun/faces/context/FacesContextFactoryImpl.java index c4aff33cf5..2d65ad7b42 100644 --- a/impl/src/main/java/com/sun/faces/context/FacesContextFactoryImpl.java +++ b/impl/src/main/java/com/sun/faces/context/FacesContextFactoryImpl.java @@ -91,7 +91,7 @@ private void savePerRequestInitParams(FacesContext context, WebConfiguration web webConfig.isOptionEnabled(ViewRootPhaseListenerQueuesException) ? Boolean.TRUE : Boolean.FALSE); attrs.put(EnableValidateWholeBean.getQualifiedName(), webConfig.isOptionEnabled(EnableValidateWholeBean) ? Boolean.TRUE : Boolean.FALSE); - String facesConfigVersion = "" + appMap.get(RIConstants.FACES_CONFIG_VERSION); + String facesConfigVersion = String.valueOf(appMap.get(RIConstants.FACES_CONFIG_VERSION)); attrs.put(RIConstants.FACES_CONFIG_VERSION, facesConfigVersion); } diff --git a/impl/src/main/java/com/sun/faces/context/InitParameterMap.java b/impl/src/main/java/com/sun/faces/context/InitParameterMap.java index 860527d90f..7c41a21cd6 100644 --- a/impl/src/main/java/com/sun/faces/context/InitParameterMap.java +++ b/impl/src/main/java/com/sun/faces/context/InitParameterMap.java @@ -76,8 +76,8 @@ public boolean equals(Object obj) { @Override public int hashCode() { int hashCode = 7 * servletContext.hashCode(); - for (Iterator i = entrySet().iterator(); i.hasNext();) { - hashCode += i.next().hashCode(); + for (Map.Entry stringStringEntry : entrySet()) { + hashCode += stringStringEntry.hashCode(); } return hashCode; } diff --git a/impl/src/main/java/com/sun/faces/context/PartialViewContextImpl.java b/impl/src/main/java/com/sun/faces/context/PartialViewContextImpl.java index 2d650e03cf..961155f544 100644 --- a/impl/src/main/java/com/sun/faces/context/PartialViewContextImpl.java +++ b/impl/src/main/java/com/sun/faces/context/PartialViewContextImpl.java @@ -65,7 +65,7 @@ public class PartialViewContextImpl extends PartialViewContext { // Log instance for this class - private static Logger LOGGER = FacesLogger.CONTEXT.getLogger(); + private static final Logger LOGGER = FacesLogger.CONTEXT.getLogger(); private boolean released; diff --git a/impl/src/main/java/com/sun/faces/context/RequestCookieMap.java b/impl/src/main/java/com/sun/faces/context/RequestCookieMap.java index b8ef82ec05..954688d1aa 100644 --- a/impl/src/main/java/com/sun/faces/context/RequestCookieMap.java +++ b/impl/src/main/java/com/sun/faces/context/RequestCookieMap.java @@ -56,9 +56,9 @@ public Object get(Object key) { String keyString = key.toString(); Object result = null; - for (int i = 0; i < cookies.length; i++) { - if (cookies[i].getName().equals(keyString)) { - result = cookies[i]; + for (Cookie cookie : cookies) { + if (cookie.getName().equals(keyString)) { + result = cookie; break; } } @@ -88,8 +88,8 @@ public boolean equals(Object obj) { @Override public int hashCode() { int hashCode = 7 * request.hashCode(); - for (Iterator i = entrySet().iterator(); i.hasNext();) { - hashCode += i.next().hashCode(); + for (Map.Entry stringObjectEntry : entrySet()) { + hashCode += stringObjectEntry.hashCode(); } return hashCode; } @@ -113,7 +113,7 @@ protected Iterator getValueIterator() { // ----------------------------------------------------------- Inner Classes - private static class CookieArrayEnumerator implements Enumeration { + private static class CookieArrayEnumerator implements Enumeration { Cookie[] cookies; int curIndex = -1; @@ -130,7 +130,7 @@ public boolean hasMoreElements() { } @Override - public Object nextElement() { + public String nextElement() { curIndex++; if (curIndex < upperBound) { return cookies[curIndex].getName(); diff --git a/impl/src/main/java/com/sun/faces/context/RequestHeaderMap.java b/impl/src/main/java/com/sun/faces/context/RequestHeaderMap.java index 14c2b2aa79..7173c9da14 100644 --- a/impl/src/main/java/com/sun/faces/context/RequestHeaderMap.java +++ b/impl/src/main/java/com/sun/faces/context/RequestHeaderMap.java @@ -76,8 +76,8 @@ public boolean equals(Object obj) { @Override public int hashCode() { int hashCode = 7 * request.hashCode(); - for (Iterator i = entrySet().iterator(); i.hasNext();) { - hashCode += i.next().hashCode(); + for (Map.Entry stringStringEntry : entrySet()) { + hashCode += stringStringEntry.hashCode(); } return hashCode; } diff --git a/impl/src/main/java/com/sun/faces/context/RequestHeaderValuesMap.java b/impl/src/main/java/com/sun/faces/context/RequestHeaderValuesMap.java index 99013b46ed..d345d12f35 100644 --- a/impl/src/main/java/com/sun/faces/context/RequestHeaderValuesMap.java +++ b/impl/src/main/java/com/sun/faces/context/RequestHeaderValuesMap.java @@ -54,12 +54,12 @@ public String[] get(Object key) { Util.notNull("key", key); List valuesList = new ArrayList<>(); - Enumeration valuesEnum = request.getHeaders(key.toString()); + Enumeration valuesEnum = request.getHeaders(key.toString()); while (valuesEnum.hasMoreElements()) { - valuesList.add((String) valuesEnum.nextElement()); + valuesList.add(valuesEnum.nextElement()); } - return valuesList.toArray(new String[valuesList.size()]); + return valuesList.toArray(new String[0]); } @Override diff --git a/impl/src/main/java/com/sun/faces/context/RequestMap.java b/impl/src/main/java/com/sun/faces/context/RequestMap.java index 9a91d96091..59c49eff35 100644 --- a/impl/src/main/java/com/sun/faces/context/RequestMap.java +++ b/impl/src/main/java/com/sun/faces/context/RequestMap.java @@ -48,7 +48,7 @@ public void clear() { // Supported by maps if overridden @Override - public void putAll(Map t) { + public void putAll(Map t) { for (Iterator i = t.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); request.setAttribute((String) entry.getKey(), entry.getValue()); diff --git a/impl/src/main/java/com/sun/faces/context/RequestParameterMap.java b/impl/src/main/java/com/sun/faces/context/RequestParameterMap.java index 309a10cc94..402c696830 100644 --- a/impl/src/main/java/com/sun/faces/context/RequestParameterMap.java +++ b/impl/src/main/java/com/sun/faces/context/RequestParameterMap.java @@ -54,7 +54,7 @@ public String get(Object key) { String mapKey = key.toString(); String mapValue = request.getParameter(mapKey); if (mapValue == null && !mapKey.startsWith(getNamingContainerPrefix())) { - // Support cases where enduser manually obtains a request parameter while in a namespaced view. + // Support cases where end user manually obtains a request parameter while in a namespaced view. mapValue = request.getParameter(getNamingContainerPrefix() + mapKey); } return mapValue; @@ -107,8 +107,8 @@ public boolean equals(Object obj) { @Override public int hashCode() { int hashCode = 7 * request.hashCode(); - for (Iterator i = entrySet().iterator(); i.hasNext();) { - hashCode += i.next().hashCode(); + for (Map.Entry stringStringEntry : entrySet()) { + hashCode += stringStringEntry.hashCode(); } return hashCode; } diff --git a/impl/src/main/java/com/sun/faces/context/SessionMap.java b/impl/src/main/java/com/sun/faces/context/SessionMap.java index 9ccf3b3c8b..eb23164d3b 100644 --- a/impl/src/main/java/com/sun/faces/context/SessionMap.java +++ b/impl/src/main/java/com/sun/faces/context/SessionMap.java @@ -17,10 +17,7 @@ package com.sun.faces.context; import java.io.Serializable; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.Map; +import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; @@ -54,8 +51,8 @@ public SessionMap(HttpServletRequest request, ProjectStage stage) { public void clear() { HttpSession session = getSession(false); if (session != null) { - for (Enumeration e = session.getAttributeNames(); e.hasMoreElements();) { - String name = (String) e.nextElement(); + for (Enumeration e = session.getAttributeNames(); e.hasMoreElements();) { + String name = e.nextElement(); session.removeAttribute(name); } } @@ -63,20 +60,17 @@ public void clear() { // Supported by maps if overridden @Override - public void putAll(Map t) { + public void putAll(Map map) { HttpSession session = getSession(true); - for (Iterator i = t.entrySet().iterator(); i.hasNext();) { - Map.Entry entry = (Map.Entry) i.next(); - Object v = entry.getValue(); - Object k = entry.getKey(); - if (ProjectStage.Development.equals(stage) && !(v instanceof Serializable)) { + map.forEach( (key, value) -> { + if (ProjectStage.Development.equals(stage) && !(value instanceof Serializable)) { if (LOGGER.isLoggable(Level.WARNING)) { - LOGGER.log(Level.WARNING, "faces.context.extcontext.sessionmap.nonserializable", new Object[] { k, v.getClass().getName() }); + LOGGER.log(Level.WARNING, "faces.context.extcontext.sessionmap.nonserializable", new Object[]{key, value.getClass().getName()}); } } // noinspection NonSerializableObjectBoundToHttpSession - session.setAttribute((String) k, v); - } + session.setAttribute(key, value); + }); } @Override @@ -133,7 +127,7 @@ public boolean containsKey(Object key) { @Override public boolean equals(Object obj) { - return !(obj == null || !(obj instanceof SessionMap)) && super.equals(obj); + return obj instanceof SessionMap && super.equals(obj); } @Override @@ -141,8 +135,8 @@ public int hashCode() { HttpSession session = getSession(false); int hashCode = 7 * (session != null ? session.hashCode() : super.hashCode()); if (session != null) { - for (Iterator i = entrySet().iterator(); i.hasNext();) { - hashCode += i.next().hashCode(); + for (Map.Entry stringObjectEntry : entrySet()) { + hashCode += stringObjectEntry.hashCode(); } } return hashCode; @@ -156,8 +150,7 @@ protected Iterator> getEntryIterator() { if (session != null) { return new EntryIterator(session.getAttributeNames()); } else { - Map empty = Collections.emptyMap(); - return empty.entrySet().iterator(); + return Collections.emptyIterator(); } } @@ -167,8 +160,7 @@ protected Iterator getKeyIterator() { if (session != null) { return new KeyIterator(session.getAttributeNames()); } else { - Map empty = Collections.emptyMap(); - return empty.keySet().iterator(); + return Collections.emptyIterator(); } } @@ -178,8 +170,7 @@ protected Iterator getValueIterator() { if (session != null) { return new ValueIterator(session.getAttributeNames()); } else { - Map empty = Collections.emptyMap(); - return empty.values().iterator(); + return Collections.emptyIterator(); } } diff --git a/impl/src/main/java/com/sun/faces/context/StateContext.java b/impl/src/main/java/com/sun/faces/context/StateContext.java index 32811c7164..8c0d3af7d1 100644 --- a/impl/src/main/java/com/sun/faces/context/StateContext.java +++ b/impl/src/main/java/com/sun/faces/context/StateContext.java @@ -63,7 +63,7 @@ public class StateContext { private boolean partialLocked; private boolean trackMods = true; private AddRemoveListener modListener; - private ApplicationStateInfo stateInfo; + private final ApplicationStateInfo stateInfo; private WeakReference viewRootRef = new WeakReference<>(null); private static final Logger LOGGER = FacesLogger.CONTEXT.getLogger(); @@ -252,7 +252,7 @@ public List getDynamicActions() { * * @return the hash map of dynamic components. */ - public HashMap getDynamicComponents() { + public Map getDynamicComponents() { return modListener != null ? modListener.getDynamicComponents() : null; } @@ -262,12 +262,12 @@ private AddRemoveListener createAddRemoveListener(FacesContext context, UIViewRo return isPartialStateSaving(context, root.getViewId()) ? new DynamicAddRemoveListener(context) : new StatelessAddRemoveListener(context); } - abstract private class AddRemoveListener implements SystemEventListener { + abstract private static class AddRemoveListener implements SystemEventListener { /** * Stores the state context we work for, */ - private StateContext stateCtx; + private final StateContext stateCtx; /** * Constructor. @@ -290,7 +290,7 @@ protected AddRemoveListener(FacesContext context) { * * @return the hash map of dynamic components. */ - abstract public HashMap getDynamicComponents(); + abstract public Map getDynamicComponents(); /** * Process the add/remove event. @@ -346,12 +346,12 @@ public boolean isListenerForSource(Object source) { abstract protected void handleAdd(FacesContext context, UIComponent component); } - public class NoopAddRemoveListener extends AddRemoveListener { + public static class NoopAddRemoveListener extends AddRemoveListener { - // This is silly. We should be able to use Colletions.emptyMap(), + // This is silly. We should be able to use Collections.emptyMap(), // but cannot as StateContext.getDynamicComponents() API returns a // HashMap instead of a Map. - private HashMap emptyComponentsMap = new HashMap(); + private final Map emptyComponentsMap = Collections.emptyMap(); public NoopAddRemoveListener(FacesContext context) { super(context); @@ -363,7 +363,7 @@ public List getDynamicActions() { } @Override - public HashMap getDynamicComponents() { + public Map getDynamicComponents() { return emptyComponentsMap; } @@ -381,7 +381,7 @@ protected void handleAdd(FacesContext context, UIComponent component) { * itself. Instead, we use expando attributes on the dynamic components (and their parents) to track/preserve the * dynamic nature of these components. */ - public class StatelessAddRemoveListener extends NoopAddRemoveListener { + public static class StatelessAddRemoveListener extends NoopAddRemoveListener { public StatelessAddRemoveListener(FacesContext context) { super(context); @@ -564,7 +564,7 @@ public List getDynamicActions() { * @return the hash map of dynamic components. */ @Override - public HashMap getDynamicComponents() { + public Map getDynamicComponents() { synchronized (this) { if (dynamicComponents == null) { dynamicComponents = new HashMap<>(); @@ -639,16 +639,13 @@ protected void handleAdd(FacesContext context, UIComponent component) { * @param component the component to look for in the facets map entry value. * @return the facet name or null if the component is not the value of a facets map entry. */ - private String findFacetNameForComponent(UIComponent component) { + private String findFacetNameForComponent(final UIComponent component) { Set> entrySet = component.getParent().getFacets().entrySet(); - Iterator> entries = entrySet.iterator(); - while (entries.hasNext()) { - Entry candidate = entries.next(); - if (component == candidate.getValue()) { - return candidate.getKey(); - } - } - return null; + return entrySet.stream() + .filter(candidate -> component.equals(candidate.getValue())) + .findFirst() + .map(Entry::getKey) + .orElse(null); } /** @@ -686,7 +683,7 @@ private String findFacetNameForComponent(UIComponent component) { */ private void handleAddRemoveWithAutoPrune(UIComponent component, ComponentStruct struct) { List actionList = getDynamicActions(); - HashMap componentMap = getDynamicComponents(); + Map componentMap = getDynamicComponents(); int firstIndex = actionList.indexOf(struct); if (firstIndex == -1) { diff --git a/impl/src/main/java/com/sun/faces/context/StateHolderSaver.java b/impl/src/main/java/com/sun/faces/context/StateHolderSaver.java index 712cbbe4ef..4cb359c65d 100644 --- a/impl/src/main/java/com/sun/faces/context/StateHolderSaver.java +++ b/impl/src/main/java/com/sun/faces/context/StateHolderSaver.java @@ -17,6 +17,7 @@ package com.sun.faces.context; import java.io.Serializable; +import java.lang.reflect.InvocationTargetException; import jakarta.faces.component.StateHolder; import jakarta.faces.component.UIComponent; @@ -124,17 +125,13 @@ public Object restore(FacesContext context) throws IllegalStateException { throw new IllegalStateException(e); } - if (null != toRestoreClass) { - try { - result = toRestoreClass.newInstance(); - } catch (InstantiationException e) { - throw new IllegalStateException(e); - } catch (IllegalAccessException a) { - throw new IllegalStateException(a); - } + try { + result = toRestoreClass.getDeclaredConstructor().newInstance(); + } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { + throw new IllegalStateException(e); } - if (null != result && null != savedState && result instanceof StateHolder) { + if (null != savedState && result instanceof StateHolder) { // don't need to check transient, since that was done on // the saving side. Serializable[] tuple = (Serializable[]) savedState; @@ -143,7 +140,7 @@ public Object restore(FacesContext context) throws IllegalStateException { return result; } - private static Class loadClass(String name, Object fallbackClass) throws ClassNotFoundException { + private static Class loadClass(String name, Object fallbackClass) throws ClassNotFoundException { ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader == null) { loader = fallbackClass.getClass().getClassLoader(); diff --git a/impl/src/main/java/com/sun/faces/context/StringArrayValuesMap.java b/impl/src/main/java/com/sun/faces/context/StringArrayValuesMap.java index 07293ff87d..8e7104d84b 100644 --- a/impl/src/main/java/com/sun/faces/context/StringArrayValuesMap.java +++ b/impl/src/main/java/com/sun/faces/context/StringArrayValuesMap.java @@ -18,6 +18,7 @@ import java.util.Arrays; import java.util.Map; +import java.util.Objects; import java.util.Set; /** @@ -36,15 +37,12 @@ public boolean containsValue(Object value) { return false; } - Set entrySet = entrySet(); - for (Object anEntrySet : entrySet) { - Map.Entry entry = (Map.Entry) anEntrySet; - // values will be arrays - if (Arrays.equals((Object[]) value, (Object[]) entry.getValue())) { - return true; - } - } - return false; + final Object[] array = (Object[]) value; + + // values will be arrays + return entrySet().stream() + .map(Map.Entry::getValue) + .anyMatch(v -> Arrays.equals(array, v)); } @Override @@ -89,10 +87,9 @@ public int hashCode() { protected int hashCode(Object someObject) { int hashCode = 7 * someObject.hashCode(); - for (Object o : entrySet()) { - Map.Entry entry = (Map.Entry) o; + for ( Map.Entry entry : entrySet()) { hashCode += entry.getKey().hashCode(); - hashCode += Arrays.hashCode((Object[]) entry.getValue()); + hashCode += Arrays.hashCode(entry.getValue()); } return hashCode; } diff --git a/impl/src/main/java/com/sun/faces/context/UrlBuilder.java b/impl/src/main/java/com/sun/faces/context/UrlBuilder.java index d51c3fb83d..c040a3f17e 100644 --- a/impl/src/main/java/com/sun/faces/context/UrlBuilder.java +++ b/impl/src/main/java/com/sun/faces/context/UrlBuilder.java @@ -16,21 +16,15 @@ package com.sun.faces.context; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - import com.sun.faces.util.Util; - import jakarta.faces.context.FacesContext; import jakarta.faces.lifecycle.ClientWindow; import jakarta.faces.render.ResponseStateManager; +import java.net.URLEncoder; +import java.nio.charset.Charset; +import java.util.*; + /** *

* The UrlBuilder provides a convenient way to assemble a URL. It follows the standard Builder Pattern. @@ -51,14 +45,14 @@ class UrlBuilder { public static final String FRAGMENT_SEPARATOR = "#"; public static final String DEFAULT_ENCODING = "UTF-8"; - private static final List NULL_LIST = Arrays.asList((String) null); + private static final List NULL_LIST = Collections.singletonList(null); - private StringBuilder url; + private final StringBuilder url; private String path; private String queryString; private String fragment; private Map> parameters; - private String encoding; + private final Charset encoding; // ------------------------------------------------------------ Constructors @@ -68,7 +62,7 @@ public UrlBuilder(String url, String encoding) { } this.url = new StringBuilder(url.length() * 2); extractSegments(url); - this.encoding = encoding; + this.encoding = Charset.forName(encoding); // PERF TL lookup per-instance } @@ -93,8 +87,7 @@ public UrlBuilder addParameters(Map> params) { if (entry.getKey() == null || entry.getKey().trim().length() == 0) { throw new IllegalArgumentException("Parameter name cannot be empty"); } - List values = entry.getValue(); - List retValues = values; + List retValues = entry.getValue(); addValuesToParameter(entry.getKey().trim(), retValues, true); } } @@ -268,14 +261,9 @@ protected void addValueToParameter(String name, String value, boolean replace) { protected void addValuesToParameter(String name, List valuesRef, boolean replace) { List values = new ArrayList<>(); if (valuesRef != null) { - for (Iterator it = valuesRef.iterator(); it.hasNext();) { - String string = it.next(); + for (String string : valuesRef) { if (encoding != null) { - try { - values.add(URLEncoder.encode(string, encoding)); - } catch (UnsupportedEncodingException ex) { - throw new RuntimeException(ex); - } + values.add(URLEncoder.encode(string, encoding)); } else { values.add(string); } @@ -290,12 +278,7 @@ protected void addValuesToParameter(String name, List valuesRef, boolean if (replace) { parameters.put(name, values); } else { - List currentValues = parameters.get(name); - if (currentValues == null) { - currentValues = new ArrayList<>(1); - parameters.put(name, currentValues); - } - currentValues.addAll(values); + parameters.computeIfAbsent(name, k -> new ArrayList<>(1)).addAll(values); } } diff --git a/impl/src/main/java/com/sun/faces/el/CompositeComponentAttributesELResolver.java b/impl/src/main/java/com/sun/faces/el/CompositeComponentAttributesELResolver.java index 6609db3803..be23afbd9c 100644 --- a/impl/src/main/java/com/sun/faces/el/CompositeComponentAttributesELResolver.java +++ b/impl/src/main/java/com/sun/faces/el/CompositeComponentAttributesELResolver.java @@ -296,8 +296,8 @@ private static final class ExpressionEvalMap implements Map, Com @Override public ValueExpression getExpression(String name) { - Object ve = cc.getValueExpression(name); - return ve instanceof ValueExpression ? (ValueExpression) ve : null; + return cc.getValueExpression(name); +// return ve instanceof ValueExpression ? (ValueExpression) ve : null; } // ---------------------------------------------------- Methods from Map @@ -335,15 +335,12 @@ public Object get(Object key) { return ((ValueExpression) v).getValue(ctx.getELContext()); } } - if (v != null && v instanceof MethodExpression) { - return v; - } return v; } @Override public Object put(String key, Object value) { - // Unlinke AttributesMap.get() which will obtain a value from + // Unlike AttributesMap.get() which will obtain a value from // a ValueExpression, AttributesMap.put(), when passed a value, // will never call ValueExpression.setValue(), so we have to take // matters into our own hands... diff --git a/impl/src/main/java/com/sun/faces/el/ELContextImpl.java b/impl/src/main/java/com/sun/faces/el/ELContextImpl.java index 723c75b779..0061038cba 100644 --- a/impl/src/main/java/com/sun/faces/el/ELContextImpl.java +++ b/impl/src/main/java/com/sun/faces/el/ELContextImpl.java @@ -43,7 +43,7 @@ public class ELContextImpl extends ELContext { private FunctionMapper functionMapper = new NoopFunctionMapper(); private VariableMapper variableMapper; - private ELResolver resolver; + private final ELResolver resolver; // ------------------------------------------------------------ Constructors @@ -66,7 +66,7 @@ public ELContextImpl(FacesContext facesContext) { putContext(ExpressionFactory.class, expressionFactory); } - if (facesContext instanceof InitFacesContext == false) { + if ( !(facesContext instanceof InitFacesContext) ) { UIViewRoot root = facesContext.getViewRoot(); if (root != null) { setLocale(root.getLocale()); @@ -104,7 +104,7 @@ public void setFunctionMapper(FunctionMapper functionMapper) { private static class VariableMapperImpl extends VariableMapper { - private Map variables; + private final Map variables; public VariableMapperImpl() { variables = new HashMap<>(); diff --git a/impl/src/main/java/com/sun/faces/el/ELContextListenerImpl.java b/impl/src/main/java/com/sun/faces/el/ELContextListenerImpl.java index cec107e9b6..bd210c956a 100644 --- a/impl/src/main/java/com/sun/faces/el/ELContextListenerImpl.java +++ b/impl/src/main/java/com/sun/faces/el/ELContextListenerImpl.java @@ -53,8 +53,7 @@ public void contextCreated(ELContextEvent ece) { if (listeners == null) { return; } - for (int i = 0; i < listeners.length; ++i) { - ELContextListener elcl = listeners[i]; + for (ELContextListener elcl : listeners) { elcl.contextCreated(new ELContextEvent(source)); } } diff --git a/impl/src/main/java/com/sun/faces/el/ELUtils.java b/impl/src/main/java/com/sun/faces/el/ELUtils.java index dee44542e7..3fa323bb79 100644 --- a/impl/src/main/java/com/sun/faces/el/ELUtils.java +++ b/impl/src/main/java/com/sun/faces/el/ELUtils.java @@ -128,7 +128,7 @@ public static boolean isCompositeComponentExpr(String expression) { if (evaluationResult != null) { // fast path - this expression has already been evaluated, therefore return its evaluation result - return evaluationResult.booleanValue(); + return evaluationResult; } // TODO we should be trying to re-use the Matcher by calling diff --git a/impl/src/main/java/com/sun/faces/el/FacesResourceBundleELResolver.java b/impl/src/main/java/com/sun/faces/el/FacesResourceBundleELResolver.java index b87b00bbcc..147555ea8c 100644 --- a/impl/src/main/java/com/sun/faces/el/FacesResourceBundleELResolver.java +++ b/impl/src/main/java/com/sun/faces/el/FacesResourceBundleELResolver.java @@ -17,11 +17,7 @@ package com.sun.faces.el; import java.beans.FeatureDescriptor; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.Locale; -import java.util.Map; -import java.util.ResourceBundle; +import java.util.*; import com.sun.faces.application.ApplicationAssociate; import com.sun.faces.application.ApplicationResourceBundle; @@ -140,17 +136,17 @@ public Iterator getFeatureDescriptors(ELContext context, Obje return null; } - ArrayList list = new ArrayList<>(); + FacesContext facesContext = (FacesContext) context.getContext(FacesContext.class); ApplicationAssociate associate = ApplicationAssociate.getCurrentInstance(); Map rbMap = associate.getResourceBundles(); if (rbMap == null) { - return list.iterator(); + return Collections.emptyIterator(); } // iterate over the list of managed beans - for (Iterator> i = rbMap.entrySet().iterator(); i.hasNext();) { - Map.Entry entry = i.next(); + List list = new ArrayList<>(); + for (Map.Entry entry : rbMap.entrySet()) { String var = entry.getKey(); ApplicationResourceBundle bundle = entry.getValue(); if (bundle != null) { diff --git a/impl/src/main/java/com/sun/faces/el/ScopedAttributeELResolver.java b/impl/src/main/java/com/sun/faces/el/ScopedAttributeELResolver.java index 83ff7a0d8c..3225b1101a 100644 --- a/impl/src/main/java/com/sun/faces/el/ScopedAttributeELResolver.java +++ b/impl/src/main/java/com/sun/faces/el/ScopedAttributeELResolver.java @@ -83,11 +83,7 @@ public Object getValue(ELContext elContext, Object base, Object property) throws // check application result = externalContext.getApplicationMap().get(attribute); - if (result != null) { - return result; - } - - return null; + return result; } @Override diff --git a/impl/src/main/java/com/sun/faces/ext/component/MessageFactory.java b/impl/src/main/java/com/sun/faces/ext/component/MessageFactory.java index 14f5b20b8d..e6d6d71023 100644 --- a/impl/src/main/java/com/sun/faces/ext/component/MessageFactory.java +++ b/impl/src/main/java/com/sun/faces/ext/component/MessageFactory.java @@ -183,7 +183,7 @@ private static Application getApplication() { return afactory.getApplication(); } - private static ClassLoader getCurrentLoader(Class fallbackClass) { + private static ClassLoader getCurrentLoader(Class fallbackClass) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader == null) { loader = fallbackClass.getClassLoader(); @@ -255,7 +255,7 @@ private String getFormattedString(String msgtext, Object[] params) { if (params == null || msgtext == null) { return msgtext; } - StringBuffer b = new StringBuffer(100); + StringBuilder b = new StringBuilder(100); MessageFormat mf = new MessageFormat(msgtext); if (locale != null) { mf.setLocale(locale); @@ -265,8 +265,8 @@ private String getFormattedString(String msgtext, Object[] params) { return localizedStr; } - private Locale locale; - private Object[] parameters; + private final Locale locale; + private final Object[] parameters; private Object[] resolvedParameters; } diff --git a/impl/src/main/java/com/sun/faces/ext/component/UIValidateWholeBean.java b/impl/src/main/java/com/sun/faces/ext/component/UIValidateWholeBean.java index 10238200ad..e33300e7ea 100644 --- a/impl/src/main/java/com/sun/faces/ext/component/UIValidateWholeBean.java +++ b/impl/src/main/java/com/sun/faces/ext/component/UIValidateWholeBean.java @@ -66,7 +66,7 @@ public Object getSubmittedValue() { } @Override - public void setConverter(Converter converter) { + public void setConverter(Converter converter) { } @Override diff --git a/impl/src/main/java/com/sun/faces/facelets/compiler/CompilationManager.java b/impl/src/main/java/com/sun/faces/facelets/compiler/CompilationManager.java index 2360230daa..c59fa4c3c4 100644 --- a/impl/src/main/java/com/sun/faces/facelets/compiler/CompilationManager.java +++ b/impl/src/main/java/com/sun/faces/facelets/compiler/CompilationManager.java @@ -446,9 +446,9 @@ private Tag trimJSFCAttribute(Tag tag) { TagAttribute[] oa = tag.getAttributes().getAll(); TagAttribute[] na = new TagAttribute[oa.length - 1]; int p = 0; - for (int i = 0; i < oa.length; i++) { - if (!"jsfc".equals(oa[i].getLocalName())) { - na[p++] = oa[i]; + for (TagAttribute tagAttribute : oa) { + if (!"jsfc".equals(tagAttribute.getLocalName())) { + na[p++] = tagAttribute; } } return new Tag(tag, new TagAttributesImpl(na)); @@ -479,7 +479,7 @@ private Tag trimNSAttributes(Tag tag) { } attrList.add(attr[i]); } - attr = attrList.toArray(new TagAttribute[attrList.size()]); + attr = attrList.toArray(new TagAttribute[0]); return new Tag(tag.getLocation(), tag.getNamespace(), tag.getLocalName(), tag.getQName(), new TagAttributesImpl(attr)); } } @@ -497,7 +497,7 @@ private CompilationUnit getViewRootUnitFromStack(Stack units) { if (compilationUnit instanceof TagUnit) { TagUnit tagUnit = (TagUnit) compilationUnit; String ns = tagUnit.getTag().getNamespace(); - if (CoreLibrary.NAMESPACES.contains(ns) && tagUnit.getTag().getLocalName().equals("view")) { + if (CoreLibrary.NAMESPACES.contains(ns) && "view".equals(tagUnit.getTag().getLocalName())) { result = tagUnit; break; } diff --git a/impl/src/main/java/com/sun/faces/facelets/compiler/SAXCompiler.java b/impl/src/main/java/com/sun/faces/facelets/compiler/SAXCompiler.java index 4780104665..b945643662 100644 --- a/impl/src/main/java/com/sun/faces/facelets/compiler/SAXCompiler.java +++ b/impl/src/main/java/com/sun/faces/facelets/compiler/SAXCompiler.java @@ -251,9 +251,7 @@ public void processingInstruction(String target, String data) throws SAXExceptio boolean processAsXhtml = unit.getWebConfiguration().getFaceletsConfiguration().isProcessCurrentDocumentAsFaceletsXhtml(alias); if (processAsXhtml) { - StringBuffer sb = new StringBuffer(64); - sb.append("\n"); - unit.writeInstruction(sb.toString()); + unit.writeInstruction("\n"); } } } @@ -391,7 +389,7 @@ public FaceletHandler doMetadataCompile(URL src, String alias) throws IOExceptio return doCompile(mgr, handler, src, alias); } - protected FaceletHandler doCompile(CompilationManager mngr, CompilationHandler handler, URL src, String alias) throws IOException { + private FaceletHandler doCompile(CompilationManager mngr, CompilationHandler handler, URL src, String alias) throws IOException { String encoding = getEncoding(); try (InputStream is = new BufferedInputStream(src.openStream(), 1024);) { @@ -426,7 +424,7 @@ private String getEncoding() { return result; } - protected static void writeXmlDecl(InputStream is, String encoding, CompilationManager mngr) throws IOException { + private static void writeXmlDecl(InputStream is, String encoding, CompilationManager mngr) throws IOException { is.mark(128); try { byte[] b = new byte[128]; diff --git a/impl/src/main/java/com/sun/faces/facelets/compiler/UILeaf.java b/impl/src/main/java/com/sun/faces/facelets/compiler/UILeaf.java index c3a11263f2..349f84c177 100644 --- a/impl/src/main/java/com/sun/faces/facelets/compiler/UILeaf.java +++ b/impl/src/main/java/com/sun/faces/facelets/compiler/UILeaf.java @@ -164,7 +164,7 @@ protected void addFacesListener(FacesListener faces) { } @Override - protected FacesListener[] getFacesListeners(Class faces) { + protected FacesListener[] getFacesListeners(Class faces) { return null; } @@ -199,7 +199,7 @@ protected FacesContext getFacesContext() { } @Override - protected Renderer getRenderer(FacesContext faces) { + protected Renderer getRenderer(FacesContext faces) { return null; } diff --git a/impl/src/main/java/com/sun/faces/facelets/component/UIRepeat.java b/impl/src/main/java/com/sun/faces/facelets/component/UIRepeat.java index 217d790f7a..83132e0666 100644 --- a/impl/src/main/java/com/sun/faces/facelets/component/UIRepeat.java +++ b/impl/src/main/java/com/sun/faces/facelets/component/UIRepeat.java @@ -65,12 +65,12 @@ public class UIRepeat extends UINamingContainer { public static final String COMPONENT_FAMILY = "facelets"; - private final static DataModel EMPTY_MODEL = new ListDataModel<>(Collections.emptyList()); + private final static DataModel EMPTY_MODEL = new ListDataModel<>(Collections.emptyList()); // our data private Object value; - private transient DataModel model; + private transient DataModel model; // variables private String var; @@ -203,12 +203,12 @@ private void resetDataModel(FacesContext context) { } } - private void setDataModel(DataModel model) { + private void setDataModel(DataModel model) { // noinspection unchecked this.model = model; } - private DataModel getDataModel() { + private DataModel getDataModel() { if (model == null) { Object val = getValue(); if (val == null) { @@ -378,9 +378,9 @@ private void removeChildState(FacesContext faces, UIComponent c) { String id = c.getId(); c.setId(id); - Iterator itr = c.getFacetsAndChildren(); + Iterator itr = c.getFacetsAndChildren(); while (itr.hasNext()) { - removeChildState(faces, (UIComponent) itr.next()); + removeChildState(faces, itr.next()); } if (childState != null) { childState.remove(c.getClientId(faces)); @@ -400,9 +400,9 @@ private void saveChildState(FacesContext faces, UIComponent c) { } // continue hack - Iterator itr = c.getFacetsAndChildren(); + Iterator itr = c.getFacetsAndChildren(); while (itr.hasNext()) { - saveChildState(faces, (UIComponent) itr.next()); + saveChildState(faces, itr.next()); } } @@ -433,9 +433,9 @@ private void restoreChildState(FacesContext faces, UIComponent c) { } // continue hack - Iterator itr = c.getFacetsAndChildren(); + Iterator itr = c.getFacetsAndChildren(); while (itr.hasNext()) { - restoreChildState(faces, (UIComponent) itr.next()); + restoreChildState(faces, itr.next()); } } @@ -454,7 +454,7 @@ private boolean hasErrorMessages(FacesContext context) { private void setIndex(FacesContext ctx, int index) { - DataModel localModel = getDataModel(); + DataModel localModel = getDataModel(); // save child state if (this.index != -1 && localModel.isRowAvailable()) { @@ -510,7 +510,7 @@ public void process(FacesContext faces, PhaseId phase) { try { // has children if (getChildCount() > 0) { - Iterator itr; + Iterator itr; UIComponent c; Integer begin = getBegin(); @@ -529,7 +529,7 @@ public void process(FacesContext faces, PhaseId phase) { // grab renderer String rendererType = getRendererType(); - Renderer renderer = null; + Renderer renderer = null; if (rendererType != null) { renderer = getRenderer(faces); } @@ -701,7 +701,7 @@ private boolean requiresRowIteration(VisitContext ctx) { if (!shouldIterate) { FacesContext faces = ctx.getFacesContext(); String sourceId = BEHAVIOR_SOURCE_PARAM.getValue(faces); - boolean containsSource = sourceId != null ? sourceId.startsWith(super.getClientId(faces) + getSeparatorChar(faces)) : false; + boolean containsSource = sourceId != null && sourceId.startsWith(super.getClientId(faces) + getSeparatorChar(faces)); return containsSource; } else { return shouldIterate; diff --git a/impl/src/main/java/com/sun/faces/facelets/el/DefaultFunctionMapper.java b/impl/src/main/java/com/sun/faces/facelets/el/DefaultFunctionMapper.java index 61ab2e9e8f..b8c444a703 100644 --- a/impl/src/main/java/com/sun/faces/facelets/el/DefaultFunctionMapper.java +++ b/impl/src/main/java/com/sun/faces/facelets/el/DefaultFunctionMapper.java @@ -41,7 +41,7 @@ public final class DefaultFunctionMapper extends FunctionMapper implements Exter private static final long serialVersionUID = 1L; - private Map functions = null; + private Map functions = null; /* * (non-Javadoc) @@ -51,7 +51,7 @@ public final class DefaultFunctionMapper extends FunctionMapper implements Exter @Override public Method resolveFunction(String prefix, String localName) { if (functions != null) { - Function f = (Function) functions.get(prefix + ":" + localName); + Function f = functions.get(prefix + ':' + localName); return f.getMethod(); } return null; @@ -59,7 +59,7 @@ public Method resolveFunction(String prefix, String localName) { public void addFunction(String prefix, String localName, Method m) { if (functions == null) { - functions = new HashMap(); + functions = new HashMap<>(); } Function f = new Function(prefix, localName, m); synchronized (this) { @@ -84,15 +84,15 @@ public void writeExternal(ObjectOutput out) throws IOException { */ @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { - functions = (Map) in.readObject(); + functions = (Map) in.readObject(); } @Override public String toString() { - StringBuffer sb = new StringBuffer(128); + StringBuilder sb = new StringBuilder(128); sb.append("FunctionMapper[\n"); - for (Iterator itr = functions.values().iterator(); itr.hasNext();) { - sb.append(itr.next()).append('\n'); + for (Object o : functions.values()) { + sb.append(o).append('\n'); } sb.append(']'); return sb.toString(); @@ -215,7 +215,7 @@ public int hashCode() { @Override public String toString() { - StringBuffer sb = new StringBuffer(32); + StringBuilder sb = new StringBuilder(32); sb.append("Function["); if (prefix != null) { sb.append(prefix).append(':'); diff --git a/impl/src/main/java/com/sun/faces/facelets/el/ELText.java b/impl/src/main/java/com/sun/faces/facelets/el/ELText.java index d5eb54c1b6..83e567dce2 100644 --- a/impl/src/main/java/com/sun/faces/facelets/el/ELText.java +++ b/impl/src/main/java/com/sun/faces/facelets/el/ELText.java @@ -87,12 +87,12 @@ public T getValue(ELContext context) { } @Override - public Class getType(ELContext context) { + public Class getType(ELContext context) { return null; } @Override - public Class getExpectedType() { + public Class getExpectedType() { return null; } @@ -108,23 +108,23 @@ public ELTextComposite(ELText[] txt) { @Override public void write(Writer out, ELContext ctx) throws ELException, IOException { - for (int i = 0; i < txt.length; i++) { - txt[i].write(out, ctx); + for (ELText elText : txt) { + elText.write(out, ctx); } } @Override public void writeText(ResponseWriter out, ELContext ctx) throws ELException, IOException { - for (int i = 0; i < txt.length; i++) { - txt[i].writeText(out, ctx); + for (ELText elText : txt) { + elText.writeText(out, ctx); } } @Override public String toString(ELContext ctx) { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < txt.length; i++) { - sb.append(txt[i].toString(ctx)); + StringBuilder sb = new StringBuilder( 8 * txt.length); + for (ELText elText : txt) { + sb.append(elText.toString(ctx)); } return sb.toString(); } @@ -136,9 +136,9 @@ public String toString(ELContext ctx) { @Override public String toString() { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < txt.length; i++) { - sb.append(txt[i].toString()); + StringBuilder sb = new StringBuilder( 8 * txt.length); + for (ELText elText : txt) { + sb.append(elText.toString()); } return sb.toString(); } @@ -324,7 +324,7 @@ public static ELText parse(ExpressionFactory fact, ELContext ctx, String in, Str boolean esc = false; int vlen = 0; - StringBuffer buff = new StringBuffer(128); + StringBuilder buff = new StringBuilder(128); List text = new ArrayList<>(); ELText t = null; ValueExpression ve = null; @@ -387,7 +387,7 @@ public static ELText parse(ExpressionFactory fact, ELContext ctx, String in, Str } else if (text.size() == 1) { return text.get(0); } else { - ELText[] ta = text.toArray(new ELText[text.size()]); + ELText[] ta = text.toArray(new ELText[0]); return new ELTextComposite(ta); } } diff --git a/impl/src/main/java/com/sun/faces/facelets/impl/DefaultFaceletContext.java b/impl/src/main/java/com/sun/faces/facelets/impl/DefaultFaceletContext.java index b7a995b8e7..3f61184f56 100644 --- a/impl/src/main/java/com/sun/faces/facelets/impl/DefaultFaceletContext.java +++ b/impl/src/main/java/com/sun/faces/facelets/impl/DefaultFaceletContext.java @@ -204,8 +204,8 @@ public String generateUniqueId(String base) { if (prefix == null) { StringBuilder builder = new StringBuilder(faceletHierarchy.size() * 30); - for (int i = 0; i < faceletHierarchy.size(); i++) { - DefaultFacelet facelet = (DefaultFacelet) faceletHierarchy.get(i); + for (Facelet value : faceletHierarchy) { + DefaultFacelet facelet = (DefaultFacelet) value; builder.append(facelet.getAlias()); } Integer prefixInt = builder.toString().hashCode(); @@ -215,7 +215,7 @@ public String generateUniqueId(String base) { prefixes.put(prefixInt, 0); prefix = prefixInt.toString(); } else { - int i = cnt.intValue() + 1; + int i = cnt + 1; prefixes.put(prefixInt, i); prefix = prefixInt + "_" + i; } @@ -230,7 +230,7 @@ public String generateUniqueId(String base) { uniqueIdBuilder.append(base); return uniqueIdBuilder.toString(); } else { - int i = cnt.intValue() + 1; + int i = cnt + 1; ids.put(base, i); uniqueIdBuilder.delete(0, uniqueIdBuilder.length()); uniqueIdBuilder.append(prefix); @@ -294,7 +294,7 @@ public ELResolver getELResolver() { @Override public void popClient(TemplateClient client) { if (!clients.isEmpty()) { - Iterator itr = clients.iterator(); + Iterator itr = clients.iterator(); while (itr.hasNext()) { if (itr.next().equals(client)) { itr.remove(); diff --git a/impl/src/main/java/com/sun/faces/facelets/impl/DefaultFaceletFactory.java b/impl/src/main/java/com/sun/faces/facelets/impl/DefaultFaceletFactory.java index b0678ebcb4..c578978c45 100644 --- a/impl/src/main/java/com/sun/faces/facelets/impl/DefaultFaceletFactory.java +++ b/impl/src/main/java/com/sun/faces/facelets/impl/DefaultFaceletFactory.java @@ -39,6 +39,7 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import java.util.function.Function; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; diff --git a/impl/src/main/java/com/sun/faces/facelets/impl/DefaultResourceResolver.java b/impl/src/main/java/com/sun/faces/facelets/impl/DefaultResourceResolver.java index 7cde391063..6ae5f6c38b 100644 --- a/impl/src/main/java/com/sun/faces/facelets/impl/DefaultResourceResolver.java +++ b/impl/src/main/java/com/sun/faces/facelets/impl/DefaultResourceResolver.java @@ -24,7 +24,7 @@ public class DefaultResourceResolver { - private ResourceHandler resourceHandler; + private final ResourceHandler resourceHandler; public DefaultResourceResolver(ResourceHandler resourceHandler) { this.resourceHandler = resourceHandler; diff --git a/impl/src/main/java/com/sun/faces/facelets/impl/FaceletCacheFactoryImpl.java b/impl/src/main/java/com/sun/faces/facelets/impl/FaceletCacheFactoryImpl.java index ceac74dacc..34a5767d20 100644 --- a/impl/src/main/java/com/sun/faces/facelets/impl/FaceletCacheFactoryImpl.java +++ b/impl/src/main/java/com/sun/faces/facelets/impl/FaceletCacheFactoryImpl.java @@ -35,9 +35,8 @@ public FaceletCache getFaceletCache() { WebConfiguration webConfig = WebConfiguration.getInstance(); String refreshPeriod = webConfig.getOptionValue(WebConfiguration.WebContextInitParameter.FaceletsDefaultRefreshPeriod); long period = Long.parseLong(refreshPeriod) * 1000; - FaceletCache result = new DefaultFaceletCache(period); + FaceletCache result = new DefaultFaceletCache(period); return result; - } } diff --git a/impl/src/main/java/com/sun/faces/facelets/impl/IdMapper.java b/impl/src/main/java/com/sun/faces/facelets/impl/IdMapper.java index c3156a8929..09879e8872 100644 --- a/impl/src/main/java/com/sun/faces/facelets/impl/IdMapper.java +++ b/impl/src/main/java/com/sun/faces/facelets/impl/IdMapper.java @@ -17,6 +17,7 @@ package com.sun.faces.facelets.impl; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; import com.sun.faces.util.Cache; import com.sun.faces.util.Util; @@ -24,13 +25,13 @@ import jakarta.faces.context.FacesContext; /** - * Used to provide aliases to Facelets generated unique IDs with tend to be womewhat long. + * Used to provide aliases to Facelets generated unique IDs with tend to be somewhat long. */ public class IdMapper { private static final String KEY = IdMapper.class.getName(); - private Cache idCache = new Cache<>(new IdGen()); + private final Cache idCache = new Cache<>(new IdGen()); // ------------------------------------------------------------ Constructors @@ -67,7 +68,7 @@ public static IdMapper getMapper(FacesContext ctx) { private static final class IdGen implements Cache.Factory { - private AtomicInteger counter = new AtomicInteger(0); + private final AtomicInteger counter = new AtomicInteger(0); // ------------------------------------------ Methods from Cache.Factory diff --git a/impl/src/main/java/com/sun/faces/facelets/tag/TagAttributesImpl.java b/impl/src/main/java/com/sun/faces/facelets/tag/TagAttributesImpl.java index 062b0f34f1..3fb35c121b 100644 --- a/impl/src/main/java/com/sun/faces/facelets/tag/TagAttributesImpl.java +++ b/impl/src/main/java/com/sun/faces/facelets/tag/TagAttributesImpl.java @@ -44,6 +44,11 @@ public final class TagAttributesImpl extends TagAttributes { private Tag tag; + // + // todo: why don't use a TreeMap attrsByNamespaceByLocalName ? + // stream(attrs).groupingBy(TagAttribute::getNamespace,TreeMap::new , .... ) + // + /** * */ @@ -106,13 +111,14 @@ public TagAttribute get(String localName) { */ @Override public TagAttribute get(String ns, String localName) { + // todo: with the TreeMap would be a map.get(namespace).get(localName) if (ns != null && localName != null) { int idx = Arrays.binarySearch(this.ns, ns); if (idx >= 0) { TagAttribute[] uia = (TagAttribute[]) nsattrs.get(idx); - for (int i = 0; i < uia.length; i++) { - if (localName.equals(uia[i].getLocalName())) { - return uia[i]; + for (TagAttribute tagAttribute : uia) { + if (localName.equals(tagAttribute.getLocalName())) { + return tagAttribute; } } } @@ -170,9 +176,9 @@ public void setTag(Tag tag) { */ @Override public String toString() { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < attrs.length; i++) { - sb.append(attrs[i]); + StringBuilder sb = new StringBuilder(); + for (TagAttribute attr : attrs) { + sb.append(attr); sb.append(' '); } if (sb.length() > 1) { diff --git a/impl/src/main/java/com/sun/faces/facelets/tag/composite/BehaviorHolderWrapper.java b/impl/src/main/java/com/sun/faces/facelets/tag/composite/BehaviorHolderWrapper.java index a0f89fe76d..5c5a0a975d 100644 --- a/impl/src/main/java/com/sun/faces/facelets/tag/composite/BehaviorHolderWrapper.java +++ b/impl/src/main/java/com/sun/faces/facelets/tag/composite/BehaviorHolderWrapper.java @@ -16,12 +16,9 @@ package com.sun.faces.facelets.tag.composite; -import static java.util.Collections.unmodifiableMap; - import java.io.IOException; import java.util.Collection; import java.util.Collections; -import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; @@ -408,12 +405,12 @@ protected FacesContext getFacesContext() { } @Override - protected FacesListener[] getFacesListeners(Class clazz) { + protected FacesListener[] getFacesListeners(Class clazz) { return new FacesListener[0]; } @Override - protected Renderer getRenderer(FacesContext context) { + protected Renderer getRenderer(FacesContext context) { return null; } @@ -439,10 +436,7 @@ public void addClientBehavior(String eventName, ClientBehavior behavior) { public Map> getClientBehaviors() { if (parent instanceof ClientBehaviorHolder) { ClientBehaviorHolder parentHolder = (ClientBehaviorHolder) parent; - Map> behaviors = new HashMap<>(1); - behaviors.put(virtualEvent, parentHolder.getClientBehaviors().get(event)); - - return unmodifiableMap(behaviors); + return Map.of( virtualEvent, parentHolder.getClientBehaviors().get(event) ); } throw new FacesException("Unable to get behaviors from non-ClientBehaviorHolder parent:" + parent); diff --git a/impl/src/main/java/com/sun/faces/facelets/tag/composite/InterfaceHandler.java b/impl/src/main/java/com/sun/faces/facelets/tag/composite/InterfaceHandler.java index 52cb6c9d6f..82035896c7 100644 --- a/impl/src/main/java/com/sun/faces/facelets/tag/composite/InterfaceHandler.java +++ b/impl/src/main/java/com/sun/faces/facelets/tag/composite/InterfaceHandler.java @@ -90,7 +90,7 @@ private void validateComponent(FacesContext context, UIComponent ccParent) throw String key; Object requiredValue; boolean found = false, required = false; - StringBuffer buf = null; + StringBuilder buf = null; String attrMessage = "", facetMessage = ""; // Traverse the attributes of this component @@ -121,7 +121,7 @@ private void validateComponent(FacesContext context, UIComponent ccParent) throw } if (!found) { if (null == buf) { - buf = new StringBuffer(); + buf = new StringBuilder(); buf.append(key); } else { buf.append(", " + key); @@ -152,7 +152,7 @@ private void validateComponent(FacesContext context, UIComponent ccParent) throw key = cur.getName(); if (!cc.getFacets().containsKey(key)) { if (null == buf) { - buf = new StringBuffer(); + buf = new StringBuilder(); buf.append(key); } else { buf.append(", " + key); diff --git a/impl/src/main/java/com/sun/faces/facelets/tag/faces/BehaviorTagHandlerDelegateImpl.java b/impl/src/main/java/com/sun/faces/facelets/tag/faces/BehaviorTagHandlerDelegateImpl.java index a92ac93dd7..66cb1bae4d 100644 --- a/impl/src/main/java/com/sun/faces/facelets/tag/faces/BehaviorTagHandlerDelegateImpl.java +++ b/impl/src/main/java/com/sun/faces/facelets/tag/faces/BehaviorTagHandlerDelegateImpl.java @@ -131,7 +131,7 @@ public void applyAttachedObject(FacesContext context, UIComponent parent) { } @Override - public MetaRuleset createMetaRuleset(Class type) { + public MetaRuleset createMetaRuleset(Class type) { Util.notNull("type", type); MetaRuleset m = new MetaRulesetImpl(owner.getTag(), type); m = m.ignore("event"); diff --git a/impl/src/main/java/com/sun/faces/facelets/tag/faces/ComponentTagHandlerDelegateImpl.java b/impl/src/main/java/com/sun/faces/facelets/tag/faces/ComponentTagHandlerDelegateImpl.java index 4a9b9c1637..8221c6b543 100644 --- a/impl/src/main/java/com/sun/faces/facelets/tag/faces/ComponentTagHandlerDelegateImpl.java +++ b/impl/src/main/java/com/sun/faces/facelets/tag/faces/ComponentTagHandlerDelegateImpl.java @@ -260,7 +260,7 @@ private void adjustIndexOfDynamicChildren(FacesContext context, UIComponent pare } @Override - public MetaRuleset createMetaRuleset(Class type) { + public MetaRuleset createMetaRuleset(Class type) { Util.notNull("type", type); MetaRuleset m = new MetaRulesetImpl(owner.getTag(), type); diff --git a/impl/src/main/java/com/sun/faces/facelets/tag/faces/ConverterTagHandlerDelegateImpl.java b/impl/src/main/java/com/sun/faces/facelets/tag/faces/ConverterTagHandlerDelegateImpl.java index c127e8bb49..12702bcad7 100644 --- a/impl/src/main/java/com/sun/faces/facelets/tag/faces/ConverterTagHandlerDelegateImpl.java +++ b/impl/src/main/java/com/sun/faces/facelets/tag/faces/ConverterTagHandlerDelegateImpl.java @@ -69,7 +69,7 @@ public void apply(FaceletContext ctx, UIComponent parent) throws IOException { } @Override - public MetaRuleset createMetaRuleset(Class type) { + public MetaRuleset createMetaRuleset(Class type) { Util.notNull("type", type); MetaRuleset m = new MetaRulesetImpl(owner.getTag(), type); diff --git a/impl/src/main/java/com/sun/faces/facelets/tag/faces/ValidatorTagHandlerDelegateImpl.java b/impl/src/main/java/com/sun/faces/facelets/tag/faces/ValidatorTagHandlerDelegateImpl.java index 8764ba95e5..9d22944691 100644 --- a/impl/src/main/java/com/sun/faces/facelets/tag/faces/ValidatorTagHandlerDelegateImpl.java +++ b/impl/src/main/java/com/sun/faces/facelets/tag/faces/ValidatorTagHandlerDelegateImpl.java @@ -71,7 +71,7 @@ public void apply(FaceletContext ctx, UIComponent parent) throws IOException { } @Override - public MetaRuleset createMetaRuleset(Class type) { + public MetaRuleset createMetaRuleset(Class type) { Util.notNull("type", type); MetaRuleset m = new MetaRulesetImpl(owner.getTag(), type); diff --git a/impl/src/main/java/com/sun/faces/facelets/tag/ui/UIDebug.java b/impl/src/main/java/com/sun/faces/facelets/tag/ui/UIDebug.java index 5a5d436f16..13255c3ba1 100644 --- a/impl/src/main/java/com/sun/faces/facelets/tag/ui/UIDebug.java +++ b/impl/src/main/java/com/sun/faces/facelets/tag/ui/UIDebug.java @@ -18,7 +18,6 @@ import java.io.IOException; import java.util.ArrayList; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -27,6 +26,7 @@ import com.sun.faces.renderkit.RenderKitUtils; import com.sun.faces.renderkit.html_basic.ScriptRenderer; +import com.sun.faces.util.LRUMap; import jakarta.faces.component.UIComponentBase; import jakarta.faces.context.FacesContext; import jakarta.faces.context.ResponseWriter; @@ -80,7 +80,7 @@ public void encodeBegin(FacesContext facesContext) throws IOException { pushComponentToEL(facesContext, this); String actionId = facesContext.getApplication().getViewHandler().getActionURL(facesContext, facesContext.getViewRoot().getViewId()); - StringBuffer sb = new StringBuffer(512); + StringBuilder sb = new StringBuilder(512); sb.append("// session = faces.getExternalContext().getSessionMap(); Map debugs = (Map) session.get(KEY); if (debugs == null) { - debugs = new LinkedHashMap() { - - private static final long serialVersionUID = 2541609242499547693L; - - @Override - protected boolean removeEldestEntry(Map.Entry eldest) { - return size() > 5; - } - }; + debugs = new LRUMap<>(5); } session.put(KEY, debugs); - String id = "" + nextId++; + String id = String.valueOf(nextId++); debugs.put(id, fw.toString()); return id; } private static String fetchDebugOutput(FacesContext faces, String id) { - Map session = faces.getExternalContext().getSessionMap(); + Map session = faces.getExternalContext().getSessionMap(); Map debugs = (Map) session.get(KEY); if (debugs != null) { return (String) debugs.get(id); diff --git a/impl/src/main/java/com/sun/faces/facelets/util/Classpath.java b/impl/src/main/java/com/sun/faces/facelets/util/Classpath.java index ac2bbce3b3..cf613d9d7a 100644 --- a/impl/src/main/java/com/sun/faces/facelets/util/Classpath.java +++ b/impl/src/main/java/com/sun/faces/facelets/util/Classpath.java @@ -23,6 +23,7 @@ import java.net.URL; import java.net.URLConnection; import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; import java.util.Enumeration; import java.util.LinkedHashSet; import java.util.Set; @@ -65,20 +66,20 @@ public static URL[] search(ClassLoader cl, String prefix, String suffix) throws } public static URL[] search(ClassLoader cl, String prefix, String suffix, SearchAdvice advice) throws IOException { - Enumeration[] e = new Enumeration[] { cl.getResources(prefix), cl.getResources(prefix + "MANIFEST.MF") }; - Set all = new LinkedHashSet(); + Enumeration[] e = new Enumeration[] { cl.getResources(prefix), cl.getResources(prefix + "MANIFEST.MF") }; + Set all = new LinkedHashSet<>(); URL url; URLConnection conn; JarFile jarFile; - for (int i = 0, s = e.length; i < s; ++i) { - while (e[i].hasMoreElements()) { - url = (URL) e[i].nextElement(); + for (Enumeration urlEnumeration : e) { + while (urlEnumeration.hasMoreElements()) { + url = urlEnumeration.nextElement(); // Defensive programming. Due to issue 13045 this collection // can contain URLs that have their spaces incorrectly escaped // by having %20 replaced with %2520. This quick conditional // check catches this particular case and averts it. String str = url.getPath(); - if (-1 != str.indexOf("%2520")) { + if (str.contains("%2520")) { str = url.toExternalForm(); str = str.replace("%2520", "%20"); url = new URL(str); @@ -93,18 +94,18 @@ public static URL[] search(ClassLoader cl, String prefix, String suffix, SearchA if (jarFile != null) { searchJar(cl, all, jarFile, prefix, suffix, advice); } else { - boolean searchDone = searchDir(all, new File(URLDecoder.decode(url.getFile(), "UTF-8")), suffix); + boolean searchDone = searchDir(all, new File(URLDecoder.decode(url.getFile(), StandardCharsets.UTF_8)), suffix); if (!searchDone) { searchFromURL(all, prefix, suffix, url); } } } } - URL[] urlArray = (URL[]) all.toArray(new URL[all.size()]); + URL[] urlArray = all.toArray(new URL[0]); return urlArray; } - private static boolean searchDir(Set result, File file, String suffix) throws IOException { + private static boolean searchDir(Set result, File file, String suffix) throws IOException { if (file.exists() && file.isDirectory()) { File[] fc = file.listFiles(); String path; @@ -115,13 +116,13 @@ private static boolean searchDir(Set result, File file, String suffix) throws IO return false; } - for (int i = 0; i < fc.length; i++) { - path = fc[i].getAbsolutePath(); - if (fc[i].isDirectory()) { - searchDir(result, fc[i], suffix); + for (File value : fc) { + path = value.getAbsolutePath(); + if (value.isDirectory()) { + searchDir(result, value, suffix); } else if (path.endsWith(suffix)) { // result.add(new URL("file:/" + path)); - result.add(fc[i].toURL()); + result.add(value.toURL()); } } return true; @@ -139,7 +140,7 @@ private static boolean searchDir(Set result, File file, String suffix) throws IO * * @throws IOException for any error */ - private static void searchFromURL(Set result, String prefix, String suffix, URL url) throws IOException { + private static void searchFromURL(Set result, String prefix, String suffix, URL url) throws IOException { boolean done = false; InputStream is = getInputStream(url); if (is != null) { @@ -182,7 +183,7 @@ private static void searchFromURL(Set result, String prefix, String suffix, URL } /** - * Join tokens, exlude last if param equals true. + * Join tokens, exclude last if param equals true. * * @param tokens the tokens * @param excludeLast do we exclude last token @@ -190,7 +191,7 @@ private static void searchFromURL(Set result, String prefix, String suffix, URL * @return joined tokens */ private static String join(String[] tokens, boolean excludeLast) { - StringBuffer join = new StringBuffer(); + StringBuilder join = new StringBuilder(); for (int i = 0; i < tokens.length - (excludeLast ? 1 : 0); i++) { join.append(tokens[i]).append("/"); } @@ -244,7 +245,7 @@ static JarFile getAlternativeJarFile(String urlFile) throws IOException { // And trim off any "file:" prefix. if (jarFileUrl.startsWith("file:")) { jarFileUrl = jarFileUrl.substring("file:".length()); - jarFileUrl = URLDecoder.decode(jarFileUrl, "UTF-8"); + jarFileUrl = URLDecoder.decode(jarFileUrl, StandardCharsets.UTF_8); } boolean foundExclusion = false; for (int i = 0; i < PREFIXES_TO_EXCLUDE.length; i++) { @@ -266,19 +267,19 @@ static JarFile getAlternativeJarFile(String urlFile) throws IOException { return null; } - private static void searchJar(ClassLoader cl, Set result, JarFile file, String prefix, String suffix, SearchAdvice advice) throws IOException { - Enumeration e = file.entries(); + private static void searchJar(ClassLoader cl, Set result, JarFile file, String prefix, String suffix, SearchAdvice advice) throws IOException { + Enumeration e = file.entries(); JarEntry entry; String name; while (e.hasMoreElements()) { try { - entry = (JarEntry) e.nextElement(); + entry = e.nextElement(); } catch (Throwable t) { continue; } name = entry.getName(); if (name.startsWith(prefix) && name.endsWith(suffix)) { - Enumeration e2 = cl.getResources(name); + Enumeration e2 = cl.getResources(name); while (e2.hasMoreElements()) { result.add(e2.nextElement()); if (advice == SearchAdvice.FirstMatchOnly) { diff --git a/impl/src/main/java/com/sun/faces/facelets/util/ReflectionUtil.java b/impl/src/main/java/com/sun/faces/facelets/util/ReflectionUtil.java index fc207039d2..341b59dbd9 100644 --- a/impl/src/main/java/com/sun/faces/facelets/util/ReflectionUtil.java +++ b/impl/src/main/java/com/sun/faces/facelets/util/ReflectionUtil.java @@ -146,11 +146,11 @@ public static String[] toTypeNameArray(Class[] c) { // return null; // } - protected static final String paramString(Class[] types) { + protected static String paramString(Class[] types) { if (types != null) { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < types.length; i++) { - sb.append(types[i].getName()).append(", "); + StringBuilder sb = new StringBuilder(); + for (Class type : types) { + sb.append(type.getName()).append(", "); } if (sb.length() > 2) { sb.setLength(sb.length() - 2); @@ -163,14 +163,12 @@ protected static final String paramString(Class[] types) { public static Object decorateInstance(Class clazz, Class rootType, Object root) { Object returnObject = null; try { - if (returnObject == null) { - // Look for an adapter constructor if we've got - // an object to adapt - if (rootType != null && root != null) { - Constructor construct = ReflectionUtils.lookupConstructor(clazz, rootType); - if (construct != null) { - returnObject = construct.newInstance(root); - } + // Look for an adapter constructor if we've got + // an object to adapt + if (rootType != null && root != null) { + Constructor construct = ReflectionUtils.lookupConstructor(clazz, rootType); + if (construct != null) { + returnObject = construct.newInstance(root); } } if (clazz != null && returnObject == null) { diff --git a/impl/src/main/java/com/sun/faces/renderkit/AttributeManager.java b/impl/src/main/java/com/sun/faces/renderkit/AttributeManager.java index 091d63e887..28d3113a7f 100644 --- a/impl/src/main/java/com/sun/faces/renderkit/AttributeManager.java +++ b/impl/src/main/java/com/sun/faces/renderkit/AttributeManager.java @@ -40,7 +40,7 @@ public enum Key { OUTPUTBODY, OUTPUTDOCTYPE, OUTPUTHEAD; } - private static Map ATTRIBUTE_LOOKUP = CollectionsUtils.map() + private static final Map ATTRIBUTE_LOOKUP = CollectionsUtils.map() .add(Key.COMMANDBUTTON, ar(attr("accesskey"), attr("dir"), attr("lang"), attr("onblur", "blur"), attr("onchange", "change"), attr("ondblclick", "dblclick"), attr("onfocus", "focus"), attr("onkeydown", "keydown"), attr("onkeypress", "keypress"), attr("onkeyup", "keyup"), diff --git a/impl/src/main/java/com/sun/faces/renderkit/RenderKitImpl.java b/impl/src/main/java/com/sun/faces/renderkit/RenderKitImpl.java index 13c1000810..681514423c 100644 --- a/impl/src/main/java/com/sun/faces/renderkit/RenderKitImpl.java +++ b/impl/src/main/java/com/sun/faces/renderkit/RenderKitImpl.java @@ -42,6 +42,7 @@ import com.sun.faces.util.MessageUtils; import com.sun.faces.util.Util; +import jakarta.faces.component.UIComponent; import jakarta.faces.context.FacesContext; import jakarta.faces.context.ResponseStream; import jakarta.faces.context.ResponseWriter; @@ -70,17 +71,17 @@ public class RenderKitImpl extends RenderKit { * Keys are String renderer family. Values are HashMaps. Nested HashMap keys are Strings for the rendererType, and * values are the Renderer instances themselves. */ - private ConcurrentHashMap> rendererFamilies = new ConcurrentHashMap<>(); + private final ConcurrentHashMap>> rendererFamilies = new ConcurrentHashMap<>(); /** * For Behavior Renderers: Keys are Strings for the behaviorRendererType, and values are the behaviorRenderer instances * themselves. */ - private ConcurrentHashMap behaviorRenderers = new ConcurrentHashMap<>(); + private final ConcurrentHashMap behaviorRenderers = new ConcurrentHashMap<>(); private ResponseStateManager responseStateManager = new ResponseStateManagerImpl(); - private WebConfiguration webConfig; + private final WebConfiguration webConfig; public RenderKitImpl() { @@ -90,17 +91,13 @@ public RenderKitImpl() { } @Override - public void addRenderer(String family, String rendererType, Renderer renderer) { + public void addRenderer(String family, String rendererType, Renderer renderer) { Util.notNull("family", family); Util.notNull("rendererType", rendererType); Util.notNull("renderer", renderer); - HashMap renderers = rendererFamilies.get(family); - if (renderers == null) { - renderers = new HashMap<>(); - rendererFamilies.put(family, renderers); - } + Map> renderers = rendererFamilies.computeIfAbsent(family, k -> new HashMap<>()); if (LOGGER.isLoggable(Level.FINE) && renderers.containsKey(rendererType)) { LOGGER.log(Level.FINE, "rendererType {0} has already been registered for family {1}. Replacing existing renderer class type {2} with {3}.", @@ -111,14 +108,14 @@ public void addRenderer(String family, String rendererType, Renderer renderer) { } @Override - public Renderer getRenderer(String family, String rendererType) { + public Renderer getRenderer(String family, String rendererType) { Util.notNull("family", family); Util.notNull("rendererType", rendererType); - assert rendererFamilies != null; + assert rendererFamilies != null; // ?? - HashMap renderers = rendererFamilies.get(family); + Map> renderers = rendererFamilies.get(family); return renderers != null ? renderers.get(rendererType) : null; } @@ -143,16 +140,12 @@ public ClientBehaviorRenderer getClientBehaviorRenderer(String behaviorRendererT Util.notNull("behaviorRendererType", behaviorRendererType); - return behaviorRenderers != null ? behaviorRenderers.get(behaviorRendererType) : null; + return behaviorRenderers.get(behaviorRendererType); } @Override public Iterator getClientBehaviorRendererTypes() { - if (null == behaviorRenderers) { - Set empty = Collections.emptySet(); - return empty.iterator(); - } return behaviorRenderers.keySet().iterator(); } @@ -198,7 +191,7 @@ public ResponseWriter createResponseWriter(Writer writer, String desiredContentT if (null == desiredContentTypeList || contentTypeNullFromResponse) { String[] typeArray = context.getExternalContext().getRequestHeaderValuesMap().get("Accept"); if (typeArray.length > 0) { - StringBuffer buff = new StringBuffer(); + StringBuilder buff = new StringBuilder(); buff.append(typeArray[0]); for (int i = 1, len = typeArray.length; i < len; i++) { buff.append(','); @@ -279,15 +272,13 @@ private String findMatch(String desiredContentTypeList, String[] supportedTypes) // For each entry in the desiredTypes array, look for a match in // the supportedTypes array - for (int i = 0, ilen = desiredTypes.length; i < ilen; i++) { - String curDesiredType = desiredTypes[i]; - for (int j = 0, jlen = supportedTypes.length; j < jlen; j++) { - String curContentType = supportedTypes[j].trim(); + for (String curDesiredType : desiredTypes) { + for (String supportedType : supportedTypes) { + String curContentType = supportedType.trim(); if (curDesiredType.contains(curContentType)) { if (curContentType.contains(RIConstants.HTML_CONTENT_TYPE)) { contentType = RIConstants.HTML_CONTENT_TYPE; - } else if (curContentType.contains(RIConstants.XHTML_CONTENT_TYPE) || curContentType.contains(RIConstants.APPLICATION_XML_CONTENT_TYPE) - || curContentType.contains(RIConstants.TEXT_XML_CONTENT_TYPE)) { + } else if (curContentType.contains(RIConstants.XHTML_CONTENT_TYPE) || curContentType.contains(RIConstants.APPLICATION_XML_CONTENT_TYPE) || curContentType.contains(RIConstants.TEXT_XML_CONTENT_TYPE)) { contentType = RIConstants.XHTML_CONTENT_TYPE; } break; @@ -310,12 +301,12 @@ public void write(int b) throws IOException { } @Override - public void write(byte b[]) throws IOException { + public void write(byte[] b) throws IOException { output.write(b); } @Override - public void write(byte b[], int off, int len) throws IOException { + public void write(byte[] b, int off, int len) throws IOException { output.write(b, off, len); } @@ -347,12 +338,11 @@ public Iterator getComponentFamilies() { @Override public Iterator getRendererTypes(String componentFamily) { - Map family = rendererFamilies.get(componentFamily); + Map> family = rendererFamilies.get(componentFamily); if (family != null) { return family.keySet().iterator(); } else { - Set empty = Collections.emptySet(); - return empty.iterator(); + return Collections.emptyIterator(); } } diff --git a/impl/src/main/java/com/sun/faces/renderkit/html_basic/HtmlBasicRenderer.java b/impl/src/main/java/com/sun/faces/renderkit/html_basic/HtmlBasicRenderer.java index 2c56873c9a..883c73b399 100644 --- a/impl/src/main/java/com/sun/faces/renderkit/html_basic/HtmlBasicRenderer.java +++ b/impl/src/main/java/com/sun/faces/renderkit/html_basic/HtmlBasicRenderer.java @@ -44,6 +44,7 @@ import com.sun.faces.util.MessageUtils; import com.sun.faces.util.Util; +import jakarta.faces.application.FacesMessage; import jakarta.faces.component.NamingContainer; import jakarta.faces.component.UIComponent; import jakarta.faces.component.UIInput; @@ -278,7 +279,7 @@ protected Iterator getChildren(UIComponent component) { if (childCount > 0) { return component.getChildren().iterator(); } else { - return Collections.emptyList().iterator(); + return Collections.emptyIterator(); } } @@ -467,7 +468,7 @@ protected String getFormattedValue(FacesContext context, UIComponent component, private static final Set EXPRESSION_HINTS = EnumSet.of(SearchExpressionHint.IGNORE_NO_RESULT, SearchExpressionHint.RESOLVE_SINGLE_COMPONENT); - protected Iterator getMessageIter(FacesContext context, String forComponent, UIComponent component) { + protected Iterator getMessageIter(FacesContext context, String forComponent, UIComponent component) { // no "for" expression - return all messages if (forComponent == null) { return context.getMessages(); @@ -510,7 +511,7 @@ protected Param[] getParamList(UIComponent command) { } } } - return parameterList.toArray(new Param[parameterList.size()]); + return parameterList.toArray(new Param[0]); } else { return EMPTY_PARAMS; } @@ -550,7 +551,7 @@ protected Collection getBehaviorParameters(UICo } } - return params == null ? Collections.emptyList() : params; + return params == null ? Collections.emptyList() : params; } protected Object getValue(UIComponent component) { @@ -708,9 +709,7 @@ private static UIComponent findUIComponentBelow(UIComponent startPoint, String f UIComponent retComp = null; if (startPoint.getChildCount() > 0) { List children = startPoint.getChildren(); - for (int i = 0, size = children.size(); i < size; i++) { - UIComponent comp = children.get(i); - + for (UIComponent comp : children) { if (comp instanceof NamingContainer) { try { retComp = comp.findComponent(forComponent); diff --git a/impl/src/main/java/com/sun/faces/renderkit/html_basic/MenuRenderer.java b/impl/src/main/java/com/sun/faces/renderkit/html_basic/MenuRenderer.java index 9477b9ae30..3d3edfcc27 100644 --- a/impl/src/main/java/com/sun/faces/renderkit/html_basic/MenuRenderer.java +++ b/impl/src/main/java/com/sun/faces/renderkit/html_basic/MenuRenderer.java @@ -791,7 +791,7 @@ protected Collection createCollectionFromHint(Object collectionTypeHint) collectionType = (Class>) collectionTypeHint; } else if (collectionTypeHint instanceof String) { try { - collectionType = Util.loadClass((String) collectionTypeHint, this); + collectionType = (Class>) Util.loadClass((String) collectionTypeHint, this); } catch (ClassNotFoundException cnfe) { throw new FacesException(cnfe); } @@ -820,7 +820,7 @@ private void decodeUISelectMany(FacesContext context, UISelectMany component, St Map requestParameterValuesMap = context.getExternalContext().getRequestParameterValuesMap(); if (requestParameterValuesMap.containsKey(clientId)) { - String newValues[] = requestParameterValuesMap.get(clientId); + String[] newValues = requestParameterValuesMap.get(clientId); if (newValues != null && newValues.length > 0) { Set disabledSelectItemValues = getDisabledSelectItemValues(context, component); @@ -828,7 +828,7 @@ private void decodeUISelectMany(FacesContext context, UISelectMany component, St List newValuesList = new ArrayList<>(Arrays.asList(newValues)); if (newValuesList.removeAll(disabledSelectItemValues)) { - newValues = newValuesList.toArray(new String[newValuesList.size()]); + newValues = newValuesList.toArray(new String[0]); } } } diff --git a/impl/src/main/java/com/sun/faces/renderkit/html_basic/OutputLinkRenderer.java b/impl/src/main/java/com/sun/faces/renderkit/html_basic/OutputLinkRenderer.java index 2bb779516d..2232224579 100644 --- a/impl/src/main/java/com/sun/faces/renderkit/html_basic/OutputLinkRenderer.java +++ b/impl/src/main/java/com/sun/faces/renderkit/html_basic/OutputLinkRenderer.java @@ -23,6 +23,7 @@ import java.io.IOException; import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import com.sun.faces.renderkit.Attribute; import com.sun.faces.renderkit.AttributeManager; @@ -166,20 +167,20 @@ protected void renderAsActive(FacesContext context, UIComponent component) throw // Write Anchor attributes - Param paramList[] = getParamList(component); - StringBuffer sb = new StringBuffer(); + Param[] paramList = getParamList(component); + StringBuilder sb = new StringBuilder(); sb.append(hrefVal); boolean paramWritten = hrefVal.indexOf('?') > 0; - for (int i = 0, len = paramList.length; i < len; i++) { - String pn = paramList[i].name; + for (Param param : paramList) { + String pn = param.name; if (pn != null && pn.length() != 0) { - String pv = paramList[i].value; + String pv = param.value; sb.append(paramWritten ? '&' : '?'); - sb.append(URLEncoder.encode(pn, "UTF-8")); + sb.append(URLEncoder.encode(pn, StandardCharsets.UTF_8)); sb.append('='); if (pv != null && pv.length() != 0) { - sb.append(URLEncoder.encode(pv, "UTF-8")); + sb.append(URLEncoder.encode(pv, StandardCharsets.UTF_8)); } paramWritten = true; } diff --git a/impl/src/main/java/com/sun/faces/renderkit/html_basic/OutputMessageRenderer.java b/impl/src/main/java/com/sun/faces/renderkit/html_basic/OutputMessageRenderer.java index 69d2e07a3f..345eb70446 100644 --- a/impl/src/main/java/com/sun/faces/renderkit/html_basic/OutputMessageRenderer.java +++ b/impl/src/main/java/com/sun/faces/renderkit/html_basic/OutputMessageRenderer.java @@ -83,7 +83,7 @@ public void encodeEnd(FacesContext context, UIComponent component) throws IOExce if (parameterList.size() > 0) { MessageFormat fmt = new MessageFormat(currentValue, context.getViewRoot().getLocale()); StringBuffer buf = new StringBuffer(currentValue.length() * 2); - fmt.format(parameterList.toArray(new Object[parameterList.size()]), buf, null); + fmt.format(parameterList.toArray(new Object[0]), buf, null); message = buf.toString(); } else { message = currentValue; @@ -121,7 +121,7 @@ public void encodeEnd(FacesContext context, UIComponent component) throws IOExce } Object val = component.getAttributes().get("escape"); - boolean escape = val != null && Boolean.valueOf(val.toString()); + boolean escape = val != null && Boolean.parseBoolean(val.toString()); if (escape) { writer.writeText(message, component, "value"); diff --git a/impl/src/main/java/com/sun/faces/util/ComponentStruct.java b/impl/src/main/java/com/sun/faces/util/ComponentStruct.java index f2d7ab5a81..ccdb5c8a86 100644 --- a/impl/src/main/java/com/sun/faces/util/ComponentStruct.java +++ b/impl/src/main/java/com/sun/faces/util/ComponentStruct.java @@ -19,6 +19,8 @@ import jakarta.faces.component.StateHolder; import jakarta.faces.context.FacesContext; +import java.util.Objects; + /** * Utility class to enable partial state saving of components that have been dynamically added to the view. */ @@ -73,7 +75,7 @@ public void restoreState(FacesContext ctx, Object state) { return; } - Object s[] = (Object[]) state; + Object[] s = (Object[]) state; action = (String) s[0]; parentClientId = (String) s[1]; clientId = (String) s[2]; @@ -87,7 +89,7 @@ public Object saveState(FacesContext ctx) { throw new NullPointerException(); } - Object state[] = new Object[5]; + Object[] state = new Object[5]; state[0] = action; state[1] = parentClientId; state[2] = clientId; diff --git a/impl/src/main/java/com/sun/faces/util/HtmlUtils.java b/impl/src/main/java/com/sun/faces/util/HtmlUtils.java index 0815690a3d..230d2eb61e 100644 --- a/impl/src/main/java/com/sun/faces/util/HtmlUtils.java +++ b/impl/src/main/java/com/sun/faces/util/HtmlUtils.java @@ -167,7 +167,7 @@ static public void writeAttribute(Writer out, boolean escapeUnicode, boolean esc if (ch >= 0x3f) { if (ch == 's') { // If putting scripts in attribute values - // has been disabled (the defualt), look for + // has been disabled (the default), look for // script: in the attribute value. // ensure the attribute value is long enough // to accomodate "script:" diff --git a/impl/src/main/java/com/sun/faces/util/LRUMap.java b/impl/src/main/java/com/sun/faces/util/LRUMap.java index dc14511294..82521b304f 100644 --- a/impl/src/main/java/com/sun/faces/util/LRUMap.java +++ b/impl/src/main/java/com/sun/faces/util/LRUMap.java @@ -25,7 +25,7 @@ public class LRUMap extends LinkedHashMap { private static final long serialVersionUID = -7137951139094651602L; - private int maxCapacity; + private final int maxCapacity; // ------------------------------------------------------------ Constructors diff --git a/impl/src/main/java/com/sun/faces/util/MessageFactory.java b/impl/src/main/java/com/sun/faces/util/MessageFactory.java index 1e907b6f71..c0ea8865b7 100644 --- a/impl/src/main/java/com/sun/faces/util/MessageFactory.java +++ b/impl/src/main/java/com/sun/faces/util/MessageFactory.java @@ -309,7 +309,7 @@ private String getFormattedString(String msgtext, Object[] params) { if (params == null || msgtext == null) { return msgtext; } - StringBuffer b = new StringBuffer(100); + StringBuilder b = new StringBuilder(100); MessageFormat mf = new MessageFormat(msgtext); if (locale != null) { mf.setLocale(locale); @@ -319,8 +319,8 @@ private String getFormattedString(String msgtext, Object[] params) { return localizedStr; } - private Locale locale; - private Object[] parameters; + private final Locale locale; + private final Object[] parameters; private Object[] resolvedParameters; } diff --git a/impl/src/main/java/com/sun/faces/util/MostlySingletonSet.java b/impl/src/main/java/com/sun/faces/util/MostlySingletonSet.java index 95f86dc4ee..e77a44346d 100644 --- a/impl/src/main/java/com/sun/faces/util/MostlySingletonSet.java +++ b/impl/src/main/java/com/sun/faces/util/MostlySingletonSet.java @@ -63,7 +63,7 @@ public boolean addAll(Collection c) { boolean result = true; if (null == inner && 1 == c.size()) { - inner = (Set) Collections.singleton(c.iterator().next()); + inner = Collections.singleton(c.iterator().next()); } else { // If we need to transition from one to more-than-one if (1 == inner.size()) { @@ -126,7 +126,7 @@ public boolean removeAll(Collection c) { if (null != inner) { if (1 == inner.size()) { // May throw NPE per spec for Collection.removeAll() - Iterator incomingIter = c.iterator(); + Iterator incomingIter = c.iterator(); E oneAndOnlyElement = inner.iterator().next(); // Iterate over the incoming collection // looking for a member that is equal to our one and only diff --git a/impl/src/main/java/com/sun/faces/util/ScopedRunner.java b/impl/src/main/java/com/sun/faces/util/ScopedRunner.java index 25645a0270..b5ab0de7bb 100644 --- a/impl/src/main/java/com/sun/faces/util/ScopedRunner.java +++ b/impl/src/main/java/com/sun/faces/util/ScopedRunner.java @@ -30,9 +30,9 @@ */ public class ScopedRunner { - private FacesContext context; - private Map scopedVariables; - private Map previousVariables = new HashMap<>(); + private final FacesContext context; + private final Map scopedVariables; + private final Map previousVariables = new HashMap<>(); public ScopedRunner(FacesContext context) { this(context, new HashMap<>()); diff --git a/impl/src/main/java/com/sun/faces/util/Util.java b/impl/src/main/java/com/sun/faces/util/Util.java index 14c62e2db7..dc10ce6292 100644 --- a/impl/src/main/java/com/sun/faces/util/Util.java +++ b/impl/src/main/java/com/sun/faces/util/Util.java @@ -317,7 +317,7 @@ public static SchemaFactory createSchemaFactory(String uri) { return factory; } - public static Class loadClass(String name, Object fallbackClass) throws ClassNotFoundException { + public static Class loadClass(String name, Object fallbackClass) throws ClassNotFoundException { ClassLoader loader = Util.getCurrentLoader(fallbackClass); String[] primitiveNames = { "byte", "short", "int", "long", "float", "double", "boolean", "char" }; @@ -897,7 +897,7 @@ public static String getStackTraceString(Throwable e) { } StackTraceElement[] stacks = e.getStackTrace(); - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); for (StackTraceElement stack : stacks) { sb.append(stack.toString()).append('\n'); } @@ -1435,7 +1435,7 @@ public String getPrefix(String namespaceURI) { } @Override - public Iterator getPrefixes(String namespaceURI) { + public Iterator getPrefixes(String namespaceURI) { return null; } } diff --git a/impl/src/main/java/com/sun/faces/vendor/WebContainerInjectionProvider.java b/impl/src/main/java/com/sun/faces/vendor/WebContainerInjectionProvider.java index aa563c211c..68e9c88951 100644 --- a/impl/src/main/java/com/sun/faces/vendor/WebContainerInjectionProvider.java +++ b/impl/src/main/java/com/sun/faces/vendor/WebContainerInjectionProvider.java @@ -47,7 +47,7 @@ public class WebContainerInjectionProvider implements InjectionProvider { private static final Logger LOGGER = FacesLogger.APPLICATION.getLogger(); - private static Map, ConcurrentHashMap, MethodHolder>> methodsPerClazz = new ConcurrentHashMap<>(); + private static final Map, ConcurrentHashMap, MethodHolder>> methodsPerClazz = new ConcurrentHashMap<>(); // ------------------------------------------ Methods from InjectionProvider @@ -74,7 +74,7 @@ public void invokePostConstruct(Object managedBean) throws InjectionProviderExce private static void invokeAnnotatedMethod(Method method, Object managedBean) throws InjectionProviderException { if (method != null) { - boolean accessible = method.isAccessible(); + boolean accessible = method.canAccess(managedBean); method.setAccessible(true); try { diff --git a/impl/src/main/java/jakarta/faces/annotation/ApplicationMap.java b/impl/src/main/java/jakarta/faces/annotation/ApplicationMap.java index 753da6d89f..d384ce5df0 100644 --- a/impl/src/main/java/jakarta/faces/annotation/ApplicationMap.java +++ b/impl/src/main/java/jakarta/faces/annotation/ApplicationMap.java @@ -49,7 +49,7 @@ * * @since 4.0 */ - public static final class Literal extends AnnotationLiteral implements ApplicationMap { + final class Literal extends AnnotationLiteral implements ApplicationMap { private static final long serialVersionUID = 1L; /** diff --git a/impl/src/main/java/jakarta/faces/application/Application.java b/impl/src/main/java/jakarta/faces/application/Application.java index 3a0484ffc5..0961525c58 100644 --- a/impl/src/main/java/jakarta/faces/application/Application.java +++ b/impl/src/main/java/jakarta/faces/application/Application.java @@ -941,7 +941,7 @@ public UIComponent createComponent(FacesContext context, Resource componentResou * @throws FacesException if the {@link Converter} cannot be created * @throws NullPointerException if converterId is null */ - public abstract Converter createConverter(String converterId); + public abstract Converter createConverter(String converterId); /** *

@@ -982,7 +982,7 @@ public UIComponent createComponent(FacesContext context, Resource componentResou * @throws FacesException if the {@link Converter} cannot be created * @throws NullPointerException if targetClass is null */ - public abstract Converter createConverter(Class targetClass); + public abstract Converter createConverter(Class targetClass); /** *

@@ -1224,7 +1224,7 @@ public ELContextListener[] getELContextListeners() { * @throws FacesException if a {@link Validator} of the specified id cannot be created * @throws NullPointerException if validatorId is null */ - public abstract Validator createValidator(String validatorId) throws FacesException; + public abstract Validator createValidator(String validatorId) throws FacesException; /** *

diff --git a/impl/src/main/java/jakarta/faces/application/ApplicationWrapper.java b/impl/src/main/java/jakarta/faces/application/ApplicationWrapper.java index fa112728f2..fd08ac1488 100644 --- a/impl/src/main/java/jakarta/faces/application/ApplicationWrapper.java +++ b/impl/src/main/java/jakarta/faces/application/ApplicationWrapper.java @@ -331,7 +331,7 @@ public void addConverter(Class targetClass, String converterClass) { *

*/ @Override - public Converter createConverter(String converterId) { + public Converter createConverter(String converterId) { return getWrapped().createConverter(converterId); } @@ -342,7 +342,7 @@ public Converter createConverter(String converterId) { *

*/ @Override - public Converter createConverter(Class targetClass) { + public Converter createConverter(Class targetClass) { return getWrapped().createConverter(targetClass); } diff --git a/impl/src/main/java/jakarta/faces/component/AttachedObjectListHolder.java b/impl/src/main/java/jakarta/faces/component/AttachedObjectListHolder.java index c15d76fcac..bdf820302f 100644 --- a/impl/src/main/java/jakarta/faces/component/AttachedObjectListHolder.java +++ b/impl/src/main/java/jakarta/faces/component/AttachedObjectListHolder.java @@ -22,6 +22,7 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import java.util.Objects; import jakarta.faces.context.FacesContext; @@ -76,10 +77,7 @@ public void clearInitialState() { @Override public Object saveState(FacesContext context) { - - if (context == null) { - throw new NullPointerException(); - } + Objects.requireNonNull(context); if (attachedObjects == null) { return null; @@ -114,10 +112,7 @@ public Object saveState(FacesContext context) { @Override public void restoreState(FacesContext context, Object state) { - - if (context == null) { - throw new NullPointerException(); - } + Objects.requireNonNull(context); if (state == null) { return; @@ -133,8 +128,8 @@ public void restoreState(FacesContext context, Object state) { this.attachedObjects = new ArrayList<>(2); } - for (int i = 0, len = attachedObjects.length; i < len; i++) { - T restored = (T) ((StateHolderSaver) attachedObjects[i]).restore(context); + for (Object attachedObject : attachedObjects) { + T restored = (T) ((StateHolderSaver) attachedObject).restore(context); if (restored != null) { add(restored); } diff --git a/impl/src/main/java/jakarta/faces/component/EditableValueHolder.java b/impl/src/main/java/jakarta/faces/component/EditableValueHolder.java index 5253c27b15..c4cd72be27 100644 --- a/impl/src/main/java/jakarta/faces/component/EditableValueHolder.java +++ b/impl/src/main/java/jakarta/faces/component/EditableValueHolder.java @@ -145,7 +145,7 @@ public interface EditableValueHolder extends ValueHolder { * * @throws NullPointerException if validator is null */ - void addValidator(Validator validator); + void addValidator(Validator validator); /** *

@@ -155,7 +155,7 @@ public interface EditableValueHolder extends ValueHolder { * * @return the validators, or a zero-length array. */ - Validator[] getValidators(); + Validator[] getValidators(); /** *

@@ -165,7 +165,7 @@ public interface EditableValueHolder extends ValueHolder { * * @param validator The {@link Validator} to remove */ - void removeValidator(Validator validator); + void removeValidator(Validator validator); /** *

diff --git a/impl/src/main/java/jakarta/faces/component/MessageFactory.java b/impl/src/main/java/jakarta/faces/component/MessageFactory.java index 367ce62fc7..cc14e00c7b 100644 --- a/impl/src/main/java/jakarta/faces/component/MessageFactory.java +++ b/impl/src/main/java/jakarta/faces/component/MessageFactory.java @@ -307,7 +307,7 @@ private String getFormattedString(String msgtext, Object[] params) { if (params == null || msgtext == null) { return msgtext; } - StringBuffer b = new StringBuffer(100); + StringBuilder b = new StringBuilder(100); MessageFormat mf = new MessageFormat(msgtext); if (locale != null) { mf.setLocale(locale); @@ -317,8 +317,8 @@ private String getFormattedString(String msgtext, Object[] params) { return localizedStr; } - private Locale locale; - private Object[] parameters; + private final Locale locale; + private final Object[] parameters; private Object[] resolvedParameters; } diff --git a/impl/src/main/java/jakarta/faces/component/SelectItemsIterator.java b/impl/src/main/java/jakarta/faces/component/SelectItemsIterator.java index 47ba51c16f..aaddfccb28 100644 --- a/impl/src/main/java/jakarta/faces/component/SelectItemsIterator.java +++ b/impl/src/main/java/jakarta/faces/component/SelectItemsIterator.java @@ -70,7 +70,7 @@ public SelectItemsIterator(FacesContext ctx, UIComponent parent) { * Iterator over the children of the parent component. *

*/ - private ListIterator kids; + private final ListIterator kids; /** * Expose single SelectItems via an Iterator. This iterator will be reset/reused for each individual SelectItem instance @@ -81,7 +81,7 @@ public SelectItemsIterator(FacesContext ctx, UIComponent parent) { /** * The {@link FacesContext} for the current request. */ - private FacesContext ctx; + private final FacesContext ctx; // -------------------------------------------------------- Iterator Methods @@ -274,12 +274,12 @@ private void updateItem(SelectItem item) { */ private static final class MapIterator implements Iterator { - private SelectItem item = new SelectItem(); - private Iterator iterator; + private final SelectItem item = new SelectItem(); + private final Iterator> iterator; // -------------------------------------------------------- Constructors - private MapIterator(Map map) { + private MapIterator(Map map) { iterator = map.entrySet().iterator(); @@ -297,7 +297,7 @@ public boolean hasNext() { @Override public SelectItem next() { - Map.Entry entry = (Map.Entry) iterator.next(); + Map.Entry entry = iterator.next(); Object key = entry.getKey(); Object value = entry.getValue(); item.setLabel(key != null ? key.toString() : value.toString()); @@ -403,9 +403,9 @@ private static final class GenericObjectSelectItem extends SelectItem { /** * The request-scoped variable under which the current object will be exposed. */ - private String var; + private final String var; - private UISelectItems sourceComponent; + private final UISelectItems sourceComponent; // -------------------------------------------------------- Constructors @@ -448,9 +448,9 @@ private void updateItem(FacesContext ctx, Object value) { setValue(itemValueResult != null ? itemValueResult : value); setLabel(itemLabelResult != null ? itemLabelResult.toString() : value.toString()); setDescription(itemDescriptionResult != null ? itemDescriptionResult.toString() : null); - setEscape(itemEscapedResult != null ? Boolean.valueOf(itemEscapedResult.toString()) : true); - setDisabled(itemDisabledResult != null ? Boolean.valueOf(itemDisabledResult.toString()) : false); - setNoSelectionOption(noSelectionOptionResult != null ? Boolean.valueOf(noSelectionOptionResult.toString()) : false); + setEscape(itemEscapedResult == null || Boolean.parseBoolean(itemEscapedResult.toString())); + setDisabled(itemDisabledResult != null && Boolean.parseBoolean(itemDisabledResult.toString())); + setNoSelectionOption(noSelectionOptionResult != null && Boolean.parseBoolean(noSelectionOptionResult.toString())); } finally { if (var != null) { if (oldVarValue != null) { @@ -489,9 +489,9 @@ private void readObject(ObjectInputStream in) throws IOException { */ private static final class ArrayIterator extends GenericObjectSelectItemIterator { - private FacesContext ctx; - private Object array; - private int count; + private final FacesContext ctx; + private final Object array; + private final int count; private int index; // -------------------------------------------------------- Constructors @@ -538,15 +538,15 @@ public void remove() { } // END ArrayIterator /** - * Handles Collections of SelectItems, generic Objects, or combintations of both. + * Handles Collections of SelectItems, generic Objects, or combinations of both. * * A single GenericObjectSelectItem will be leverage for any non-SelectItem objects * encountered. */ private static final class IterableItemIterator extends GenericObjectSelectItemIterator { - private FacesContext ctx; - private Iterator iterator; + private final FacesContext ctx; + private final Iterator iterator; // -------------------------------------------------------- Constructors diff --git a/impl/src/main/java/jakarta/faces/component/SelectUtils.java b/impl/src/main/java/jakarta/faces/component/SelectUtils.java index 4850650540..83d9b5c8c8 100644 --- a/impl/src/main/java/jakarta/faces/component/SelectUtils.java +++ b/impl/src/main/java/jakarta/faces/component/SelectUtils.java @@ -49,14 +49,14 @@ private SelectUtils() { * @param items Iterator over the {@link jakarta.faces.model.SelectItem}s to be checked * @param converter the {@link Converter} associated with this component */ - static boolean matchValue(FacesContext ctx, UIComponent component, Object value, Iterator items, Converter converter) { + static boolean matchValue(FacesContext ctx, UIComponent component, Object value, Iterator items, Converter converter) { while (items.hasNext()) { SelectItem item = items.next(); if (item instanceof SelectItemGroup) { - SelectItem subitems[] = ((SelectItemGroup) item).getSelectItems(); + SelectItem[] subitems = ((SelectItemGroup) item).getSelectItems(); if (subitems != null && subitems.length > 0) { - if (matchValue(ctx, component, value, new ArrayIterator(subitems), converter)) { + if (matchValue(ctx, component, value, new ArrayIterator<>(subitems), converter)) { return true; } } @@ -92,15 +92,15 @@ static boolean matchValue(FacesContext ctx, UIComponent component, Object value, * @return */ - static boolean valueIsNoSelectionOption(FacesContext ctx, UIComponent component, Object value, Iterator items, Converter converter) { + static boolean valueIsNoSelectionOption(FacesContext ctx, UIComponent component, Object value, Iterator items, Converter converter) { boolean result = false; while (items.hasNext()) { SelectItem item = items.next(); if (item instanceof SelectItemGroup) { - SelectItem subitems[] = ((SelectItemGroup) item).getSelectItems(); + SelectItem[] subitems = ((SelectItemGroup) item).getSelectItems(); if (subitems != null && subitems.length > 0) { - if (valueIsNoSelectionOption(ctx, component, value, new ArrayIterator(subitems), converter)) { + if (valueIsNoSelectionOption(ctx, component, value, new ArrayIterator<>(subitems), converter)) { result = true; break; } @@ -128,7 +128,7 @@ static boolean valueIsNoSelectionOption(FacesContext ctx, UIComponent component, return result; } - private static Object doConversion(FacesContext ctx, UIComponent component, SelectItem item, Object value, Converter converter) + private static Object doConversion(FacesContext ctx, UIComponent component, SelectItem item, Object value, Converter converter) throws IllegalStateException { Object itemValue = item.getValue(); if (itemValue == null && value == null) { @@ -159,7 +159,7 @@ private static Object doConversion(FacesContext ctx, UIComponent component, Sele * @param value the value to coerce * @param toType the type value should be coerced to * - * @return the result of the Jakarta Expression Language coersion + * @return the result of the Jakarta Expression Language coercion * * @see ExpressionFactory#coerceToType(Object, Class) */ @@ -185,13 +185,13 @@ private static Object coerceToModelType(FacesContext ctx, Object value, Class /** * Exposes an Array via an Iterator */ - static class ArrayIterator implements Iterator { + static class ArrayIterator implements Iterator { - public ArrayIterator(Object items[]) { + public ArrayIterator(T[] items) { this.items = items; } - private Object items[]; + private final T[] items; private int index = 0; @Override @@ -200,7 +200,7 @@ public boolean hasNext() { } @Override - public Object next() { + public T next() { try { return items[index++]; } catch (IndexOutOfBoundsException e) { diff --git a/impl/src/main/java/jakarta/faces/component/UIComponent.java b/impl/src/main/java/jakarta/faces/component/UIComponent.java index 73ca46a156..f6dbb58997 100644 --- a/impl/src/main/java/jakarta/faces/component/UIComponent.java +++ b/impl/src/main/java/jakarta/faces/component/UIComponent.java @@ -312,10 +312,7 @@ public Map getPassThroughAttributes(boolean create) { * */ public ValueExpression getValueExpression(String name) { - - if (name == null) { - throw new NullPointerException(); - } + Objects.requireNonNull(name); @SuppressWarnings("unchecked") Map map = (Map) getStateHelper().get(UIComponentBase.PropertyKeys.bindings); @@ -1572,9 +1569,9 @@ public static boolean isCompositeComponent(UIComponent component) { if (component == null) { throw new NullPointerException(); } - boolean result = false; + boolean result; if (null != component.isCompositeComponent) { - result = component.isCompositeComponent.booleanValue(); + result = component.isCompositeComponent; } else { result = component.isCompositeComponent = component.getAttributes().containsKey(Resource.COMPONENT_RESOURCE_KEY); } @@ -1705,7 +1702,7 @@ public static UIComponent getCurrentCompositeComponent(FacesContext context) { * @throws IllegalArgumentException if class is not, and does not implement, {@link FacesListener} * @throws NullPointerException if clazz is null */ - protected abstract FacesListener[] getFacesListeners(Class clazz); + protected abstract FacesListener[] getFacesListeners(Class clazz); /** *

@@ -1980,11 +1977,10 @@ public void processEvent(ComponentSystemEvent event) throws AbortProcessingExcep * Convenience method to return the {@link Renderer} instance associated with this component, if any; otherwise, return * null. *

- * * @param context {@link FacesContext} for the current request * @return the renderer, or null. */ - protected abstract Renderer getRenderer(FacesContext context); + protected abstract Renderer getRenderer(FacesContext context); // --------------------------------------------------------- Package Private diff --git a/impl/src/main/java/jakarta/faces/component/UIComponentBase.java b/impl/src/main/java/jakarta/faces/component/UIComponentBase.java index 8ccbfee967..4ab9391ef1 100644 --- a/impl/src/main/java/jakarta/faces/component/UIComponentBase.java +++ b/impl/src/main/java/jakarta/faces/component/UIComponentBase.java @@ -42,20 +42,8 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import java.util.AbstractCollection; -import java.util.AbstractMap; -import java.util.AbstractSet; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import java.util.NoSuchElementException; -import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.logging.Level; @@ -652,7 +640,7 @@ protected void addFacesListener(FacesListener listener) { * @throws NullPointerException {@inheritDoc} */ @Override - protected FacesListener[] getFacesListeners(Class clazz) { + protected FacesListener[] getFacesListeners(Class clazz) { if (clazz == null) { throw new NullPointerException(); @@ -672,7 +660,7 @@ protected FacesListener[] getFacesListeners(Class clazz) { List results = new ArrayList<>(listeners.length); for (FacesListener listener : listeners) { - if (((Class) clazz).isAssignableFrom(listener.getClass())) { + if (clazz.isAssignableFrom(listener.getClass())) { results.add(listener); } } @@ -763,11 +751,7 @@ public void subscribeToEvent(Class eventClass, ComponentS } SystemEventListener facesLifecycleListener = new ComponentSystemEventListenerAdapter(componentListener, this); - List listenersForEventClass = listenersByEventClass.get(eventClass); - if (listenersForEventClass == null) { - listenersForEventClass = new ArrayList<>(3); - listenersByEventClass.put(eventClass, listenersForEventClass); - } + List listenersForEventClass = listenersByEventClass.computeIfAbsent(eventClass, k -> new ArrayList<>(3)); if (!listenersForEventClass.contains(facesLifecycleListener)) { listenersForEventClass.add(facesLifecycleListener); @@ -1038,9 +1022,9 @@ protected FacesContext getFacesContext() { } @Override - protected Renderer getRenderer(FacesContext context) { + protected Renderer getRenderer(FacesContext context) { - Renderer renderer = null; + Renderer renderer = null; String rendererType = getRendererType(); if (rendererType != null) { @@ -1052,7 +1036,7 @@ protected Renderer getRenderer(FacesContext context) { } else { if (LOGGER.isLoggable(FINE)) { String id = getId(); - LOGGER.fine("No renderer-type for component " + id != null ? id : getClass().getName()); + LOGGER.fine("No renderer-type for component " + (id != null ? id : getClass().getName()) ); } } @@ -1272,9 +1256,7 @@ public void setTransient(boolean transientFlag) { */ public static Object saveAttachedState(FacesContext context, Object attachedObject) { - if (context == null) { - throw new NullPointerException(); - } + Objects.requireNonNull(context); if (attachedObject == null) { return null; @@ -1295,7 +1277,7 @@ public static Object saveAttachedState(FacesContext context, Object attachedObje } if (newWillSucceed && attachedObject instanceof Collection) { - Collection attachedCollection = (Collection) attachedObject; + Collection attachedCollection = (Collection) attachedObject; List resultList = new ArrayList<>(attachedCollection.size() + 1); resultList.add(new StateHolderSaver(context, mapOrCollectionClass)); for (Object item : attachedCollection) { diff --git a/impl/src/main/java/jakarta/faces/component/UIInput.java b/impl/src/main/java/jakarta/faces/component/UIInput.java index ad8ad72001..4c3a1bb0b3 100644 --- a/impl/src/main/java/jakarta/faces/component/UIInput.java +++ b/impl/src/main/java/jakarta/faces/component/UIInput.java @@ -16,10 +16,7 @@ package jakarta.faces.component; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Map; +import java.util.*; import jakarta.el.ELException; import jakarta.el.ValueExpression; @@ -155,7 +152,7 @@ public class UIInput extends UIOutput implements EditableValueHolder { */ public static final String ALWAYS_PERFORM_VALIDATION_WHEN_REQUIRED_IS_TRUE = "jakarta.faces.ALWAYS_PERFORM_VALIDATION_WHEN_REQUIRED_IS_TRUE"; - private static final Validator[] EMPTY_VALIDATOR = new Validator[0]; + private static final Validator[] EMPTY_VALIDATOR = new Validator[0]; private transient Boolean emptyStringIsNull; @@ -1124,21 +1121,12 @@ public static boolean isEmpty(Object value) { } else if (value instanceof String && ((String) value).length() < 1) { return true; } else if (value.getClass().isArray()) { - if (0 == java.lang.reflect.Array.getLength(value)) { - return true; - } + return 0 == java.lang.reflect.Array.getLength(value); } else if (value instanceof List) { - if (((List) value).isEmpty()) { - return true; - } + return ((List) value).isEmpty(); } else if (value instanceof Collection) { - if (((Collection) value).isEmpty()) { - return true; - } - } else if (value instanceof Map && ((Map) value).isEmpty()) { - return true; - } - return false; + return ((Collection) value).isEmpty(); + } else return value instanceof Map && ((Map) value).isEmpty(); } /** @@ -1157,11 +1145,8 @@ public static boolean isEmpty(Object value) { * @throws NullPointerException if validator is null */ @Override - public void addValidator(Validator validator) { - - if (validator == null) { - throw new NullPointerException(); - } + public void addValidator(Validator validator) { + Objects.requireNonNull(validator); if (validators == null) { validators = new AttachedObjectListHolder<>(); @@ -1177,7 +1162,7 @@ public void addValidator(Validator validator) { *

*/ @Override - public Validator[] getValidators() { + public Validator[] getValidators() { return validators != null ? validators.asArray(Validator.class) : EMPTY_VALIDATOR; @@ -1192,7 +1177,7 @@ public Validator[] getValidators() { * @param validator The {@link Validator} to remove */ @Override - public void removeValidator(Validator validator) { + public void removeValidator(Validator validator) { if (validator == null) { return; @@ -1291,8 +1276,8 @@ public void restoreState(FacesContext context, Object state) { } - private Converter getConverterWithType(FacesContext context) { - Converter converter = getConverter(); + private Converter getConverterWithType(FacesContext context) { + Converter converter = getConverter(); if (converter != null) { return converter; } diff --git a/impl/src/main/java/jakarta/faces/component/UIOutput.java b/impl/src/main/java/jakarta/faces/component/UIOutput.java index bb5be933bd..5fd4212465 100644 --- a/impl/src/main/java/jakarta/faces/component/UIOutput.java +++ b/impl/src/main/java/jakarta/faces/component/UIOutput.java @@ -19,6 +19,8 @@ import jakarta.faces.context.FacesContext; import jakarta.faces.convert.Converter; +import java.util.Objects; + /** *

* UIOutput is a {@link UIComponent} that has a @@ -98,17 +100,17 @@ public String getFamily() { // --------------------------------------- EditableValueHolder Properties @Override - public Converter getConverter() { + public Converter getConverter() { if (converter != null) { return converter; } - return (Converter) getStateHelper().eval(PropertyKeys.converter); + return (Converter) getStateHelper().eval(PropertyKeys.converter); } @Override - public void setConverter(Converter converter) { + public void setConverter(Converter converter) { clearInitialState(); // we don't push the converter to the StateHelper @@ -173,7 +175,7 @@ public void clearInitialState() { super.clearInitialState(); Converter c = getConverter(); - if (c != null && c instanceof PartialStateHolder) { + if (c instanceof PartialStateHolder) { ((PartialStateHolder) c).clearInitialState(); } } @@ -181,9 +183,7 @@ public void clearInitialState() { @Override public Object saveState(FacesContext context) { - if (context == null) { - throw new NullPointerException(); - } + Objects.requireNonNull(context); Object converterState = null; if (converter != null) { @@ -222,10 +222,7 @@ public Object saveState(FacesContext context) { @Override public void restoreState(FacesContext context, Object state) { - - if (context == null) { - throw new NullPointerException(); - } + Objects.requireNonNull(context); if (state == null) { return; diff --git a/impl/src/main/java/jakarta/faces/component/UISelectMany.java b/impl/src/main/java/jakarta/faces/component/UISelectMany.java index 046e1c1baf..b4e7fcea4c 100644 --- a/impl/src/main/java/jakarta/faces/component/UISelectMany.java +++ b/impl/src/main/java/jakarta/faces/component/UISelectMany.java @@ -18,14 +18,17 @@ package jakarta.faces.component; import java.lang.reflect.Array; +import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; +import java.util.stream.IntStream; import jakarta.el.ValueExpression; import jakarta.faces.application.FacesMessage; import jakarta.faces.context.FacesContext; import jakarta.faces.convert.Converter; +import jakarta.faces.model.SelectItem; /** *

@@ -413,9 +416,9 @@ protected boolean compareValues(Object previous, Object value) { // it will not suffice to just compare the element position and position. int count1; int count2; - for (int i = 0; i < oldarray.length; ++i) { - count1 = countElementOccurrence(oldarray[i], oldarray); - count2 = countElementOccurrence(oldarray[i], newarray); + for (Object oldElement : oldarray) { + count1 = countElementOccurrence(oldElement, oldarray); + count2 = countElementOccurrence(oldElement, newarray); if (count1 != count2) { valueChanged = true; break; @@ -435,8 +438,7 @@ protected boolean compareValues(Object previous, Object value) { */ private static int countElementOccurrence(Object element, Object[] array) { int count = 0; - for (int i = 0; i < array.length; ++i) { - Object arrayElement = array[i]; + for (Object arrayElement : array) { if (arrayElement != null && element != null) { if (arrayElement.equals(element)) { count++; @@ -523,9 +525,9 @@ protected void validateValue(FacesContext context, Object value) { // Ensure that the values match one of the available options // Don't arrays cast to "Object[]", as we may now be using an array // of primitives - Converter converter = getConverter(); - for (Iterator i = getValuesIterator(value); i.hasNext();) { - Iterator items = new SelectItemsIterator(context, this); + Converter converter = getConverter(); + for (Iterator i = getValuesIterator(value); i.hasNext();) { + Iterator items = new SelectItemsIterator(context, this); Object currentValue = i.next(); if (!SelectUtils.matchValue(context, this, currentValue, items, converter)) { doAddMessage = true; @@ -536,8 +538,8 @@ protected void validateValue(FacesContext context, Object value) { // Ensure that if the value is noSelection and a // value is required, a message is queued if (isRequired()) { - for (Iterator i = getValuesIterator(value); i.hasNext();) { - Iterator items = new SelectItemsIterator(context, this); + for (Iterator i = getValuesIterator(value); i.hasNext();) { + Iterator items = new SelectItemsIterator(context, this); Object currentValue = i.next(); if (SelectUtils.valueIsNoSelectionOption(context, this, currentValue, items, converter)) { doAddMessage = true; @@ -557,12 +559,12 @@ protected void validateValue(FacesContext context, Object value) { // --------------------------------------------------------- Private Methods - private Iterator getValuesIterator(Object value) { + private Iterator getValuesIterator(Object value) { if (value instanceof Collection) { - return ((Collection) value).iterator(); + return ((Collection) value).iterator(); } - return new ArrayIterator(value); + return new ArrayIterator<>(value); } // ---------------------------------------------------------- Nested Classes @@ -570,19 +572,17 @@ private Iterator getValuesIterator(Object value) { /** * Exposes an Array as an Iterator. */ - private static final class ArrayIterator implements Iterator { + private static final class ArrayIterator implements Iterator { - private int length; + private final int length; private int idx = 0; - private Object value; + private final Object value; // -------------------------------------------------------- Constructors ArrayIterator(Object value) { - this.value = value; length = Array.getLength(value); - } // ------------------------------------------------------------ Iterator @@ -593,21 +593,18 @@ public boolean hasNext() { } @Override - public Object next() { - + @SuppressWarnings("unchecked") + public T next() { if (idx >= length) { throw new NoSuchElementException(); } else { - return Array.get(value, idx++); + return (T)Array.get(value, idx++); } - } @Override public void remove() { - throw new UnsupportedOperationException(); - } } diff --git a/impl/src/main/java/jakarta/faces/component/ValueHolder.java b/impl/src/main/java/jakarta/faces/component/ValueHolder.java index 254801c2dc..d180e607d6 100644 --- a/impl/src/main/java/jakarta/faces/component/ValueHolder.java +++ b/impl/src/main/java/jakarta/faces/component/ValueHolder.java @@ -68,7 +68,7 @@ public interface ValueHolder { * * @return the converter. */ - Converter getConverter(); + Converter getConverter(); /** *

@@ -77,5 +77,5 @@ public interface ValueHolder { * * @param converter New {@link Converter} (or null) */ - void setConverter(Converter converter); + void setConverter(Converter converter); } diff --git a/impl/src/main/java/jakarta/faces/convert/MessageFactory.java b/impl/src/main/java/jakarta/faces/convert/MessageFactory.java index 757a946022..1d4e33c7fc 100644 --- a/impl/src/main/java/jakarta/faces/convert/MessageFactory.java +++ b/impl/src/main/java/jakarta/faces/convert/MessageFactory.java @@ -309,7 +309,7 @@ private String getFormattedString(String msgtext, Object[] params) { if (params == null || msgtext == null) { return msgtext; } - StringBuffer b = new StringBuffer(100); + StringBuilder b = new StringBuilder(100); MessageFormat mf = new MessageFormat(msgtext); if (locale != null) { mf.setLocale(locale); @@ -319,8 +319,8 @@ private String getFormattedString(String msgtext, Object[] params) { return localizedStr; } - private Locale locale; - private Object[] parameters; + private final Locale locale; + private final Object[] parameters; private Object[] resolvedParameters; } diff --git a/impl/src/main/java/jakarta/faces/render/RenderKit.java b/impl/src/main/java/jakarta/faces/render/RenderKit.java index 6f2e677e41..2686e8c5ab 100644 --- a/impl/src/main/java/jakarta/faces/render/RenderKit.java +++ b/impl/src/main/java/jakarta/faces/render/RenderKit.java @@ -20,7 +20,6 @@ import java.io.Writer; import java.util.Collections; import java.util.Iterator; -import java.util.Set; import jakarta.faces.component.UIComponent; import jakarta.faces.context.ResponseStream; @@ -64,22 +63,19 @@ public abstract class RenderKit { * * @throws NullPointerException if family or rendererType or renderer is null */ - public abstract void addRenderer(String family, String rendererType, Renderer renderer); + public abstract void addRenderer(String family, String rendererType, Renderer renderer); /** *

* Return the {@link Renderer} instance most recently registered for the specified component family and * rendererType, if any; otherwise, return null. *

- * - * @param family Component family of the requested {@link Renderer} instance + * @param family Component family of the requested {@link Renderer} instance * @param rendererType Renderer type of the requested {@link Renderer} instance - * - * @throws NullPointerException if family or rendererType is null - * * @return the {@link Renderer} instance + * @throws NullPointerException if family or rendererType is null */ - public abstract Renderer getRenderer(String family, String rendererType); + public abstract Renderer getRenderer(String family, String rendererType); /** *

@@ -155,10 +151,7 @@ public abstract class RenderKit { * */ public Iterator getComponentFamilies() { - - Set empty = Collections.emptySet(); - return empty.iterator(); - + return Collections.emptyIterator(); } /** @@ -183,10 +176,7 @@ public Iterator getComponentFamilies() { * */ public Iterator getRendererTypes(String componentFamily) { - - Set empty = Collections.emptySet(); - return empty.iterator(); - + return Collections.emptyIterator(); } /** diff --git a/impl/src/main/java/jakarta/faces/render/RenderKitWrapper.java b/impl/src/main/java/jakarta/faces/render/RenderKitWrapper.java index 2187e52928..2e8ba0e955 100644 --- a/impl/src/main/java/jakarta/faces/render/RenderKitWrapper.java +++ b/impl/src/main/java/jakarta/faces/render/RenderKitWrapper.java @@ -21,6 +21,7 @@ import java.util.Iterator; import jakarta.faces.FacesWrapper; +import jakarta.faces.component.UIComponent; import jakarta.faces.context.ResponseStream; import jakarta.faces.context.ResponseWriter; @@ -81,7 +82,7 @@ public RenderKit getWrapped() { * @see RenderKit#addRenderer(String, String, Renderer) */ @Override - public void addRenderer(String family, String rendererType, Renderer renderer) { + public void addRenderer(String family, String rendererType, Renderer renderer) { getWrapped().addRenderer(family, rendererType, renderer); } @@ -116,11 +117,10 @@ public ResponseWriter createResponseWriter(Writer writer, String contentTypeList * The default behavior of this method is to call {@link RenderKit#getRenderer(String, String)} on the wrapped * {@link RenderKit} object. *

- * * @see RenderKit#getRenderer(String, String) */ @Override - public Renderer getRenderer(String family, String rendererType) { + public Renderer getRenderer(String family, String rendererType) { return getWrapped().getRenderer(family, rendererType); } diff --git a/impl/src/main/java/jakarta/faces/render/Renderer.java b/impl/src/main/java/jakarta/faces/render/Renderer.java index be48e83ef0..678c768beb 100644 --- a/impl/src/main/java/jakarta/faces/render/Renderer.java +++ b/impl/src/main/java/jakarta/faces/render/Renderer.java @@ -135,7 +135,7 @@ public void encodeBegin(FacesContext context, T component) throws IOException { * @throws IOException if an input/output error occurs while rendering * @throws NullPointerException if context or component is null */ - public void encodeChildren(FacesContext context, T component) throws IOException { + public void encodeChildren(FacesContext context, T component) throws IOException { if (context == null || component == null) { throw new NullPointerException(); } diff --git a/impl/src/main/java/jakarta/faces/render/RendererWrapper.java b/impl/src/main/java/jakarta/faces/render/RendererWrapper.java index 7043463880..8d863aa7e4 100644 --- a/impl/src/main/java/jakarta/faces/render/RendererWrapper.java +++ b/impl/src/main/java/jakarta/faces/render/RendererWrapper.java @@ -38,9 +38,9 @@ * @since 2.2 */ -public abstract class RendererWrapper extends Renderer implements FacesWrapper { +public abstract class RendererWrapper extends Renderer implements FacesWrapper> { - private Renderer wrapped; + private Renderer wrapped; /** * @deprecated Use the other constructor taking the implementation being wrapped. @@ -59,12 +59,12 @@ public RendererWrapper() { * @param wrapped The implementation being wrapped. * @since 2.3 */ - public RendererWrapper(Renderer wrapped) { + public RendererWrapper(Renderer wrapped) { this.wrapped = wrapped; } @Override - public Renderer getWrapped() { + public Renderer getWrapped() { return wrapped; } @@ -79,22 +79,22 @@ public Object getConvertedValue(FacesContext context, UIComponent component, Obj } @Override - public void decode(FacesContext context, UIComponent component) { + public void decode(FacesContext context, T component) { getWrapped().decode(context, component); } @Override - public void encodeBegin(FacesContext context, UIComponent component) throws IOException { + public void encodeBegin(FacesContext context, T component) throws IOException { getWrapped().encodeBegin(context, component); } @Override - public void encodeChildren(FacesContext context, UIComponent component) throws IOException { + public void encodeChildren(FacesContext context, T component) throws IOException { getWrapped().encodeChildren(context, component); } @Override - public void encodeEnd(FacesContext context, UIComponent component) throws IOException { + public void encodeEnd(FacesContext context, T component) throws IOException { getWrapped().encodeEnd(context, component); } diff --git a/impl/src/main/java/jakarta/faces/validator/DoubleRangeValidator.java b/impl/src/main/java/jakarta/faces/validator/DoubleRangeValidator.java index 70c6a9478a..8708d92c6e 100644 --- a/impl/src/main/java/jakarta/faces/validator/DoubleRangeValidator.java +++ b/impl/src/main/java/jakarta/faces/validator/DoubleRangeValidator.java @@ -286,11 +286,10 @@ public boolean equals(Object otherObj) { */ @Override public int hashCode() { - - int hashCode = Double.valueOf(getMinimum()).hashCode() + Double.valueOf(getMaximum()).hashCode() + Boolean.valueOf(isMinimumSet()).hashCode() - + Boolean.valueOf(isMaximumSet()).hashCode(); - return hashCode; - + return Double.hashCode(getMinimum()) + + Double.hashCode(getMaximum()) + + Boolean.hashCode(isMinimumSet()) + + Boolean.hashCode(isMaximumSet()); } // --------------------------------------------------------- Private Methods @@ -315,7 +314,7 @@ private static double doubleValue(Object attributeValue) throws NumberFormatExce private static String stringValue(UIComponent component, Double toConvert, FacesContext context) { - Converter converter = context.getApplication().createConverter("jakarta.faces.Number"); + Converter converter = context.getApplication().createConverter("jakarta.faces.Number"); return converter.getAsString(context, component, toConvert); } @@ -341,7 +340,7 @@ public Object saveState(FacesContext context) { throw new NullPointerException(); } if (!initialStateMarked()) { - Object values[] = new Object[2]; + Object[] values = new Object[2]; values[0] = maximum; values[1] = minimum; return values; @@ -357,7 +356,7 @@ public void restoreState(FacesContext context, Object state) { throw new NullPointerException(); } if (state != null) { - Object values[] = (Object[]) state; + Object[] values = (Object[]) state; maximum = (Double) values[0]; minimum = (Double) values[1]; } diff --git a/impl/src/main/java/jakarta/faces/validator/MessageFactory.java b/impl/src/main/java/jakarta/faces/validator/MessageFactory.java index 7a0083b00a..c971792bb9 100644 --- a/impl/src/main/java/jakarta/faces/validator/MessageFactory.java +++ b/impl/src/main/java/jakarta/faces/validator/MessageFactory.java @@ -309,7 +309,7 @@ private String getFormattedString(String msgtext, Object[] params) { if (params == null || msgtext == null) { return msgtext; } - StringBuffer b = new StringBuffer(100); + StringBuilder b = new StringBuilder(100); MessageFormat mf = new MessageFormat(msgtext); if (locale != null) { mf.setLocale(locale); @@ -319,8 +319,8 @@ private String getFormattedString(String msgtext, Object[] params) { return localizedStr; } - private Locale locale; - private Object[] parameters; + private final Locale locale; + private final Object[] parameters; private Object[] resolvedParameters; } diff --git a/impl/src/main/java/jakarta/faces/view/Location.java b/impl/src/main/java/jakarta/faces/view/Location.java index 1991973578..a41a58e2fa 100644 --- a/impl/src/main/java/jakarta/faces/view/Location.java +++ b/impl/src/main/java/jakarta/faces/view/Location.java @@ -80,6 +80,6 @@ public String getPath() { @Override public String toString() { - return path + " @" + line + "," + column; + return path + ' ' + '@' + line + ',' + column; } } diff --git a/impl/src/main/java/jakarta/faces/view/ViewMetadata.java b/impl/src/main/java/jakarta/faces/view/ViewMetadata.java index 4b5e89f610..d96546b35f 100644 --- a/impl/src/main/java/jakarta/faces/view/ViewMetadata.java +++ b/impl/src/main/java/jakarta/faces/view/ViewMetadata.java @@ -134,7 +134,7 @@ public static boolean hasMetadata(UIViewRoot root) { @SuppressWarnings("unchecked") private static List getMetadataChildren(UIViewRoot root, Class type) { - return (List) getMetadataFacet(root).map(m -> m.getChildren()).orElseGet(Collections::emptyList).stream().filter(c -> type.isInstance(c)) + return (List) getMetadataFacet(root).map(UIComponent::getChildren).orElseGet(Collections::emptyList).stream().filter(type::isInstance) .collect(Collectors.toList()); } diff --git a/impl/src/main/java/jakarta/faces/view/facelets/FaceletCacheFactory.java b/impl/src/main/java/jakarta/faces/view/facelets/FaceletCacheFactory.java index 37d31b1b5a..430ea97091 100644 --- a/impl/src/main/java/jakarta/faces/view/facelets/FaceletCacheFactory.java +++ b/impl/src/main/java/jakarta/faces/view/facelets/FaceletCacheFactory.java @@ -16,6 +16,7 @@ package jakarta.faces.view.facelets; +import com.sun.faces.facelets.impl.DefaultFaceletFactory; import jakarta.faces.FacesWrapper; /** diff --git a/impl/src/main/java/jakarta/faces/view/facelets/Tag.java b/impl/src/main/java/jakarta/faces/view/facelets/Tag.java index 2acc954b39..2d16b39390 100644 --- a/impl/src/main/java/jakarta/faces/view/facelets/Tag.java +++ b/impl/src/main/java/jakarta/faces/view/facelets/Tag.java @@ -143,6 +143,6 @@ public String getQName() { */ @Override public String toString() { - return location + " <" + qName + ">"; + return location + " <" + qName + '>'; } } diff --git a/impl/src/main/java/jakarta/faces/view/facelets/TagHandlerDelegate.java b/impl/src/main/java/jakarta/faces/view/facelets/TagHandlerDelegate.java index bd1d30438e..0a077e2ddc 100644 --- a/impl/src/main/java/jakarta/faces/view/facelets/TagHandlerDelegate.java +++ b/impl/src/main/java/jakarta/faces/view/facelets/TagHandlerDelegate.java @@ -43,7 +43,7 @@ public abstract class TagHandlerDelegate { * * @since 2.0 */ - public abstract MetaRuleset createMetaRuleset(Class type); + public abstract MetaRuleset createMetaRuleset(Class type); /** *

diff --git a/impl/src/main/java/jakarta/faces/webapp/MessageFactory.java b/impl/src/main/java/jakarta/faces/webapp/MessageFactory.java index 299bd1ed15..30a0764611 100644 --- a/impl/src/main/java/jakarta/faces/webapp/MessageFactory.java +++ b/impl/src/main/java/jakarta/faces/webapp/MessageFactory.java @@ -309,7 +309,7 @@ private String getFormattedString(String msgtext, Object[] params) { if (params == null || msgtext == null) { return msgtext; } - StringBuffer b = new StringBuffer(100); + StringBuilder b = new StringBuilder(100); MessageFormat mf = new MessageFormat(msgtext); if (locale != null) { mf.setLocale(locale); @@ -319,8 +319,8 @@ private String getFormattedString(String msgtext, Object[] params) { return localizedStr; } - private Locale locale; - private Object[] parameters; + private final Locale locale; + private final Object[] parameters; private Object[] resolvedParameters; } diff --git a/impl/src/test/java/com/sun/faces/mock/MockApplication.java b/impl/src/test/java/com/sun/faces/mock/MockApplication.java index b1dcf084ff..d1fdfc00a7 100644 --- a/impl/src/test/java/com/sun/faces/mock/MockApplication.java +++ b/impl/src/test/java/com/sun/faces/mock/MockApplication.java @@ -203,7 +203,7 @@ public void setStateManager(StateManager stateManager) { this.stateManager = stateManager; } - private Map components = new HashMap<>(); + private final Map components = new HashMap<>(); @Override public void addComponent(String componentType, String componentClass) { @@ -234,7 +234,7 @@ public Iterator getComponentTypes() { return (components.keySet().iterator()); } - private Map converters = new HashMap<>(); + private final Map converters = new HashMap<>(); @Override public void addConverter(String converterId, String converterClass) { @@ -247,18 +247,18 @@ public void addConverter(Class targetClass, String converterClass) { } @Override - public Converter createConverter(String converterId) { + public Converter createConverter(String converterId) { String converterClass = converters.get(converterId); try { - Class clazz = Class.forName(converterClass); - return ((Converter) clazz.getDeclaredConstructor().newInstance()); + Class clazz = (Class) Class.forName(converterClass); + return (Converter) clazz.getDeclaredConstructor().newInstance(); } catch (Exception e) { throw new FacesException(e); } } @Override - public Converter createConverter(Class targetClass) { + public Converter createConverter(Class targetClass) { throw new UnsupportedOperationException(); } @@ -284,7 +284,7 @@ public String getMessageBundle() { return messageBundle; } - private Map validators = new HashMap<>(); + private final Map validators = new HashMap<>(); @Override public void addValidator(String validatorId, String validatorClass) { @@ -292,11 +292,11 @@ public void addValidator(String validatorId, String validatorClass) { } @Override - public Validator createValidator(String validatorId) { + public Validator createValidator(String validatorId) { String validatorClass = validators.get(validatorId); try { - Class clazz = Class.forName(validatorClass); - return ((Validator) clazz.getDeclaredConstructor().newInstance()); + Class clazz = (Class) Class.forName(validatorClass); + return ((Validator) clazz.getDeclaredConstructor().newInstance()); } catch (Exception e) { throw new FacesException(e); } diff --git a/impl/src/test/java/com/sun/faces/mock/MockRenderKit.java b/impl/src/test/java/com/sun/faces/mock/MockRenderKit.java index 8c2471b0c0..78814500c5 100644 --- a/impl/src/test/java/com/sun/faces/mock/MockRenderKit.java +++ b/impl/src/test/java/com/sun/faces/mock/MockRenderKit.java @@ -52,12 +52,11 @@ public MockRenderKit() { responseStateManager = new MockResponseStateManager(); } - private Map renderers = new HashMap<>(); + private final Map> renderers = new HashMap<>(); private ResponseStateManager responseStateManager = null; @Override - public void addRenderer(String family, String rendererType, - Renderer renderer) { + public void addRenderer(String family, String rendererType, Renderer renderer) { if ((family == null) || (rendererType == null) || (renderer == null)) { throw new NullPointerException(); } @@ -65,7 +64,7 @@ public void addRenderer(String family, String rendererType, } @Override - public Renderer getRenderer(String family, String rendererType) { + public Renderer getRenderer(String family, String rendererType) { if ((family == null) || (rendererType == null)) { throw new NullPointerException(); } @@ -115,7 +114,7 @@ public ResponseStateManager getResponseStateManager() { return responseStateManager; } - class TestRenderer extends Renderer { + static class TestRenderer extends Renderer { public TestRenderer() { } @@ -163,12 +162,5 @@ public void encodeChildren(FacesContext context, UIComponent component) } } - @Override - public void encodeEnd(FacesContext context, UIComponent component) - throws IOException { - if ((context == null) || (component == null)) { - throw new NullPointerException(); - } - } } } diff --git a/impl/src/test/java/com/sun/faces/util/MostlySingletonTest.java b/impl/src/test/java/com/sun/faces/util/MostlySingletonTest.java index 26ead141bf..3c08ffd841 100644 --- a/impl/src/test/java/com/sun/faces/util/MostlySingletonTest.java +++ b/impl/src/test/java/com/sun/faces/util/MostlySingletonTest.java @@ -28,7 +28,7 @@ public MostlySingletonTest() { @Test public void testAdd() { - MostlySingletonSet set = new MostlySingletonSet(); + MostlySingletonSet set = new MostlySingletonSet<>(); set.add(1); assertTrue(1 == set.size()); @@ -60,12 +60,12 @@ public void testAddWithNulls() { @Test public void testAddAll() { - Set otherSet = new HashSet(); + Set otherSet = new HashSet<>(); otherSet.add(4); otherSet.add(5); otherSet.add(6); - MostlySingletonSet set = new MostlySingletonSet(); + MostlySingletonSet set = new MostlySingletonSet<>(); set.add(1); assertTrue(1 == set.size()); @@ -112,7 +112,7 @@ public void testAddAll() { @Test public void testRemove() { - MostlySingletonSet set = new MostlySingletonSet(); + MostlySingletonSet set = new MostlySingletonSet<>(); set.add(1); assertTrue(1 == set.size()); @@ -154,7 +154,7 @@ public void testRemove() { @Test public void testRemoveWithNulls() { - MostlySingletonSet set = new MostlySingletonSet(); + MostlySingletonSet set = new MostlySingletonSet<>(); set.add(1); assertTrue(1 == set.size()); diff --git a/impl/src/test/java/jakarta/faces/model/ListenerTestImpl.java b/impl/src/test/java/jakarta/faces/model/ListenerTestImpl.java index de1a9dcaeb..6e64bd48d2 100644 --- a/impl/src/test/java/jakarta/faces/model/ListenerTestImpl.java +++ b/impl/src/test/java/jakarta/faces/model/ListenerTestImpl.java @@ -27,7 +27,7 @@ public class ListenerTestImpl implements DataModelListener { public void rowSelected(DataModelEvent event) { Object rowData = event.getRowData(); int rowIndex = event.getRowIndex(); - trace("" + rowIndex); + trace(String.valueOf(rowIndex)); if ((rowIndex >= 0) && (rowData == null)) { throw new IllegalArgumentException("rowIndex=" + rowIndex + " but rowData is null");