Hi Chamikara,

I dont understand why I have error.
I send you files. in the sandesha2.mar, I change the InvokeInOrder.

Thanks a lot,

Regards
Elodie

package fr.gouv.finances.dgme.presto;

import java.io.File;
import java.io.FileInputStream;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.OMText;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.axiom.soap.SOAP12Constants;
import org.apache.axis2.Constants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.client.async.AsyncResult;
import org.apache.axis2.client.async.Callback;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.context.MessageContextConstants;
import org.apache.sandesha2.client.SandeshaClientConstants;


public class PrestoWSRM_MTOMtest extends junit.framework.TestCase{

	static String fileXMLName="test_data_in.xml";
	static String fileNameAttach="fichier.txt";
	private static EndpointReference targetEPR = new EndpointReference("http://localhost:8080/axis2/services/PrestoSvc";);
	private static String targetEPRTcpmon ="http://localhost:8070/axis2/services/PrestoSvc";;
	static String namespace="http://dgme.finances.gouv.fr/presto";;
	private static String CLIENT_REPO_PATH = "RepoClient";
	private static String axis2_xml = CLIENT_REPO_PATH + File.separator +"conf" + File.separator + "axis2.xml";

	/**
	 * Call submitRequestReponse with attachment
	 *
	 */
	public  void testSubmitRequestResponseWSRMAddressable() throws Exception{

		String nameMethod="submit";
		ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(CLIENT_REPO_PATH,axis2_xml);
		ServiceClient serviceClient = new ServiceClient (configContext,null);

		Options options=initOptions("submit",true);
		serviceClient.setOptions(options);
		String acksTo = serviceClient.getMyEPR(Constants.TRANSPORT_HTTP).getAddress();
		options.setProperty(SandeshaClientConstants.AcksTo,acksTo);

		System.out.println("Envoi");
		Callback callback1 = new TestCallback ("Callback 1");
		serviceClient.sendReceiveNonBlocking (getOMBlock("message1","sequence1",nameMethod),callback1);

		while (!callback1.isComplete()) {
			System.out.println("boucle1");
			Thread.sleep(1000);
		}

		Callback callback2 = new TestCallback ("Callback 2");
		serviceClient.sendReceiveNonBlocking(getOMBlock("message2","sequence1",nameMethod),callback2);

		while (!callback2.isComplete()) {
			System.out.println("boucle2");
			Thread.sleep(1000);
		}

		options.setProperty(SandeshaClientConstants.LAST_MESSAGE, "true");
		Callback callback3 = new TestCallback ("Callback 3");
		serviceClient.sendReceiveNonBlocking(getOMBlock("message3","sequence1",nameMethod),callback3);

		while (!callback3.isComplete()) {
			System.out.println("boucle3");
			Thread.sleep(1000);
		}
		System.out.println("Fin du programme");
		Thread.sleep(10000);
		serviceClient.finalizeInvoke();

	}


	/**
	 * Call submitOneWay with attachment
	 *
	 */
	public  void testSubmitOneWayWSRMEmetteurAnonyme() throws Exception {

		String nameMethod="submitOneWay";
		ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(CLIENT_REPO_PATH,axis2_xml);
		ServiceClient sender = new ServiceClient (configContext,null);

		Options options=initOptions("submitOneWay", false);
		sender.setOptions(options);

		System.out.println("Envoi");

		sender.fireAndForget(getOMBlock("","ping1",nameMethod));
		sender.fireAndForget(getOMBlock("","ping2",nameMethod));

		options.setProperty(SandeshaClientConstants.LAST_MESSAGE, "true");
		sender.fireAndForget(getOMBlock("","ping3",nameMethod));

		Thread.sleep(10000);
		System.out.println("\nResult :");
		System.out.println("NO RETURN FOR WEBSERVICE");
		sender.finalizeInvoke();

	}

