Data de Inclusão:
02/09/2006 | Última Alteração:
02/09/2006
Tipo:Tutoriais | Enviada por:
Moderador Oracle_br (moderador@oraclebr.com.br)
IMPLEMENTAÇÃO DE UMA JAVA STORED PROCEDURE PARA MOVER, COPIAR, RENOMEAR E EXCLUIR ARQUIVOS DO SERVIDOR
Observações:
A - Funciona em bancos de dados Oracle versões 8.x e superiores
B - Testada com banco Oracle 8.1.7.4 e 9.2.0.3.0 em um servidor Linux com Sistema Operacional RED HAT Advanced Server 2.1. (com upgrade do Kernel para 2.4.9.38SMP)
C ? É necessário estar instalado o JServer. (Para instalações padrão ele é instalado automaticamente. Para se certificar se ele realmente está instalado se conecte no SQL Plus. Deve aparecer algo assim no cabeçalho:
Conectado a:
Oracle9i Enterprise Edition Release 9.2.0.3.0 - Production
With the Partitioning, OLAP and Oracle Data Mining options
JServer Release 9.2.0.3.0 ? Production => Aqui indica o JServer instalado
1 - Conectar como sys ou system e conceder privilégios Java nos diretórios origem e destino para o owner dos objetos
GRANT JAVAUSERPRIV to 'USER'
/
GRANT JAVASYSPRIV to 'USER'
/
begin
dbms_java.grant_permission( 'USER','SYS:java.io.FilePermission', '/CAMINHO DO DIRETÓRIO FONTE/','read, write, execute');
end;
/
begin
dbms_java.grant_permission( 'USER','SYS:java.io.FilePermission', '/CAMINHO DO DIRETÓRIO DESTINO/','read, write, execute');
end;
/
2 ? Conectar no usuário onde se deseja criar os objetos e criar uma tabela temporária (que será usada para listar os arquivos do diretório)
create global temporary table GTABTEMP_ARQUIVOS_OS
( filename varchar2(255) )
on commit delete rows = > Limpa a tabela no commit
/
3 - Criar o java source (composta por uma classe chamada ManipulaFiles e três métodos (listaArquivos, moveArquivos e removeArquivos)
listaArquivos => lista os arquivos no diretório especificado utilizando uma tabela temporária (no commit a tabela é limpa)
moveArquivos => move os arquivos do diretório origem para o destino (o nome do arquivo pode ser renomeado neste processo pois a origem e o destino devem possuir o endereço completo inclusive o nome do arquivo). Retorna 1 se executou com sucesso ou 0 caso dê algum erro.
copiaArquivos => copia os arquivos do diretório origem para o destino (a origem e o destino devem possuir o endereço completo inclusive o nome do arquivo). Retorna 1 se executou com sucesso ou 0 caso dê algum erro.
removeArquivos => exclui o arquivo do diretório. Retorna 1 se executou com sucesso ou 0 caso dê algum erro.
create or replace
and compile java source named "ManipulaFiles"
as
import java.io.*;
import java.sql.*;
public class ManipulaFiles
{
public static void listaArquivos(String directory)
throws SQLException
{
File path = new File( directory );
String[] list = path.list();
String element;
for(int i = 0; i < list.length; i++)
{
element = list[i];
#sql { INSERT INTO GTABTEMP_ARQUIVOS_OS (FILENAME)
VALUES (:element) };
}
}
public static int moveArquivos(String fileName,String Newname)
{
File myFile = new File (fileName);
File myFile1= new File(Newname);
boolean retval = myFile.renameTo(myFile1);
if (retval) return 1; else return 0;
}
public static int copiaArquivos(String srcFile, String dstFile) {
try {
File Origem = new File(srcFile);
File Destino = new File(dstFile);
RandomAccessFile raf = new RandomAccessFile(Origem,"r");
RandomAccessFile raf1 = new RandomAccessFile(Destino,"rw");
//read a byte
long i =0;
while(i < raf.length()){
raf1.writeByte(raf.readUnsignedByte());
i++;
}
raf.close();
raf1.close();
return 1;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public static int removeArquivo(String filename)
throws Exception
{
File myfile = new File(filename);
if ( myfile.delete() )
return 1;
else
return 0;
}
}
/
4 ? Criar as procedures e funções baseadas no código Java
create or replace
procedure lista_arquivos( p_directory in varchar2 )
as language java
name 'ManipulaFiles.listaArquivos( java.lang.String )';
/
create or replace
function move_arquivos( p_sourceFile in varchar2,p_destFile in varchar2 )
return number
as language java
name 'ManipulaFiles.moveArquivos( java.lang.String,java.lang.String ) return java.lang.String';
/
create or replace
function copia_arquivos( p_sourceFile in varchar2,p_destFile in varchar2 )
return number
as language java
name 'ManipulaFiles.copiaArquivos( java.lang.String,java.lang.String ) return java.lang.String';
/
create or replace
function remove_arquivo( p_FileName in varchar2)
return number
as language java
name 'ManipulaFiles.removeArquivo( java.lang.String) return java.lang.String';
/
5 ? Executar os testes
5.1 ? exec lista_arquivos('/tmp/origem'); => Insere os arquivos na tabela temporária
5.2 ? select * from gtabtemp_arquivos_os; => Lista os arquivos
5.3 ? commit; => Limpa a tabela temporária
5.4 ? select move_arquivos(?/tmp/origem/teste.txt?,?/tmp/destino/teste.txt?) from dual; => Move o arquivo teste.txt do diretório origem para o diretório destino. Neste caso poderia-se mudar o nome do arquivo durante a movimentação (select move_arquivos(?/tmp/origem/teste.txt?,?/tmp/destino/teste_old.txt?) from dual ou também renomeá-lo no mesmo diretório (select move_arquivos(?/tmp/origem/teste.txt?,?/tmp/origem/teste_old.txt?) from dual. O retorno deve ser igual a 1. Se retornou 0 é porque deu algum erro.
5.5 ? select copia_arquivos(?/tmp/origem/teste.txt?,?/tmp/destino/teste.txt?) from dual; O retorno deve ser igual a 1. Se retornou 0 é porque deu algum erro.
5.6 ? select remove_arquivo(?/tmp/origem/teste.txt?) from dual; O retorno deve ser igual a 1. Se retornou 0 é porque deu algum erro.
OBSERVAÇÃO IMPORTANTE: PARA QUE SE CONSIGA LISTAR, MOVER, COPIAR OU REMOVER OS ARQUIVOS OS DIRETÓRIOS UNIX DEVEM ESTAR COM AS PERMISSÕES DE LEITURA, GRAVAÇÃO E EXCLUSÃO.
Fontes de pesquisa:
http://asktom.oracle.com
http://metalink.oracle.com
http://forum.java.sun.com