Friday, July 05, 2013

ADF MDS : Use MDS API to remove Customizations and/or merge Documents

import java.io.StringReader;


import java.io.StringWriter;

import java.util.Iterator;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import oracle.adf.share.ADFContext;
import oracle.adf.share.config.UserCC;

import oracle.apps.fnd.applcore.log.AppsLogger;

import oracle.mds.config.CustConfig;
import oracle.mds.core.ConcurrentMOChangeException;
import oracle.mds.core.MDSInstance;
import oracle.mds.core.MDSSession;
import oracle.mds.core.MOReference;
import oracle.mds.core.MetadataNotFoundException;
import oracle.mds.core.MetadataObject;
import oracle.mds.core.RestrictedSession;
import oracle.mds.core.SessionOptions;
import oracle.mds.core.ValidationException;
import oracle.mds.core.ValidationType;
import oracle.mds.cust.CacheHint;
import oracle.mds.cust.CustClassList;
import oracle.mds.cust.CustomizationClass;
import oracle.mds.exception.UnsupportedUpdateException;
import oracle.mds.internal.query.NameQueryImpl;
import oracle.mds.naming.ReferenceException;
import oracle.mds.persistence.MDSIOException;
import oracle.mds.query.ConditionFactory;
import oracle.mds.query.QueryResult;

import org.w3c.dom.DOMException;
import org.w3c.dom.Document;


import org.xml.sax.InputSource;

public class MDSOperations {

    public MDSOperations() {
        super();
    }

    public void removeCustomizations() {
        MDSSession mdsReadSession =
            (MDSSession)ADFContext.getCurrent().getMDSSessionAsObject();
        MDSInstance mdsInstance =
            (MDSInstance)ADFContext.getCurrent().getMDSInstanceAsObject();
        MDSSession mdsWriteSession =
            mdsInstance.createSession(new SessionOptions(null, null,
                                                         CustConfig.NO_CUSTOMIZATIONS),
                                      null);
        String appUserFromDoc =
            ADFContext.getCurrent().getSecurityContext().getUserName();
        NameQueryImpl query =
            new NameQueryImpl(mdsReadSession, ConditionFactory.createNameCondition("/mypackage/mdssys/cust/User/"+appUserFromDoc,
                                                                                   "%ParamaterViewDef.xml.xml",
                                                                                   true));
        Iterator<QueryResult> result = query.execute();
        while (result.hasNext()) {
            try {
                QueryResult qr = result.next();
                String mdsDocFullName = qr.getAbsoluteName();
                String mdsDocName = qr.getResourceName().getLocalName();
                mdsReadSession.flushChanges(false,
                                             new ValidationType[] { ValidationType.RELATIONSHIP_VALIDATION });
             
                mdsReadSession.flushChanges(false,
                                             new ValidationType[] { ValidationType.RELATIONSHIP_VALIDATION });
             
                if (mdsDocFullName.startsWith("/mypackage/mdssys/cust/User/" +
                                              appUserFromDoc)) {
                 
                    String baseDocFilePath =
                        "/mypackage/" +
                        mdsDocName.substring(0, mdsDocName.lastIndexOf("."));
                 
                    CustomizationClass[] custClass =
                        new CustomizationClass[] { new MyUserCC("User",
                                                                 appUserFromDoc) };
                    CustClassList custCCList = new CustClassList(custClass);

                    MetadataObject mo11 =
                        mdsReadSession.getMetadataObject(baseDocFilePath,
                                                         custCCList, null);

                    Document mergedDoc = mo11.getDocument(true);
                    String mergedXMLStr = getXMLAsString(mergedDoc);                  

                    MOReference baseDocRef =
                        mdsWriteSession.getMOReference(baseDocFilePath);
                    MetadataObject baseMO =
                        mdsWriteSession.getMutableMO(baseDocRef);
                    Document baseDoc = baseMO.getDocument();
                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder builder;
                    builder = factory.newDocumentBuilder();
                    baseDoc = builder.parse(new InputSource(new StringReader(mergedXMLStr)));
                 
                    mdsWriteSession.deleteAllCustomizations(baseDocRef);
                    mdsWriteSession.deleteMetadataObject(baseDocRef);
                    mdsWriteSession.createMetadataObject(baseDocFilePath, baseDoc);

                    mdsWriteSession.flushChanges(false,
                                                 new ValidationType[] { ValidationType.RELATIONSHIP_VALIDATION });

                 
                    MetadataObject baseMO1 =
                        mdsReadSession.getMetadataObject(baseDocFilePath);
                    baseDoc = baseMO1.getDocument();
                 
                    mdsWriteSession.deleteAllCustomizations(baseDocRef);
                    mdsWriteSession.flushChanges(false,
                                                 new ValidationType[] { ValidationType.RELATIONSHIP_VALIDATION });
                }
            } catch (MetadataNotFoundException mnfe) {
            } catch (UnsupportedUpdateException uue) {
            } catch (MDSIOException mdsioe) {
            } catch (ReferenceException re) {
            } catch (ConcurrentMOChangeException cmoce) {
            } catch (DOMException dome) {
            } catch (ValidationException ve) {
            } catch (Exception e) {
            }
        }
    }
 
    private static String getXMLAsString(Document document) throws Exception{
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        //initialize StreamResult with File object to save to file
        StreamResult result = new StreamResult(new StringWriter());
        String xmlString = null;
        try {
            DOMSource source = new DOMSource(document);
            transformer.transform(source, result);
            xmlString = result.getWriter().toString();
         
        } catch (TransformerException te) {
        } catch (Exception e) {
             
        } finally {
            result.getWriter().close();
        }
        return xmlString;          
    }
}
/**
 *  Customization class for the User Layer only required at runtime.
 */
class MyUserCC extends UserCC {
    String layerName = "User";
    String layerValue = null;

    /**
     * Public Constructor
     */
    public MyUserCC() {
        super();
    }

    public MyUserCC(String layerName, String layerValue) {
        super();
        this.layerName = layerName;
        this.layerValue = layerValue;
    }

    /**
     * Getter method for CacheHint.
     * @return CacheHint.
     */
    public CacheHint getCacheHint() {
        return CacheHint.USER;
    }

    /**
     * Getter method for Name.
     * @return String Name
     */
    public String getName() {
        return "User";
    }

    /**
     * Getter method for value.
     * @param sess RestrictedSession
     * @param mo MetadataObject
     * @return String[] value.
     */
    public String[] getValue(RestrictedSession sess, MetadataObject mo) {
        return new String[] { this.layerValue };
    }

    /**
     * This method is used by level picker functionality to set the value for the level.
     *
     * @param value
     */
    public void setValue(String value) {
        // not required for constant value.
    }

}

1 comment:

Dale Sean said...

Thanks for your sharing,i learn a lot from your post.There is a lot of very useful knowledge in your post.I enjoy reading it and hope to see more.Can you write more?I am very interested in it.Waiting for your new post.
QR Code