package com.eactive.eai.rms.onl.manage.rule.layoutsync;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.Reader;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.View;
import org.xml.sax.InputSource;

import com.eactive.eai.agent.command.CommonCommand;
import com.eactive.eai.common.util.UUIDGenerator;
import com.eactive.eai.rms.common.base.OnlBaseAnnotationController;
import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.common.interceptor.InterceptorSkipController;
import com.eactive.eai.rms.common.logging.UserAccessLogger;
import com.eactive.eai.rms.common.login.SessionManager;
import com.eactive.eai.rms.common.util.AgentParserUtils;
import com.eactive.eai.rms.common.util.CommonUtil;
import com.eactive.eai.rms.common.util.StringUtils;
import com.eactive.eai.rms.onl.common.exception.BizException;
import com.eactive.eai.rms.onl.common.util.DateUtil;
import com.eactive.eai.transformer.layout.Item;
import com.eactive.eai.transformer.layout.Types;

@Controller
@RequestMapping("/layoutSync.do")
public class LayoutSyncController extends OnlBaseAnnotationController implements InterceptorSkipController {

    private static final Logger logger = Logger.getLogger(LayoutSyncController.class);

    @Autowired
    @Qualifier("layoutSyncService")
    private LayoutSyncService service;
    
    @Autowired
    private MonitoringContext monitoringContext;
	/**
	 * xml 형식으로 전달 된 레이아웃을 LayoutVo로 전환
	 * 
	 * @param e
	 * @param msgType
	 * @param loutName
	 * @return
	 * @throws Exception
	 */
	private List<HashMap<String,Object>> setLayoutItems(Element e, String msgType, String loutName ) throws Exception {
		List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>();

        List<Element> items = e.getChildren();
        for(Element el : items) {
    		// Layout Item Format (TR08)
            HashMap<String,Object> item = new HashMap<String,Object>();

            item.put("loutName",loutName);
            item.put("loutItemName",el.getAttributeValue("id"));
            item.put("loutItemSerno", Integer.parseInt(el.getAttributeValue("no")) );
            item.put("loutItemIDName",Integer.parseInt(el.getAttributeValue("no")) + 1000);
            String no = el.getParentElement().getAttributeValue("no");
            item.put("parntLoutItemIDName",Integer.parseInt( no == null ? "0":no ) + 1000 );
            item.put("loutItemDesc",el.getAttributeValue("desc"));
            
            int node = 0;
            if( "GROUP".equals(el.getName().toUpperCase()) ) {
            	node = Item.NODE_GROUP;
            } else if("GRID".equals(el.getName().toUpperCase())) {
            	node = Item.NODE_GROUP;
            } else if("ATTR".equals(el.getName().toUpperCase())) {
            	node = Item.NODE_ATTR;
            } else {
            	node = Item.NODE_FIELD;
            }
            
            item.put("loutItemNodePtrnIDName",node);

            int loutType = Types.TYPE_UNKNOWN;
            if( el.getAttributeValue("type") == null ||  "".equals(el.getAttributeValue("type"))) {            	
            } else if( "GRID".equals(el.getName().toUpperCase()) || "GROUP".equals(el.getName().toUpperCase()) ) {       	
            } else if( msgType.equals("XML") ) {     
            	loutType = "VARCHAR".startsWith(el.getAttributeValue("type").toUpperCase()) ? Types.TYPE_STRING : Types.TYPE_INT;  // TYPE_LONG, TYPE_SHORT, TYPE_DOUBLE, TYPE_FLOAT

            	//loutType = Types.TYPE_STRING;
            } else {
            	loutType = Types.TYPE_BYTEARRAY;
            }
            
            item.put("loutItemPtrnIDName",loutType);
            item.put("loutItemLenCnt","".equals(el.getAttributeValue("len")) ? 0 : Integer.parseInt(el.getAttributeValue("len")));
            item.put("loutItemRefInfo2",el.getAttributeValue("count")); // 
            
            
            // MIN, MAX 설정
            // 통합인터페이스는 * , 숫자만 보냄 ( 가변은 * 고정은 숫자 ) 
            String occurNoitm = el.getAttributeValue("maxCnt");
            int max = 0;
            int min = 0;
            if( String.valueOf(Item.OCC_MULTI_OR_NONE).equals(occurNoitm) ) {  // *
            	max = -1;
            } else if ( String.valueOf(Item.OCC_ONCE_OR_NONE).equals(occurNoitm) ) {  // ?
            	max = 1;
            } else if ( String.valueOf(Item.OCC_MULTI_OR_ONCE).equals(occurNoitm) ) {  // +
            	min = 1;
            	max = -1;
            } else if ( "".equals(occurNoitm) ) {  // ""
            	min = 1;
            	max = 1;
            } else if ( occurNoitm.matches("[0-9]+") ) {  // ""
            	min = StringUtils.isNotEmpty(el.getAttributeValue("count")) ? 0 : Integer.parseInt(occurNoitm);
            	max =  Integer.parseInt(occurNoitm);
            }
            
            // 반복횟수 참조정보가 없는데 MIN, MAX 값이 설정되지 않은 경우 오류
            if( max == 0 && min == 0 ) {
            	if("GRID".equals(el.getName().toUpperCase()) ) {
            		if ( !StringUtils.isEmpty(el.getAttributeValue("count")) ) {            		
                	} else {
                		throw new Exception("반복횟수 참조정보 오류");
                	}
            	} else {
            		min = 1;
        		    max = 1;
            	}            	
            }
            
            if( "0".equals(occurNoitm) ) {
            	occurNoitm = "";         		
        	}
            
            item.put("loutItemOccurPtrnDstcd",occurNoitm); // 레이아웃항목발생유형구분코드
            item.put("loutItemMaxOccurNoitm",max); // 레이아웃항목최대발생건수
            item.put("loutItemMinOccurNoitm",min); // 레이아웃항목최소발생건수
            
            item.put("loutItemBascVal",el.getAttributeValue("default"));  // 레이아웃항목기본값
            item.put("loutItemMskYn",el.getAttributeValue("mask")); // [Y/N/ ]
            if( "Y".equals(item.get("loutItemMskYn")) ) item.put("loutItemMaskLength",Integer.parseInt(el.getAttributeValue("maskLength")));
            item.put("lyoutDptCnt",Integer.parseInt(el.getAttributeValue("depth")) + 1 );  // 통합인터페이스 전달되는 Depth + 1을 해야 함
            item.put("decptLenCnt","".equals(el.getAttributeValue("scale")) ? 0 : Integer.parseInt(el.getAttributeValue("scale"))); // 소수점길이 META에서 "" 이면 "" 으로 표현함
            
            
            
            String dataType = "";
            if( el.getAttributeValue("type") == null ||  "".equals(el.getAttributeValue("type"))) {            	
            } else if( "VARCHAR".startsWith(el.getAttributeValue("type").toUpperCase()) ) { // Varchar, Number
            	dataType = "String";
            } else if( "NUMBER".startsWith(el.getAttributeValue("type").toUpperCase()) ) { // Varchar, Number
            	dataType = "Integer";
            }            
            item.put("lyoutItemRefPtrnIDName",dataType); // 데이터타입

            list.add(item);
            if( el.getChildren() != null && el.getChildren().size() > 0 ) {
            	list.addAll(setLayoutItems(el, msgType, loutName));
            }
        }  // end FOR
		
		return list;
	}
	
