agtemplateweb/src/main/java/br/com/agapesistemas/agtemplate/util/Utils.java

216 lines
8.2 KiB
Java

package br.com.agapesistemas.agtemplate.util;
import java.io.Serializable;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.List;
import java.util.Collection;
import jakarta.faces.application.FacesMessage;
import jakarta.faces.context.ExternalContext;
import jakarta.faces.context.FacesContext;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import jakarta.faces.component.UIViewRoot;
import jakarta.faces.component.UIComponent;
import jakarta.faces.component.UIInput;
import org.primefaces.PrimeFaces;
import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
public class Utils implements Serializable {
public static final char INFO = 'I';
public static final char ERRO = 'E';
public static final char OBSERVACAO = 'O';
public static final char FATAL = 'F';
public static void clearSession(){
getExternalContext().getSessionMap().clear();
((HttpSession)getExternalContext().getSession(false)).invalidate();
}
public static void download(String nome, byte[] data) throws IOException {
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
response.setContentType("application/download");
response.setHeader("Content-disposition", "attachment;filename=" + nome);
ServletOutputStream ouputStream = response.getOutputStream();
ouputStream.write(data, 0, data.length);
response.getOutputStream().close();
facesContext.responseComplete();
}
public static void download(String nome, File arquivo) throws IOException, Exception {
byte[] data = fileToByte(arquivo);
download(nome,data);
}
public static byte[] fileToByte(File arquivo) throws Exception {
FileInputStream fis = new FileInputStream(arquivo);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[8192];
int bytesRead = 0;
while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
baos.write(buffer, 0, bytesRead);
}
fis.close();
baos.close();
baos.flush();
return baos.toByteArray();
}
public static long getDiasEntreData(Date inicio, Date fim) throws ParseException {
return (fim.getTime() - inicio.getTime() + 3600000L) / 86400000L;
}
public static String getDiretorioReal(String diretorio){
HttpSession request = (HttpSession) getExternalContext().getSession(false);
return request.getServletContext().getRealPath(diretorio);
}
public static ExternalContext getExternalContext(){
return FacesContext.getCurrentInstance().getExternalContext();
}
/**
*
* @param caminho Empresa, forms/crud/EmpresaConsultLazy
* @param modal true, false
* @param options
options.put("width", 640);
options.put("height", 340);
options.put("contentWidth", "100%");
options.put("contentHeight", "100%");
options.put("headerElement", "customheader");
**/
public static void abrirDialogXhtml(String caminho, boolean modal, Map<String, Object> options) {
if(options == null){
options = new HashMap<>();
}
options.put("modal", modal);
/*
options.put("width", 640);
options.put("height", 340);
options.put("contentWidth", "100%");
options.put("contentHeight", "100%");
options.put("headerElement", "customheader");
*/
PrimeFaces.current().dialog().openDynamic(caminho, options, null);
}
public static void fecharDialogXhtml(String nome) {
PrimeFaces.current().dialog().closeDynamic(nome);
}
public static void abrirDialogJS(String vwDialog) {
PrimeFaces.current().executeScript("PF('"+vwDialog+"').show();");
}
public static void fecharDialogJS(String vwDialog) {
PrimeFaces.current().executeScript("PF('"+vwDialog+"').hide();");
}
public static void executeScriptJS(String script) {
PrimeFaces.current().executeScript(script);
}
public static String getPaginaAcesso() {
return ((HttpServletRequest)getExternalContext().getRequest()).getRequestURI();
}
public static String getParam(String parametro){
return FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get(parametro);
}
public static Object getSessionObject(String nome){
return getExternalContext().getSessionMap().get(nome);
}
public static Object removeSessionObject(String nome){
return getExternalContext().getSessionMap().remove(nome);
}
public boolean isPossuiErro() {
for (FacesMessage fm : FacesContext.getCurrentInstance().getMessageList()) {
if (fm.getSeverity().equals(FacesMessage.SEVERITY_ERROR) || fm.getSeverity().equals(FacesMessage.SEVERITY_FATAL)) {
return true;
}
}
return false;
}
public static String gerarSenha(int nCaracteres) {
char[] letras = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
char[] numeros = "0123456789".toCharArray();
char[] ordem = "01".toCharArray();
Random rand = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < nCaracteres; i++) {
int valor = rand.nextInt(ordem.length);
char character = ordem[valor];
if(character == '0'){
valor = rand.nextInt(letras.length);
character = letras[valor];
}else{
valor = rand.nextInt(numeros.length);
character = numeros[valor];
}
sb.append(character);
}
return sb.toString();
}
public static void setAlerta(String mensagem, char tipo){
FacesMessage msg = null;
switch (tipo){
case 'O' : msg = new FacesMessage(FacesMessage.SEVERITY_WARN, mensagem, "");break;
case 'I' : msg = new FacesMessage(FacesMessage.SEVERITY_INFO, mensagem, "");break;
case 'E' : msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, mensagem, "");break;
case 'F' : msg = new FacesMessage(FacesMessage.SEVERITY_FATAL, mensagem, "");break;
}
FacesContext.getCurrentInstance().addMessage(null, msg);
//Essa linha vai fazer com que suas mensagens sejam armazenadas no escopo de Flash.
//A duração desse escopo vai ser o suficiente para que você consiga exibir as mensagens adicionadas depois do redirecionamento.
getExternalContext().getFlash().setKeepMessages(true);
}
public static void setSessionObject(String nome, Object objeto){
getExternalContext().getSessionMap().put(nome, objeto);
}
public void resetInput(){
FacesContext context = FacesContext.getCurrentInstance();
UIViewRoot viewRoot = context.getViewRoot();
List<UIComponent> children = viewRoot.getChildren();
resetInputValues(children);
}
private void resetInputValues(List<UIComponent> children) {
for (UIComponent component : children) {
if (component.getChildCount() > 0) {
resetInputValues(component.getChildren());
} else {
if (component instanceof UIInput) {
UIInput input = (UIInput) component;
input.resetValue();
}
}
}
}
public static <T> T getBean(String beanName, Class<T> beanClass) { FacesContext facesContext = FacesContext.getCurrentInstance(); return facesContext.getApplication().evaluateExpressionGet(facesContext, "#{" + beanName + "}", beanClass); }
public static void updateRegion(String id){ PrimeFaces.current().ajax().update(id); }
public static void updateRegion(Collection<String> ids){ PrimeFaces.current().ajax().update(ids); }
}