Archive for the ‘Programação’ Category.

PLSQL consuming Web Services

This is a simple sample, how to do to consuming Web Services from Oracle database using PL/SQL. This tutorial was tested in Oracle database versions 9i, 10g and 11g.

The Web Services used is avaliable in webservicex.net, see this link, there are more details.

declare
 soap_request  varchar2(30000);
 soap_respond  varchar2(30000);
 http_req      utl_http.req;
 http_resp     utl_http.resp;

 l_launch_url varchar2(240) := 'http://www.webservicex.net/geoipservice.asmx?WSDL';
 l_soap_action varchar2(240) := 'http://www.webservicex.net/GetGeoIP';
 l_ip varchar2(100) := '189.100.4.198'; // IP just for test

Now, second step you have to build the SOAP request it’s may be boring if you parameter list too long, so you can use the soapUI to test and prepared the string of requisition.

begin

soap_request :=
'<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://www.webservicex.net/">
 <soapenv:Header/>
 <soapenv:Body>
 <web:GetGeoIP>
 <web:IPAddress>'|| l_ip || '</web:IPAddress>
 </web:GetGeoIP>
 </soapenv:Body>
</soapenv:Envelope>
';
 dbms_output.put_line(soap_request);
 HTTP_REQ:= UTL_HTTP.BEGIN_REQUEST(l_launch_url, -- web services url
 'POST',
 'HTTP/1.1');
 UTL_HTTP.SET_HEADER(HTTP_REQ,'Content-Type', 'text/xml'); -- since we are dealing with plain text in XML documents
 UTL_HTTP.SET_HEADER(HTTP_REQ,'Content-Length', length(soap_request));
 UTL_HTTP.SET_HEADER(HTTP_REQ,'SOAPAction' , l_soap_action); -- required to specify this is a SOAP communication
 UTL_HTTP.WRITE_TEXT(HTTP_REQ, SOAP_REQUEST);
 HTTP_RESP := UTL_HTTP.GET_RESPONSE(HTTP_REQ);
 UTL_HTTP.READ_TEXT(HTTP_RESP, SOAP_RESPOND);
 UTL_HTTP.END_RESPONSE(HTTP_RESP);

 dbms_output.put_line('-------------------------');
 dbms_output.put_line(soap_respond); -- here is the response
end;

Okay, that’s the cake recipe…

Enjoy it.

JDeveloper with Maven 2

The best IDE to development Java isn’t the JDeveloper, it’s a fact.
Sometimes we have using it same we don’t like it, whatever, if you are in this situation, I told you, use Maven.

Maven is a wonderful open-source tool, you can see more here.
Since Jdeveloper 11.1.1 version provide support to Maven, you just to install a extention. Some peoples wrote about it as Shay Shmeltzer and Aino Andriessen, two great names of Oracle’s world.

See into this link how to do to integrate Jdeveloper with Maven 2, it’s easy and fast.
Remember, you have setup application pom.xml file with that plugin, it’s very important, like this:

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.myfaces.trinidadbuild</groupId>
<artifactId>maven-jdev-plugin</artifactId>
</plugin>
</plugins>
</build>

Now, my two cents here. After install maven and jdeveloper setup you may know some commands.

To clean up project’s target.

mvn clean

To compile and build the target.

mvn install

And as last but very important. This command prepared the .jpr files with pom.xml configuration to work with JDeveloper.

mvn -Djdev.release=11.1.1.3.0 org.apache.myfaces.trinidadbuild:maven-jdev-plugin:jdev

I think it’s will fix your problem between Maven and Jdev.
Have fun.

Startup error Weblogic running on Windows 7 64bit

Hello there, this is my first post in english so I will try keep the same content but now writing in english, just for fun, I hope this work and I can talk with you fine… well that’s all.

Since last week I trying deploy an application in Weblogic Server 10.3.3 using Spring + CXF + Hibernate, I found many problems, the most of problems is incompatibility between classpath Weblogic and libraries application. My intention is make a post about this problem and how I fixed it…t

