Arquivo para janeiro \29\-03:00 2010

Code: /dev/null ‘s like implementation for java

(This title is weird)

Just to remember, a implementation that send to garbage all the System.out.println messages:

//Java implementation for /dev/null
System.setOut(new java.io.PrintStream(new java.io.OutputStream() {public void write(int b) {}}));
System.out.println("This goes to the void");

Source: http://coding.derkeiler.com/Archive/Java/comp.lang.java.programmer/2006-11/msg03469.html

ArrayStringBuilder makes StringBuilder acts as an array

String concat is something that we need to do a lot when creating SQLs but there is a problem by using string-plus-string concatenation (“string”+””string”): Every couple of quotations java will create and alocate one String class, this can be a trigger for memory problems.

The orientation (at Celepar) is to use StringBuffer that is faster than simple concat. Searching the web i found that StringBuilder is a bit faster than StringBuffer.

Now let me go to the point, i needed to make an join and use a separator at a group of strings, but memory was something i was worried, then i tried to simulate an array over StringBuilder,  the result was the following class.

p.s: I really doen’t feel that there aren’t a better and faster way to do this, but i didn’t found anything at this time;

package com.br.webcentro.utils;

import java.util.Arrays;

/**
 * This class works using the java.lang.StringBuilder,
 * but this simulates an array to implement a joinable splitable string
 *
 * may be better extend the class AbstractStringBuilder but for now it will only work using it;
 *
 * feel free to post implementations
 *
 * If you have some advice please contact me at webcentro(at)gmail.com
 * @author alandanielweiss
 * @since 2010-01-22
 */

public class ArrayStringBuilder implements java.io.Serializable{

	private StringBuilder builder;

	private boolean isMultiEnabled = false;
	private boolean isEmptyAllowed = true;

	private int start[];
	private int len[];
	private int counter=0;
	private int totalLen=0;

	private static final long serialVersionUID = -2443226579329551214L;

	/**
     * Constructs a string builder with no characters in it and an
     * initial capacity of 16 characters.
     */

	public ArrayStringBuilder() {
		this.builder = new StringBuilder();
		this.start   = new int[16];
		this.len     = new int[16];
    }

	/**
	 * Sets the initial StringBuilder capacity
	 * @param capacity
	 */
	public ArrayStringBuilder(int capacity) {
		this.builder = new StringBuilder(capacity);
		this.start   = new int[capacity];
		this.len     = new int[capacity];
    }

	/**
	 * Create class and append string
	 * @param string
	 */
    public ArrayStringBuilder(String string) {
    	this();
    	this.add(string);
    }

	/**
	 * Create class and the the StringBuilder
	 * @param string
	 */
    public ArrayStringBuilder(StringBuilder builder) {
		this.start   = new int[16];
		this.len     = new int[16];

		this.counter = 1;
    	this.start[0] = 0;
    	this.len[0] = builder.toString().length();
    	this.totalLen = this.len[0];

    	this.builder = builder;
    }

    /**
     * Append a string
     * @param str
     * @return
     */
	public ArrayStringBuilder add(String str){
		if (str == null)
			str = "null";
	    int len = str.length();
		if (len == 0 && !isEmptyAllowed)
			return this;

		//multi-line don't increment counter
		if(!this.isMultiEnabled)
			this.counter ++;

		if (this.counter > start.length)
		    expandCapacity(this.counter);

		if(!this.isMultiEnabled)
			this.start[this.counter-1] = this.totalLen;

		if(this.isMultiEnabled)
			len +=this.len[this.counter-1];

		this.len[this.counter-1]   = len;

		this.totalLen += str.length();
		this.builder.append(str);
		return this;
	}

	/**
	 * start multiline array
	 * when done use the method end()
	 * @return
	 */
	public ArrayStringBuilder start(String str){
		this.isMultiEnabled = false;
		this.add(str);
		this.isMultiEnabled = true;
		return this;
	}

	/**
	 * finish multiline array
	 * @return
	 */
	public ArrayStringBuilder finish(String str){
		this.add(str);
		this.isMultiEnabled = false;
		return this;
	}

	void expandCapacity(int minimumCapacity) {
		int newCapacity = (start.length + 1) * 2;
        if (newCapacity < 0) {
        	newCapacity = Integer.MAX_VALUE;
        } else if (minimumCapacity > newCapacity) {
        	newCapacity = minimumCapacity;
		}
        this.start = Arrays.copyOf(this.start, newCapacity);
        this.len = Arrays.copyOf(this.len, newCapacity);
    }

