Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generics + Some code optimization (at least for readability) #5242

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -479,7 +479,7 @@ public Converter<?> createConverter(String converterId) {
* @see jakarta.faces.application.Application#createConverter(Class)
*/
@Override
public Converter<?> createConverter(Class<?> targetClass) {
public <T> Converter<T> createConverter(Class<T> targetClass) {
return instanceFactory.createConverter(targetClass);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ synchronized void loadFlows(FacesContext context, FlowHandler flowHandler) throw

WebConfiguration config = WebConfiguration.getInstance();
for (Producer<Flow> flowProducer : flowProducers) {
Flow toAdd = flowProducer.produce(beanManager.<Flow>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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@
*/
public class NamedEventManager {

private Map<String, Class<? extends SystemEvent>> namedEvents = new ConcurrentHashMap<>();
private Map<String, Set<Class<? extends SystemEvent>>> duplicateNames = new ConcurrentHashMap<>();
private final Map<String, Class<? extends SystemEvent>> namedEvents = new ConcurrentHashMap<>();
private final Map<String, Set<Class<? extends SystemEvent>>> duplicateNames = new ConcurrentHashMap<>();

public NamedEventManager() {
namedEvents.put("jakarta.faces.event.PreRenderComponent", PreRenderComponentEvent.class);
Expand All @@ -66,7 +66,7 @@ public Class<? extends SystemEvent> getNamedEvent(String name) {

if (namedEvent == null) {
try {
namedEvent = loadClass(name, this);
namedEvent = (Class<? extends SystemEvent>) loadClass(name, this);
} catch (ClassNotFoundException ex) {
throw new FacesException("An unknown event type was specified: " + name, ex);
}
Expand All @@ -81,12 +81,8 @@ public Class<? extends SystemEvent> getNamedEvent(String name) {

public void addDuplicateName(String name, Class<? extends SystemEvent> event) {
Class<? extends SystemEvent> registeredEvent = namedEvents.remove(name);
Set<Class<? extends SystemEvent>> events = duplicateNames.get(name);
Set<Class<? extends SystemEvent>> events = duplicateNames.computeIfAbsent(name, k -> new HashSet<>());

if (events == null) {
events = new HashSet<>();
duplicateNames.put(name, events);
}
events.add(event);

if (registeredEvent != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down Expand Up @@ -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) {
Expand All @@ -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<String> toFlowDocumentIdParam = asList(caseStruct.navCase.getToFlowDocumentId());
List<String> toFlowDocumentIdParam = Collections.singletonList(caseStruct.navCase.getToFlowDocumentId());
parameters.put(TO_FLOW_DOCUMENT_ID_REQUEST_PARAM_NAME, toFlowDocumentIdParam);

List<String> flowIdParam = asList(caseStruct.newFlow.getId());
List<String> flowIdParam = Collections.singletonList(caseStruct.newFlow.getId());
parameters.put(FLOW_ID_REQUEST_PARAM_NAME, flowIdParam);
}
}
Expand Down Expand Up @@ -475,9 +475,7 @@ private void initializeNavigationFromFlowNonThreadSafe(Flow toInspect) {
NavigationInfo info = new NavigationInfo();
if (!switches.isEmpty()) {
info.switches = new ConcurrentHashMap<>();
for (Map.Entry<String, SwitchNode> cur : switches.entrySet()) {
info.switches.put(cur.getKey(), cur.getValue());
}
info.switches.putAll(switches);
}
if (!navRules.isEmpty()) {
info.ruleSet = new NavigationMap();
Expand Down Expand Up @@ -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<String, Set<NavigationCase>> navMap = getNavigationMap(ctx);

Expand Down Expand Up @@ -866,8 +864,8 @@ private CaseStruct findImplicitMatch(FacesContext context, String viewId, String
Map<String, Object> appMap = context.getExternalContext().getApplicationMap();

String[] queryElements = Util.split(appMap, queryString, "&amp;|&");
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() : "";
Expand All @@ -877,19 +875,12 @@ private CaseStruct findImplicitMatch(FacesContext context, String viewId, String
}
rightHandSide = "";
}

if (parameters == null) {
parameters = new LinkedHashMap<>(len / 2, 1.0f);
List<String> values = new ArrayList<>(2);
values.add(rightHandSide);
parameters.put(elements[0], values);
} else {
List<String> 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);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
*/
public class PropertyEditorHelper {

private Application app;
private final Application app;

public PropertyEditorHelper(Application app) {
this.app = app;
Expand All @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -435,9 +435,9 @@ public Converter<?> createConverter(String converterId) {
/*
* @see jakarta.faces.application.Application#createConverter(Class)
*/
public Converter createConverter(Class<?> targetClass) {
public <T> Converter<T> createConverter(Class<T> targetClass) {
notNull("targetClass", targetClass);
Converter returnVal = null;
Converter<T> returnVal = null;

BeanManager beanManager = getBeanManager();
returnVal = CdiUtils.createConverter(beanManager, targetClass);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,25 +17,27 @@
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<Class<?>, Cache<Class<? extends SystemEvent>, EventInfo>> sourceCache;
private final Cache<Class<?>, Cache<Class<? extends SystemEvent>, EventInfo>> sourceCache;

// -------------------------------------------------------- Constructors

public ComponentSystemEventHelper() {

// Initialize the 'sources' cache for, ahem, readability...
// ~generics++
Factory<Class<?>, Cache<Class<? extends SystemEvent>, EventInfo>> eventCacheFactory = sourceClass -> {
Factory<Class<? extends SystemEvent>, EventInfo> eventInfoFactory = systemEventClass -> new EventInfo(systemEventClass, sourceClass);
Cache.Factory<Class<?>, Cache<Class<? extends SystemEvent>, EventInfo>> eventCacheFactory = sourceClass -> {
Cache.Factory<Class<? extends SystemEvent>, EventInfo> eventInfoFactory = systemEventClass -> new EventInfo(systemEventClass, sourceClass);
return new Cache<>(eventInfoFactory);
};
sourceCache = new Cache<>(eventCacheFactory);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,12 @@ public class ResourceCache {
/**
* The <code>ResourceInfo<code> cache.
*/
private MultiKeyConcurrentHashMap<Object, ResourceInfoCheckPeriodProxy> resourceCache;
private final MultiKeyConcurrentHashMap<Object, ResourceInfoCheckPeriodProxy> resourceCache;

/**
* Resource check period in minutes.
*/
private long checkPeriod;
private final long checkPeriod;

// ------------------------------------------------------------ Constructors

Expand Down Expand Up @@ -99,7 +99,7 @@ public ResourceInfo add(ResourceInfo info, List<String> 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;

Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,12 +87,12 @@ public class FaceletFullStateManagementStrategy extends StateManagementStrategy
/**
* Stores the class map.
*/
private Map<String, Class<?>> classMap;
private final Map<String, Class<?>> classMap;

/**
* Are we in development mode.
*/
private boolean isDevelopmentMode;
private final boolean isDevelopmentMode;

/**
* Constructor.
Expand Down Expand Up @@ -348,10 +348,10 @@ private void restoreComponentState(final FacesContext context, final HashMap<Str
*
* @param context the Faces context.
* @param stateContext the state context.
* @param stateMap the state.
* @param viewRoot the view root.
* @param state the state.
*
*/
private void restoreDynamicActions(FacesContext context, StateContext stateContext, HashMap<String, Object> state) {
private void restoreDynamicActions(FacesContext context, StateContext stateContext, Map<String, Object> state) {
if (LOGGER.isLoggable(FINEST)) {
LOGGER.finest("FaceletFullStateManagementStrategy.restoreDynamicActions");
}
Expand Down Expand Up @@ -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);
Expand All @@ -628,15 +628,15 @@ 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)) {
LOGGER.finest("FaceletFullStateManagementStrategy.saveDynamicActions");
}

List<ComponentStruct> actions = stateContext.getDynamicActions();
HashMap<String, UIComponent> componentMap = stateContext.getDynamicComponents();
Map<String, UIComponent> componentMap = stateContext.getDynamicComponents();

if (actions != null) {
List<Object> savedActions = new ArrayList<>(actions.size());
Expand Down Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,7 @@ private void saveDynamicActions(FacesContext context, StateContext stateContext,
}

List<ComponentStruct> actions = stateContext.getDynamicActions();
HashMap<String, UIComponent> componentMap = stateContext.getDynamicComponents();
Map<String, UIComponent> componentMap = stateContext.getDynamicComponents();

if (actions != null) {
List<Object> savedActions = new ArrayList<>(actions.size());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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('[');
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -1231,7 +1231,7 @@ private void retargetHandler(FacesContext context, AttachedObjectHandler handler
private static final class MethodMetadataIterator implements Iterable<CompCompInterfaceMethodMetadata>, Iterator<CompCompInterfaceMethodMetadata> {

private final PropertyDescriptor[] descriptors;
private FacesContext context;
private final FacesContext context;
private int curIndex = -1;

// -------------------------------------------------------- Constructors
Expand Down Expand Up @@ -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());

}

Expand Down Expand Up @@ -1400,8 +1400,8 @@ public String getName() {
*/
private static final class MethodRetargetHandlerManager {

private Map<String, MethodRetargetHandler> handlerMap = new HashMap<>(4, 1.0f);
private MethodRetargetHandler arbitraryHandler = new ArbitraryMethodRegargetHandler();
private final Map<String, MethodRetargetHandler> handlerMap = new HashMap<>(4, 1.0f);
private final MethodRetargetHandler arbitraryHandler = new ArbitraryMethodRegargetHandler();

// -------------------------------------------------------- Constructors

Expand Down Expand Up @@ -1914,11 +1914,11 @@ private Stream<String> mapIfNeeded(Stream<String> 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) {
Expand Down
Loading
Loading