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
051            stream.close();
052            stream = null;
053
054            this.contents = stringOutputStream.toString();
055            
056            this.knownHosts = this.loadKnownHosts( this.contents );
057        }
058        finally
059        {
060            IOUtil.close( stream );
061        }
062    }
063    
064    protected Set<KnownHostEntry> loadKnownHosts( String contents )
065        throws IOException
066    {
067        Set<KnownHostEntry> hosts = new HashSet<KnownHostEntry>();
068        
069        BufferedReader br = new BufferedReader( new StringReader( contents ) );
070        
071        String line;
072        
073        do 
074        {
075            line = br.readLine();
076            if ( line != null )
077            {
078                String tokens[] = StringUtils.split( line );
079                if ( tokens.length == 3 )
080                {
081                    hosts.add( new KnownHostEntry( tokens[0], tokens[1], tokens[2] ) );
082                }
083            }
084            
085        }
086        while ( line != null );
087        
088        return hosts;
089    }
090}