001package org.kuali.common.util.ssh.model; 002 003import org.kuali.common.util.Assert; 004import org.kuali.common.util.spring.env.EnvUtils; 005import org.kuali.common.util.spring.env.EnvironmentService; 006 007import com.google.common.base.Optional; 008 009public final class GenerateKeyPairContext { 010 011 private final String name; 012 private final Algorithm algorithm; 013 private final int size; 014 015 public static class Builder { 016 017 // Required 018 private final String name; 019 020 // Optional 021 private Algorithm algorithm = Algorithm.RSA; 022 private int size = 2048; 023 024 private Optional<EnvironmentService> env = EnvUtils.ABSENT; 025 private static final String NAME_KEY = "ssh.keyName"; 026 private static final String ALGORITHM_KEY = "ssh.algorithm"; 027 private static final String SIZE_KEY = "ssh.keySize"; 028 029 public Builder(String name) { 030 this(EnvUtils.ABSENT, name); 031 } 032 033 public Builder(EnvironmentService env, String name) { 034 this(Optional.of(env), name); 035 } 036 037 private Builder(Optional<EnvironmentService> env, String name) { 038 this.env = env; 039 if (env.isPresent()) { 040 this.name = env.get().getString(NAME_KEY, name); 041 } else { 042 this.name = name; 043 } 044 } 045 046 public Builder algorithm(Algorithm algorithm) { 047 this.algorithm = algorithm; 048 return this; 049 } 050 051 public Builder size(int size) { 052 this.size = size; 053 return this; 054 } 055 056 private void validate(GenerateKeyPairContext context) { 057 Assert.noBlanks(context.getName()); 058 Assert.positive(context.getSize()); 059 } 060 061 private void override() { 062 if (env.isPresent()) { 063 algorithm(env.get().getProperty(ALGORITHM_KEY, Algorithm.class, algorithm)); 064 size(env.get().getInteger(SIZE_KEY, size)); 065 } 066 } 067 068 public GenerateKeyPairContext build() { 069 override(); 070 GenerateKeyPairContext context = new GenerateKeyPairContext(this); 071 validate(context); 072 return context; 073 } 074 075 } 076 077 private GenerateKeyPairContext(Builder builder) { 078 this.name = builder.name; 079 this.algorithm = builder.algorithm; 080 this.size = builder.size; 081 } 082 083 public String getName() { 084 return name; 085 } 086 087 public Algorithm getAlgorithm() { 088 return algorithm; 089 } 090 091 public int getSize() { 092 return size; 093 } 094 095}