cancel
Showing results for 
Search instead for 
Did you mean: 

Error in Adapter Module to unzip files

ralf_zimmerningkat3
Participant
0 Kudos

Hello ,

I wish to unzip many files with use of an adapter module

To du this I use following code


package de.lsv.moduledevelopement;
import java.io.*;
import java.util.Hashtable;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.ejb.CreateException;

import com.sap.aii.af.mp.module.Module;
import com.sap.aii.af.mp.module.ModuleContext;
import com.sap.aii.af.mp.module.ModuleData;
import com.sap.aii.af.mp.module.ModuleException;
import com.sap.aii.af.ra.ms.api.Message;
import com.sap.aii.af.ra.ms.api.MessageDirection;
import com.sap.aii.af.ra.ms.api.Payload;
import com.sap.aii.af.ra.ms.spi.Trace;
import com.sap.aii.af.service.auditlog.Audit;
import com.sap.aii.af.service.auditlog.AuditDirection;
import com.sap.aii.af.service.auditlog.AuditLogStatus;
import com.sap.aii.af.service.auditlog.AuditMessageKey;

/**
 * @ejbLocal <{de.lsv.moduledevelopement.UnZipFilesLocal}>
 * @ejbLocalHome <{de.lsv.moduledevelopement.UnZipFilesLocalHome}>
 * @stateless 
 */
public class UnZipFilesBean implements SessionBean, Module {

	static AuditMessageKey amk = null;
	static String auditStr = "UnzipFilesBean - ";
	static ModuleException mEx = null;

	public static final String VERSION_ID =
		"$Id://de.lsv.moduledevelopement.UnZipFilesBean.java#1 $";

	private static final Trace TRACE = new Trace(VERSION_ID);
	public void ejbRemove() {
	}

	public void ejbActivate() {
	}

	public void ejbPassivate() {
	}

	public void setSessionContext(SessionContext context) {
		myContext = context;
	}

	private SessionContext myContext;
	/**
	 * Create Method.
	 */
	public void ejbCreate() throws CreateException {
		// TODO : Implement
	}

	/* (non-Javadoc)
	 * @see com.sap.aii.af.mp.module.Module#process(com.sap.aii.af.mp.module.ModuleContext, com.sap.aii.af.mp.module.ModuleData)
	 */
	public ModuleData process(
		ModuleContext moduleContext,
		ModuleData inputModuleData)
		throws ModuleException {
		Object obj = null;
		Message msg = null;
		Payload attachment = null;
		//initializing variables for module parameters
		String modkey = "";
		String fileMask = "";
		String directory = "";
		String saveDirectory = "";
		//	String newMimeType = "";
		//	String newAttachmentName = "";
		//	String newAttachmentExtension = "";
		//	String newAttachmentNameReplace = "";
		//this block is to manage the adapter when is not file/FTP
		try {
			//get the XI Message
			obj = inputModuleData.getPrincipalData();
			msg = (Message) obj;
			// create AuditMessageKey object to write audit log.
			if (msg.getMessageDirection() == MessageDirection.INBOUND)
				amk =
					new AuditMessageKey(
						msg.getMessageId(),
						AuditDirection.INBOUND);
			else
				amk =
					new AuditMessageKey(
						msg.getMessageId(),
						AuditDirection.OUTBOUND);
			// ******start get the module parameters from the configuration******
			modkey = moduleContext.getContextData("module.key");
			Audit.addAuditLogEntry(
				amk,
				AuditLogStatus.SUCCESS,
				auditStr + "Module Configuration Key: " + modkey);
			//***** einlesen der Moduke Parameter******************
			//***** DateiMaske
			fileMask = moduleContext.getContextData("FileMask");
			Audit.addAuditLogEntry(
				amk,
				AuditLogStatus.SUCCESS,
				auditStr + "FileMask: " + fileMask);

			// check ob fileMask definiert ist
			if (fileMask == null || fileMask.equalsIgnoreCase("")) {
				//if no attachment name is specified in the module configuration the module will end the execution
				throw mEx =
					new ModuleException(
						auditStr
							+ "!FileMask in Modulconfiguration nicht definiert!");
			}

			//***** DateiMaske2
			String fileMask2 = moduleContext.getContextData("FileMask2");
			Audit.addAuditLogEntry(
				amk,
				AuditLogStatus.SUCCESS,
				auditStr + "FileMask2: " + fileMask2);

			//***** Directory
			directory = moduleContext.getContextData("Directory");
			Audit.addAuditLogEntry(
				amk,
				AuditLogStatus.SUCCESS,
				auditStr + "Directory: " + directory);

			// Fehler wenn Directory nicht definiert
			if (directory == null || directory.equalsIgnoreCase("")) {
				//the module will end the execution
				throw mEx =
					new ModuleException(
						auditStr
							+ "Directory in Modulconfiguration nicht definiert");
			}
			//***** Sicherungs Verzeichnis
			saveDirectory = moduleContext.getContextData("SaveDirectory");
			Audit.addAuditLogEntry(
				amk,
				AuditLogStatus.SUCCESS,
				auditStr + "SaveDirectory: " + saveDirectory);

			// entpacken aufrufen

			entpacke(directory, saveDirectory, fileMask);
			if (fileMask2.length() > 0) {
				entpacke(directory, saveDirectory, fileMask2);
			}

			//update the XI Message
			inputModuleData.setPrincipalData(msg);
		} catch (Exception e) {
			String errorMessage =
				auditStr + "Error bei der . Exception:" + e.getMessage();
			Audit.addAuditLogEntry(amk, AuditLogStatus.ERROR, errorMessage);
			throw mEx = new ModuleException(auditStr + errorMessage);
		}
		Audit.addAuditLogEntry(
			amk,
			AuditLogStatus.SUCCESS,
			auditStr + "Verarbeitung beendet ");
		return inputModuleData;
	}

