package com.mousetech.gourmetj;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import jakarta.faces.application.FacesMessage;
import jakarta.faces.context.ExternalContext;
import jakarta.faces.context.FacesContext;
import jakarta.faces.context.Flash;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JSFUtils {
/* Logger */
private static final Logger log =
LoggerFactory.getLogger(JSFUtils.class);
private static ExternalContext getExternalContext() {
FacesContext facesContext =
FacesContext.getCurrentInstance();
ExternalContext externalContext =
facesContext.getExternalContext();
return externalContext;
}
/**
* Obtain resource as Stream. The caller must close this
* stream after use.
*
* @param pathName Path of the resource. For example,
* "/WEB-INF/classes/xys.properties".
* @return InputStream or null
, if no such
* resource exists.
*/
public static InputStream getResourceStream(
String pathName) {
InputStream response = getExternalContext()
.getResourceAsStream(pathName);
return response;
}
// ===
/**
* Post an info-level message to the FacesContext where the
* <h:messages> tag can display it.
*
* @param string Message text
*/
public static void addInfoMessage(String string) {
FacesMessage message = new FacesMessage(
FacesMessage.SEVERITY_INFO, string, string);
FacesContext.getCurrentInstance().addMessage(null,
message);
}
public static void addWarningMessage(String msgString) {
FacesMessage message = new FacesMessage(
FacesMessage.SEVERITY_WARN, "WARNING", msgString);
FacesContext.getCurrentInstance().addMessage(null,
message);
}
/**
* Post an error-level message to the FacesContext where the
* <h:messages> tag can display it.
*
* @param string Message text
*/
public static void addErrorMessage(String string) {
FacesMessage message = new FacesMessage(
FacesMessage.SEVERITY_ERROR, string, string);
FacesContext.getCurrentInstance().addMessage(null,
message);
}
public static void addErrorMessage(String string,
Exception e) {
if (e instanceof NullPointerException) {
addErrorMessage(
"Internal logic error (NullPointerException)");
} else {
addErrorMessage(string);
}
log.error(string, e);
}
public static Flash flashScope() {
return (FacesContext.getCurrentInstance()
.getExternalContext().getFlash());
}
/**
* Look in Flash scope for item.
*
* @param key Item to retrieve
* @return Item, or null if not in Flash OR Flash not active
*/
public static Object getFlash(String key) {
Flash flash = flashScope();
try {
return flash.get(key);
} catch ( NullPointerException nex ) {
// If session is expired, flash.get() will fail!
return null;
}
}
public static void putFlash(String key, Object value) {
flashScope().put(key, value);
}
//***********
//* COOKIE!!!
//***********
/**
* Get cookie values.
*/
public static Map getCookies() {
Map m0 =
getExternalContext().getRequestCookieMap();
Map m1 = new HashMap();
m1 = m0.entrySet().stream()
.collect(Collectors.toMap(e -> e.getKey(),
e -> ((Cookie) e.getValue()).getValue()));
return m1;
}
public static String getCookie(String cookieName) {
Map map =
getExternalContext().getRequestCookieMap();
if (map == null) {
return null; // no cookies at all
}
Cookie cookie = (Cookie) map.get(cookieName);
if (cookie == null) {
return null;
}
return cookie.getValue();
}
/**
* Set a cookie value in Response.
*
* @param name Cookie name
* @param value Cookie value
* @param properties Cookie property Map (timeout,
* etc.)
* @throws UnsupportedEncodingException
*/
public static void outputCookie(String name, String value,
Map properties)
throws UnsupportedEncodingException {
// getExternalContext().addResponseCookie(name,
// URLEncoder.encode(value, "UTF-8"),
// properties);
Cookie cookie = new Cookie(name, value);
cookie.setMaxAge(31536000);
cookie.setPath("/");
jakarta.servlet.http.HttpServletResponse resp =
(HttpServletResponse) getExternalContext()
.getResponse();
resp.addCookie(cookie);
}
/**
* Destroy current session, logging user out.
*/
public static void logout() {
log.warn("Logging out session");
jakarta.servlet.http.HttpSession session =
(HttpSession) getExternalContext().getSession(false);
if ( session != null ) {
session.invalidate();
} else {
log.warn("Session did not exist.");
}
}
public static HttpSession getSession(boolean create) {
return (HttpSession) getExternalContext().getSession(create);
}
}