Arquivo

Archive for the ‘JAVA’ Category

Adding DB2 jdbc drivers to a Maven Java project

You need to get the DB2 drivers, in my case db2jcc.jar and db2jcc_license_cu.jar, then, drop it to a folder at your file system, also, in my case I created a folder /opt/driveDB2 and drop the 2 files there.

Then, run the mvn install command, like in my examples (pay attention in your Version):

mvn install:install-file -Dfile=/opt/driveDB2/db2jcc.jar -DgroupId=com.ibm.db2.jcc -DartifactId=db2jcc4 -Dversion=10.1 -Dpackaging=jar -DgeneratePom=true -DcreateChecksum=true

mvn install:install-file -Dfile=/opt/driveDB2/db2jcc_license_cu.jar -DgroupId=com.ibm.db2 -DartifactId=db2jcc_license_cu -Dversion=10.1 -Dpackaging=jar -DgeneratePom=true -DcreateChecksum=true

At your project, just add the following lines to the pom.xml file:

<dependency>
    <groupId>com.ibm.db2.jcc</groupId>
    <artifactId>db2jcc4</artifactId>
    <version>10.1</version>
</dependency>

<dependency>
    <groupId>com.ibm.db2</groupId>
    <artifactId>db2jcc_license_cu</artifactId>
    <version>10.1</version>
</dependency>

Voa lá!

Anúncios
Categorias:DB2 / Banco de dados, JAVA Tags:, ,

Pequeno exemplo de Threads em Java

Compartilhando uma pequena solução utilizada em POCs (provas de conceito) quando preciso demonstrar alguma coisa utilizando Threads, segue um pequeno trecho que pode ser útil para alguém, e certamente para mim mesmo (quem escreve e compartilha – nunca esquece… ou quase isso).

Criei uma classe para ser minha gerenciadora de thread:

package br.com.ibm.threads;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class ThreadExecutorMaganer {
private ExecutorService executor;
private long timeout;

private List<Callable<String>> callables;

public ThreadExecutorMaganer(int maxThreads, long timeoutInSeconds) {
this.executor = Executors.newFixedThreadPool(maxThreads);
this.callables = new ArrayList<Callable<String>>();
this.timeout = timeoutInSeconds;
}

public void add(Callable<String> callable) {
this.callables.add(callable);
}

public List<Future<String>> start() {
List<Future<String>> futures = null;

try {
futures = executor.invokeAll(callables, timeout, TimeUnit.SECONDS);

executor.shutdown();
} catch (InterruptedException e) {
e.printStackTrace();

executor.shutdownNow();
}

return futures;
}

}

Esta é minha Thread em si (veja que tem um IF la com um sleep só pra provocar erro e testar), ela é do tipo Callable;

package br.com.ibm.threads;

import java.util.concurrent.Callable;

public class CallableTask implements Callable<String>{

private final String tarefa;

public CallableTask(String tarefa) {
this.tarefa = tarefa;
}

@Override
public String call() throws Exception {
System.out.println("Inside call-->" + tarefa);
if (tarefa.equals("C")){
System.out.println("Sleeping 6 seconds");
Thread.sleep(6000);
}
return tarefa;
}

}

E esta é minha classe principal que invoca o circo:

package br.com.ibm.threads;

import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import com.ibm.services.tools.wexws.utils.ThreadExecutorMaganer;

public class CallThreadExecutorMaganer {

public static void main(String[] args) {
String[] restfulUrls = "A,B,C,D,E".split(",");
ThreadExecutorMaganer tem = new ThreadExecutorMaganer(100, 5);

for (String url : restfulUrls) {
tem.add(new CallableTask(url));
}
List<Future<String>> futureResponses = tem.start();

for (Future<String> futureResponse : futureResponses) {
try {
String resp = futureResponse.get();
System.out.println(resp);

}catch (ExecutionException ex){
System.out.println("ExecutionException while getting WEX response="+ex.getCause().getMessage());
}catch (Exception e) {
System.out.println("Fail to query WEX server:"+e.getMessage());
}
}

}

}

Antes que a patrulha critique: É um SIMPLES exemplo, não deve ser utilizado profissionalmente sem uma análise e adequação para seu caso, como tipagens adequadas, tratamento de erros, etc…

Enjoy!

Categorias:JAVA Tags:, , , ,

Reading XML with Java – Quick and simple example

