001/*
002 *  Copyright 2010 Anyware Services
003 *
004 *  Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0
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.ametys.plugins.repository.metadata.jcr;
017
018import javax.jcr.Node;
019import javax.jcr.RepositoryException;
020
021import org.apache.jackrabbit.util.Text;
022
023import org.ametys.plugins.repository.AmetysRepositoryException;
024import org.ametys.plugins.repository.metadata.ModifiableFile;
025
026/**
027 * Java binding of a nt:file JCR Node.<p>
028 * {@link Text#escapeIllegalJcrChars(String)} is used for
029 * escaping invalid JCR characters or character sequences.
030 */
031public class JCRFile implements ModifiableFile
032{
033    private Node _node;
034    
035    /**
036     * Constructor
037     * @param node the nt:file Node
038     */
039    public JCRFile(Node node)
040    {
041        _node = node;
042    }
043    
044    /**
045     * Retrieves the underlying node.
046     * @return the underlying node.
047     */
048    public Node getNode()
049    {
050        return _node;
051    }
052    
053    @Override
054    public String getName() throws AmetysRepositoryException
055    {
056        try
057        {
058            return Text.unescapeIllegalJcrChars(_node.getName());
059        }
060        catch (RepositoryException e)
061        {
062            throw new AmetysRepositoryException(e);
063        }
064    }
065    
066    public JCRResource getResource() throws AmetysRepositoryException
067    {
068        try
069        {
070            Node resourceNode = null;
071            
072            if (_node.hasNode("jcr:content"))
073            {
074                // Already exists
075                resourceNode = _node.getNode("jcr:content");
076            }
077            else
078            {
079                resourceNode = _node.addNode("jcr:content", "nt:resource");
080            }
081            
082            return new JCRResource(resourceNode);
083        }
084        catch (RepositoryException e)
085        {
086            throw new AmetysRepositoryException(e);
087        }
088    }
089}