Well, Weblogic Server running in Windows 7 64bit after instalation and creation of domain, I found this error message in command prompt when I try start Weblogic:

QTJava.zip was unexpected at this time.
\user_projects\domains\base_domain>

I think this is a common problem in 64bit platform, I don’t why, however easily I fixed it go to domain directory in Weblogic installation, and edit startWebLogic.cmdC:\Oracle\Middleware\user_projects\domains\base_domain – see:

set DOMAIN_HOME=C:\Oracle\Middleware\user_projects\domains\base_domain
set CLASSPATH=
call “%DOMAIN_HOME%\bin\startWebLogic.cmd” %*

Only setting CLASSPATH like null.

But, this isn’t enough, again I don’t why, but you have change CLASSPATH system setting up QTJava.zip see link below to understand.

http://forums.oracle.com/forums/thread.jspa?threadID=922895

See image with my CLASSPATH system.

If same after you did this and the link “Start Admin Server for Weblogic Server Domain” from start menu not work, go to domain directory and execute startWebLogic.cmd file from there, it’s will work.

Maven2 com Oracle JDBC

Se você é um dos milhares que sofre com o erro abaixo, fique calmo, o seu problema está resolvido!

[INFO] Unable to find resource 'com.oracle:ojdbc14:jar:10.2.0.3.0' in repository central
(http://repo1.maven.org/maven2)

[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Failed to resolve artifact.

Missing:
----------
1) com.oracle:ojdbc14:jar:10.2.0.3.0

 Try downloading the file manually from the project website.

 Then, install it using the command:
 mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc14
-Dversion=10.2.0.3.0 -Dpackaging=jar -Dfile=/path/to/file

 Alternatively, if you host your own repository you can deploy the file there:
 mvn deploy:deploy-file -DgroupId=com.oracle -DartifactId=ojdbc14
-Dversion=10.2.0.3.0 -Dpackaging=jar -Dfile=/path/to/file -
Durl=[url] -DrepositoryId=[id]

 Path to dependency:
 1) br.com.ninecon.core:isupport:war:0.0.1-SNAPSHOT
 2) com.oracle:ojdbc14:jar:10.2.0.3.0

É possível configurar o repositório do Maven, utilizando a biblioteca localmente, ou seja, se você já tem o arquivo .jar em seu computador, pode corrigir o problema adicionando este arquivo ao repositório.

No meu caso foi simples, pois eu já tinha o banco de dados Oracle instalado localmente, mas caso você não tenha, faça o download library OJDBC.

Acesse o diretório onde esta o arquivo jar.

C:\Users\luciano>cd %ORACLE_HOME%/jdbc/lib

Execute o comando de instalação da library conforme abaixo passando os parametros necessários. No exemplo o banco utilizado é o 10.2.0.3.0.

c:\oracle\product\10.2.0\db_1\jdbc\lib>mvn install:install-file -Dfile=ojdbc14.jar -DgroupId=com.oracle -DartifactId=oracle -Dversion=10.2.0.3.0 -Dpackaging=jar -DgeneratePom=true
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'install'.
[INFO] org.apache.maven.plugins: checking for updates from central
[INFO] org.codehaus.mojo: checking for updates from central
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Default Project
[INFO]    task-segment: [install:install-file] (aggregator-style)
[INFO] ------------------------------------------------------------------------
[INFO] [install:install-file {execution: default-cli}]
[INFO] Installing c:\oracle\product\10.2.0\db_1\jdbc\lib\ojdbc14.jar to C:\Users\luciano\.m2\repository\com\oracle\oracle\10.2.0.3
.0\oracle-10.2.0.3.0.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3 seconds
[INFO] Finished at: Wed Jun 09 20:32:02 BRT 2010
[INFO] Final Memory: 3M/15M
[INFO] ------------------------------------------------------------------------
'cmd' is not recognized as an internal or external command,
operable program or batch file.
c:\oracle\product\10.2.0\db_1\jdbc\lib>

Perceba que o artifactId esta como oracle, portanto o seu pom.xml deve ser modificado também.

Com este simples comando você resolverá um problemão chato! ;)