	//+++++++++++++++++++++++++
	private static void entpacke(
		String directory,
		String saveDirectory,
		String mask)
		 {
		// TODO Auto-generated method stub
		Audit.addAuditLogEntry(
			amk,
			AuditLogStatus.SUCCESS,
			auditStr + "Funktion entpacke");
		if (!directory.endsWith("\")) {
			directory = directory + "\";
		} // if
		File f;
		f = new File(directory);
		Audit.addAuditLogEntry(
			amk,
			AuditLogStatus.SUCCESS,
			auditStr + "f = new File(directory)");
//		// Achtung Klasse in einer Klasse :-)
//		String[] strFiles = f.list(new FilenameFilter() {
//			public boolean accept(File file, String filename) {
//				Wildcard wildcard1 = new Wildcard(mask);
//				Audit.addAuditLogEntry(
//					amk,
//					AuditLogStatus.SUCCESS,
//					auditStr + "wc1");
//				return wildcard1.match(filename, false);
//			}
//		});

		String [] strFiles = f.list(new MyFilter(mask));

		// Liste der Gefundenen dateien
		Audit.addAuditLogEntry(
			amk,
			AuditLogStatus.SUCCESS,
			auditStr + "Anzahl gepackter Dateien: " + strFiles.length);

		//System.out.println( strFiles.length + " Dateien zum entpacken");
		for (int i = 0; i < strFiles.length; i++) {
			Audit.addAuditLogEntry(
				amk,
				AuditLogStatus.SUCCESS,
				auditStr + "verarbeite Datei: : " + strFiles<i>);
			//	System.out.println("f[" + i + "]=" + strFiles<i>);
		} // for

		// *****entpacken**********************
		for (int i = 0; i < strFiles.length; i++) {
			try {

				byte[] buf = new byte[4096];
				ZipInputStream in =
					new ZipInputStream(
						new FileInputStream(directory + strFiles<i>));

				Audit.addAuditLogEntry(
					amk,
					AuditLogStatus.SUCCESS,
					auditStr + "Entpacke " + directory + strFiles<i>);
				//System.out.println("Entpacke " + directory + strFiles<i>);
				int count = 0;
				while (true) {
					count++;
					// Nächsten Eintrag lesen
					ZipEntry entry = in.getNextEntry();
					if (entry == null) {
						break;
					}
					// Beschreibung ausgeben

					Audit.addAuditLogEntry(
						amk,
						AuditLogStatus.SUCCESS,
						auditStr + entry.getName());
					//System.out.println(entry.getName());
					// Ausgabedatei erzeugen
					FileOutputStream out =
						new FileOutputStream(directory + entry.getName());
					int len;
					while ((len = in.read(buf)) > 0) {
						out.write(buf, 0, len);
					}
					out.close();
					// Eintrag schließen
					in.closeEntry();
				} // while
				in.close();
				Audit.addAuditLogEntry(
					amk,
					AuditLogStatus.SUCCESS,
					auditStr + count + "Dateien entpackt");
				//System.out.println(count + "Dateien entpackt");

				// verschieben
				if (saveDirectory.length() > 0) {
					File quelle = new File(directory + strFiles<i>);
					File ziel = new File(saveDirectory + strFiles<i>);
					boolean bla = quelle.renameTo(ziel);
					if (!bla) {
						Audit.addAuditLogEntry(
							amk,
							AuditLogStatus.SUCCESS,
							auditStr
								+ strFiles<i>
								+ " konnte nicht verschoben werden");
					} else {
						Audit.addAuditLogEntry(
							amk,
							AuditLogStatus.SUCCESS,
							auditStr
								+ strFiles<i>
								+ "verschoben nach "
								+ saveDirectory);

						//		System.out.println(
						//			strFiles<i> + "verscgoben nach " + directory + "sik//");
					}
				} // if

			} catch (Exception e) {
				String errorMessage =
					auditStr
						+ "Error in entpacken. Exception:"
						+ e.getMessage();
				Audit.addAuditLogEntry(amk, AuditLogStatus.ERROR, errorMessage);
			} // catch

			// *****entpacken*************
		} // for

	} //entpacke

} // UnzipFilesBean

class Wildcard {
	