	public void testSubmitOneWayWSRMEmetteurAdressable() throws Exception {

		String nameMethod="submitOneWay";
		ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(CLIENT_REPO_PATH,axis2_xml);
		ServiceClient sender = new ServiceClient (configContext,null);

		Options options = initOptions("submitOneWay", true);
		String acksTo = sender.getMyEPR(Constants.TRANSPORT_HTTP).getAddress();
		options.setProperty(SandeshaClientConstants.AcksTo,acksTo);
		sender.setOptions(options);

		System.out.println("Envoi");
		Callback callback1 = new TestCallback ("Callback 1");
		sender.sendReceiveNonBlocking(getOMBlock("","ping1",nameMethod),callback1);

		Callback callback2 = new TestCallback ("Callback 2");
		sender.sendReceiveNonBlocking(getOMBlock("","ping2",nameMethod),callback2);

		Callback callback3 = new TestCallback ("Callback 3");
		options.setProperty(SandeshaClientConstants.LAST_MESSAGE, "true");
		sender.sendReceiveNonBlocking(getOMBlock("","ping3",nameMethod),callback3);

		Thread.sleep(10000);
		System.out.println("NO RETURN FOR WEBSERVICE");
		sender.finalizeInvoke();

	}

	private OMElement getOMBlock(String text, String sequenceKey, String nameMethod) throws Exception{

		OMFactory fac = OMAbstractFactory.getOMFactory();
		OMNamespace omNs = fac.createOMNamespace(namespace, "m");
		OMElement payload = getPayload(nameMethod);

		// Attachement du fichier texte
       	OMElement filetxt=createAttachment(fac,omNs);
       	payload.addChild(filetxt);

//      Ajout d une variable pour le mtomrm
		OMElement mtomrmElem = fac.createOMElement("mtomrm",omNs);
		mtomrmElem.setText("true");
		payload.addChild(mtomrmElem);

		// Ajout d un numero de sequence
		OMElement sequenceElem = fac.createOMElement("Sequence",omNs);
		if (nameMethod.equalsIgnoreCase("submit")) sequenceElem.setText(sequenceKey + "-" + text);
		else sequenceElem.setText(sequenceKey);
		payload.addChild(sequenceElem);

		System.out.println("Document sent : "+payload);

		return payload;

	}


	static class TestCallback extends Callback {

		String name = null;
		public TestCallback (String name) {
			this.name = name;
		}

		public void onComplete(AsyncResult result) {
//			Traitement du résultat et affichage
			System.out.println("\nResult :");
			System.out.println("Callback '" + name +  "' got result:" + result.getResponseEnvelope());
		}

		public void onError (Exception e) {
			System.out.println("Error reported for test call back");
			e.printStackTrace();
		}
	}

	/**
	 * Definition les options de l'envoie
	 *
	 */
	private static Options initOptions(String nameMethod,boolean SeparateListener){

		Options options = new Options ();
		options.setTo(targetEPR);
		options.setAction(nameMethod);
		options.setSoapVersionURI(SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI);
		options.setTransportInProtocol(Constants.TRANSPORT_HTTP);
		options.setUseSeparateListener(SeparateListener);
		options.setProperty(MessageContextConstants.TRANSPORT_URL,targetEPRTcpmon);
		options.setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE);

		return options;
	}

	/**
	 * Recuperation du fichier
	 *
	 */
	private OMElement getPayload(String operation) throws Exception {
		OMFactory fac = OMAbstractFactory.getOMFactory();
		// Declaration du namespace
		OMNamespace omNs = fac.createOMNamespace("http://dgme.finances.gouv.fr/presto";, "m");
		// Creation du sommet de l'arborescence
		OMElement payload = fac.createOMElement(operation, omNs);

		// Lecture du fichier a recuperer
		XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(new FileInputStream("test_data_in.xml"));
		// Construction de l'element
		StAXOMBuilder builder = new StAXOMBuilder(fac, parser);
		// Intergration dans l arborescence
		payload.addChild(builder.getDocumentElement());

		return payload;
	}

	/**
	 * Methode permettant l'attachement
	 *
	 */
	private static OMElement createAttachment(OMFactory fac, OMNamespace omNs) throws Exception{

		OMElement attach = null;

		// Creation du noeud
		attach = fac.createOMElement("attachment", omNs);
		// Lecteure de ce fichier
		File fileTxt = new File(fileNameAttach);
		FileDataSource dataSource = new FileDataSource(fileTxt);
		// Transformation en données binaires
		DataHandler expectedDH = new DataHandler(dataSource);
		OMText textData = fac.createOMText(expectedDH, true);
		// Ajout au message soap
		attach.addChild(textData);

		return attach;
	}

}

/**
 * PrestoSvcSkeleton.java This file was auto-generated from WSDL by the Apache
 * Axis2 version: 1.0 May 04, 2006 (09:21:04 IST)
 */
package fr.gouv.finances.dgme.presto;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Iterator;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.xml.namespace.QName;