Autenticação e Autorização com a API do Twitter

O Twitter veio para ficar e isto eu não discuto e, este blog quando empolgado com o micro-blog público um exemplo simples de como utilizar o Twitter4j. Agora estou tentando mostrar uma forma mais avançada de comunicação com o Twitter, utilizando o modo de autenticação/autorização.

No exemplo anterior além de obter o Customer Key e Secret, você irá precisar do Usuário e Senha do Twitter, para assim obter a comunicação devida. Bem, nem todo mundo sente-se disposto a oferecer seus dados confidênciais para um software ou site qualquer. Portanto, este novo exemplo mostrará como você deve comunicar com o Twitter deixando a autenticação por parte do micro-blog e autorização por parte do próprio usuário.

Dando sequência ao assunto, inicialmente você precisará registrar uma aplicação no Twitter caso ainda não a tenha, guarde os dados Consumer Key e Secret. Existem dois tipos de aplicações a Client (Desktop) e Browser (Web), sendo que a segunda precisará de uma url que receberá o Token de autenticação.

Infelizmente, este post foi prejudicado pela falta de um web hosting que suporte Java, a Locaweb (atual host deste blog) cobra valores mensais absurdos, que inviabiliza blogs com intuito simplesmente acadêmico, como este, de realizar testes utilizando a linguagem Java.

Consegui descobrir lendo aqui, aqui e aqui que é possível configurar o seu localhost como Callback URL no Twitter, assim não será necessário ter um site publicado na internet para seus testes.

Web Autenticação

Durante o registro você irá informar o tipo de aplicação Browser e uma Callback URL, é para onde o navegador será redirecionado após a autorização do usuário. Já o campo Application Website, é a origem da sua aplicação web, ou seja, serão aceitas as chamadas feitas apenas a partir deste site.

O código abaixo irá fazer iniciar o processo de autenticação, o navegador vai ser redirecionado para a página de login do Twitter.

 final String CALLBACK_URL     = "http://127.0.0.1:8080/BlogTwitt4u/"; // a mesma configurada na aplicação
 final String CUSTOMER_KEY     = "6MWotGxvuNVGfK4lDqAqhg";
 final String CUSTOMER_SEC     = "oRH0YviLum2Rrii25ePj0DEk6VnmNjoTG0ESUpqSY";

 OAuthConsumer consumer         = new DefaultOAuthConsumer(CUSTOMER_KEY, CUSTOMER_SEC);
 OAuthProvider provider         = new DefaultOAuthProvider( "https://twitter.com/oauth/request_token",
 "https://twitter.com/oauth/access_token",
 "https://twitter.com/oauth/authorize" );

 //
 // Solicita a autorização
 //
 String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
 session.setAttribute("token",         consumer.getToken());
 session.setAttribute("tokenSecret", consumer.getTokenSecret());

 //
 //
 // Redireciona para  o Twitter solicitar o Usuário e Senha, e Autorização para a aplicação
 // Em seguida será redirecionado para a callback url
 response.sendRedirect(authUrl);

Após fazer o login e autorizar a sua aplicação, o navegador será redirecionado novamente para o seu site, com dois parâmetros preenchidos, como esta abaixo:


http://127.0.0.1:8080/BlogTwitt4u/?oauth_token=RQVPENBxDbQuI1bJ1rjELuVSyZhMYqr8Fcs5eqyZw&oauth_verifier=a8FuEeitfdCR2IfgisfsHopMAUevs4cDyRWkbZz4

