|
| 1 | +package com.danlangford.selectoserve; |
| 2 | + |
| 3 | +import java.io.BufferedWriter; |
| 4 | +import java.io.File; |
| 5 | +import java.io.FileWriter; |
| 6 | +import java.io.IOException; |
| 7 | +import java.util.Scanner; |
| 8 | + |
| 9 | + |
| 10 | +public class HostEditor { |
| 11 | + |
| 12 | + private static final String NL = System.getProperty("line.separator"); |
| 13 | + |
| 14 | + public void update(String hostPath, String user, String address) { |
| 15 | + if( nullOrEmpty(hostPath, user, address) ) throw new RuntimeException("All parameters are required"); |
| 16 | + |
| 17 | + File host = new File(hostPath); |
| 18 | + if( !host.exists() ) throw new RuntimeException("Host File Doesn't exist: " + hostPath); |
| 19 | + if( !host.canRead() || !host.canWrite() ) throw new RuntimeException("Host file must allow read/write"); |
| 20 | + |
| 21 | + try { |
| 22 | + File newHost = File.createTempFile("tmd", "hostfile"); |
| 23 | + BufferedWriter out = new BufferedWriter(new FileWriter(newHost)); |
| 24 | + |
| 25 | + boolean found = false; |
| 26 | + |
| 27 | + Scanner scanner = new Scanner(host); |
| 28 | + while(scanner.hasNext()) { |
| 29 | + found |= onReadLine(scanner.nextLine(), out, user, address); |
| 30 | + } |
| 31 | + |
| 32 | + if(!found) { |
| 33 | + out.write(address + "\t" + user + "\t#" + user + NL); |
| 34 | + } |
| 35 | + |
| 36 | + out.flush(); |
| 37 | + out.close(); |
| 38 | + |
| 39 | + scanner.close(); |
| 40 | + newHost.renameTo(host); |
| 41 | + } catch (IOException e) { |
| 42 | + throw new RuntimeException("I/O error", e); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + private boolean onReadLine(String line, BufferedWriter out, String user, String address) throws IOException { |
| 47 | + String[] inputs = line.split("\\s+"); |
| 48 | + |
| 49 | + // handle a line with no words |
| 50 | + boolean skipLine = inputs.length < 3; |
| 51 | + // handle comment lines |
| 52 | + skipLine = skipLine || inputs[0].trim().isEmpty() || inputs[0].trim().charAt(0) == '#'; |
| 53 | + |
| 54 | + // at this point, 0 = ip, 1 = name, 2 = username comment |
| 55 | + // if it's not our user, don't touch it |
| 56 | + skipLine = skipLine || !("#" + user).equalsIgnoreCase(inputs[2]); |
| 57 | + |
| 58 | + if(skipLine) { |
| 59 | + out.write(line + NL); |
| 60 | + return false; |
| 61 | + } |
| 62 | + |
| 63 | + out.write(address + "\t" + user + "\t#" + user + NL); |
| 64 | + return true; |
| 65 | + } |
| 66 | + |
| 67 | + private boolean nullOrEmpty(String... values) { |
| 68 | + for(String value : values) { |
| 69 | + if( value == null || value.trim().isEmpty() ) { |
| 70 | + return true; |
| 71 | + } |
| 72 | + } |
| 73 | + return false; |
| 74 | + } |
| 75 | + |
| 76 | + public static void main(String[] args) throws Exception{ |
| 77 | + HostEditor editor = new HostEditor(); |
| 78 | + editor.update("/etc/hosts", "andre", "192.168.1.100"); |
| 79 | + } |
| 80 | +} |
0 commit comments