	static AuditMessageKey amk = null;
	static String auditStr = "WildCard - ";
	static ModuleException mEx = null;
	private final String wildcardString;

	/**
	 * Der Konstruktor für die WildcardSuche.
	 * 
	 * @param wildcardString
	 *            Der WildcardString
	 */
	public Wildcard(String wildcardString) {
		this.wildcardString = wildcardString;
		Audit.addAuditLogEntry(
			amk,
			AuditLogStatus.SUCCESS,
			auditStr + "Constructor");

	}

	/**
	 * Die Methode, welche den Vergleich durchführt.
	 * 
	 * @param str
	 *            Der String, welcher darauf überprüft werden soll, ob er dem
	 *            WildcardString entspricht.
	 * @return true Wenn der String dem wildcardString entspricht.
	 */
	public boolean match(String str, boolean fCasesensitive) {
		if (str == null || wildcardString == null) {
			return false;
		}
		return recursiveMatch(wildcardString, str, fCasesensitive);
	}

	/**
	 * Hier wird der eigentliche Vergleich durchgeführt
	 * 
	 * @param strWildcard
	 *            Der Wildcardstring, z.B.: "Test*"
	 * @param str
	 *            Der zu überprüfende String, z.B. "Testlauf"
	 * @return true, wenn eine Übereinstimmung vorhanden ist, sonst false
	 */
	private boolean recursiveMatch(
		String strWildcard,
		String str,
		boolean fCasesensitive) {
		while (true) {
			if (strWildcard.length() == 0)
				return str.length() == 0;
			char ch = strWildcard.charAt(0);
			switch (ch) {
				case '?' :
					if (str.length() == 0)
						return false;
					break;
				case '*' :
					strWildcard = strWildcard.substring(1);
					while (true) {
						if (recursiveMatch(strWildcard, str, fCasesensitive))
							return true;
						if (str.length() == 0)
							return false;
						str = str.substring(1);
					}
				default :
					if (str.length() == 0)
						return false;
					if (fCasesensitive) {
						if (ch != str.charAt(0))
							return false;
					} else if (
						Character.toLowerCase(ch)
							!= Character.toLowerCase(str.charAt(0)))
						return false;
					break;
			}
			strWildcard = strWildcard.substring(1);
			str = str.substring(1);
		}
	}

	//++++++++++++++++++++++++++

} // class

/** Nun der eigentliche Filter */
class MyFilter implements FilenameFilter {
	
	static AuditMessageKey amk = null;
	static String auditStr = "MyFilter - ";
	static ModuleException mEx = null;

	
	String fileMask;

	public MyFilter(String fileMask) {
		this.fileMask = fileMask;
		Audit.addAuditLogEntry(
			amk,
			AuditLogStatus.SUCCESS,
			auditStr + "Constructor");
	} //constructor

