Pessoal, estou precisando da ajuda de voces…
Tenho um servidor FTP de onde baixo um arquivo pra dentro da pasta temp do meu projeto, está parte esta funcionando perfeitamente so que quando o usuario clica no bt salvar ele deve apagra o arquivo do FTP e apagar o arquivo da pasta temp onde ele baixou, o que acontece é que ele nao apaga o arquivo o metodo delete sempre me retona false, entao em testes feitos manualmente eu tentei apagar o arquivo na mao, deu um erro dizendo que nao poderia apagar o arquivo pq ele estava sendo usado pela javaw.exe, pensei que fosse algum arquivo que estivesse aberto examinei todo o codigo e fechei todos testei pela aplicação novamente e o erro permanece sera que alguem poderia me ajudar com este problema por favor ja estou a dias batendo nisso e nao encontro uma soluçao, abaixo segue o codigo que estou usuando.
obs: marquei os pontos que estao com dado o problema.
clienteBean:
public void salvarIndexadores() {
cx = new ContCX();
try{
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
cliente = (Cliente) session.getAttribute("cliente");
IndexacaoBusiness indexacaoBusiness = IndexacaoBusiness.getInstance();
ClienteBusiness clienteBusiness = ClienteBusiness.getInstance();
DocumentoBusiness documentoBusiness = DocumentoBusiness.getInstance();
List<Indexador> lidx = (List<Indexador>) dataTable.getValue();
cliente = clienteBusiness.buscaCliente(cliente);
documentoBusiness.explodeString(cliente);
cx.setCliente(cliente);
indexacaoBusiness.insereIndexadores(lidx,cx);
cliente = documentoBusiness.moverArquivo(cliente);
salvarDocumento(cliente);
documentoBusiness.apagaArquivoFtp(cliente);
[color=red]documentoBusiness.apagaArquivoServidor(cliente);[/color]
baixarDocumento();
}catch (Exception e){
System.out.println(e);
}
}
codigo do DocumentoBusiness:
package br.com.agm.business;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.faces.bean.ManagedProperty;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import br.com.agm.bean.Cliente;
import br.com.agm.bean.Documento;
import br.com.agm.dao.DocumentoDAO;
import br.com.agm.manager.SessionBean;
import com.itextpdf.text.pdf.PdfReader;
public class DocumentoBusiness {
@ManagedProperty(value="#{sessionBean}")
private SessionBean session;
static DocumentoBusiness documentoBusiness = null;
DocumentoDAO documentoDao = new DocumentoDAO();
/**
* Usando o Padrao de Projeto Singleton
* metodo retorna uma única instância de UsuarioBusiness
* @return enqueteSVBusiness
*/
public static DocumentoBusiness getInstance() {
if (documentoBusiness == null) {
documentoBusiness = new DocumentoBusiness();
}
return documentoBusiness;
}
/**
*
* Busca arquivos no FTP
*
* @param cliente
* @return
*/
public String buscaDocumentoFtp(Cliente cliente) {
FTPClient ftp = new FTPClient();
FileOutputStream fio = null;
String[] larquivos = null;
String diretorio = null;
try{
ftp.connect("servidor");
if(FTPReply.isPositiveCompletion(ftp.getReplyCode())){
boolean sucess = ftp.login("user", "senha");
ftp.enterLocalPassiveMode();
String PS = System.getProperty("file.separator");
diretorio = cliente.getCusto().getVcdescriacao_cc();
if(diretorio.contains("/")){
diretorio = diretorio.replaceAll("/", "_");
cliente.getDocumento().setCaminho(diretorio);
}
ftp.cwd("/DigitalNew/"+cliente.getNome()+"/"+diretorio+"/"+cliente.getDocumento().getNumLote());
larquivos = ftp.listNames();
if(larquivos != null){
//String caminho = System.getProperty("user.dir");
FacesContext fc = FacesContext.getCurrentInstance();
ServletContext sc = (ServletContext) fc.getExternalContext().getContext();
String realpath = sc.getRealPath(File.separator+"temp");
fio = new FileOutputStream(realpath+PS+larquivos[0]);
ftp.retrieveFile(larquivos[0], fio);
}
}
} catch(Exception e){
System.out.println("erro metodo buscaDocumentoFtp()"+e.getMessage());
} finally{
try{
ftp.disconnect();
fio.flush();
fio.close();
}catch(Exception e){
System.out.println();
}
}
return larquivos[0];
}
public static List<String> listaDocsFTP() throws IOException{
FTPClient ftp = new FTPClient();
String[] larquivos = null;
List<String> listaDocs = null;
try{
ftp.connect("server");
if(FTPReply.isPositiveCompletion(ftp.getReplyCode())){
ftp.login("user", "senha");
larquivos = ftp.listNames("/teste/teste2");
larquivos = ftp.listNames();
listaDocs = Arrays.asList(larquivos);
}
}catch(Exception e){
System.out.println("erro no metodo listaDocsFTP()"+e.getMessage());
} finally {
ftp.disconnect();
}
return listaDocs;
}
/**
* Metodo que busca o docuemnto dentro da pasta do servidor de aplicção
* @param arquivo
* @return
*/
public List<Cliente> buscaDocumento(String arquivo){
Cliente cliente = new Cliente();;
List<Cliente> ldoc = null;
File file = null;
try{
FacesContext fc = FacesContext.getCurrentInstance();
ServletContext sc = (ServletContext) fc.getExternalContext().getContext();
String realpath = sc.getRealPath(File.separator+"temp");
//String caminho = System.getProperty("user.home");
file = new File(realpath);
File[] arquivos = file.listFiles();
String[] caminho = arquivos[0].toString().split("webapps");
ldoc = new ArrayList<Cliente>();
cliente.getDocumento().setCaminho(caminho[1]);
ldoc.add(cliente);
}catch(Exception e){
System.out.println(""+e.getMessage());
} finally {
}
return ldoc;
}
public void NextList(){
String docs[] = session.getDocumentos();
Documento documento = new Documento();
List<String> ldocs = Arrays.asList(docs);
@SuppressWarnings("unused")
int index = 0;
try{
for(int i = 0; i<ldocs.size(); i++){
if(ldocs.get(i).equals("")){
index = i+1;
documento = new Documento();
documento.setNome(ldocs.get(i+1));
System.out.println(documento.getNome());
break;
}
}
} catch(ArrayIndexOutOfBoundsException e){
System.out.println("ultimo item da lista");
}
}
/**
* Metodo que quebra a string no do documento
* @param documento
*/
public Documento explodeString(Cliente cliente){
String nome = cliente.getDocumento().getNome();
if(nome.contains("_")){
String[] separador = nome.split("_");
String codigoDoc = separador[0];
String codDelta = separador[1];
String[] separador2 = codDelta.split("\\.");
String novoCodDelta = separador2[0];
cliente.getDocumento().setCodDocumento(codigoDoc);
cliente.getDocumento().setCoddelta(novoCodDelta);
}
return cliente.getDocumento();
}
/**
* Movendo o arquivo para o diretorio real, e apagando no FTP
* @param arquivo
* @param cliente
* @throws SocketException
* @throws IOException
*/
public void apagaArquivoFtp(Cliente cliente) throws SocketException, IOException{
FTPClient ftp = new FTPClient();
String diretorio;
try{
ftp.connect("server");
if(FTPReply.isPositiveCompletion(ftp.getReplyCode())){
ftp.login("user", "senha");
ftp.enterLocalPassiveMode();
diretorio = cliente.getCusto().getVcdescriacao_cc();
if(diretorio.contains("/")){
diretorio = diretorio.replaceAll("/", "_");
cliente.getDocumento().setCaminho(diretorio);
}
ftp.cwd("/DigitalNew/"+cliente.getNome()+"/"+diretorio+"/"+cliente.getDocumento().getNumLote());
ftp.deleteFile(cliente.getDocumento().getNome());
}
} catch(Exception e){
System.out.println();
}finally{
ftp.disconnect();
}
}
[color=darkblue]public static void apagaArquivoServidor(Cliente cliente) throws IOException{[/color]
File file = null;
//System.exit(0);
FacesContext fc = FacesContext.getCurrentInstance();
ServletContext sc = (ServletContext) fc.getExternalContext().getContext();
String realpath = sc.getRealPath(File.separator+"temp");
[color=darkred]file = new File("C:\\Projetos Eclipse\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\DigitalizacaoApp\\temp\\"+cliente.getDocumento().getNome());//realpath+File.separator+cliente.getDocumento().getNome());
file.getName();[/color]
boolean sucess = file.delete();
}
/**
* Movendo arquivos que nao foram indexado para um novo diretorio.
* @param cliente
* @return
*/
public Cliente moverNaoIndexado(Cliente cliente){
FTPClient ftp = new FTPClient();
FileInputStream arqEnviar = null;
String diretorio;
try {
ftp.connect("server");
if(FTPReply.isPositiveCompletion(ftp.getReplyCode())){
ftp.login("user", "senha");
ftp.enterLocalPassiveMode();
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.setFileTransferMode(FTP.BINARY_FILE_TYPE);
FacesContext fc = FacesContext.getCurrentInstance();
ServletContext sc = (ServletContext) fc.getExternalContext().getContext();
String realpath = sc.getRealPath(File.separator+"temp");
diretorio = cliente.getCusto().getVcdescriacao_cc();
if(diretorio.contains("/")){
diretorio = diretorio.replaceAll("/", "_");
cliente.getDocumento().setCaminho(diretorio);
}
ftp.changeWorkingDirectory("/Nao_Indexado");
ftp.makeDirectory(cliente.getNome());
ftp.changeWorkingDirectory(cliente.getNome());
ftp.makeDirectory(diretorio);
ftp.changeWorkingDirectory(diretorio);
ftp.makeDirectory(cliente.getDocumento().getNumLote());
File file = new File(realpath+File.separator+cliente.getDocumento().getNome());
arqEnviar = new FileInputStream(file);
boolean sucess = ftp.storeFile(cliente.getDocumento().getNome(), arqEnviar);
if(sucess){
System.out.println("ok");
}else{
System.out.println("fail!!");
}
}
} catch(Exception e){
System.out.println(e.getMessage());
} finally{
try {
arqEnviar.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return cliente;
}
/**
* Movendo aquivos para o novo diretorio
* @param cliente
* @return
*/
public Cliente moverArquivo(Cliente cliente){
FTPClient ftp = new FTPClient();
FileInputStream arqEnviar = null;
String diretorio;
try {
ftp.connect("server");
if(FTPReply.isPositiveCompletion(ftp.getReplyCode())){
ftp.login("user", "senha");
ftp.enterLocalPassiveMode();
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.setFileTransferMode(FTP.BINARY_FILE_TYPE);
FacesContext fc = FacesContext.getCurrentInstance();
ServletContext sc = (ServletContext) fc.getExternalContext().getContext();
String realpath = sc.getRealPath(File.separator+"temp");
diretorio = cliente.getCusto().getVcdescriacao_cc();
if(diretorio.contains("/")){
diretorio = diretorio.replaceAll("/", "_");
cliente.getDocumento().setCaminho(diretorio);
}
ftp.changeWorkingDirectory("/DigitalNew");
ftp.changeWorkingDirectory("Movidos");
ftp.makeDirectory(cliente.getNome());
ftp.changeWorkingDirectory(cliente.getNome());
ftp.makeDirectory(diretorio);
ftp.changeWorkingDirectory(diretorio);
ftp.makeDirectory(cliente.getDocumento().getNumLote());
ftp.makeDirectory(cliente.getDocumento().getNumLote());
File file = new File(realpath+File.separator+cliente.getDocumento().getNome());
arqEnviar = new FileInputStream(file);
boolean sucess = ftp.storeFile(cliente.getDocumento().getNome(), arqEnviar);
if(sucess){
System.out.println("ok");
}else{
System.out.println("fail!!");
}
}
} catch(Exception e){
System.out.println(e.getMessage());
} finally{
try {
ftp.disconnect();
arqEnviar.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return cliente;
}
/**
* Retorna a quantidade de paginas de um arquivo PDF
* @param tp
* @return
*/
/**
* Salva dados do documento indexado
* @param cliente
*/
public void salvarDocumento(Cliente cliente){
try {
DocumentoDAO documentoDAO = new DocumentoDAO();
documentoDAO.salvar(cliente);
} catch(Exception e){
System.out.println(e.getMessage());
}
}
}
obrigado pessoal…