I always need some code to read XML with Java. This is a place holder to me, but, maybe can be useful to other people.

Here is my XML example:

<operator logic="and">
<operator logic="or">
<term field="query" input-type="user" processing="strict" str="は" />
<term field="query" input-type="user" phrase="phrase" processing="strict" str="銀行業務" weight="1" />
<term field="query" input-type="user" processing="strict" str="持つ" />
<term field="query" input-type="user" phrase="phrase" processing="strict" str="java開発者" weight="1.69" />
<term field="query" input-type="user" processing="strict" str="探して" />
</operator>
</operator>

Here is my Java code:

import org.w3c.dom.*;
import org.xml.sax.InputSource;

import javax.xml.parsers.*;
import java.io.*;

public class ParseXML {

	public static void main(String[] args) {
		String xml = "<operator logic=\"or\"><term field=\"query\" input-type=\"user\" processing=\"strict\" str=\"は\" /><term field=\"query\" input-type=\"user\" phrase=\"phrase\" processing=\"strict\" str=\"銀行業務\" weight=\"1\" /><term field=\"query\" input-type=\"user\" processing=\"strict\" str=\"持つ\" /><term field=\"query\" input-type=\"user\" phrase=\"phrase\" processing=\"strict\" str=\"java開発者\" weight=\"1.69\" /><term field=\"query\" input-type=\"user\" processing=\"strict\" str=\"探して\" /></operator>";
		try {	
			Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
			doc.getDocumentElement().normalize();
			
			System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
			NodeList nList = doc.getElementsByTagName("term");
			System.out.println("----------------------------");
			for (int temp = 0; temp < nList.getLength(); temp++) {
				Node nNode = nList.item(temp);
				System.out.println("\nCurrent Element :" + nNode.getNodeName());
				if (nNode.getNodeType() == Node.ELEMENT_NODE) {
					Element eElement = (Element) nNode;
					System.out.println("processing : " + eElement.getAttribute("processing"));
					System.out.println("str : " + eElement.getAttribute("str"));
	            }
	         }
	      } catch (Exception e) {
	         e.printStackTrace();
	      }
	}
}
Categorias:JAVA Tags:, , , , , , ,

Solução para o teste EQUI no Codility

Muitas pessoas estão fazendo testes / provas online no Codility como parte de entrevistas de emprego, principalmente, para vagas no exterior. Eu recomendo fazer os tutorias antes de tentar fazer qualquer teste oficial lá, pois somente assim, você vai ver como realmente é a prova, como rodar, testar, e dessa forma, sentir-se confortável com a mesma.

Eu efetuei o teste EQUI, que tem a solução em C aqui. Resolvi em JAVA. Recomendo tentar fazer antes de olhar a solução. Ai vai:


package br.com.ibm.tests;

public class Solution {

public static void main(String[] args) throws Exception {
Solution s = new Solution();
// int[] A = {2, 2, 2, 2, 2, 2, 2, 2, 2};
int[] A = { -7, 1, 5, 2, -4, 3, 0 };
System.out.print(s.solution(A));
}

public int solution(int[] A) {
int sub = 0;
int sum = 0;
int left = 0;
int right = 0;

if (A.length != -1) {
for (int i = 0; i < A.length; i++) {
sum = sum + A[i];
}
}

for (int i = 0; i < A.length; i++) {
sub = sub + A[i];
left = sub - A[i];
right = sum - sub;

if (left == right) {
return i;
}
}
return -1;
}

}

Uma solução mais performática e menos propensa a estouros utilizando BigInteger é:

package br.com.ibm.tests;

import java.math.BigInteger;

public class Solution {

public static void main(String[] args) throws Exception {
Solution s = new Solution();
// int[] A = {2, 2, 2, 2, 2, 2, 2, 2, 2};
int[] A = { -7, 1, 5, 2, -4, 3, 0 };
System.out.print(s.solution(A));
}

public int solution(int[] A) {
BigInteger sub = BigInteger.ZERO;
BigInteger sum = BigInteger.ZERO;
BigInteger left = BigInteger.ZERO;
BigInteger right = BigInteger.ZERO;

if (A.length != -1) {
for (int i = 0; i < A.length; i++) {
sum = sum.add(BigInteger.valueOf(A[i]));
}
}

for (int i = 0; i < A.length; i++) {
sub = sub.add(BigInteger.valueOf(A[i]));
left = sub.subtract(BigInteger.valueOf(A[i]));
right = sum.subtract(sub);

if (left.equals(right)) {
return i;
}
}
return -1;
}

}