    /**
     * 통합인터페이스 시스템(iim)에서 전문 레이아웃에 대한 INSERT, DELETE 요청
     * *
     * @param request
     * @param response
     * @param schema
     * @return
     * @throws Exception
     */
    @RequestMapping(params = "cmd=Message")
    public View parseMessage(HttpServletRequest request, HttpServletResponse response, String schema) throws Exception {
        UserAccessLogger.log(request, "Layout", "L", "cmd=Message");
        Document rDoc = null;
        Element results = null;
        String  resultS = null;
        ServletInputStream sis = null;

        HashMap<String, String> param = new HashMap<String, String>();
        String recvTime = DateUtil.getDateTime("yyyyMMddHHmmssSS").substring(0, 16);

    	// 초기화
        if (schema != null) {
        	DataSourceContextHolder.setDataSourceType(DataSourceTypeManager.getDataSourceType(schema));
        } else {
        	logger.error(">>> DataSourceTypeManager.getDataSourceType(schema) error. schema is null");
        	return null;
        }
    	try { 

	    	SAXBuilder builder = new SAXBuilder();
	    	
	        // 응답 전문
	        File res = new File( request.getSession().getServletContext().getRealPath("/WEB-INF/") + "/layout-messagesync-res.xml" );
	        rDoc = builder.build(res);
	        results = rDoc.getRootElement();
	        
	    	// 요청 전문
	    	sis = request.getInputStream();	
	        Document doc = builder.build(sis);
	        
	        // log 기록 
	        byte[] arg = new byte[request.getContentLength()];
	        int resultSet =0;
	        int total = 0;
	        try {
	        	resultSet = sis.readLine(arg, 0, arg.length);
	        	while(resultSet != -1) {
	        		total += resultSet;
	        		resultSet = sis.readLine(arg, total, 1024);
	        	}
	        	
	        	param.put("recvData", new String(arg));
	        } catch(Exception e) {
	        	logger.error("MessageSync.err - don't read the XML File - " + new String(arg), e);
	        	param.put("recvData", "");
	        }
	        
	        param.put("logPrcssSeqno", UUIDGenerator.getUUID());
	        // xml 1.1
	        Element message = doc.getRootElement();
	        
	        // Command 확인
	        String command = message.getChild("Header").getChild("Command").getText();
	        
	        Element body = message.getChild("Body").getChild("Layout");
	        String layoutName = body.getChild("id").getText();

	        param.put("serviceName", message.getChild("Header").getChild("ServiceName").getText());
	        param.put("command", command);
	        param.put("loutName", layoutName);
			param.put("recvAmndHMS", recvTime);
	        
	        logger.info(layoutName + " command - [" + command +"]");	       
	        //HashMap<String, Object> returnMap = new HashMap<String,Object>();
	        if( command.equals("delete") ) {
	            HashMap<String,Object> vo = new HashMap<String,Object>();
	            vo.put("loutName",layoutName);
	        	
	            service.deleteLayout(vo);
	            
	            CommonCommand commonCommand = new CommonCommand("com.eactive.eai.agent.transformer.RemoveLayoutCommand",vo.get("loutName"));
	            HashMap<String,String> result = AgentParserUtils.parse(commonCommand, agentUtilService,"prcssRslt","prcssRsltCmnt");
	            param.putAll(result);
	            
	            service.addLayoutSyncLog(param);
	        	
	        } else {
	        	// LoutName 검증
	        	// 인터페이스 이름 20자리 이하  
	        	// EAI _CBSS _CBSR _CBSE _UAIR
	        	// FEP _CBS _ORG
	        	String fattern = "[A-Z0-9]{3}_[A-Z0-9]{3}[A-Z0-9]*_[A-Z0-9]{3,4}";
	        	if(!layoutName.matches(fattern)) {
	        		throw new BizException("잘못된 전문레이아웃명 입니다.\n명명규칙을 확인하세요.\n[A-Z0-9]{3}_[A-Z0-9]{3}[A-Z0-9]*_[A-Z0-9]{3,4}");
	        	}
	        	
		        String layout = body.getChild("data").getText();
				logger.info(layoutName + " recv Data - [" + layout + "]");
				param.put("recvData", layout);
				
		        Document doc2 = builder.build(new ByteArrayInputStream(layout.getBytes()));
	
		        HashMap<String,Object> vo = new HashMap<String,Object>();
		        
				Element format = doc2.getRootElement();
		
		        String msgType = format.getAttributeValue("msgType");
		        if( "ASCII".equals(format.getAttributeValue("msgType")) ) {
		        	msgType = "BYTES";
		        } else if( "VASCII".equals(format.getAttributeValue("msgType")) ) {
		        	msgType = "VBYTES";
		        }
		        
				// Layout Format (TR07)
		        vo.put("loutName",layoutName);
		        vo.put("loutPtrnName",msgType); //  ASCII, EBCDIC, XML
		        vo.put("loutDesc",format.getAttributeValue("desc"));  

		        String date = format.getAttributeValue("date");
		        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		        vo.put("lastAmndHMS",new SimpleDateFormat("yyyyMMddHHmmssSS").format(sdf.parse(date)));
		        
		        vo.put("eaiBzwkDstcd",format.getAttributeValue("group"));
		        
		        if( !"".equals(format.getAttributeValue("createBy"))) {
		        	vo.put("createBy",format.getAttributeValue("createBy"));
		        }

		        if( !"".equals(format.getAttributeValue("updateBy"))) {
		        	vo.put("updateBy",format.getAttributeValue("updateBy"));
		        }
		        
		        
				// Layout Item Format (TR08)
		        List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>();
		        HashMap<String,Object> tr08 = new HashMap<String,Object>();
		        tr08.put("loutName",layoutName);
		        tr08.put("loutItemName",layoutName);
		        tr08.put("loutItemSerno",0);
		        tr08.put("loutItemIDName",1000);
		        tr08.put("parntLoutItemIDName",0);
		        tr08.put("loutItemDesc",format.getAttributeValue("desc"));
		        tr08.put("loutItemNodePtrnIDName",Item.NODE_MESSAGE);
		        tr08.put("loutItemPtrnIDName",Types.TYPE_UNKNOWN);
		        tr08.put("loutItemPathName",""); // 
		        tr08.put("loutItemLenCnt",0);
		        tr08.put("loutItemRefInfo",""); // GROUP NAME
		        tr08.put("loutItemRefInfo2",""); // 
		        tr08.put("loutItemOccurPtrnDstcd",""); // 레이아웃항목발생유형구분코드
		        tr08.put("loutItemMaxOccurNoitm",0); // 레이아웃항목최대발생건수
		        tr08.put("loutItemMinOccurNoitm",0); // 레이아웃항목최소발생건수
		        tr08.put("loutItemBascVal","");  // 레이아웃항목기본값
		        tr08.put("loutItemMskYn"," "); // 
		        tr08.put("lyoutDptCnt",1);
		        tr08.put("decptLenCnt",0); // 소수점길이
		        tr08.put("lyoutItemRefPtrnIdName",""); // 데이터타입
		        
		        list.add(tr08);
		        list.addAll(setLayoutItems(format, msgType, layoutName));
				
		        service.insertLayout(vo, list);  //FIXME : 스키마 변경 룰 적용해야 함
		        
	            CommonCommand commonCommand = new CommonCommand("com.eactive.eai.agent.transformer.ReloadLayoutCommand",vo.get("loutName"));
	            HashMap<String,String> result = AgentParserUtils.parse(commonCommand, agentUtilService,"prcssRslt","prcssRsltCmnt");
	            param.putAll(result);
		    	service.addLayoutSyncLog(param);
		        
		        
	        }
	        results.getChild("Result").setText("S".equals(param.get("prcssRslt"))?"True":"False");
	        results.getChild("ResultMessage").setText("S".equals(param.get("prcssRslt"))?"성공":param.get("prcssRsltCmnt"));

	        resultS = StringUtils.toXMLString(rDoc, true);
	        
    	} catch( Exception e ) {
    		logger.error(e);
    		logger.error(e.getStackTrace()[0]);
    		try {
	    		if( results != null ) {
			        results.getChild("Result").setText("False");
			        results.getChild("ResultMessage").setText( e.getMessage() );
			        
			        resultS = StringUtils.toXMLString(rDoc, true);
	    		}
	    		if( param.get("logPrcssSeqno") == null ) {
	    			param.put("logPrcssSeqno", UUIDGenerator.getUUID());
	    			param.put("ServiceName", "MessageSync");
	    			param.put("RecvAmndHMS", recvTime);
	    		}
	    		param.put("PrcssRslt", "F");
				param.put("PrcssRsltCmnt", StringUtils.cuttings(CommonUtil.getArrayString(e.getStackTrace(), "\n"), 4000)[0]);
	    		service.addLayoutSyncLog(param);
    		} catch(Exception ee) {
        		//ee.printStackTrace();
    			logger.error("error",e);
    		}
    	}

		ServletOutputStream sos = null;
    	try {
    		sos = response.getOutputStream();
    		if(resultS != null) {
    		  sos.write(resultS.getBytes());
   			}
   			
    	} catch( Exception e ) {
    		//e.printStackTrace();
    		//취약점코드 수정 2019.08.22 SW
			logger.error(e.getMessage());
    	} finally {
    		if( sis != null ) sis.close();
    		if( sos != null ) sos.close();
    	}
    	return null;
    }
    
