Segue um link interessante que apresenta quadros e gráfico representando a utilização de linguagens de programação no desenvolvimento de software.
http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html
sexta-feira, 7 de novembro de 2008
sexta-feira, 10 de outubro de 2008
Manipulando datas em java
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
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
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);
quarta-feira, 10 de setembro de 2008
Mover objetos entre esquemas oracle
SELECT 'ALTER TABLE nome_do_esquema.' || table_name || ' MOVE TABLESPACE nome_do_novo_tablespace;'
FROM dba_tables
WHERE
owner = 'nome_do_esquema';
SELECT 'ALTER INDEX nome_do_esquema.' || index_name || ' REBUILD TABLESPACE nome_do_novo_tablespace;'
FROM dba_indexes
WHERE
owner = 'nome_do_esquema' AND
index_type != 'LOB';
SELECT
'ALTER TABLE nome_do_esquema.' || table_name ||
' MOVE LOB( ' || COLUMN_NAME ||
' ) STORE AS (TABLESPACE nome_do_novo_tablespace);'
FROM dba_tab_columns
WHERE
owner = 'nome_do_esquema' AND
data_type LIKE '%LOB';
FROM dba_tables
WHERE
owner = 'nome_do_esquema';
SELECT 'ALTER INDEX nome_do_esquema.' || index_name || ' REBUILD TABLESPACE nome_do_novo_tablespace;'
FROM dba_indexes
WHERE
owner = 'nome_do_esquema' AND
index_type != 'LOB';
SELECT
'ALTER TABLE nome_do_esquema.' || table_name ||
' MOVE LOB( ' || COLUMN_NAME ||
' ) STORE AS (TABLESPACE nome_do_novo_tablespace);'
FROM dba_tab_columns
WHERE
owner = 'nome_do_esquema' AND
data_type LIKE '%LOB';
quinta-feira, 21 de agosto de 2008
quarta-feira, 20 de agosto de 2008
NumericTextField
#exemplo retirado de: http://faq.javaranch.com/java/NumericTextField
import java.awt.BorderLayout;
import java.util.regex.Pattern;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
@SuppressWarnings("serial")
public class JavaRanch extends JPanel
{
private JLabel inputLabel;
private NumericTextField inputField;
public JavaRanch()
{
super(new BorderLayout());
inputLabel = new JLabel("Enter value: ");
inputField = new NumericTextField();
inputField.setColumns(10);
this.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
this.add(inputLabel, BorderLayout.WEST);
this.add(inputField, BorderLayout.CENTER);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
JFrame frame = new JFrame("Numeric Text Field Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JavaRanch());
frame.pack();
frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
}
@SuppressWarnings("serial")
class NumericTextField extends JTextField
{
@Override
protected Document createDefaultModel()
{
return new NumericDocument();
}
private static class NumericDocument extends PlainDocument
{
// The regular expression to match input against (zero or more digits)
private final static Pattern DIGITS = Pattern.compile("\\d*");
@Override
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
{
// Only insert the text if it matches the regular expression
if (str != null && DIGITS.matcher(str).matches())
super.insertString(offs, str, a);
}
}
}
import java.awt.BorderLayout;
import java.util.regex.Pattern;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
@SuppressWarnings("serial")
public class JavaRanch extends JPanel
{
private JLabel inputLabel;
private NumericTextField inputField;
public JavaRanch()
{
super(new BorderLayout());
inputLabel = new JLabel("Enter value: ");
inputField = new NumericTextField();
inputField.setColumns(10);
this.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
this.add(inputLabel, BorderLayout.WEST);
this.add(inputField, BorderLayout.CENTER);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
JFrame frame = new JFrame("Numeric Text Field Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JavaRanch());
frame.pack();
frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
}
@SuppressWarnings("serial")
class NumericTextField extends JTextField
{
@Override
protected Document createDefaultModel()
{
return new NumericDocument();
}
private static class NumericDocument extends PlainDocument
{
// The regular expression to match input against (zero or more digits)
private final static Pattern DIGITS = Pattern.compile("\\d*");
@Override
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
{
// Only insert the text if it matches the regular expression
if (str != null && DIGITS.matcher(str).matches())
super.insertString(offs, str, a);
}
}
}
Assinar:
Postagens (Atom)