	 public boolean accept(File file, String filename) {
		// TODO Auto-generated method stub
		//fileMask = "?5LBL*";
		Wildcard wildcard1 = new Wildcard(fileMask);
		return wildcard1.match(filename, false);
	}
} //class

But in Audit Protocol it failed after:

17.09.2008 17:33:19 Erfolgreich UnzipFilesBean - Module Configuration Key: 2

17.09.2008 17:33:19 Erfolgreich UnzipFilesBean - FileMask: ?5LBL???

17.09.2008 17:33:19 Erfolgreich UnzipFilesBean - FileMask2:

17.09.2008 17:33:19 Erfolgreich UnzipFilesBean - Directory: //transfer//X1E//100//99//lb//ein

17.09.2008 17:33:19 Erfolgreich UnzipFilesBean - SaveDirectory: //transfer//X1E//100//99//lb//ein_s

17.09.2008 17:33:19 Erfolgreich UnzipFilesBean - Funktion entpacke

17.09.2008 17:33:19 Erfolgreich UnzipFilesBean - f = new File(directory)

17.09.2008 17:33:19 Fehler UnzipFilesBean - Error bei der . Exception:null

I could not find the error??

Were there any log files to look into?

regarts

Zimmerningkat

Accepted Solutions (0)

Answers (5)

Answers (5)

ralf_zimmerningkat3
Participant
0 Kudos

I found the error!

If your xi system is on unix you have to

describe the path in this way

/xxx/xx/

now adapter module works, on file will be read form xi and all other files in the directory describet in mask will be unziped.

regarts

former_member181985
Active Contributor
0 Kudos

Hi Ralf,

Can you brief your scenario requirement?

Lets look into technical implementation aspects later......

Thanks,

Gujjeti.

ralf_zimmerningkat3
Participant
0 Kudos

Hi, Gujjeti

there are par example 3 files file 1 named xml1 is an zip file which discribe pictures. this file will bee pickt up by xi and processed with payloadzipbean.

file 2 named jpgzip1 and file3 named jpgzip2 were also zip files with many jpg files.

in message mapping xi had to read the unpacked jpg files!

former_member181985
Active Contributor
0 Kudos

Hi Ralf,

I am late..........

I am bit confused with your explanation.

1. Does all zip files will be picked by file adapter in one shot or is it conditional, since you have a XML descriptor file in firts zip file and the XML files describes the list of JPEG files which might be stored in the other zipped JPEG files?

2. Can you tell the exact flow of your scenario

3. Receiver in your scenario?

Thanks,

Gujjeti.

madhusudana_reddy2
Contributor
0 Kudos

Hi,

Go to the server check the folder with name "log" and check for latest log file.

the path will appear like

usr/sap/"ur system id"/DVEBMGS01/j2ee/cluster/server/log

thanks,

madhusudhan.

former_member192295
Active Contributor
0 Kudos

Hi,

Check this link will help u

bhavesh_kantilal
Active Contributor
0 Kudos

Why not use the standard module from SAP - "PayloadZipBean".

Stefan Grube has written a excellent blog on this, accessible here,

Regards,

Bhavesh

ralf_zimmerningkat3
Participant
0 Kudos

@ Bhavesh

PayloadZipBean dosn't fit,

we have to unzip many files for on message.

we try to use bs command but if this fail do to corrupt zip file there is no return code to the adaper and we could not stop processing ?

bhavesh_kantilal
Active Contributor
0 Kudos

Hello Ralf,

I have not tried this, but if I understand how the zip module works, you should be able to use PayloadZipBean the attachments.

XI would treat each individual file as a Attachment and then you write a custom module to just add these Attachments into the main payload so that they are accessible within the mapping and so on.

Will try to use the PayloadZipBean in the unzip mode and see if they attachments are created and if yes, then you just need to worry abt writing the module to read the attachment and create a generic main payload and so on.

Regards,

Bhavesh

ralf_zimmerningkat3
Participant
0 Kudos

Hi, Bhavesh

I Dont want to use the files in mapping i only want to unzip the files.

Before use of Adapter Module i use BS Command for this but

BS Command have the problem if it failed i could not stop the message processing !

bhavesh_kantilal
Active Contributor
0 Kudos

Ralf,

Few questions,

1. What is the BS command?

2. What do you mean when you say you want to only Unzlip files? What happens after XI picks up the files, unzips them using the BS command / Adapter Module? What is the end to end interface flow?

I will not be of much help with the Adapter Module code, but I will definitely try to see if there are options to use the PayloadZipBean and then extend the solution to meet your actual requirements.

Regards,

Bhavesh

ralf_zimmerningkat3
Participant
0 Kudos

Hello Bhavesh

we have to process many pictures in zip-files and one xml file.

so xi picks up the xml file and have to unzip all other files!

the xml file has an field with the name of the jpg.file, an so xi will pick up this jpg convert to base64 and process.

BS Command could unzip this picture zips but if BS Command have any probems with the zip-files

xi would try to process and give an mapping error if an picture was not unzippt.

We wish to stop processing if zip faild before mapping!

Former Member
0 Kudos