package org.openslx.imagemaster.db;
import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.util.List;
import org.apache.log4j.Logger;
import org.openslx.encryption.AsymKeyHolder;
import org.openslx.imagemaster.thrift.iface.OrganizationData;
/**
* Represents a satellite in the database.
* Is used to authenticate the satellite.
*/
public class DbSatellite
{
private static final Logger LOG = Logger.getLogger( DbSatellite.class );
private String organizationId, address, name, publickeyString;
private PublicKey publickey = null;
public DbSatellite( String organizationId, String address, String name, String publickeyString )
{
this.organizationId = organizationId;
this.address = address;
this.name = name;
this.publickeyString = publickeyString;
}
public static DbSatellite fromOrganizationId( String organizationId )
{
return MySQL
.findUniqueOrNull(
DbSatellite.class,
"SELECT satellite.organizationid, satellite.address, satellite.name, satellite.publickey FROM satellite WHERE satellite.organizationid = ? LIMIT 1",
organizationId );
}
public static DbSatellite fromSuffix( String suffix )
{
return MySQL
.findUniqueOrNull(
DbSatellite.class,
"SELECT satellite.organizationid, satellite.address, satellite.name, satellite.publickey FROM satellite"
+ " INNER JOIN satellite_suffix USING (organizationid)"
+ " WHERE satellite_suffix.suffix = ? LIMIT 1",
suffix );
}
/**
* Return all known satellites/organizations as List of {@link OrganizationData}, which can be
* used directly by the thrift API.
*
* @return list of all known organizations/satellites
*/
public static List<OrganizationData> asOrganizationDataList()
{
return MySQL.findAll( OrganizationData.class, "SELECT satellite.organizationid, satellite.name, satellite.authmethod FROM satellite" );
}
public static DbSatellite fromPrefix( String prefix )
{
return null;
}
/*
* Member methods
*/
public String getAddress()
{
return address;
}
public String getName()
{
return name;
}
public String getOrganizationId()
{
return organizationId;
}
/**
* Get the public key of this organization, if known and valid.
*
* @return Public key, null on error or not known
*/
public PublicKey getPubkey()
{
if ( publickey == null && publickeyString != null ) {
String parts[] = publickeyString.split( " " );
if ( parts.length != 2 )
return null;
try {
BigInteger mod = new BigInteger( parts[0] );
BigInteger exp = new BigInteger( parts[1] );
publickey = new AsymKeyHolder( null, exp, mod ).getPublicKey();
} catch ( InvalidKeySpecException | NoSuchAlgorithmException e ) {
LOG.info( "PubKey of " + this.name + " is not valid.", e );
} catch ( NumberFormatException e ) {
LOG.info( "PubKey of " + this.name + " is corrupted in database!", e );
}
}
return publickey;
}
}