on 02-01-2013 5:02 PM
Ola pessoal.
Estou tentando pegar um arquivo zip q esta em base64 dentro desse xml.
<?xml version="1.0" encoding="UTF-8" ?>
- <ns0:mt_csa_source xmlns:ns0="urn:empresa.com:OU030:csa-fi">
- <rset>
- <row>
<FIELD>UEsDBAoAAAAAANZzOUJ1Y8G+GwAAABsAAAAKAAAAYXR0YWNoLnR4dEluZm9ybWF6aW9uZQ0KSW5mb3JtYXppb25lMlBLAQI/AAoAAAAAANZzOUJ1Y8G+GwAAABsAAAAKACQAAAAAAAAAIAAAAAAAAABhdHRhY2gudHh0CgAgAAAAAAABABgAwHajjgj7zQHAdqOOCPvNARiqbMkQ+s0BUEsFBgAAAAABAAEAXAAAAEMAAAAAAA==</FIELD>
</row>
</rset>
</ns0:mt_csa_source>
eu pego o conteudo do campo FIELD e decodifico para um array de byte, poré nos logs me da esse erro:
Adapter Framework caught exception: Exception in XML Parser (format problem?):'org.xml.sax.SAXParseException: Character reference "" is an invalid XML character.'
Tentei mudar a versao do xml para 1.1, porém me da outro erro.
Alguém ai sabe oq pode estar acontecendo e como pode ser resolvido?
Valeu.
Bom dia Devaney,
A primeira coisa que provavelmente já devem ter te perguntado é: porque raios alguém está codificando pra base64 um zip? Isso tem cheiro de gambiarra desnecessária.
De qualquer forma, não entendi direito o seu cenário.
Posta o seu código, a entrada e o ponto onde o erro ocorre. Talvez aí consigamos entender.
Um abraço!
Waldemar
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Eu tb acho q deve ser uma gambiarra. To dando uma mao p um colega.
O sender faz o trabalho dele (pega o arquivo transforma em base64 e coloca dentro do xml.
No final c o receiver eu consegui criar o arquivo c o FileInputStream do java.
Agora o problema é outro, no receiver eu preciso pegar o nome do arquivo tb. Eu até consegui achar uma propriedade q me da um nome de arquivo, mas parece um nome aleatorio, tipo AYORAKMF.txt, eu quero o nome original do arquivo.
Se alguém tiver uma sugestao melhor eu aceito.
Aqui vai o codigo:
/**
*
*/
package com.sap.utils.n4n.payloadEncoder;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.rmi.RemoteException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.ejb.TimedObject;
import javax.ejb.Timer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;
import com.n4n.std.FileManager;
import com.sap.aii.af.lib.mp.module.ModuleContext;
import com.sap.aii.af.lib.mp.module.ModuleData;
import com.sap.aii.af.lib.mp.module.ModuleException;
import com.sap.aii.af.service.cpa.BinaryData;
import com.sap.aii.af.service.cpa.CPAException;
import com.sap.aii.af.service.cpa.CPAObjectNotFoundException;
import com.sap.aii.af.service.cpa.CPAObjectType;
import com.sap.aii.af.service.cpa.Channel;
import com.sap.aii.af.service.cpa.LookupManager;
import com.sap.aii.mapping.api.DynamicConfiguration;
import com.sap.aii.mapping.api.DynamicConfigurationKey;
import com.sap.aii.mapping.api.StreamTransformationConstants;
import com.sap.aii.mappingtool.tf7.rt.Container;
import com.sap.engine.interfaces.messaging.api.Message;
import com.sap.engine.interfaces.messaging.api.MessageDirection;
import com.sap.engine.interfaces.messaging.api.MessageKey;
import com.sap.engine.interfaces.messaging.api.MessagePropertyKey;
import com.sap.engine.interfaces.messaging.api.PublicAPIAccessFactory;
import com.sap.engine.interfaces.messaging.api.XMLPayload;
import com.sap.engine.interfaces.messaging.api.auditlog.AuditAccess;
import com.sap.engine.interfaces.messaging.api.auditlog.AuditLogStatus;
import com.sap.engine.messaging.impl.util.base64.Base64;
import com.sap.tc.logging.Location;
public class OurPayload implements SessionBean, TimedObject{
/**
*
*/
private static final long serialVersionUID = 1L;
private SessionContext myContext;
private static final String M_NAME = "PayloadEncoderEx: ";
private Location location = null;
private AuditAccess audit = null;
private ModuleContext mc;
static String regexMask = "";
public void ejbActivate() throws EJBException, RemoteException {
}
public void ejbPassivate() throws EJBException, RemoteException {
}
public void ejbRemove() throws EJBException, RemoteException {
}
public void setSessionContext(SessionContext context) {
myContext = context;
}
public void ejbTimeout(Timer arg0) {
}
public void afterBegin() throws EJBException, RemoteException {
}
public void afterCompletion(boolean arg0) throws EJBException,
RemoteException {
}
public void beforeCompletion() throws EJBException, RemoteException {
}
public void ejbCreate() throws javax.ejb.CreateException {
}
@SuppressWarnings("deprecation")
public ModuleData process(ModuleContext moduleContext,
ModuleData inputModuleData) throws ModuleException{
String SIGNATURE =
"process(ModuleContext moduleContext, ModuleData inputModuleData)";
mc = moduleContext;
try {
location = Location.getLocation(this.getClass().getName());
} catch (Exception t) {
t.printStackTrace();
ModuleException me = new ModuleException(
"Unable to create trace location", t);
throw me;
}
Object obj = null;
Message msg = null;
MessageKey key = null;
try {
obj = inputModuleData.getPrincipalData();
msg = (Message) obj;
key = new MessageKey(msg.getMessageId(), msg.getMessageDirection());
audit = PublicAPIAccessFactory.getPublicAPIAccess()
.getAuditAccess();
audit.addAuditLogEntry(key, AuditLogStatus.SUCCESS, M_NAME
+ "Module called");
} catch (Exception e) {
ModuleException me = new ModuleException(e);
throw me;
}
if(!msg.getMessageDirection().equals(MessageDirection.INBOUND) &&
!msg.getMessageDirection().equals(MessageDirection.OUTBOUND)){
raise(key, SIGNATURE,
"wrong ccDirection set." +
"Accepted values for pex.ccDirection: 'send'|'recv'");
}
String encoding = moduleContext.getContextData("pex.encoding"); // e.g.
encoding = encoding.trim();
if (encoding == null || encoding.equals("")) {
raise(
key,
SIGNATURE,
"no encoding set. Add the encoding property " +
"'pex.enconding' to the module parameter list.");
}
String fileName = "";
String filenameKey = "";
String pathSrc = "";
String maskFile = "";
String msgType = "";
String nameSpace = "";
Channel ch = null;
try {
ch =
(Channel)LookupManager.getInstance().getCPAObject(
CPAObjectType.CHANNEL, moduleContext.getChannelID());
} catch (CPAObjectNotFoundException e1) {
audit.addAuditLogEntry(key, AuditLogStatus.ERROR, M_NAME
+ " " + e1.getMessage() );
throw new ModuleException(e1.getMessage());
} catch (CPAException e1) {
audit.addAuditLogEntry(key, AuditLogStatus.ERROR, M_NAME
+ " " + e1.getMessage() );
throw new ModuleException(e1.getMessage());
}
if(msg.getMessageDirection().equals(MessageDirection.INBOUND)){
filenameKey = mpget("pex.filenameKey"); // e.g.
// Detect filename
if (filenameKey.equalsIgnoreCase("asma")) {
fileName = getFileName(msg);
audit.addAuditLogEntry(key, AuditLogStatus.SUCCESS , M_NAME
+ " THIS IS ASMA - NEW FILE NAME " + fileName);
}else{
// Do something
}
} else { // send
pathSrc = mpget("pex.sourcePath");
pathSrc = pathSrc.trim();
if (pathSrc == null || pathSrc.equals("")) {
raise(
key,
SIGNATURE,
"no sourcePath set. Add the sourcePath property" +
"'pex.sourcePath' to the module parameter list.");
}
maskFile = mpget("pex.maskFile");
maskFile = maskFile.trim();
if (maskFile == null || maskFile.equals("")) {
raise(
key,
SIGNATURE,
"no maskFile set. Add the maskFileproperty" +
"'pex.maskFile' to the module parameter list.");
}
msgType = mpget("pex.messageType");
msgType = msgType.trim();
if (msgType == null || msgType.equals("")) {
raise(
key,
SIGNATURE,
"no messageType set. Add the messageType property" +
"'pex.messageType' to the module parameter list.");
}
nameSpace = mpget("pex.namespace");
nameSpace = nameSpace.trim();
if (nameSpace == null || nameSpace.equals("")) {
raise(
key,
SIGNATURE,
"no namespace set. Add the namespace property" +
"'pex.namespace' to the module parameter list.");
}
}
if (msg.getMessageDirection()
.equals(MessageDirection.INBOUND)){ //Receiver case (Inbound)
String pathDir =null;
try {
pathDir = ch.getValueAsString("file.targetDir");
} catch (CPAException e1) {
audit.addAuditLogEntry(key, AuditLogStatus.ERROR, M_NAME
+ " " + e1.getMessage() );
throw new ModuleException(e1.getMessage());
}
msg = receiveProcess(msg,
key, encoding, fileName, filenameKey, pathDir);
} else{ //Sender (Outbound) case
audit.addAuditLogEntry(key, AuditLogStatus.SUCCESS, M_NAME);
try {
msg = sendProcess(msg, inputModuleData,
key, encoding, pathSrc, maskFile,
msgType, nameSpace);
} catch (IOException e) {
raise(key, SIGNATURE, e.getMessage());
audit.addAuditLogEntry(key, AuditLogStatus.ERROR, M_NAME
+ e.getMessage());
} catch (Exception e) {
audit.addAuditLogEntry(key, AuditLogStatus.ERROR, M_NAME
+ e.getMessage());
raise(key, SIGNATURE, e.getMessage());
}
}
// Assign new message to AF
inputModuleData.setPrincipalData(msg);
return inputModuleData;
}
/**
* @param msg
* @param key
* @param encoding
* @param fileName
* @param fileNameKey
* @return
*
*
*
* @throws ModuleException
*/
private Message receiveProcess(Message msg,
MessageKey key,
String encoding,
String fileName,
String fileNameKey,
String pathDir)
throws ModuleException {
// extract payload
byte by[] = msg.getDocument().getContent();
byte[] newContent = null;
XMLPayload xmlpayload = msg.getDocument();
// *** Switch on encoding types *** //
// Base64
if (encoding.equalsIgnoreCase("base64")) {
byte[] decodedBinary = null;
String decodedText = null;
DocumentBuilderFactory factory;
factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder=null;
Document document=null;
try {
builder = factory.newDocumentBuilder();
document = builder.parse(
(InputStream) xmlpayload.getInputStream());
} catch (ParserConfigurationException e) {
audit.addAuditLogEntry(key, AuditLogStatus.ERROR, M_NAME
+ e.getMessage());
} catch (SAXException e) {
audit.addAuditLogEntry(key, AuditLogStatus.ERROR, M_NAME
+ e.getMessage());
} catch (IOException e) {
audit.addAuditLogEntry(key, AuditLogStatus.ERROR, M_NAME
+ e.getMessage());
}
Element root = document.getDocumentElement();
Node child = root.getChildNodes().item(0);
while (child.hasChildNodes()){
child = child.getChildNodes().item(0);
}
/* Decode Base64 in String*/
decodedBinary = Base64.decode(child.getNodeValue());
decodedText = new String(decodedBinary);
audit.addAuditLogEntry(key, AuditLogStatus.SUCCESS, M_NAME
+ "This is the content "
+ decodedText);
/*
TransformerFactory tfactory = TransformerFactory.newInstance();
Transformer transformer;
try {
transformer = tfactory.newTransformer();
DOMSource src = new DOMSource(docNew);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
StreamResult dest = new StreamResult(baos);
transformer.transform(src, dest);
newContent = baos.toByteArray();
Result dbg =
new StreamResult(
new File("/usr/sap/mydirectory/tmp/OurIn.zip"));
transformer.transform(src, dbg);
} catch (TransformerConfigurationException e){
audit.addAuditLogEntry(key, AuditLogStatus.ERROR, mName
+ " " + e.getMessage());
}catch (TransformerException e) {
audit.addAuditLogEntry(key, AuditLogStatus.ERROR, mName
+ " " + e.getMessage());
}
*/
File f1 = new File(pathDir + File.separator + fileName);
FileOutputStream fos=null;
try {
fos = new FileOutputStream(f1);
fos.write(decodedBinary);
} catch (FileNotFoundException e) {
audit.addAuditLogEntry(key, AuditLogStatus.ERROR, M_NAME
+ " " + e.getMessage());
} catch (IOException e) {
audit.addAuditLogEntry(key, AuditLogStatus.ERROR, M_NAME
+ " " + e.getMessage());
}finally{
try {
fos.close();
} catch (IOException e) {
audit.addAuditLogEntry(key, AuditLogStatus.ERROR, M_NAME
+ e.getMessage());
}
}
} else
// Zip
if (encoding.equalsIgnoreCase("zip")) {
//ZIP ALL FILES AND SEND IT
}
// Change old message content with the new one
try {
if (newContent != null) {
xmlpayload.setContent(newContent);
}
audit.addAuditLogEntry(key, AuditLogStatus.SUCCESS, M_NAME
+ "Content was correctly dencoded "
+ encoding.toLowerCase());
} catch (Exception e) {
ModuleException me = new ModuleException(e);
throw me;
}
return msg;
}
/**
* @param msg
* @param key
* @param encoding
* @param path
* @param maskFile
* @param messageType
* @param namespace
* @return Restituisce il payload secondo la seguente struttura: <?xml
* version="1.0" encoding="UTF-8"?> <ns0:your_messagetype
* xmlns:ns0="your_namespace"> <rset> <row> <FIELD/> </row> </rset>
* </ns0:your_messagetype>
*
* dove: your_messagetype e' pex.messageType your_namespace e' pex.namespace
* @throws Exception
*/
private Message sendProcess(Message msg, ModuleData inputModuleData,
MessageKey key,
String encoding,
String path,
String maskFile,
String messageType,
String namespace)
throws Exception {
final String SIGNATURE = "sendProcess(ModuleContext moduleContext," +
"ModuleData inputModuleData)";
final String NAMESPACE_URI = namespace;
final String NAMESPACE_PREFIX = "ns0";
String[] files = getFilenames(path, maskFile);
byte[] newContent = null;
Map param =new HashMap();;
DynamicConfigurationKey k1 =
DynamicConfigurationKey.create(
"http://sap.com/xi/XI/System/File", "FileName");
// prepares payload XML structure
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = factory.newDocumentBuilder();
Document dom = docBuilder.newDocument();
Element rootElem = dom.createElementNS(NAMESPACE_URI, NAMESPACE_PREFIX
+ ":" + messageType);
dom.appendChild(rootElem);
Element rsetElem = dom.createElement("rset");
rootElem.appendChild(rsetElem);
for (int i = 0; i < files.length; i++) {
byte[] by = FileManager.readBinaryFile(files[i]);
// *** Switch on encoding types *** //
// Base64
if (encoding.equalsIgnoreCase("base64")) {
audit.addAuditLogEntry(key, AuditLogStatus.SUCCESS, M_NAME
+ "Using filename: " + files[i] + " for base64.");
BinaryData bd = new BinaryData(by);
String b64 = bd.toBase64EncodedString();
// completes XML payload
Element rowElem = dom.createElement("row");
rsetElem.appendChild(rowElem);
Element fieldElem = dom.createElement("FIELD");
Text fieldVal = dom.createTextNode(b64);
fieldElem.appendChild(fieldVal);
rowElem.appendChild(fieldElem);
//
} else {
// Zip
if (encoding.equalsIgnoreCase("zip")) {
audit.addAuditLogEntry(key, AuditLogStatus.SUCCESS, M_NAME
+ "Using filename: " + files[i] + " for zip.");
try {
newContent = zip(files[i], by);
} catch (IOException e) {
raise(key, SIGNATURE, e);
}
}
}
}
// Transforming the DOM object to Stream object.
TransformerFactory tfactory = TransformerFactory.newInstance();
Transformer transformer = tfactory.newTransformer();
DOMSource src = new DOMSource(dom);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
StreamResult dest = new StreamResult(baos);
//transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
//transformer.setOutputProperty(OutputKeys.INDENT,"yes");
transformer.transform(src, dest);
Result dbg =
new StreamResult(new File("/usr/sap/ID6/arch_int/tmp/OUR-LOG.xml"));
transformer.transform(src, dbg);
newContent = baos.toByteArray();
XMLPayload xmlpayload = msg.getDocument();
if (newContent != null) {
xmlpayload.setContent(newContent);
inputModuleData.setPrincipalData(msg);
}
// Change old message content with the new one
try {
//msg.getDocument().setContent(newContent);
audit.addAuditLogEntry(key, AuditLogStatus.SUCCESS, M_NAME
+ "Content correctly encoded using encoding "
+ encoding.toLowerCase());
} catch (Exception e) {
audit.addAuditLogEntry(key, AuditLogStatus.ERROR, M_NAME
+ e.getMessage());
ModuleException me = new ModuleException(e);
throw me;
}
return msg;
}
/**
*
* @param key
* @param SIGNATURE
* @param text
* @throws ModuleException
*/
private void raise(MessageKey key, String SIGNATURE, String text)
throws ModuleException {
audit.addAuditLogEntry(key, AuditLogStatus.ERROR, M_NAME + text);
location.errorT(SIGNATURE, M_NAME + text);
ModuleException me = new ModuleException(M_NAME + text);
throw me;
}
private static String[] getFilenames(String path, String mask) {
String[] files = {};
// converte il mask filename in sintassi regex
regexMask = "(?-i)^"
+ mask.replace(".", "[.]").replace("*", ".*").replace("?", ".")
+ "$";
File d = new File(path);
FilenameFilter ff = new FilenameFilter() {
public boolean accept(File dir, String name) {
Pattern p = Pattern.compile(regexMask);
Matcher m = p.matcher(name);
if (m.find()) {
return true;
}
return false;
}
};
files = d.list(ff);
if (files != null) {
for (int i = 0; i < files.length; i++) {
files[i] = d + File.separator + files[i];
}
}
return files;
}
private void raise(MessageKey key, String SIGNATURE, Exception e)
throws ModuleException {
audit.addAuditLogEntry(key, AuditLogStatus.ERROR, M_NAME
+ e.getMessage());
location.errorT(SIGNATURE, M_NAME + e.getMessage());
ModuleException me = new ModuleException(e);
throw me;
}
public byte[] zip(String unzippedFilename, byte[] content)
throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zop = new ZipOutputStream(baos);
ZipEntry ze = new ZipEntry(unzippedFilename);
zop.putNextEntry(ze);
zop.write(content);
zop.flush();
zop.close();
return baos.toByteArray();
}
/**
* Reads adapter parameter returning "" instead of null
*
* @param param
* @return
*/
private String mpget(String param) {
String tempParam = mc.getContextData(param);
return (tempParam == null ? "" : tempParam);
}
private String getFileName(Message msg) {
String fileName = null;
// Hashtable mp =
// (Hashtable)inputModuleData
// .getSupplementalData("audit.key");
//
// Map param =new HashMap();;
//
// DynamicConfiguration conf =
// (DynamicConfiguration)param.get(
// StreamTransformationConstants.DYNAMIC_CONFIGURATION);
//
// DynamicConfigurationKey k1 =
// DynamicConfigurationKey.create(
// "http://sap.com/xi/XI/System/File", "FileName");
// fileName = conf.get(k1);
// fileName = (String)mp.get("FileName");
fileName =
msg.getMessageProperty("http://sap.com/xi/XI/System/File", "FileName");
return fileName;
}
}
Valeu
User | Count |
---|---|
16 | |
3 | |
2 | |
1 | |
1 | |
1 | |
1 | |
1 | |
1 | |
1 |
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.