	/**
	 * Joins the StringBuilder using the passed separator
	 * @param separator
	 * @return
	 */
	public String join(String separator){
		StringBuilder str = new StringBuilder();
		for (int idx=0; idx<this.counter;idx++){
			str.append(this.builder.substring(this.start[idx], this.start[idx]+this.len[idx]));
			if(idx+1<this.counter)
				str.append(separator);
	    }
		return str.toString();
	}

	public String[] toArray(){
		String[] str = new String[this.counter];
		for (int idx=0; idx<this.counter;idx++){
			str[idx] = this.builder.substring(this.start[idx], this.start[idx]+this.len[idx]);
	    }
		return str;
	}

	/**
	 * To string...
	 * @return String
	 */
    public String toString() {
    	return this.builder.toString();
    }

    /**
     * Creates a StringBuilder with the actual object values
     * @return builder:StringBuilder
     */
    public StringBuilder getStringBuilder(){
    	return this.builder;
    }

    /**
     * when true every time you use add/start/finish with an empty string it will add a new array
     * if false the command add/start/finish empty has no effect
     */
    public void setEmptyAllowed(boolean isMultiEnabled){
    	this.isMultiEnabled = isMultiEnabled;
    }

    public static void main(String[] args) {
		//Sample 1
    	StringBuilder strb = new StringBuilder();
    	strb.append("to be");
    	ArrayStringBuilder arrb = new ArrayStringBuilder(strb);
    	arrb.start(" or ");
    	arrb.add("not ");
    	arrb.add("to ");
    	arrb.finish("be");
		ArrayStringBuilder arrb2 = new ArrayStringBuilder(arrb.join(","));
		System.out.println(arrb2.add(": that's").add("the").add("question").join(" "));

		//Sample 2
		ArrayStringBuilder fields = new ArrayStringBuilder();
		fields.add("id");
		if(1==1)
			fields.add("name");
		if(1==2)
			fields.add("profession");
		StringBuilder sql = new StringBuilder();
		sql.append("select ").append(fields.join(" , ")).append(" from table ");
		System.out.println(sql.toString());
	}
}

A good comparision between StringBuilder and StringBuffer can be found at: StringBuilder vs StringBuffer vs String.concat – done right

Please feel free to send comments, to improve this class.

Memoria: Modelo de Curriculum OpenOffice e Comparação de Frameworks

Template de Curriculum Vitae para OpenOffice:

http://templates.services.openoffice.org/en/node/977

Comparação de Frameworks WEB Java e outras:

http://en.wikipedia.org/wiki/List_of_web_application_frameworks#Java_2

Proposal: XMLBean Framework

In these days we listen a lot about MDA that ains liberty of programming language o technology and the problem the company i work was facing, the “neccesary redundancy” of creating data validation on server and client side, I was wondering:

Create instead o POJO , JavaBeans, DTO, FORM (struts), create some XML Schema that we can call XMLBeans, this way we can share between many technologies the ways the data is expected.

I fast-drawed this model:

This .XSD files will be useful for:

  • Form Validation
  • Data Transfer
  • Data Persistence

These FILE must have nothing to do with business logic, otherwise will be too much complexity!

Soon i will work on some proto.

I’ve searched the web to and found some reference that may help:

http://www.ibm.com/developerworks/library/x-flexschema/
http://www.javaworld.com/javaworld/jw-09-2000/jw-0908-validation.html
http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/validation/Validator.html
http://xmlbeans.apache.org/

Code: Um pouco de Shell Script

Para aliviar a memória:

Shell Script,  usado Linux Debian.

