Você tem que definir uma família de algoritmos, encapsular cada um e torná-los intercambiáveis.
2. Chain of Responsibility (Cadeia de Responsabilidades)
É como a implementação de uma LinkedList, mas com regras de negócios, onde você tenta satisfazer a regra que você precisa e, se não for possível, vá para a próxima regra. Cada regra sabe a próxima regra que deve chamar.
3. Template Method (Método de Modelo)
Crie uma abstração do algoritmo, implementando a lógica chamando métodos abstratos que serão implementados pelas classes que estenderão a classe de modelo.
4. Decorator (Decorador)
Anexe responsabilidades adicionais a um objeto. Exemplo: Um imposto poderia ser composto por outros impostos, então você poderia passar o outro imposto através do construtor da classe e aplicar as suas regras para ele.
5. State (Estado)
Permitir que um objeto altere seu comportamento quando seu estágio interno muda. Use classes diferentes de uma interface para aplicar os estados ao objeto.
6. Builder (Construtor)
Separar a criação de um objeto complexo de sua representação para que o mesmo processo de criação possa criar implementação diferente. Use interfaces fluentes.
7. Observer (Observador)
Criar uma lista de implementações de uma interface, em seguida, chamá-lo para executar o método de cada implementação sempre que for necessário no código.
Data structure is a way of defining, storing and retrieving data in a structural and systematic way.
2. Sequential access
It means that a group of elements is accessed in a predetermined sequence.
ArrayList: Re-sizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. It is unsynchronized.
Vector: It is a synchronized ArrayList. It means its thread safe.
3. Linked List
Doubly-linked list implementation of the List and Deque interfaces. Implements all optional list operations, and permits all elements (including null). It stores the data in nodes that connect with the previous and next nodes since it’s doubly-linked. It could also be singly-linked.
4. Graph
A graph is a pictorial representation of a set of objects where some pairs of objects are connected by links.
5. Stack
Every new elements will be added as the first element, and only the first element can be removed. The order in which elements come off a stack gives rise to its alternative name, LIFO (for last in, first out).
6. Queue
Every new elements will be added as the last element, and only the first element can be removed. This makes the queue a First-In-First-Out (FIFO) data structure.
7. Heap
It is a special balanced binary tree data structure where root-node key is compared with its children and arranged accordingly.
8. Tree
A tree is a minimally connected graph having no loops and circuits.
Binary Tree: A binary tree has a special condition that each node can have two children at maximum.
Binary Search Tree: A binary search tree is a binary tree with a special provision where a node's left child must have value less than its parent's value and node's right child must have value greater than its parent value.
AVL Tree: It is height balancing binary search tree. AVL tree checks the height of left and right sub-trees and assures that the difference is not more than 1. This difference is called Balance Factor.
Spanning Tree: A spanning tree is a subset of Graph G, which has all the vertices covered with minimum possible number of edges. A spanning tree does not have cycles and it cannot be disconnected.
9. Set
It can store values without any particular order and no repeated values. It is a computer implementation of the mathematical concept of a finite set. Other variants, called dynamic or mutable sets, allow also the insertion and deletion of elements from the set.
10. Map
It is an object that maps keys to values. A map cannot contain duplicate keys and each key can map to at most one value. Map doesn’t implements Collection because it contains a key and a value.
The area where all java objects reside is called heap. The heap is created when the JVM starts up and may increase or decrease in size while the application runs.
2. Nursery
It is the part of the heap reserved for allocation of new objects. When the nursery becomes full, garbage is collected by running a special young collection.
3. Old Space
All objects that have lived long enough in the nursery are moved to the old space. When the old space becomes full garbage is collected there, a process called an old collection.
4. Object Allocation
Small objects are allocated in thread local areas (TLAs) and large objects that don’t fit inside a TLA are allocated directly on the heap.
5. Garbage Collection
It is the process of freeing space in the heap or the nursery for allocation of new objects.
6. The Mark and Sweep Model
A mark and sweep garbage collection consists of two phases, the mark phase and the sweep phase. This can be done in a parallel manner where all threads are paused and all available CPUs are used at the same time.
Pause phase: Sometimes this model can have a phase that pause all processes to start the Garbage Collect.
Mark phase: Java threads, native handles and other root sources are marked as alive, as well as the objects that are reachable from these objects and so forth.
Sweep phase: The heap is traversed to find the gaps between the live objects. These gaps are recorded in a free list and are made available for new object allocation.
7. Generational Garbage Collection
It is a garbage collection strategy which uses a nursery.
8. Compaction
To reduce fragmentation, JVM compacts a part of the heap at every garbage collection (old collection).
External: It evacuates objects within the compaction area to free positions outside the compaction area and as far down in the heap as possible.
Internal: It moves the objects within the compaction area as far down in the compaction area as possible, thus moving them closer together.
Lightweight: Spring is lightweight when it comes to size and transparency.
Inversion of control (IOC): Objects give their dependencies instead of creating or looking for dependent objects.
Aspect oriented (AOP): Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services.
Container: Spring contains and manages the life cycle and configuration of application objects.
MVC Framework: Provides a great alternative to other web frameworks such as Struts.
Transaction Management: Spring provides a consistent transaction management interface that can scale down to a local and scale up to global.
Exception Handling: Spring translate technology-specific exceptions into consistent, unchecked exceptions.
2. Modules
Core,
Bean,
Context,
Expression Language,
JDBC,
ORM,
OXM,
JMS,
Transaction,
Web,
Web-Servlet,
Web-Struts,
Web-Portlet
3. Inversion of Control (IOC)
This concept says that you do not create your objects but describe how they should be created. Dependency Injection is an example of it (spring injects dependencies into your attributes with @Autowire).
Containers
- Bean Factory : Container providing basic support.
- Spring ApplicationContext: adds more enterprise-specific functionality.
Types
- Constructor-based: The container invokes a class constructor with a number of arguments.
- Setter-based: Calling setter methods on your beans after invoking a no-argument constructor.
4. Scopes
Types instances that should be returned from Spring container:
Singleton: Bean definition to a single instance, it's the default.
Prototype: Single bean definition to have any number of object instances.
Request: A bean definition to an HTTP request
Session: A bean definition to an HTTP session
Global-session: A bean definition to a global HTTP session
5. Aspect-oriented programming (AOP)
It is a programming technique that allows programmers to modularize crosscutting concerns, or behavior.
Concern: It may be defined as a functionality we want to implement.
Cross-cutting concern: It's a concern which is applicable throughout the application and it affects the entire application.
Advice: This is the actual action to be taken either before or after the method execution.
- Before: Run advice before a method execution.
- After: Run advice after a method execution regardless of its outcome.
- After-returning: Run advice after a method execution only if method completes successfully.
- After-throwing: Run advice after a method execution only if method exits by throwing an exception.
- Around: Run advice before and after the advised method is invoked.
Join: This represents a point in your application where you can plug-in AOP aspect.
Pointcut : This is a set of one or more join points where an advice should be executed.
6. Annotations
@Required: Indicates that the affected bean property must be populated at configuration time.
@Autowired: It can be used to autowire bean on the setter method, constructor, a property or methods with arbitrary names and/or multiple arguments.
@Qualifier: You can use @Qualifier annotation along with @Autowired to remove the confusion by specifying which exact bean will be wired, in case of more than one bean.
@Configuration: Indicates that the class can be used by the Spring IoC container as a source of bean definitions.
@Bean: It tells Spring that a method will return an object that should be registered as a bean.
@WebApplicationContext (@ApplicationContext): It defines a class as the main class in the project.
@Controller: Indicates that a class serves the role of a controller.
@RequestMapping: It is used to map a URL to either an entire class or a particular handler method.
@PostConstruct: This annotation can be used as an alternate of initialization callback.
@PreDestroy: This annotation can be used as an alternate of destruction callback.
@Resource: It takes a 'name' attribute which will be interpreted as the bean name to be injected.
@ResponseBody: Indicates that the return type should be written straight to the HTTP response.
@RequestBody: Indicate that a method parameter should be bound to the body of the HTTP request.
Neste post irei mostrar como instalar e configurar o PostgreSQL no servidor com Ubuntu.
Parte 01: Instale o PostgreSQL:
sudo apt-get install postgresql
Parte 02: Configure o PostgreSQL:
sudo nano /etc/postgresql/9.3/main/postgresql.conf
Descomente e altere o listen_addresses no postgresql.conf conforme descrito abaixo:
listen_addresses = '*'
sudo -u postgres psql template1
> ALTER USER postgres with encrypted password 'exemploSenha';
> \q
sudo -u postgres psql postgres
> ALTER USER postgres with encrypted password 'exemploSenha';
> \q
sudo nano /etc/postgresql/9.3/main/pg_hba.conf
Altere na linha onde tiver peer por md5 conforme a linha abaixo:
local all postgres md5
Adicione a linha abaixo com o seu IP no lugar do IP de exemplo:
host all all 177.42.170.205/16 md5
sudo service postgresql restart
Obs.: A versão do Postgre muda de acordo com a versão do Ubuntu. Então a versão nos comandos também variam. Exemplo: 9.3, 9.4...
Então você quer rodar suas aplicações Java na nuvem mas está cansado de ter que colocar o 8080. A melhor forma de eliminar a necessidade de colocar a port depois do IP do seu servidor, e/ou domínio, é com o Apache.
Passo 01: Atualize seu servidor e configure o Java:
http://raulbento.tumblr.com/post/143439546479/java-8-ubuntu-cloud
Passo 02: Configure a língua e o time zone do seu servidor:
http://raulbento.tumblr.com/post/143440130229/ubuntu-em-portugu%C3%AAs-time-zone-cloud
Passo 03: Instale tanto o Tomcat quanto o Apache2:
sudo nano /etc/apache2/apache2.conf
Adicione, altere e salve a string abaixo no arquivo:
ServerName localhost
KeepAlive Off
AllowOverride All
Passo 05: Configure o Tomcat e reinicie as aplicações:
sudo nano /etc/default/tomcat7
Adicione as linhas abaixo no /etc/default/tomcat7 e salve, não esqueça de comentar a JAVA_OPTS que já tem no arquivo:
JAVA_HOME=/usr/lib/jvm/java-8-oracle
JAVA_OPTS="-Djava.security.egd=file:/dev/./urandom -Djava.awt.headless=true -Xmx512m -XX:+UseConcMarkSweepGC -Duser.language=pt -Duser.region=BR"
PS.: As aspas devem ser alteradas manualmente caso você copie e cole o texto acima. Do contrario o Tomcat não vai entender o caractere.
sudo nano /etc/tomcat7/tomcat-users.xml
Adicione as linhas abaixo no tomcat-users.xml e salve:
<!-- user manager can access only manager section -->
<role rolename="manager-gui" />
<user username="manager" password="example" roles="manager-gui" />
<!-- user admin can access manager and admin section both -->
<role rolename="admin-gui" />
<user username="admin" password=" example" roles="manager-gui,admin-gui" />
Obs.: Serve para qualquer versão do Tomcat, basta mudar para o numero da versão em todas as linhas, ou seja, onde tem 7 coloque 8 para mudar para a versão 8 do Tomcat. Exemplo: /etc/default/tomcat8.
Obs.2: Pastas importantes do seu servidor:
Pasta onde colocar os arquivos WAR:
/var/lib/tomcat7/webapps/
Pasta onde são salvos os logs dos sistemas (Catalina.out):
/var/log/tomcat7/
Quando temos um servidor na nuvem e em outro país, às vezes, queremos utilizar a ótima estrutura que eles têm, mas deixar tudo rodando como se o servidor fosse no Brasil. Aqui mostrarei como deixar grande parte do Ubuntu em português e alterar a time zone do seu Ubuntu para o Brasil.
sudo apt-get install kde-l10n-ptbr
sudo locale-gen pt_BR.UTF-8
sudo update-locale LANG=pt_BR.UTF-8
sudo dpkg-reconfigure tzdata
Mude a time zone para a qual você desejar, abaixo é a que uso:
America/Fortaleza
Hoje vamos atualizar o seu Ubuntu e instalar o Java 8 em qualquer versão do Ubuntu. Utilizaremos a versão oficial da Oracle e não o OpenJDK, que não é na minha opinião.
Então você decidiu guardar as imagens dos seus clientes no banco de dados. E todos ficam te zoando? Não se preocupe, eles apenas não tem conhecimento suficiente para entender o quão simples e vantajoso isso é. Suas imagens serão salvas e carregadas através de Streaming do próprio Hibernate, o que permite que outras atividades sejam realizadas enquanto as imagens são carregadas do banco de dados. Hoje vou explicar como salvar e obter imagens de um banco de dados através de Streaming.
Quando você precisar exibir uma imagem que esta no formato byte[] sem salvar a imagem a melhor opção é usar um DynamicImageResource com uma NonCachingImage. Por se tratar de duas classes abstratas deve-se implementar o retorno do método getImageData(Attributes attributes) do DynamicImageResource e do método getObject() do NonCachingImage. No retorno deve-se colocar o byte[] da imagem.
/* Array de Byte Com os bytes da imagem */
byte[] ARRAY_DE_BYTES_DA_IMAGEM;
/* Tipo de Imagem que será carregada */
string EXTENSAO = "image/png";
DynamicImageResource:
/* Aqui você transforma o array de bytes em uma Imagem dinâmica */
DynamicImageResource dynamicImage = new DynamicImageResource(EXTENSAO)
{
/* Não use esse, gere um número */
private static final long serialVersionUID = 1L;
O DropDownChoice do Wicket é uma implementação de um Select onde o usuário será capaz de selecionar apenas um item por vez. Todas as opções, menos a selecionada, ficam escondidas a não ser que o usuário clique no item.
Estrutura Básica (JAVA):
DropDownChoice<Object> dropDownChoice = new DropDownChoice<Object>("id");
/* Determina a lista de itens do DropDownChoice */
dropDownChoice.setChoices(new ArrayList<Object>());
/* Atributo que será mostrado no DropDownChoice */
String display = "";
/* Atributo que será retornado como valor to item selecionado */
String value = "";
/* Determina como o DropDownChoice Funcionará */
dropDownChoice.setChoiceRenderer(new ChoiceRenderer<Object>(display, value));
/* Determina qual o tipo de Object, o Modelo, que é retornado getModelObject() */
dropDownChoice.setModel(Model.of(new Object()));
/* Determina qual item estará selecionado no DropDownChoice */
dropDownChoice.setModelObject(new Object());
Obs.: Dependendo das circunstancias o getModelObject não funcionará, deverá ser usado o getValue. Caso seja necessário recuperar o objeto, ele deverá ser recuperado utilizando o getValue como parâmetro de busca do objeto.
Obs. 2: Object deverá ser substituído pelo Modelo utilizado no DropDownChoice.
Utilizar a biblioteca java.util.Date é um transtorno, principalmente tendo em vista que a maioria dos métodos contidos nessa biblioteca são deprecados. Devemos então utilizar outras bibliotecas para podermos manipular datas e utilizar a java.util.Date como a classe de armazenamento de datas.Geralmente utilizo as classes java.text.SimpleDateFormat e java.util.Calendar para manipular as data e criar métodos que tenham datas em seu processamento.
Outro dia estava precisando comparar duas data em um projeto, verificar o ano das duas para saber se o ano de uma era maior que o ano da outra e após pensar um pouco e analisar as opções, e formas, para resolver este problema, decidi fazer a comparação utilizando a biblioteca java.text.SimpleDateFormat, pois eu poderia pegar o ano da data facilmente.
public boolean dataMaiorIgual(Date dataA, Date dataB){
long anoA = Long.parseLong(new SimpleDateFormat("yyyy").format(dataA));
long anoB = Long.parseLong(new SimpleDateFormat("yyyy").format(dataB));
return anoA >= anoB;
}
Veja que na formatação da data eu utilizo o “yyyy” que é referente a pegar os quatro dígitos do ano da data, se eu quisesse pegar o dia da data eu colocaria “dd” e caso eu quisesse o mês da data eu utilizaria “MM”. Essas são convenções de data, uma data completa no formato brasileiro é “dd/MM/yyyy”, mas geralmente as datas, por padrão, vem no formato americano “MM/dd/yyyy”.
E se eu quisesse imprimir a data por extenso? Bem nesse caso você precisaria criar um método um pouco mais complexo. Vejamos:
public String dataPorExtenso(Date data) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(new SimpleDateFormat("dd").format(data));
stringBuilder.append(" de ");
stringBuilder.append(mes(Integer.parseInt(new SimpleDateFormat("MM").format(data))));
stringBuilder.append(" de ");
stringBuilder.append(new SimpleDateFormat("yyyy").format(data));
return stringBuilder.toString();
}
private String mes(int mes) {
String mesExtenso = "";
switch (mes) {
case 1: { mesExtenso = "Janeiro"; break; }
case 2: { mesExtenso = "Fevereiro"; break; }
case 3: { mesExtenso = "Março"; break; }
case 4: { mesExtenso = "Abril"; break; }
case 5: { mesExtenso = "Maio"; break; }
case 6: { mesExtenso = "Junho"; break; }
case 7: { mesExtenso = "Julho"; break; }
case 8: { mesExtenso = "Agosto"; break; }
case 9: { mesExtenso = "Setembro"; break; }
case 10: { mesExtenso = "Outubro"; break; }
case 11: { mesExtenso = "Novembro"; break; }
case 12: { mesExtenso = "Dezembro"; break; }
}
return mesExtenso;
}
Quando precisamos pegar a data atual? Existem duas formas: com um new Date() ou com um Calendar.getInstance(). A partir disso, você pode manipular essa data da forma que desejar utilizando as bibliotecas que sitadas anteriormente.
Apresentei alguns métodos bem simples com datas, e mostrei alguns caminhos para que você possa se divertir com datas por um tempo.