001/*
002 *                    BioJava development code
003 *
004 * This code may be freely distributed and modified under the
005 * terms of the GNU Lesser General Public Licence.  This should
006 * be distributed with the code.  If you do not have a copy,
007 * see:
008 *
009 *      http://www.gnu.org/copyleft/lesser.html
010 *
011 * Copyright for this code is held jointly by the individual
012 * authors.  These should be listed in @author doc comments.
013 *
014 * For more information on the BioJava project and its aims,
015 * or to join the biojava-l mailing list, visit the home page
016 * at:
017 *
018 *      http://www.biojava.org/
019 *
020 */
021
022package org.biojava.bio.seq.db;
023
024import java.io.IOException;
025import java.io.Serializable;
026
027import org.biojava.bio.BioError;
028import org.biojava.bio.seq.Sequence;
029import org.biojava.utils.StaticMemberPlaceHolder;
030
031/**
032 * Interface for objects that define how to make an ID for a sequence.
033 * <p>
034 * Nine times out of ten, you will use one of HashSequenceDB.byURN or
035 * HashSequenceDB.byName, but once in a blue-moon, you will want some other
036 * systematic way of retrieveing Sequences. This interface is here to allow
037 * you to plug in this functionality if you need it.
038 *
039 * @author Matthew Pocock
040 */
041public interface IDMaker {
042  /**
043   * Calculate the id for a sequence.
044   * <p>
045   * Each unique sequence should return a unique ID.
046   *
047   * @param seq the sequence to ID
048   * @return the id for the sequence
049   */
050  String calcID(Sequence seq);
051
052
053  /**
054   * A simple implementation of IDMaker that hashes by URN.
055   *
056   */
057  public final static IDMaker byURN = new ByURN();
058
059  static class ByURN implements Serializable, IDMaker {
060    public String calcID(Sequence seq) {
061      return seq.getURN();
062    }
063    private Object writeReplace() throws IOException {
064      try {
065        return new StaticMemberPlaceHolder(
066          IDMaker.class.getField("byURN")
067        );
068      } catch (NoSuchFieldException nsfe) {
069        throw new BioError(
070          "Could not find field while serializing",
071          nsfe
072        );
073      }
074    }
075  }
076
077  /**
078   * A simple implementation of IDMaker that hashes by sequence name.
079   *
080   */
081  public final static IDMaker byName = new ByName();
082
083  static class ByName implements Serializable, IDMaker {
084    public String calcID(Sequence seq) {
085      return seq.getName();
086    }
087    private Object writeReplace() throws IOException {
088      try {
089        return new StaticMemberPlaceHolder(
090          IDMaker.class.getField("byName")
091        );
092      } catch (NoSuchFieldException nsfe) {
093        throw new BioError(
094          "Could not find field while serializing",
095          nsfe
096        );
097      }
098    }
099  }
100}
101