    /**
     * [통합인터페이스]에 레이아웃 정보 송신
     * * schemaId에 따라 별도로 저장 됨 
     * * filePath / schemaId / layoutName .xml 형식으로 저장 됨
     * 
     * @param request   prptyGroupName=migrationLayoutInfo
     * @param response
     * @param schema    EAI/FEP 
     * @return
     * @throws Exception
     */
    @RequestMapping(params = "cmd=M_LAYOUT")
    public String migrationLayout(HttpServletRequest request, HttpServletResponse response, ModelMap model, String schema) throws Exception {

        UserAccessLogger.log(request, "Layout", "M", "cmd=SYNC");

//        if( !DataSourceTypeManager.EAI.equals(schema) && !DataSourceTypeManager.FEP.equals(schema) ) {
        	schema = DataSourceContextHolder.getDataSourceType().getName();
//        } 
        
        // 1. 파라메터 셋팅
		String migration = monitoringContext.getStringProperty("iim.layout.migration" ,"");
		String[] props = null;
        if( migration.indexOf(";") != -1 ) {
        	props = migration.split(";");
        }
        
    	HashMap<String, String> param = new HashMap<String, String>();
    	param.put("userId", SessionManager.getUserId(request));
    	param.put("schemaId", schema);
    	param.put("filePath", StringUtils.defaultString(props[0], request.getSession().getServletContext().getRealPath("/WEB-INF/")));
    	param.put("encoding", StringUtils.defaultString(props[1],"utf-8"));
    	param.put("indent",   StringUtils.defaultString(props[2],"yes"));
    	param.put("path", request.getSession().getServletContext().getRealPath("/WEB-INF/"));
    	
    	logger.debug("*** userId *** " + param.get("userId"));
    	logger.debug("*** schemaId *** " + param.get("schemaId"));
    	logger.debug("*** path *** " + param.get("path"));

    	// 2. 지정 스키마 변경 
    	DataSourceContextHolder.setDataSourceType(DataSourceTypeManager.getDataSourceType(param.get("schemaId")));

    	// 3. 전체 레이아웃 목록 조회
        List<HashMap<String,Object>> list = service.getAllLayouts();
        int succCnt = 0;
        try {

	        // 폴더 초기화 후 생성
	        File mkf = new File(param.get("filePath") + "/" + param.get("schemaId"));			        
	        if( mkf.exists() ) { 
	        	File[] fList = mkf.listFiles();
	        	if(fList != null){
	        		for( int i=0; i< fList.length; i++) {
		        		fList[i].delete();
		        	}
	        	}
	        	
	        	mkf.delete();
	        }
	        mkf.mkdir();
	        
	        
	        for( HashMap<String,Object> layout : list ) {
	        	// 4. 레이아웃 상세 정보 조회 
	        	param.put("LoutName", (String)layout.get("LOUTNAME"));
		    	HashMap<String, String> result = service.migrationLayoutToXML(param);
		        	
		    	String xmlQuery = result.get("xmlQuery");
		
				//5. XML 파일 생성
		        // Layout별로 생성
		        String newName = param.get("filePath") + "/" + param.get("schemaId") 
		                       + "/" + layout.get("LOUTNAME") + ".xml";
		        
		        // 파일 저장
		    	//File newFile = new File(newName);
		    	
		    	TransformerFactory factory = TransformerFactory.newInstance();
		    	Transformer transformer = factory.newTransformer();
		    	transformer.setOutputProperty(OutputKeys.ENCODING, param.get("encoding"));
		    	transformer.setOutputProperty(OutputKeys.INDENT, param.get("indent"))	;
		    	
		    	Reader r = new StringReader(xmlQuery);
		    	org.w3c.dom.Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(r));
		    	
		    	DOMSource src = new DOMSource(d);
		    	StreamResult rst = new StreamResult(new File(newName));
		    	transformer.transform(src,rst);
		    	succCnt++;
	        }
        } catch(Exception e) {
        	//e.printStackTrace();
        	logger.error("migrationLayout error",e);
        }

