Uma das principais dificuldades que programadores com pouca experiência em Java possuem é a manipulção de datas.
Aqui farei uma breve explicação com operações simples para manipulação do objeto java.util.Date.
Uma das principais classes que utilizamos quando manipulamos data em Java é a classe SimpleDateFormat. Ela é um subclasse de DateFormat, e nos fornece construtores com parâmetros que tornam bem flexível a formatação da data, conforme veremos nos exemplos a seguir…
Formatando datas usando um formato personalizado
DateFormat formatter = new SimpleDateFormat(”MM/dd/yy”);
Date d = (Date)formatter.parse(”25/08/1977″);
Esse código bem simples cria um objeto do tipo DateFormat para nossas datas que tem como padrão o formato passado por nós no contrutor. Aqui algumas outras formatações:
DateFormat formatter = new SimpleDateFormat(”dd-MMM-yyyy”);
Date d = (Date)formatter.parse(”25-Dec-2006″);
DateFormat formatter = new SimpleDateFormat(”dd-MM-yyyy HH:mm”);
Date d = (Date)formatter.parse(”25-12-2006 10:34″);
Simples assim. É preciso apenas ter cuidado porque se você passar uma data que não é válida para o formato passado no construtor, será lançada uma ParseException.
Podemos também fazer o processo inverso, passando um objeto Date e recebendo uma String, vejamos mais alguns exemplos:
Date d = new Date();
DateFormat formatter = new SimpleDateFormat(”dd/MM/yyyy”);
String str = formatter.format(d);
Temos uma String que será a data de hoje, no formato dd/MM/yyyy
Determinando o número de dias em um mês
Date d = new Date();
Calendar cal = new GegorianCalendar();
cal.setTime(d);
int numeroDias = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
Comparando datas
Algumas vezes podemos precisar saber a difenrença entre datas, seja em dias, em minutos ou em horas. Fazer isso também é simples, vejamos:
Calendar calendar1 = new GregorianCalendar(1977, Calendar.January, 17);
Calendar calendar2 = new GregorianCalendar(1981, Calendar.April, 16);
calendar1.before(calendar2) //true
calendar1.after(calendar2) //false
Para calcularmos as diferenças é importante pegarmos primeiro a diferença em milisegundos, é a partir dela que faremos os cálculos:
long diferenca = calendar2.getTimeInMilis() - calendar1.getTimeInMilis();
a diferença em dias:
long difDias = diferenca/(24*60*60*1000);
a diferença em horas:
long difHoras = diferenca/(60*60*1000);
a diferença em minutos:
long difMinutos = diferenca/(60*1000);
a diferença em segundos:
long difHoras = diferenca/(1000);
Nesse artigo mostrei as principais operações que fazemos com datas, e quais as classes que utilizamos para manipula-las.
Fabricio Braga
sexta-feira, 10 de outubro de 2008
Exemplo de ServiceLocator
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
/**
*
* @author Administrador
*/
public class ServiceLocator {
private InitialContext initialContext;
private static ServiceLocator locator;
/** Creates a new instance of ServiceLocator */
public ServiceLocator() throws Exception {
try {
Properties prop = new Properties();
prop.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
prop.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
prop.put(Context.PROVIDER_URL, "localhost");
initialContext = new InitialContext(prop);
} catch (Exception e) {
e.printStackTrace();
}
}
public ServiceLocator(String url) throws Exception {
try {
Properties prop = new Properties();
prop.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
prop.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
prop.put(Context.PROVIDER_URL, url);
initialContext = new InitialContext(prop);
} catch (Exception e) {
e.printStackTrace();
}
}
public static ServiceLocator getInstance() throws Exception {
if (locator == null) {
locator = new ServiceLocator();
}
return locator;
}
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException("Não é possível clonar o Service Locator");
}
public Object get(String jndiName) throws Exception {
try {
Object result = null;
result = initialContext.lookup(jndiName);
if (result == null) {
throw new NamingException("Erro ao se comunicar com serviço EJB!");
}
return result;
} catch (NamingException ne) {
ne.printStackTrace();
}
return null;
}
}
Vc usa assim:
Object ref = ServiceLocator.getInstance().get("SuaClasseBean/remote");
seuBeanRemote = (SuaInterfaceRemote) PortableRemoteObject.narrow(ref, SuaInterfaceRemote.class);
seuBeanRemote.seuMetodo();
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
/**
*
* @author Administrador
*/
public class ServiceLocator {
private InitialContext initialContext;
private static ServiceLocator locator;
/** Creates a new instance of ServiceLocator */
public ServiceLocator() throws Exception {
try {
Properties prop = new Properties();
prop.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
prop.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
prop.put(Context.PROVIDER_URL, "localhost");
initialContext = new InitialContext(prop);
} catch (Exception e) {
e.printStackTrace();
}
}
public ServiceLocator(String url) throws Exception {
try {
Properties prop = new Properties();
prop.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
prop.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
prop.put(Context.PROVIDER_URL, url);
initialContext = new InitialContext(prop);
} catch (Exception e) {
e.printStackTrace();
}
}
public static ServiceLocator getInstance() throws Exception {
if (locator == null) {
locator = new ServiceLocator();
}
return locator;
}
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException("Não é possível clonar o Service Locator");
}
public Object get(String jndiName) throws Exception {
try {
Object result = null;
result = initialContext.lookup(jndiName);
if (result == null) {
throw new NamingException("Erro ao se comunicar com serviço EJB!");
}
return result;
} catch (NamingException ne) {
ne.printStackTrace();
}
return null;
}
}
Vc usa assim:
Object ref = ServiceLocator.getInstance().get("SuaClasseBean/remote");
seuBeanRemote = (SuaInterfaceRemote) PortableRemoteObject.narrow(ref, SuaInterfaceRemote.class);
seuBeanRemote.seuMetodo();
sexta-feira, 3 de outubro de 2008
Acessando URL com proxy
System.getProperties().put("proxySet", "true");
System.getProperties().put("proxyHost", "172.1.1.2");
System.getProperties().put("proxyPort", "8080");
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
"Usuario"),"Senha").toCharArray());
}
});
URL u = new URL(url);
System.getProperties().put("proxyHost", "172.1.1.2");
System.getProperties().put("proxyPort", "8080");
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
"Usuario"),"Senha").toCharArray());
}
});
URL u = new URL(url);
Assinar:
Postagens (Atom)