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.BufferedReader;
023import java.io.IOException;
024import java.io.InputStream;
025import java.io.StringReader;
026import java.util.HashSet;
027import java.util.Set;
028
029import org.codehaus.plexus.util.IOUtil;
030import org.codehaus.plexus.util.StringOutputStream;
031import org.codehaus.plexus.util.StringUtils;
032
033/**
034 * Provides known hosts from a file
035 *
036 * @author Juan F. Codagnone
037 * @since Sep 12, 2005
038 */
039public class StreamKnownHostsProvider
040    extends AbstractKnownHostsProvider
041{
042
043    public StreamKnownHostsProvider( InputStream stream )
044        throws IOException
045    {
046        try
047        {
048            StringOutputStream stringOutputStream = new StringOutputStream();
049            IOUtil.copy( stream, stringOutputStream );
050            this.contents = stringOutputStream.toString();
051            
052            this.knownHosts = this.loadKnownHosts( this.contents );
053        }
054        finally
055        {
056            IOUtil.close( stream );
057        }
058    }
059    
060    protected Set<KnownHostEntry> loadKnownHosts( String contents )
061        throws IOException
062    {
063        Set<KnownHostEntry> hosts = new HashSet<KnownHostEntry>();
064        
065        BufferedReader br = new BufferedReader( new StringReader( contents ) );
066        
067        String line = null;
068        
069        do 
070        {
071            line = br.readLine();
072            if ( line != null )
073            {
074                String tokens[] = StringUtils.split( line );
075                if ( tokens.length == 3 )
076                {
077                    hosts.add( new KnownHostEntry( tokens[0], tokens[1], tokens[2] ) );
078                }
079            }
080            
081        }
082        while ( line != null );
083        
084        return hosts;
085    }
086}