001package org.apache.maven.wagon.providers.ssh.knownhost;
002
003/*
004 * Licensed to the Apache Software Foundation (ASF) under one
005 * or more contributor license agreements.  See the NOTICE file
006 * distributed with this work for additional information
007 * regarding copyright ownership.  The ASF licenses this file
008 * to you under the Apache License, Version 2.0 (the
009 * "License"); you may not use this file except in compliance
010 * with the License.  You may obtain a copy of the License at
011 *
012 *   http://www.apache.org/licenses/LICENSE-2.0
013 *
014 * Unless required by applicable law or agreed to in writing,
015 * software distributed under the License is distributed on an
016 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
017 * KIND, either express or implied.  See the License for the
018 * specific language governing permissions and limitations
019 * under the License.
020 */
021
022import java.io.ByteArrayInputStream;
023import java.io.File;
024import java.io.FileInputStream;
025import java.io.IOException;
026import java.io.InputStream;
027import java.util.Set;
028
029import org.codehaus.plexus.util.FileUtils;
030
031/**
032 * Provides known hosts from a file
033 *
034 * @author Juan F. Codagnone
035 * @since Sep 12, 2005
036 * 
037 * @plexus.component role="org.apache.maven.wagon.providers.ssh.knownhost.KnownHostsProvider"
038 *    role-hint="file"
039 *    instantiation-strategy="per-lookup"
040 */
041public class FileKnownHostsProvider
042    extends StreamKnownHostsProvider
043{
044    private final File file;
045
046    /**
047     * Creates the FileKnownHostsProvider.
048     *
049     * @param file the file that holds the known hosts, in the openssh format
050     * @throws IOException
051     */
052    public FileKnownHostsProvider( File file )
053        throws IOException
054    {
055        super( file.exists() ? (InputStream) new FileInputStream( file ) : new ByteArrayInputStream( "".getBytes() ) );
056        this.file = file;
057    }
058
059    /**
060     * Creates a FileKnownHostsProvider using as file openssh knwon_host
061     *
062     * @throws IOException
063     * @see #FileKnownHostsProvider(File)
064     */
065    public FileKnownHostsProvider()
066        throws IOException
067    {
068        this( new File( System.getProperty( "user.home" ), ".ssh/known_hosts" ) );
069    }
070
071    public void storeKnownHosts( String contents )
072        throws IOException
073    {
074        Set<KnownHostEntry> hosts = this.loadKnownHosts( contents );
075        
076        if ( ! this.knownHosts.equals( hosts ) )
077        {
078            file.getParentFile().mkdirs();
079            FileUtils.fileWrite( file.getAbsolutePath(), contents );
080            this.knownHosts = hosts;
081        }
082    }
083    
084    public File getFile()
085    {
086        return file;
087    }
088}