001/*
002 * Copyright 2011 The Kuali Foundation.
003 *
004 * Licensed under the Educational Community License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.opensource.org/licenses/ecl2.php
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.kuali.ole;
017
018import org.apache.commons.io.IOUtils;
019import org.apache.jackrabbit.commons.cnd.CndImporter;
020import org.apache.jackrabbit.commons.cnd.ParseException;
021import org.kuali.ole.pojo.OleException;
022
023import javax.jcr.RepositoryException;
024import javax.jcr.Session;
025import javax.jcr.nodetype.NodeType;
026import java.io.*;
027
028/**
029 * Created by IntelliJ IDEA.
030 * User: peris
031 * Date: 5/1/11
032 * Time: 12:57 PM
033 * To change this template use File | Settings | File Templates.
034 */
035public class CustomNodeRegistrar {
036    private String CUSTOM_NODES_FILE_NAME = "customFileNode.cnd";
037
038    public NodeType[] registerCustomNodeTypes(Session session) throws OleException {
039
040        NodeType[] nodeTypes = new NodeType[0];
041        try {
042            File tempDir = new File(System.getProperty("java.io.tmpdir"));
043            File temporaryFile = new File(tempDir, CUSTOM_NODES_FILE_NAME);
044            InputStream templateStream = getClass().getResourceAsStream(CUSTOM_NODES_FILE_NAME);
045            IOUtils.copy(templateStream, new FileOutputStream(temporaryFile));
046            String absolutePath = temporaryFile.getAbsolutePath();
047            Session newSession = null;
048            if (session == null) {
049                newSession = getSession();
050                session = newSession;
051            }
052            nodeTypes = CndImporter.registerNodeTypes(new FileReader(new File(absolutePath)), session);
053            if (newSession != null) {
054                RepositoryManager.getRepositoryManager().logout(newSession);
055            }
056        } catch (ParseException e) {
057            throw new OleException(e.getMessage());
058        } catch (RepositoryException e) {
059            throw new OleException(e.getMessage());
060        } catch (IOException e) {
061            throw new OleException(e.getMessage());
062        }
063        return nodeTypes;
064    }
065
066    public Session getSession() throws OleException {
067        RepositoryManager repositoryManager = RepositoryManager.getRepositoryManager();
068        Session session = repositoryManager.getSession("CustomNodeRegistrar", "getSession");
069        return session;
070    }
071}