Boa sorte.

Categorias:JAVA Tags:, , , ,

Improve programmer Skills

As a programmer, I’m always looking for challenges. Solving “random” problems can always make us learn more and being more smart, knowing more structures and patterns.

For those who want to improve your skills as a programmer, I found a good list, with explanations and challenges at https://codility.com/programmers/

It’s free. You can play a lot!

Enjoy!

Introdução a Big Data e Apache Solr

Para quem está interessado em Big Data e além disso quer algo prático utilizando Apache Solr, disponibilizo um conjunto de slides que podem ser utilizados por Estudantes, Professores e profissionais. Usem e distribuam a vontade!

Finding bottlenecks at Watson Explorer queries

If you are having problem with some Watson Explorer query, an excellent way to find bottlenecks is to perform the query with Debug and Profile options enabled, it will help you to find where exactly you have problems.

Usually, when you perform a query at WEX, you call some URL like the following (in my case port is 7205, MY_COLLECTION can be a shard, for example MY_COLLECTION_1_1):

<SERVER>:<PORT>/search?collection=MY_COLLECTION&query-xml=<%3fxml version%3d”1.0″ encoding%3d”UTF-8″%3f><operator logic%3d”and”%2f>&num=1&max=1&binning-mode=normal&start=0&show-duplicates=1&doc-axl=<%3fxml version%3d”1.0″ encoding%3d”UTF-8″%3f><document key-hash%3d”{vse%3adoc-hash()}”%2f>&binning-config=<%3fxml version%3d”1.0″ encoding%3d”UTF-8″%3f><binning-sets><binning-set bs-id%3d”VENDOR” logic%3d”or” max-bins%3d”8″ select%3d”%24VENDOR”%2f><binning-set bs-id%3d”REVENUE_USD_FACET” logic%3d”or” max-bins%3d”11″ select%3d”%24REVENUE_USD_FACET”%2f>……………field%3d”SERVICE_AREA”><field-to name%3d”SERVICE_AREA”%2f><%2ffield-map><field-map field%3d”MAX_IGS_REV_OM_BRAND_CD”><field-to name%3d”MAX_IGS_REV_OM_BRAND_CD”%2f><%2ffield-map><field-map field%3d”EMAIL_SENT”><field-to name%3d”EMAIL_SENT”%2f><%2ffield-map><field-map field%3d”REVENUE_USD_FACET”><field-to name%3d”REVENUE_USD_FACET”%2f><%2ffield-map><field-map field%3d”REVENUE”><field-to name%3d”REVENUE”%2f><%2ffield-map><field-map field%3d”CLIENT_NAME”><field-to name%3d”CLIENT_NAME”%2f><%2ffield-map><%2ffield-mapping>&sort-keys=1&score=1&shingles=0&summarize=0&gen-key=0&cache-data=0&force-binning=1&output-acls=1

If you don’t have IDEA about HOW to get the query that your Application is doing, you can enable Debug at your collection. Go to WEX console, under Configuration -> Searching -> Debugging and enable Query Logging.

Selection_355

When saved, it will start to generate log in a file called queries.log, under you collection folder, some place like:

/opt/IBM/dataexplorer/WEX-11/Engine/data/search-collections/YYY/MY_COLLECTION/crawl1/

You can check it at WEX console, under your collection configuration, tab META, field Filebase.

Ok, now, if you call this URL from your browser, appending “&debug=1&profile=1″ to the URL, you will got a XML file. Download it and lets analyze. For our case, see this:

<xpath-performances>
<xpath-performance xpath=”($FIELD_X) = ‘GBS – No’ or ($FIELD_X) = ‘GBS – Yes'” slow-ms=”10295″ n-slow=”192000″ n-fast=”0″ n-direct=”0″ n-hashes=”1″ />
</xpath-performances>

THIS tell me that JUST in order to get the field FIELD_X, I’m having slow! (I’m my case it is because my Field its an Array)

So, probably I have a problem with this field, that can be a lot, for example:
1- Null values (see my other posts)
2- Its an array to index
3- Its a long text field
4- You have a lot of possible statements using it (OR, AND, WHERE, etc)

With this information, you can go to next step, that is find a way to change the field and make it work better.

Important: I tested this with Watson Explorer 9, 10 and 11. Running at Linux Machines.

Enjoy!