Pronto, ai você já pode colher as informações que desejar, veja:

 if( oauthVerifier!=null && !oauthVerifier.trim().equals("") ){

 String token            = (String) session.getAttribute("token");
 String tokenSecret        = (String) session.getAttribute("tokenSecret");

 //
 consumer.setTokenWithSecret(token, tokenSecret);

 //
 //
 provider.setOAuth10a(true);
 provider.retrieveAccessToken(consumer, oauthVerifier);

 out.println("<h1>AUTORIZADO!</h1>");
 out.println("<pre>");
 out.println("token:\t\t" + consumer.getToken());
 out.println("tokenSecret:\t\t" + consumer.getTokenSecret());
 out.println("oauthVerifier:\t\t" + oauthVerifier);
 out.println("oauthToken:\t\t" + oauthToken);

 //
 //
 URL url                         = new URL("http://twitter.com/statuses/mentions.json");
 HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
 consumer.sign( urlConnection );
 urlConnection.connect();

 BufferedReader in    = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()) );
 String inputLine     = "";
 String content       = "";
 while ((inputLine = in.readLine()) != null){
     content += inputLine;
 }// while end
 in.close();

 int statusCode = urlConnection.getResponseCode();
 out.println("statusCode: " + statusCode);
 out.println("</pre>");

 JSONArray json = JSONArray.fromObject( content );

 out.println("<hr>");
 out.println("<h3>Mentions</h3>");
 out.println("<pre>");
 for(int i=0; i<json.size(); i++){

 JSONObject obj = (JSONObject) json.get(i);
 if( obj!=null ){
   // JSONString str = (JSONString) obj.get("text");
   out.println(obj.getString("text"));
 }

 }// for end
 out.println("</pre>");

 }

Desktop Autenticação

Este é um exemplo comum, muito conhecido em qualquer pesquisa no Google, para utiliza-lo você deve ter uma aplicação do tipo Client.

O código pede para que o usuário abra o navegador, acesse uma determinada URL e depois informe o código númerico no programa, nada eficaz né? Muitos programadores utilizam uma maneira nada elegante que é a de “hackear” esta página e pegar o código automáticamente, facilitando a vida de todo mundo. Faça isto por sua conta e risco. Perceba que quando comparado ao código de autenticação Web a única mudança é a utilização do código PIN, que não necessário informar na web.

<pre>
<pre><pre>// Lembre-se de modificar estes valores para os seus
//
final String CUSTOMER_KEY = "6MWotGxvuNVGfK4lDq";
final String CUSTOMER_SEC = "oRH0YviLum2Rrii25ePj0DEk6VnmNjoTG0ESUp";

try {
HttpURLConnection request = null;
URL url = null;
OAuthConsumer consumer = new DefaultOAuthConsumer(CUSTOMER_KEY, CUSTOMER_SEC);

OAuthProvider provider = new DefaultOAuthProvider( <a href="https://twitter.com/oauth/request_token">https://twitter.com/oauth/request_token</a>,
"https://twitter.com/oauth/access_token",
"https://twitter.com/oauth/authorize");

String authUrl = provider.retrieveRequestToken(consumer, OAuth.OUT_OF_BAND);
//
// URL Que irá retornar o PIN, necessário para formar o Token
System.out.println(authUrl);

String pinCode = JOptionPane.showInputDialog("Acesse o endereço:\n" + authUrl + "\nE Informe o PIN:");
System.out.println("PIN Code: " + pinCode);

//
provider.retrieveAccessToken(consumer, pinCode);

String tokenKey = consumer.getToken();
String tokenSec = consumer.getTokenSecret();

System.out.println("Token Key : " + tokenKey);
System.out.println("Token Sec : " + tokenSec);

consumer.setTokenWithSecret(tokenKey, tokenSec);

url  = new URL(<a href="http://twitter.com/statuses/mentions.xml">http://twitter.com/statuses/mentions.xml</a>);
 request = (HttpURLConnection) url.openConnection();
// sign the request
consumer.sign(request);

// send the request
request.connect();

// response status should be 200 OK
int statusCode = request.getResponseCode();
System.out.println("Status Code : " + statusCode);

} catch (OAuthMessageSignerException e) {
e.printStackTrace();
} catch (OAuthNotAuthorizedException e) {
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Foram utilizadas as seguintes bibliotecas:
Apache Commons BeansUtil 1.8
Apache Commons Codec 1.4
Apache Http Client 3.1
Apache Commons Lang 2.4
ezmorph 1.0.6
json-lib 2.3

Faça download do projeto, que contêm ambos exemplos de autenticação.