Aqui podemos ver exemplos da utilização de | (pipe), ` (crase), = atribuição, > direcionamento de saida, < direcionamento de entrada (os codigos estão em negrito)…

  1. Contar linhas de um texto usando o comando wc (-w conta palavras, -c conta caracteres, etc.. veja man wc):
    echo “Alan Daniel Weiss” |wc -l
  2. Mesclar valor de execução com string (preste atenção nas crases elas quem separam a string do commando)
    echo “Existe(m) `who|wc -l` pessoa(s) conectada(s) em seu computador
  3. Atribuição de variavel e utilização (não devem haver espaçoes entre a variavel e o valor)
    var=`who`
    cat <<EOF
    > Listagem de pessoas conectadas em seu computador:
    > $var
    > EOF
  4. Direcionar erros para a saida (/dev/null significa lugar nenhum, ou seja lixo, voce pode substituir a saida para um nome de arquivo existente)
    ls arquivoquenaoexiste 2>/dev/null
  5. Mescla saida do comando com o conteúdo já existente do arquivo (>> incremental):
    ls >>arquivo

Por enquanto é só isso.

Code: Methods that accept multiple arguments – Java

Pequeno exemplo do uso de HashMap, Varargs e Array para criar metodos que aceitem “multiplos argumentos”, também um exemplo de concatenação de arrays:

	@Test
	public void testMethodWithMultipleParams(){
		Map params = new HashMap<String, Object>();
		params.put("name", "Alan Daniel");

		//Iterate Over Map keys
		String[] arrKey = new String[]{};
		for (Object key: params.keySet()) {
			if(key instanceof String){
				arrKey = (String[])ArrayUtils.add(arrKey, key);
			}
		}
		//Iterate Over Map values
		String[] arrValue = new String[]{};
		for (Object value: params.values()) {
			if(value instanceof String){
				arrValue = (String[])ArrayUtils.add(arrValue, value);
			}
		}

		//Only to demonstrate how to merge / concat two arrays
		Object[] array = ArrayUtils.addAll(arrKey, arrValue);

		this.methodWithMultipleParams(params);//MAP
		this.methodWithMultipleParams((String[])array); //String[]
		this.methodWithMultipleParamsUsingVarArgs((String[])array);//String...
		this.methodWithMultipleParamsUsingVarArgs("this","way","works","too!");//String..
	}

	/**
	 * Method that accept a map as param, than you can work with the named params
	 * @param namedParams: Map
	 */
	public void methodWithMultipleParams(Map namedParams){
		System.out.print(namedParams.get("name"));
		System.out.print(namedParams.get("profession"));
		//...
	}

	/**
	 * Method that accept an array of strings than you can work with multiple args
	 * @param strings: String[]
	 */
	public void methodWithMultipleParams(String[] strings){
        for(String element : strings)
            System.out.print(element);
	}

	/**
	 * Method that accept multiple arguments via VARARGS (http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html)
	 * @param varargs:String...
	 */
	public void methodWithMultipleParamsUsingVarArgs(String...varargs){
        for(String element : (String[])varargs)
            System.out.print(element);
	}

Cópia: Qual a diferença entre cursos de Bacharelados e Tecnólogos!?

Questionamentos mais frequentes sobre a diferença entre Cursos de Bacharelado e Tecnólogos:

1) O que é um tecnólogo?
Trata-se de um profissional de nível superior, apto a desenvolver atividades em uma determinada área. Possui formação direcionada à aplicação, desenvolvimento e difusão de tecnologias, com formação em gestão de processos de produção de bens e serviços. Tem como grande diferencial a ênfase na capacitação para empreender, em sintonia com o mercado.Portanto, os cursos superiores de tecnologia formam profissionais especializados em um ramo específico de uma determinada área.

2) O diploma, a titulação obtida no Curso Superior de Tecnologia é igual à obtida em curso superior de graduação convencional (cursos em faculdades ou universidades)?
O Curso tecnólogo dá ao cidadão formado o diploma de graduação em nível superior, exatamente como qualquer outro curso de qualquer área. Enfim, trata-se de um curso superior como qualquer outro, mas direcionado para um determinado foco.

3) Qual a diferença entre um curso superior de graduação convencional (bacharelado) e um curso superior de tecnologia (tecnólogo)?
A primeira grande diferença é o tempo de formação: um tecnólogo pode ser formado após um curso com duração de 2 a 3 anos, cursando de 1600 a 2400 horas, conforme o curso. A segunda diferença é que o tecnólogo tem uma formação específica para o mercado de trabalho, ao passo que o bacharelado confere uma formação mais abrangente. A terceira diferença é que, em razão do tempo mais curto de formação, existe a possibilidade de ingresso no mercado de trabalho de forma mais rápida.

4) Depois de concluir um curso superior de tecnologia (tecnólogo), o profissional pode dar prosseguimento aos seus estudos realizando cursos de extensão, especialização, mestrado ou doutorado?
A LDB (Lei de Diretrizes e Bases da Educação, Lei 9394/1996), combinada com o Parecer 436/2001 permite que o egresso do tecnólogo (aluno formado no curso de tecnologia), dê prosseguimento aos seus estudos em outros cursos e programas de educação superior, tais como extensão, especialização, mestrado e doutorado. Depende, evidentemente, do interesse do tecnólogo.

5) Por que foram criados os tecnólogos (cursos superiores de tecnologia)?
Os tecnólogos surgiram para suprir uma demanda crescente no mercado de trabalho, que exige uma maior preparação, formação e aprimoramento educacional e profissional no menor tempo possível.Desta forma, tem-se um profissional de nível superior formado em menor tempo, tendo em vista que algumas pessoas não querem ou não podem dispor de quatro ou cinco anos para cursar uma faculdade (curso superior convencional).

Texto repassado pelo professor Giancarlo Moser – UNIASSELVI

Fonte: http://www.comunicandomoda.com/2007/05/aticle-qual-diferena-entre-cursos-de.html