        return null;
    }
    

    @RequestMapping(params = "cmd=M_LAYOUT_MAPPING")
    public String migrationLayoutMapping(HttpServletRequest request, HttpServletResponse response, ModelMap model, String schema) throws Exception {

        UserAccessLogger.log(request, "Layout", "M", "cmd=SYNC");

//        if( !DataSourceTypeManager.EAI.equals(schema) && !DataSourceTypeManager.FEP.equals(schema) ) {
        	schema = DataSourceContextHolder.getDataSourceType().getName();
//        } 
        
        // 1. 파라메터 셋팅
		String migration = monitoringContext.getStringProperty("iim.layout.migration" ,"");
		String[] props = null;
        if( migration.indexOf(";") != -1 ) {
        	props = migration.split(";");
        }
        
    	HashMap<String, String> param = new HashMap<String, String>();
    	param.put("userId", SessionManager.getUserId(request));
    	param.put("schemaId", schema);
    	param.put("filePath", StringUtils.defaultString(props[0], request.getSession().getServletContext().getRealPath("/WEB-INF/")));
    	param.put("encoding", StringUtils.defaultString(props[1],"utf-8"));
    	param.put("indent",   StringUtils.defaultString(props[2],"yes"));
    	param.put("path", request.getSession().getServletContext().getRealPath("/WEB-INF/"));
    	
    	logger.debug("*** userId *** " + param.get("userId"));
    	logger.debug("*** schemaId *** " + param.get("schemaId"));
    	logger.debug("*** path *** " + param.get("path"));

    	// 2. 지정 스키마 변경 
    	DataSourceContextHolder.setDataSourceType(DataSourceTypeManager.getDataSourceType(param.get("schemaId")));

    	// 3. 전체 eaisvcname 목록 조회     
        List<HashMap<String,Object>> list = service.getAllEAIMessages(param);	 
        int succCnt = 0;
        try {

	        // 폴더 초기화 후 생성
	        File mkf = new File(param.get("filePath") + "/mapping_" + param.get("schemaId"));			        
	        if( mkf.exists() ) { 
	        	File[] fList = mkf.listFiles();
	        	if(fList != null){
	        		for( int i=0; i< fList.length; i++) {
		        		fList[i].delete();
		        	}
	        	}
	        	
	        	mkf.delete();
	        }
	        mkf.mkdir();
	        
	        for( HashMap<String,Object> message : list ) {
	        	param.put("eaiSvcName", (String)message.get("EAISVCCD"));
	        	param.put("cmd", "insert");
	        	String xmlQuery = service.getLayoutMappingXMLList(param);
	        	
		
				//5. XML 파일 생성
		        // Layout별로 생성
		        String newName = param.get("filePath") + "/mapping_" + param.get("schemaId") + "/" + message.get("EAISVCCD") + ".xml";
		        
		        // 파일 저장
		        if( xmlQuery.indexOf("Layout") != -1) {
			    	//File newFile = new File(newName);
			    	
			    	TransformerFactory factory = TransformerFactory.newInstance();
			    	Transformer transformer = factory.newTransformer();
			    	transformer.setOutputProperty(OutputKeys.ENCODING, param.get("encoding"));
			    	transformer.setOutputProperty(OutputKeys.INDENT, param.get("indent"))	;
			    	
			    	Reader r = new StringReader(xmlQuery);
			    	org.w3c.dom.Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(r));
			    	
			    	DOMSource src = new DOMSource(d);
			    	StreamResult rst = new StreamResult(new File(newName));
			    	transformer.transform(src,rst);
			    	succCnt++;
		        }
	        }
        } catch(Exception e) {
        	//e.printStackTrace();
        	logger.error("migrationLayoutMapping error",e);
        }
        return null ;
    }

}
