1 package org.apache.maven.wagon.providers.ssh.knownhost;
2
3 /*
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
11 *
12 * http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
19 * under the License.
20 */
21
22 import java.io.ByteArrayInputStream;
23 import java.io.File;
24 import java.io.FileInputStream;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.util.Set;
28
29 import org.codehaus.plexus.util.FileUtils;
30
31 /**
32 * Provides known hosts from a file
33 *
34 * @author Juan F. Codagnone
35 * @since Sep 12, 2005
36 *
37 * @plexus.component role="org.apache.maven.wagon.providers.ssh.knownhost.KnownHostsProvider"
38 * role-hint="file"
39 * instantiation-strategy="per-lookup"
40 */
41 public class FileKnownHostsProvider
42 extends StreamKnownHostsProvider
43 {
44 private final File file;
45
46 /**
47 * Creates the FileKnownHostsProvider.
48 *
49 * @param file the file that holds the known hosts, in the openssh format
50 * @throws IOException
51 */
52 public FileKnownHostsProvider( File file )
53 throws IOException
54 {
55 super( file.exists() ? (InputStream) new FileInputStream( file ) : new ByteArrayInputStream( "".getBytes() ) );
56 this.file = file;
57 }
58
59 /**
60 * Creates a FileKnownHostsProvider using as file openssh knwon_host
61 *
62 * @throws IOException
63 * @see #FileKnownHostsProvider(File)
64 */
65 public FileKnownHostsProvider()
66 throws IOException
67 {
68 this( new File( System.getProperty( "user.home" ), ".ssh/known_hosts" ) );
69 }
70
71 public void storeKnownHosts( String contents )
72 throws IOException
73 {
74 Set<KnownHostEntry> hosts = this.loadKnownHosts( contents );
75
76 if ( ! this.knownHosts.equals( hosts ) )
77 {
78 file.getParentFile().mkdirs();
79 FileUtils.fileWrite( file.getAbsolutePath(), contents );
80 this.knownHosts = hosts;
81 }
82 }
83
84 public File getFile()
85 {
86 return file;
87 }
88 }