import org.apache.axiom.attachments.Attachments;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMAttribute;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.impl.MTOMConstants;
import org.apache.axiom.om.impl.OMNodeEx;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.context.OperationContext;
import org.apache.axis2.util.Base64;
import org.apache.axis2.util.StreamWrapper;
import org.apache.axis2.wsdl.WSDLConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * PrestoSvcSkeleton java skeleton for the axisService
 */
public class PrestoSvcSkeleton {

    String fileSaveName = "/home/mancinee/workspace/testPresto/fileresult.txt";
	private MessageContext msgcts;
    private Log log = LogFactory.getLog(getClass());

	 public void setOperationContext(OperationContext oc) throws AxisFault {
	        msgcts = oc.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
	    }

    /**
     * Auto generated method signature
     *
     * @param param0
     */
    public fr.gouv.finances.dgme.presto.SubmitResponseDocument submit (
        fr.gouv.finances.dgme.presto.SubmitDocument param0) {
        log.info("submit METHOD CALL");
        SubmitResponseDocument response= null;
		try {
		    OMElement payload = readSoapMessage(param0);
		    // Recuperation de la valeur de testDocIn/intStrElement/intElement
            int intStrValue = getIntStrValue(payload);
            // Recuperation et sauvegarde de l attachement
            saveFile(payload);
            response = SubmitResponseDocument.Factory.parse(createStringSubmitResponse(intStrValue+1));
       } catch (Exception e) {
	       log.error("Error during soap message parsing " + Arrays.asList(e.getStackTrace()));
	   }
        log.info("Fin METHOD submit");
        return response;
    }

    /**
     * Auto generated method signature
     *
     * @param param2
     * @throws IOException
     * @throws InterruptedException
     */
    public void submitOneWay(
        fr.gouv.finances.dgme.presto.SubmitOneWayDocument param2) throws InterruptedException {
        log.info("submit One Way METHOD CALL");

//      Recuperation et sauvegarde de l attachement
		OMElement payload = readSoapMessage(param2);
        saveFile(payload);
		Thread.sleep(2000);
		log.info("Fin METHOD submitOneWay");
    }

    public OMElement readSoapMessage(fr.gouv.finances.dgme.presto.SubmitDocument param0) {
    	OMFactory fac = OMAbstractFactory.getOMFactory();
        StAXOMBuilder builder = new StAXOMBuilder(fac, new StreamWrapper(param0.newXMLStreamReader())) ;
        OMElement payload = builder.getDocumentElement();
        ((OMNodeEx)payload).setParent(null);
        return payload;
    }

    public OMElement readSoapMessage(fr.gouv.finances.dgme.presto.SubmitOneWayDocument param2){
    	OMFactory fac = OMAbstractFactory.getOMFactory();
        StAXOMBuilder builder = new StAXOMBuilder(fac,new StreamWrapper(param2.newXMLStreamReader())) ;
        OMElement payload = builder.getDocumentElement();
        ((OMNodeEx)payload).setParent(null);
        return payload;
    }

