Galera,
com estudo e ajuda de membros do GUJ consegui chegar a esse ponto que eu estarei passando o código abaixo.
Criei o web service e o cliente. Meu objetivo é, como cliente, enviar um arquivo.txt, .xml para o web service e, do lado do web service, pegar este arquivo e grava-lo em outro diretorio na maaquina, e nao estou conseguindo concluir este passo
Quem puder me ajudar abaixo vai o código de meu web service (Calculator.java) e de meu cliente (UseWS.java)
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import javax.activation.DataHandler;
import javax.xml.soap.SOAPException;
import org.apache.axis.MessageContext;
import org.apache.axis.attachments.AttachmentPart;
import org.apache.log4j.Logger;
/**
* @author Rafael
*
*/
public class Calculator {
private static final String DIRETORIO_DAS_IMAGENS = "C:\Projetos\TesteWebServiceAXIS\arquivo\";
public int somar(int numA, int numB) {
return numA + numB;
}
public int subtrair(int numA, int numB) {
return numA - numB;
}
public int multiplicar(int numA, int numB) {
return numA * numB;
}
public int dividir(int numA, int numB) {
if (numB != 0) {
return numA / numB;
}
return 0;
}
public void armazenaArquivo(int id) throws Exception {
try {
// TODO este método esta usando a api do axis para retirar o
// attachment...
Iterator attachment = MessageContext.getCurrentContext()
.getCurrentMessage().getAttachments();
// Se a mensagem não tiver nem um anexo só irá fazer o log e
// retornar
if (!attachment.hasNext()) {
Logger.getRootLogger().info("Nenhum arquivo anexado " +id);
return;
}
// extraindo da mensagem soap apenas a primeira attachment part, já
// que
// só poderá ser enviada um arquivo por id
AttachmentPart attachmentPart = (AttachmentPart) attachment.next();
// verificando se o contentType do anexo é válido
String contentType = attachmentPart.getContentType();
if (!contentTypeValido(contentType)) {
throw new Exception("Content-type inválido ("
+ contentType + ").");
}
// TODO lembrar que o axis esta gravando os anexos automaticamente
// na
// pasta attachments...
// TODO tratar as excessões, por enquanto fica tudo como .txt mesmo
String extensao = ".txt";
String nomeDoArquivo = DIRETORIO_DAS_IMAGENS + id + extensao;
FileOutputStream fileOutputStream = new FileOutputStream(
nomeDoArquivo);
DataHandler dataHandler = attachmentPart.getDataHandler();
dataHandler.writeTo(fileOutputStream);
// attachmentPart.detachAttachmentFile();
// new java.io.File(dataHandler.gerName()).renameTo(new
// java.io.File(nomeDoArquivo));
Logger
.getRootLogger()
.info(
"armazenando novo arquivo de texto anexo. Nome do arquivo: nomeDoArquivo + extensao");
} catch (SOAPException e) {
throw new Exception(e.getMessage());
} catch (FileNotFoundException e) {
throw new Exception(e.getMessage());
} catch (IOException e) {
throw new Exception(e.getMessage());
}
}
/*
* public void recebeArquivo(FileInputStream arquivoRecebido) {
*
* try {
*
* while (true) { InputStreamReader readerArquivoRecebido = new
* InputStreamReader( arquivoRecebido); BufferedReader bufferArquivoRecebido =
* new BufferedReader( readerArquivoRecebido);
*
* String linha = bufferArquivoRecebido.readLine(); if (linha == null) {
* break; } System.out.println("Linha lida do arquivo recebido:\t" + linha);
* FileOutputStream os = new
* FileOutputStream("C:\Projetos\TesteWebServiceAXIS\arquivo\arquivoGerado.txt");
* PrintWriter printer = new PrintWriter(os, true); printer.println(linha);
* System.out.println("Linha copiada do arquivoGeradao -> arquivo:\t" +
* printer.toString()); }// fim while } catch (FileNotFoundException e) { //
* TODO Auto-generated catch block System.out.println("Exceção gerada:\t" +
* e.getMessage()); e.printStackTrace(); } catch (IOException ex) { // TODO
* Auto-generated catch block System.out.println("Exceção gerada:\t" +
* ex.getMessage()); ex.printStackTrace(); } }
*/
private boolean contentTypeValido(String contentType) {
// TODO Auto-generated method stub
// adicionar neste arrayList os contentTypeValidos
ArrayList<String> contentTypeValidos = new ArrayList<String>();
contentTypeValidos.add("arquivo/jpg");
return contentTypeValidos.contains(contentType);
}
}
e agora meu cliente
import java.io.IOException;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import localhost.axis.Calculator_jws.Calculator;
import localhost.axis.Calculator_jws.CalculatorProxy;
import localhost.axis.Calculator_jws.CalculatorService;
import localhost.axis.Calculator_jws.CalculatorServiceLocator;
import localhost.axis.Calculator_jws.CalculatorSoapBindingStub;
import org.apache.axis.client.Call;
/**
* @author Rafael
*
*/
public class UseWS {
public static void main(String args[]) throws IOException {
try {
CalculatorService service = new CalculatorServiceLocator();
Calculator calc = service.getCalculator();
CalculatorProxy cProxy = new CalculatorProxy();
//tratamento do envio do arquivo
CalculatorServiceLocator leitorXmlServiceLocator = new CalculatorServiceLocator();
java.net.URL endpoint = new java.net.URL(cProxy.getEndpoint());
CalculatorSoapBindingStub leitorXmlSoapBindingStub = new CalculatorSoapBindingStub(
endpoint, leitorXmlServiceLocator);
DataHandler attachmentFile = new DataHandler(new FileDataSource(
"C:\Projetos\TesteWebServiceAXIS\arquivo.txt"));
leitorXmlSoapBindingStub._setProperty(
Call.ATTACHMENT_ENCAPSULATION_FORMAT,
Call.ATTACHMENT_ENCAPSULATION_FORMAT_MIME);
leitorXmlSoapBindingStub.addAttachment(attachmentFile);
System.out.println("SOMA = " + calc.somar(2, 2) +"\t\t"
+ "SUBTRAIR = " + calc.subtrair(3, 2) +"\t\t"
+ "MULTIPLICAR = " + calc.multiplicar(3, 3)+"\t\t"
+ "DIVIDIR = " + calc.dividir(4, 2));
System.out
.println("Endpoint getEndpoint(localização do Web Service:\t"
+ cProxy.getEndpoint());
System.out.println("chamando método armazenaArquivo ... ");
calc.armazenaArquivo(6082);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
abraços