001/*
002 * ModeShape (http://www.modeshape.org)
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.modeshape.connector.git;
017
018import java.io.IOException;
019import java.io.InputStream;
020import java.util.concurrent.TimeUnit;
021import org.modeshape.common.annotation.Immutable;
022import org.modeshape.jcr.api.value.DateTime;
023import org.modeshape.jcr.value.BinaryKey;
024import org.modeshape.jcr.value.BinaryValue;
025import org.modeshape.jcr.value.ValueFactories;
026import org.modeshape.jcr.value.binary.BinaryStore;
027import org.modeshape.jcr.value.binary.BinaryStoreException;
028
029@Immutable
030public class Values {
031
032    private final ValueFactories factories;
033    private final BinaryStore binaryStore;
034
035    public Values( ValueFactories factories,
036                   BinaryStore binaryStore ) {
037        this.factories = factories;
038        this.binaryStore = binaryStore;
039    }
040
041    public DateTime dateFrom( int secondsSinceEpoch ) {
042        long millisSinceEpoch = TimeUnit.MILLISECONDS.convert(secondsSinceEpoch, TimeUnit.SECONDS);
043        return factories.getDateFactory().create(millisSinceEpoch);
044    }
045
046    public Object referenceTo( String id ) {
047        return factories.getReferenceFactory().create(id);
048    }
049
050    public BinaryValue binaryFor( BinaryKey key,
051                                  long size ) {
052        InputStream is = null;
053        try {
054            is = binaryStore.getInputStream(key);
055            return factories.getBinaryFactory().find(key, size);
056        } catch (BinaryStoreException e) {
057            // Must not have found it ...
058        } finally {
059            if (is != null) {
060                try {
061                    is.close();
062                } catch (IOException e) {
063                    //ignore
064                }
065            }
066        }
067        return null;
068    }
069
070    public BinaryValue binaryFrom( InputStream stream ) {
071        return factories.getBinaryFactory().create(stream);
072    }
073
074}