    /**
     *
     * This method handles the request: prints importants informations and
     * get attachment to save it in a file
     *
     * @param  payload  it's a OMElement
     *
     */
    private void saveFile(OMElement payload){

        try {

            OMElement attach = null;
            boolean testAttachment = false;
            Boolean mtomrm = false;
            OMElement seq = null;

            // Handling informations
            System.out.println("Document receive:\n" + payload.toString());

            for (Iterator it = payload.getChildElements();it.hasNext();) {
                OMElement el = (OMElement) it.next();

                if (el.getLocalName().equalsIgnoreCase("Sequence")) {
                    seq = el;
                    log.info("Sequence:" + seq.getText());
                } else if (el.getLocalName().equalsIgnoreCase("attachment")) {
                    attach = el;
                    testAttachment = true;
                    log.info("Attachement present dans le message");
                }else if (el.getLocalName().equalsIgnoreCase("mtomrm")) {
                    mtomrm = true;
                }
            }

            // There is no attachment
            if (testAttachment) {
                // Handling attachment
                System.out.println("Get attachment");
                File file = new File(fileSaveName);
                PrintWriter filetmp =  new PrintWriter(new BufferedWriter(new FileWriter(file, true)));

                // Case MTOM
                if (mtomrm){
                    // Get XOP informations
                    OMElement child = (OMElement) attach.getFirstOMChild();
                    OMAttribute attr = child.getAttribute(new QName("href"));
                    String contentID = attr.getAttributeValue();
                    Attachments attachment = (Attachments) msgcts.getProperty(MTOMConstants.ATTACHMENTS);
                    contentID = contentID.trim();

                    if (contentID.substring(0, 3).equalsIgnoreCase("cid")) {
                        contentID = contentID.substring(4);

                    }

                    // Get the attachment content
                    DataHandler dataHandler = attachment.getDataHandler(contentID);
                    DataSource dataSource=dataHandler.getDataSource();
                    InputStream infile = dataSource.getInputStream();

                    // Save the attachment content in a file
                    String ligne;
                    BufferedReader br = new BufferedReader(new InputStreamReader(infile,"UTF-8"));
                    while((ligne = br.readLine())!=null) filetmp.println(ligne);
                    br.close();

                // Case MTOMRM
                } else {
                    log.info("MTOM RM ");
                    // Get encoding value
                    String base64String= attach.getText().toString();
                    // Decode
                    String stringDecode=new String(Base64.decode(base64String));
                    // Save in a file
                    filetmp.println(stringDecode);
                }
                filetmp.flush();
                filetmp.close();
            }
        } catch (Exception e) {
            log.error("Erreur pendant l'enregistrement du fichier " + Arrays.asList(e.getStackTrace()));
        }
    }



    public void deleteFile(String nameFile){
   	    File file = new File(nameFile);
        if (file.exists()) {
            boolean resultat = file.delete();
            log.info("Suppression du fichier :" + nameFile+ " " + resultat);
        }
    }

    private int getIntStrValue(OMElement payload) {
        // Recuperation de la valeur du parametre IntStr
        String valueIntStr = null;
        QName testDocIn = new QName("http://dgme.finances.gouv.fr/prototype";, "testDocIn");
        Iterator testDocInIter = payload.getChildrenWithName(testDocIn);
        while (testDocInIter.hasNext()) {
            OMElement elementTestDocIn = (OMElement) testDocInIter.next();
            Iterator intStrIterator =  elementTestDocIn.getChildrenWithName(new QName("http://dgme.finances.gouv.fr/prototype";, "intStrElement"));
            while (intStrIterator.hasNext()) {
                OMElement elementIntStr = (OMElement) intStrIterator.next();
                valueIntStr = elementIntStr.getFirstElement().getText();
                break;
            }
            break;
        }
        if (valueIntStr == null)
            return 0;
        else
            return Integer.parseInt(valueIntStr);
    }

    private java.net.URL getResource(String nameString) {
        try {
            Enumeration enumResource = this.getClass().getClassLoader().getResources(nameString);
            if (enumResource.hasMoreElements())
                return (java.net.URL)enumResource.nextElement();
            else return null;
        } catch (IOException e) {
           log.error("Erreur pendant le chargement de la ressource : " + nameString + "/n" + Arrays.asList(e.getStackTrace()));
           return null;
        }
    }

    private String createStringSubmitResponse(int intStrValue) {
        StringBuffer messageResult = new StringBuffer();
        messageResult.append("<pro:submitResponse xmlns:pro=\"http://dgme.finances.gouv.fr/presto\";>");
        messageResult.append("<pro:intStrElement>");
        messageResult.append("<pro:intElement>"+ intStrValue + "</pro:intElement>");
        messageResult.append("<pro:strElement>test de string</pro:strElement>");
        messageResult.append("</pro:intStrElement>");
        messageResult.append("<pro:binaryElement>/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAPAA0DASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDp/FPjS1fWtUNtd6rcXGiahYQR2elLO6vmaMzb2jxGzOGaERyE4aI4wXIroJte10WdtfDVbEQ3W4pFa+HL29MJU4aN2jkBDKcqdyISVPyqQQNTW
 /DMLadctoWnabBqE97a3krFRALhorhJj5johJJ2tyQeW+tcXffEfwcl5IbnxRfeG9Z4TU7SztvOAnQBWVi8DozIQU3pjcFXJIVcAH//2Q==</pro:binaryElement>");
        messageResult.append("<pro:anyElement>");
        messageResult.append("<test123>1 2 3 4 5 6</test123>");
        messageResult.append("</pro:anyElement>");
        messageResult.append("</pro:submitResponse>");
        return messageResult.toString();
    }

}


---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to