From b4808cc19a107f3fa3b9f5e9b791dbf6fbe25dbf Mon Sep 17 00:00:00 2001 From: pmarguerite Date: Fri, 24 Mar 2006 15:40:31 +0000 Subject: [PATCH] vamsas api example classes - AstexViewer@MSD-EBI git-svn-id: https://svn.lifesci.dundee.ac.uk/svn/repository/trunk@207 be28352e-c001-0410-b1a7-c7978e42abec --- src/uk/ac/ebi/msd/vamsas/vamav/VAMAVClient.java | 195 +++ .../vamsas/vamav/documentmanagement/PDBUtil.java | 425 ++++++ .../VamsasDocumentProcessor.java | 1380 ++++++++++++++++++++ .../exceptions/IncorrectDocumentException.java | 61 + .../exceptions/UnableToProcessException.java | 63 + .../grouping/SequenceGrouping.java | 1169 +++++++++++++++++ .../grouping/SequenceGrouping_domain.java | 272 ++++ .../grouping/SequenceGrouping_structure.java | 298 +++++ .../UnableToGroupSequencesException.java | 61 + .../msd/vamsas/vamav/session/SessionManager.java | 983 ++++++++++++++ .../ebi/msd/vamsas/vamav/session/VAMAVSession.java | 462 +++++++ .../session/exceptions/UnableToOpenSession.java | 50 + 12 files changed, 5419 insertions(+) create mode 100755 src/uk/ac/ebi/msd/vamsas/vamav/VAMAVClient.java create mode 100755 src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/PDBUtil.java create mode 100755 src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/VamsasDocumentProcessor.java create mode 100755 src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/exceptions/IncorrectDocumentException.java create mode 100755 src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/exceptions/UnableToProcessException.java create mode 100755 src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/grouping/SequenceGrouping.java create mode 100755 src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/grouping/SequenceGrouping_domain.java create mode 100755 src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/grouping/SequenceGrouping_structure.java create mode 100755 src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/grouping/exceptions/UnableToGroupSequencesException.java create mode 100755 src/uk/ac/ebi/msd/vamsas/vamav/session/SessionManager.java create mode 100755 src/uk/ac/ebi/msd/vamsas/vamav/session/VAMAVSession.java create mode 100755 src/uk/ac/ebi/msd/vamsas/vamav/session/exceptions/UnableToOpenSession.java diff --git a/src/uk/ac/ebi/msd/vamsas/vamav/VAMAVClient.java b/src/uk/ac/ebi/msd/vamsas/vamav/VAMAVClient.java new file mode 100755 index 0000000..3734057 --- /dev/null +++ b/src/uk/ac/ebi/msd/vamsas/vamav/VAMAVClient.java @@ -0,0 +1,195 @@ +/* + *============================================================================= +* EMBL - European Bioinformatics institute +* MSD Group +* VAMSAS Project +* +* Copyright (c) 2005 The European Bioinformatics Institute. All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification. +* +*The European Bioinformatics Institute may publish revised and/or new +*versions of this license with new releases of VAMSAS software. +*============================================================================== + * + * + * Created on Feb 22, 2006 + * + * @author Pierre MARGUERITE + * @version 2 + * @since 22 Feb. 2006 + */ +package uk.ac.ebi.msd.vamsas.vamav; + +import java.io.File; + +import org.vamsas.client.ClientHandle; +import org.vamsas.client.Events; +import org.vamsas.client.IClientDocument; +import org.vamsas.client.InvalidSessionUrnException; +import org.vamsas.client.UserHandle; +import org.vamsas.client.simpleclient.SimpleClient; +import org.vamsas.client.simpleclient.VamsasSession; + +import uk.ac.ebi.msd.vamsas.vamav.communication.astexviewer.AVClientIntf; +import uk.ac.ebi.msd.vamsas.vamav.session.VAMAVSession; +import uk.ac.ebi.msd.vamsas.vamav.util.logger.VAMAVLogger; +import uk.ac.ebi.msd.vamsas.vamav.util.logger.VAMAVLoggerImpl; + + +/** + * This class represents a VAMSAS client in the VAMSAS workflow (VAMSAS Client API), + * + * @author Pierre MARGUERITE + * @since 22 Feb. 2006 + * @version 2 + * + */ +public class VAMAVClient extends SimpleClient { + + + private String lastStatus = Events.DOCUMENT_CREATE; + private final VAMAVLogger logger = new VAMAVLoggerImpl(this.getClass()); + private VAMAVSession vamavSession = null; + private AVClientIntf avclient = null; + private VamsasSession sess = null; + private IClientDocument document = null; + + + /** + * Should not be used + * @param applicationHandle application handle for the current application + * @throws InvalidSessionUrnException if a error occurs during the creation of the client and the session. + */ + @Deprecated + public VAMAVClient (ClientHandle applicationHandle)throws InvalidSessionUrnException + { + super(null, applicationHandle, null); + this.client = applicationHandle; + + } + /** + * Inits a client with a given user and a given Client handle in a given session + * @param user information, of the user opening the session + * @param client the clientHandle + * @param sess Session in which is opened the client. + * @throws InvalidSessionUrnException if a error occurs during the creation of the client and the session. + + */ + public VAMAVClient ( + UserHandle user, + ClientHandle client, + VamsasSession _sess) throws InvalidSessionUrnException{ + super(user, client, _sess); + this.sess = _sess; + } + + /** + * Inits a client with a given user and a given Client handle in a given session + * and an archive file from a previous session/treatment + * @param user information, of the user opening the session + * @param client the clientHandle + * @param _sess Session in which is opened the client. + * @param importingArchive + * + * @throws Exception raises if an error occurs during the creation of the client (archive reading, incorrect session, ...) + */ + public VAMAVClient( + UserHandle user, + ClientHandle client, + VamsasSession _sess, + File importingArchive) + throws Exception { + super(user, client, _sess, importingArchive); + this.sess = _sess; + } + + /** + * @see org.vamsas.client.IClient#getAbout() + */ + public String getAbout() { + return new String("VAMAV Client version $version$ build $build$"); + } + + /** + * a clone the current VAMSASClient object + * @return a clone object of the current object + */ + public Object clone() + { + VAMAVClient client = null; + try + { + client = new VAMAVClient(this.user, this.client, this.sess);//this.SessionUrn); + //client.setVAMAVDocument(this.getClientDocument()); + } + catch (InvalidSessionUrnException isuE) + { + this.logger.appliError("Unable to clone client."); + this.logger.sessionError("Unable to clone client."); + client = null; + } + return client; + } + + /** + * Retrieves the vAMAVSession attribut + * + * @return Returns the vAMAVSession. + */ + public VAMAVSession getVAMAVSession() + { + return this.vamavSession; + } + + /** + *Sets session attribut + * + * @param session The vAMAVSession to set. + */ + public void setVAMAVSession(VAMAVSession session) + { + this.vamavSession = session; + this.logger.setSession(session); + } + + /** + * Retrieves the avclient attribut + * + * @return Returns the avclient. + */ + public AVClientIntf getAvclient() + { + return this.avclient; + } + + /** + *Sets avclient attribut + * + * @param avclient The avclient to set. + */ + public void setAvclient(AVClientIntf avclient) + { + this.avclient = avclient; + } +/** + * Set current document associated to the current client + * @param document the document object to associate to the client + */ + public void setVAMAVDocument(IClientDocument document) + { + if (document != null) + { + this.document = document; + } + } + + public void setUser(UserHandle _user) + { + if (_user !=null) + { + this.user = _user; + } + } +} diff --git a/src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/PDBUtil.java b/src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/PDBUtil.java new file mode 100755 index 0000000..bb876e5 --- /dev/null +++ b/src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/PDBUtil.java @@ -0,0 +1,425 @@ +/* + * EMBL - European Bioinformatics institute + * MSD Group + * VAMSAS Project + * + *Created on 28 oct. 2005 + * @author Pierre MARGUERITE + * @version 1 + * @since 28 oct. 2005 + */ +package uk.ac.ebi.msd.vamsas.vamav.documentmanagement; + + +import uk.ac.ebi.msd.vamsas.vamav.session.VAMAVSession; +import uk.ac.ebi.msd.vamsas.vamav.util.data.DataBuffer; +import uk.ac.ebi.msd.vamsas.vamav.util.data.PDBEntry; +import uk.ac.ebi.msd.vamsas.vamav.util.file.PlainTextFileReader; +import uk.ac.ebi.msd.vamsas.vamav.util.logger.VAMAVLogger; +import uk.ac.ebi.msd.vamsas.vamav.util.logger.VAMAVLoggerImpl; +import uk.ac.ebi.msd.vamsas.vamav.util.pool.DataBufferPool; +import uk.ac.ebi.msd.vamsas.vamav.util.pool.StringBufferPool; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.Hashtable; + +/** + * Convenient methods for PDB entry manipulation + * + * @author Pierre MARGUERITE + * @version 1 + * @since 28 oct. 2005 + * + */ +public class PDBUtil + { + private VAMAVLogger logger = new VAMAVLoggerImpl(this.getClass()); + + private static Hashtable AminoAcids = null; + + /** + * Constructor + * + */ + public PDBUtil(String session) + { + super(); + logger.setSession(session); + + } + + /** + * Constructor + * + */ + public PDBUtil(VAMAVSession session) + { + super(); + logger.setSession(session); + + } + /** + * PDB Format + * http://www.rcsb.org/pdb/docs/format/pdbguide2.2/part_35.html + * + * @param entry + * @return + */ + public ArrayList GetChain(PDBEntry entry) + { + if( entry == null) return null; + File pdbFile = entry.getPdbFile(); + if (pdbFile == null || !pdbFile.exists() ) + { + return null; + } + logger.sessionInfo("Retrieving PDB sequence from PDB file."); + ArrayList chains = null; + PlainTextFileReader reader = new PlainTextFileReader(pdbFile); + try + { + reader.openFile(); + DataBuffer line = null; + Hashtable retrievingChains = new Hashtable(); + while (( line = reader.getLine()) !=null) + { + /*System.out.println("line "+line);*/ + if( line.toString().startsWith("SEQRES"))//.matches("^SEQRES*")) + {//chain line found + /*System.out.println("SEQRES found "); + System.out.println("line "+line);*/ + //12 Character chainID + char chainID = line.charAt(12 -1); + String chainName = String.valueOf(chainID); + /*System.out.println("chainName "+chainName);*/ + StringBuffer seq = retrievingChains.get(chainName.intern()); + if (seq == null) + { + seq = StringBufferPool.getString(); + } + + /* System.out.println("chain retrieves.");*/ +// 20 23 Residue name resName Residue name. + if(line.length()>=23 ) + { + String aa = line.substring(20-1, 23-1); + if( aa != null) + { + aa = aa.trim(); + if(aa.length()>0) + seq.append(get1LetterCodeFrom3LettersCode(aa)); + + } + } + //24 - 27 Residue name resName Residue name. + if(line.length()>=27 ) + { + String aa = line.substring(24-1, 27-1); + if( aa != null) + { + aa = aa.trim(); + if( aa.length()>0) + seq.append(get1LetterCodeFrom3LettersCode(aa)); + } + } + //28 - 30 Residue name resName Residue name. + if(line.length()>=31 ) + { + String aa = line.substring(28-1, 31-1); + if( aa != null) + { + aa = aa.trim(); + if( aa.length()>0) + seq.append(get1LetterCodeFrom3LettersCode(aa)); + } + } + //32 - 34 Residue name resName Residue name. + if(line.length()>=35 ) + { + String aa = line.substring(32-1, 35-1); + if( aa != null) + { + aa = aa.trim(); + if( aa.length()>0) + seq.append(get1LetterCodeFrom3LettersCode(aa)); + } + } + //36 - 38 Residue name resName Residue name. + if(line.length()>=39 ) + { + String aa = line.substring(36-1, 39-1); + if( aa != null) + { + aa = aa.trim(); + if( aa.length()>0) + seq.append(get1LetterCodeFrom3LettersCode(aa)); + } + } + //40 - 42 Residue name resName Residue name. + if(line.length()>=42 ) + { + String aa = line.substring(40-1, 43-1); + if( aa != null) + { + aa = aa.trim(); + if( aa.length()>0) + seq.append(get1LetterCodeFrom3LettersCode(aa)); + } + } + //44 - 46 Residue name resName Residue name. + if(line.length()>=47 ) + { + String aa = line.substring(44-1, 47-1); + if( aa != null) + { + aa = aa.trim(); + if( aa.length()>0) + seq.append(get1LetterCodeFrom3LettersCode(aa)); + } + } + //48 - 50 Residue name resName Residue name. + if(line.length()>=51 ) + { + String aa = line.substring(48-1, 51-1); + if( aa != null) + { + aa = aa.trim(); + if( aa.length()>0) + seq.append(get1LetterCodeFrom3LettersCode(aa)); + } + } + //52 - 54 Residue name resName Residue name. + if(line.length()>=55 ) + { + String aa = line.substring(52-1, 55-1); + if( aa != null) + { + aa = aa.trim(); + if( aa.length()>0) + seq.append(get1LetterCodeFrom3LettersCode(aa)); + } + } + //56 - 58 Residue name resName Residue name. + if(line.length()>=59 ) + { + String aa = line.substring(56-1, 59-1); + if( aa != null) + { + aa = aa.trim(); + if( aa.length()>0) + seq.append(get1LetterCodeFrom3LettersCode(aa)); + } + } + //60 - 62 Residue name resName Residue name. + if(line.length()>=63 ) + { + String aa = line.substring(60-1, 63-1); + if( aa != null) + { + aa = aa.trim(); + if( aa.length()>0) + seq.append(get1LetterCodeFrom3LettersCode(aa)); + } + } + //64 - 66 Residue name resName Residue name. + if(line.length()>=67 ) + { + String aa = line.substring(64-1, 67-1); + if( aa != null) + { + aa = aa.trim(); + if( aa.length()>0) + seq.append(get1LetterCodeFrom3LettersCode(aa)); + } + } + //68 - 70 Residue name resName Residue name. + if(line.length()>=71 ) + { + String aa = line.substring(68-1, 71-1); + if( aa != null) + { + aa = aa.trim(); + if( aa.length()>0) + seq.append(get1LetterCodeFrom3LettersCode(aa)); + } + } + retrievingChains.put(chainName.intern(), seq); + + //System.out.println("seq "+seq.toString()); + + //StringBufferPool.returnString(seq); + } + + //cleaning + DataBufferPool.returnString(line); + + + } + reader.closeFile(); + //cleaning + if( retrievingChains !=null) + { + if( chains == null) + + chains = new ArrayList(); + for (Enumeration elements = retrievingChains.keys() ; elements.hasMoreElements(); ) + { + String chainID = (String)elements.nextElement(); + if( chainID == null|| chainID.length()<1) continue; + StringBuffer seq = retrievingChains.get(chainID); + if(seq == null || seq.length()<1) continue; + chains.add(new PDBUtil.Chain(entry.getPdbID()+"_"+chainID, seq.toString())); + + StringBufferPool.returnString(seq); + } + retrievingChains.clear(); + retrievingChains = null; + } + + } + catch (IOException ioe) + { + logger.sessionError("error access to PDB file "+pdbFile.getName()+".",ioe); + } + if (!this.logger.isProduction()) logger.sessionDebug("retrieved chain for PDBID: "+entry.getPdbID()+" "+chains.get(0).getSequence()); + return chains; + } + +/** + * Converts a three letter code of AminoAcid to the one letter code of AminoAcid. + * @param threeLettersCode the three letter code to convert + * @return the one letter code associated to the three letter code, if found. null otherwise + */ + private static String get1LetterCodeFrom3LettersCode(String threeLettersCode) + { + /*System.out.println("threeLettersCode to convert |"+threeLettersCode+"|");*/ + if (threeLettersCode == null || threeLettersCode.length()!=3) + { + /*System.out.println("incorrect threeLettersCode "+threeLettersCode);*/ + if( threeLettersCode.length() ==1 ) return threeLettersCode; + return null; + } + String oneLetterCode = getAminoAcids().get(threeLettersCode.toLowerCase()); + if(oneLetterCode == null || oneLetterCode.length()!=1 ) oneLetterCode ="X"; + return oneLetterCode; + } + + /** + * Represents a chain contains in a PDB entry/file + * + * @author Pierre MARGUERITE + * @version 1 + * @since 28 oct. 2005 + * + */ + public static class Chain + { + /** + * name of the chain + */ + private String name = null; + private String sequence = null; + + /** + * + * Constructor for chain + * + * @param _name name of the chain + * @param _sequence sequence of the chain + */ + public Chain (String _name, String _sequence) + { + this.name = _name; + this.sequence = _sequence; + } + + /** + * Retrieves the name attribut + * + * @return Returns the name. + */ + public String getName() + { + return this.name; + } + + /** + * Retrieves the sequence attribut + * + * @return Returns the sequence. + */ + public String getSequence() + { + return this.sequence; + } + + + } + + /** + * Retrieves the aminoAcids attribut + * + *AAs = Hashtable(); + AAsAla A hydrophobic + Arginine Arg R free amino group makes it basic and hydrophilic + Asparagine Asn N carbohydrate can be covalently linked ("N-linked) to its -NH + Aspartic acid Asp D free carboxyl group makes it acidic and hydrophilic + Cysteine Cys C oxidation of their sulfhydryl (-SH) groups link 2 Cys (S-S) + Glutamic acid Glu E free carboxyl group makes it acidic and hydrophilic + Glutamine Gln Q moderately hydrophilic + Glycine Gly G so small it is amphiphilic (can exist in any surroundings) + Histidine His H basic and hydrophilic + Isoleucine Ile I hydrophobic + Leucine Leu L hydrophobic + Lysine Lys K strongly basic and hydrophilic + Methionine Met M hydrophobic + Phenylalanine Phe F very hydrophobic + Proline Pro P causes kinks in the chain + Serine Ser S carbohydrate can be covalently linked ("O-linked") to its -OH + Threonine Thr T carbohydrate can be covalently linked ("O-linked") to its -OH + Tryptophan Trp W scarce in most plant proteins + Tyrosine Tyr Y a phosphate or sulfate group can be covalently attached to its -OH + Valine Val V + + A R D N B C E Z Q G H I L K M F P S T W Y V X + * + * @return Returns the aminoAcids. + */ + private static Hashtable getAminoAcids() + { + if( AminoAcids == null) + {//lazy initialisation + AminoAcids = new Hashtable(); + AminoAcids.put("Ala".toLowerCase(), "A"); + AminoAcids.put("Arg".toLowerCase(), "R"); + AminoAcids.put("Asp".toLowerCase(), "D"); + AminoAcids.put("Asn".toLowerCase(), "N"); + AminoAcids.put("Asx".toLowerCase(), "B");// Aspartic acid or Asparagine + AminoAcids.put("Cys".toLowerCase(), "C"); + AminoAcids.put("Glu".toLowerCase(), "E"); + AminoAcids.put("Glx".toLowerCase(), "Z");// Glutamine or Glutamic acid. + AminoAcids.put("Gln".toLowerCase(), "Q"); + AminoAcids.put("Gly".toLowerCase(), "G"); + AminoAcids.put("His".toLowerCase(), "H"); + AminoAcids.put("Ile".toLowerCase(), "I"); + AminoAcids.put("Leu".toLowerCase(), "L"); + AminoAcids.put("Lys".toLowerCase(), "K"); + AminoAcids.put("Met".toLowerCase(), "M"); + AminoAcids.put("Phe".toLowerCase(), "F"); + AminoAcids.put("Pro".toLowerCase(), "P"); + AminoAcids.put("Ser".toLowerCase(), "S"); + AminoAcids.put("Thr".toLowerCase(), "T"); + AminoAcids.put("Trp".toLowerCase(), "W"); + AminoAcids.put("Tyr".toLowerCase(), "Y"); + AminoAcids.put("Val".toLowerCase(), "V"); + AminoAcids.put("Xaa".toLowerCase(), "X");// Any amino acid. + + + } + return AminoAcids; + } + + } diff --git a/src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/VamsasDocumentProcessor.java b/src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/VamsasDocumentProcessor.java new file mode 100755 index 0000000..0487002 --- /dev/null +++ b/src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/VamsasDocumentProcessor.java @@ -0,0 +1,1380 @@ + +package uk.ac.ebi.msd.vamsas.vamav.documentmanagement; + +import uk.ac.ebi.msd.vamsas.vamav.VAMAVClient; +import uk.ac.ebi.msd.vamsas.vamav.documentmanagement.exceptions.IncorrectDocumentException; +import uk.ac.ebi.msd.vamsas.vamav.documentmanagement.exceptions.UnableToProcessException; +import uk.ac.ebi.msd.vamsas.vamav.documentmanagement.grouping.SequenceGrouping; +import uk.ac.ebi.msd.vamsas.vamav.documentmanagement.grouping.SequenceGrouping_domain; +import uk.ac.ebi.msd.vamsas.vamav.documentmanagement.grouping.SequenceGrouping_structure; +import uk.ac.ebi.msd.vamsas.vamav.documentmanagement.grouping.exceptions.UnableToGroupSequencesException; +import uk.ac.ebi.msd.vamsas.vamav.exceptions.IncorrectVamavModuleInitialisation; +import uk.ac.ebi.msd.vamsas.vamav.util.logger.VAMAVLogger; +import uk.ac.ebi.msd.vamsas.vamav.util.logger.VAMAVLoggerImpl; +import uk.ac.ebi.msd.vamsas.vamav.util.mapping.MappingManager; +import uk.ac.ebi.msd.vamsas.vamav.util.properties.PropertyManager; +import org.vamsas.objects.core.Alignment; +import org.vamsas.objects.core.AlignmentAnnotations; +import org.vamsas.objects.core.AlignmentSequence; +import org.vamsas.objects.core.AnnotationElement; +import org.vamsas.objects.core.ApplicationData; +import org.vamsas.objects.core.DataSet; +import org.vamsas.objects.core.DbRef; +import org.vamsas.objects.core.Entry; +import org.vamsas.objects.core.Provenance; +import org.vamsas.objects.core.Sequence; +import org.vamsas.objects.core.SequenceType; +import org.vamsas.objects.core.Tree; +import org.vamsas.objects.core.User; +import org.vamsas.objects.core.VAMSAS; +import org.vamsas.objects.core.VamsasDocument; + +import org.vamsas.client.IClient; +import org.vamsas.client.IClientDocument; +import org.vamsas.client.simpleclient.IdFactory; +import org.vamsas.client.simpleclient.SimpleDocument; +import org.vamsas.client.simpleclient.VamsasArchive; +import org.vamsas.client.simpleclient.ClientDocument; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collection; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.Properties; +import java.util.TimeZone; + +import MSD.vamav.common.AVActiveSite; +import MSD.vamav.common.AVSequence; +import MSD.vamav.common.Highlight; +import MSD.vamav.common.ResidueAnnotation; + +/** + *

Processor for Vamsas Document, to extract data for calling an AstexViewer@MSD-EBI, for displaying the provided data

+ * + *

Grouping mode :

+ *
    + *
  • 1. per structure
  • + *
  • 2. per PFAM domain
  • + *
+ * + */ +public class VamsasDocumentProcessor implements uk.ac.ebi.msd.vamsas.vamav.VamaVModule { + + + //private IClientDocument doc = null; + private IClient client = null; + private VAMAVLogger logger = new VAMAVLoggerImpl(this.getClass()); + + private final String modulePrefix = "documentprocessor"; + private SequenceGrouping groupingManager = null; + private int moleculeNumber = 1; + private int highlightNumber = 0; + private boolean hasAlignmentSequences = false; + private MappingManager mappingManager = null; + private String activeSiteDescription = "Active Site"; + + /** + * Retrieves the modulePrefix attribut + * + * @return Returns the modulePrefix. + */ + public String getModulePrefix() + { + return this.modulePrefix; + } + + public void init(Properties moduleProperties) throws IncorrectVamavModuleInitialisation + { + PropertyManager propManager = new PropertyManager(); + Properties props = propManager.getModuleProperties(moduleProperties, this.groupingManager.getModulePrefix()); + this.groupingManager.init(props); + propManager = null; + } + + /** + * + * Constructor for a given document + * @param document Vamsas Document to process. + * @param _mappingManager mapping manager + * @throws IncorrectDocumentException if the given document is incorrect + */ + public VamsasDocumentProcessor (IClient _client, MappingManager _mappingManager ) throws IncorrectDocumentException + { + if(_client == null ) throw new IncorrectDocumentException(); + + this.client = _client; + this.logger.setSession(this.client.getSessionUrn()); + this.mappingManager = _mappingManager; + this.mappingManager.setSession(((VAMAVClient)this.client).getVAMAVSession()); + this.groupingManager = new SequenceGrouping_structure(this.mappingManager, ((VAMAVClient)this.client).getVAMAVSession()); + //this.logger = new VAMAVLoggerImpl(this.getClass(),this.client.getSessionUrn() ); + + //this.groupingManager.load(); + } + + /** + * + * Constructor for a given document + * @param document Vamsas Document to process. + * @param _mappingManager mapping manager + * @param groupingMode grouping Mode number, for sequence grouping (structure, domain) + * @throws IncorrectDocumentException if the given document is incorrect + */ + public VamsasDocumentProcessor (IClient _client, MappingManager _mappingManager, int groupingMode) throws IncorrectDocumentException + { + if(_client == null ) throw new IncorrectDocumentException(); + + this.client = _client; + this.logger.setSession(this.client.getSessionUrn()); + + + ((VAMAVClient)this.client).getVAMAVSession().setGroupingMode(groupingMode); + this.mappingManager = _mappingManager; + this.mappingManager.setSession(((VAMAVClient)this.client).getVAMAVSession()); + this.mappingManager.setSession(((VAMAVClient)this.client).getVAMAVSession()); + if( groupingMode == 0) + { + this.groupingManager = new SequenceGrouping_structure(this.mappingManager, ((VAMAVClient)this.client).getVAMAVSession()); + } + else + if( groupingMode == 1) + { + this.groupingManager = new SequenceGrouping_domain(this.mappingManager, ((VAMAVClient)this.client).getVAMAVSession()); + } + else + // default + this.groupingManager = new SequenceGrouping_structure(this.mappingManager, ((VAMAVClient)this.client).getVAMAVSession()); + + + //this.logger = new VAMAVLoggerImpl(this.getClass(),this.client.getSessionUrn() ); + + //this.groupingManager.load(); + } +/** + *

Process a document to extract element for AstexViewer@MSD-EBI

+ * + */ + public Hashtable process( ) throws IncorrectDocumentException, UnableToProcessException + { + Hashtable parameters = new Hashtable(); + //int moleculeNumber = 1; + IClientDocument doc = null; + try + { + doc = this.client.getClientDocument(); + } + catch (IOException ioe) + { + this.logger.sessionError("Unable to access to the VAMSAS document. Can not process.",ioe); + throw new IncorrectDocumentException(ioe); + } + if( doc == null) + { + this.logger.sessionError("The document is null. Can not process it."); + throw new IncorrectDocumentException(); + } + this.logger.sessionInfo("The processing vamsas document."); + try + { + VAMSAS[] roots = doc.getVamsasRoots(); + if( roots != null && roots.length>0) + for (int rootNumber = roots.length-1; rootNumber>=0; rootNumber--) + { + VAMSAS root = roots[rootNumber]; + if (root == null) continue; + Tree [] trees = root.getTree(); + //treating Trees + if (trees !=null) + { + for (int treeNumber=0; treeNumber< trees.length; treeNumber++) + { + Tree aTree = trees[treeNumber]; + if( aTree == null) continue; + parameters = this.addParameters(this.processTree(aTree), parameters); + } + } + else + { + this.logger.sessionDebug("No Tree found."); + } + int setCount = root.getDataSetCount(); + this.logger.sessionDebug("DataSet "+setCount); + if (setCount>0) + { + this.hasAlignmentSequences = false; + for (int setNumber=0; setNumber< setCount; setNumber++) + { + // treating DataSet + this.logger.sessionDebug("DataSet " +setNumber ); + DataSet set = root.getDataSet(setNumber); + if (set == null) + { + this.logger.sessionDebug("data set is null?? "+setNumber); + continue; + } + parameters = this.addParameters(this.processDataSet(set), parameters); + } + } + } + } + catch (Exception e) + { + this.logger.sessionError("VamsasDocumentProcessor process- Error during Document processing.",e); + parameters = null; + } + if (parameters!=null) this.logger.sessionDebug("parameter count "+parameters.size()); + //store PDB + //this.logger.sessionInfo("Save computed data"); + try + { + File atrFile = this.groupingManager.storeGroups(); + // this.groupingManager.getSequenceFiles() + // add atribute file parameter + if(atrFile != null) + { + this.logger.sessionDebug("Atribute file "+atrFile.getName()); + parameters.put("attribute", atrFile); + } + else + this.logger.sessionError("No atribute file created."); + + //addsequenceFile + ArrayListseqFiles = this.groupingManager.getSequenceFiles(); + if(seqFiles != null && seqFiles.size()>0) + { + for (int fileNumber = seqFiles.size() - 1;fileNumber >=0; fileNumber -- ) + { + File file = seqFiles.get(fileNumber); + if( file == null) continue; + this.logger.sessionDebug("VAMSASSequence"+(fileNumber+1)+": add sequence file to parameter "+file.getName()); + parameters.put("VAMSASSequence"+(fileNumber+1), file); + } + } + } + catch (UnableToGroupSequencesException ue) + { + this.logger.sessionError("VamsasDocumentProcessor StoreGroups - Unable to group sequences.", ue); + throw new UnableToProcessException(ue); + } + + this.groupingManager = null; + this.logger.sessionDebug("process "+(parameters==null?0:parameters.size())); + return parameters; + } + + /** + * Process Vamsas Tree object + * Currently do nothing + * @param atree the tree to process + * @return a list of parameters to call an AstexViewer@MSD-EBI client + */ + private Hashtable processTree(Tree atree) + { + return null; + } + + + private Hashtable processDataSet(DataSet aDataSet) throws UnableToGroupSequencesException + { + if (aDataSet == null) + { + this.logger.sessionDebug("data set is null??"); + return null; + } + Hashtable parameters = new Hashtable (); + int alignCount = aDataSet.getAlignmentCount(); + if (alignCount>0) + { + for (int algNumber=0; algNumber< alignCount; algNumber++) + { + this.logger.sessionDebug("Alignment " +algNumber ); + Alignment align = aDataSet.getAlignment(algNumber); + if (align == null) continue; //should not happen + Hashtable newparameters =this.ProcessAlignment(align); + this.logger.sessionDebug("end ab aligment "+(newparameters==null?0:newparameters.size())); + parameters = this.addParameters(newparameters, parameters); + this.logger.sessionDebug("end ab aligment "+(parameters==null?0:parameters.size())); + } + this.logger.sessionDebug("end aligments "+(parameters==null?0:parameters.size())); + } + int sequenceCount = aDataSet.getSequenceCount(); + if (!this.hasAlignmentSequences && sequenceCount > 0 ) + { + this.logger.sessionInfo("No alignment has been found. Process DataSet sequences."+sequenceCount); + for (int seqNumber=0; seqNumber< sequenceCount; seqNumber++) + { + Sequence seq = aDataSet.getSequence(seqNumber); + if (seq == null) + { + this.logger.sessionDebug("sequence is null??"); + continue; + } + + this.logger.sessionDebug(seq.getId()); + DbRef[] dbRefs = seq.getDbRef(); + boolean idFound = false; + if( dbRefs != null && dbRefs.length >0) + { + for (int dbRefNumber = dbRefs.length - 1; dbRefNumber >=0; dbRefNumber-- ) + { + DbRef ref = dbRefs[dbRefNumber]; + if( ref == null) continue; + + String acID = ref.getAccessionId(); + if( acID == null) + { + continue; + } + String source = ref.getSource() ; + if( source== null || source.length()<1 ) + { + continue; + } + + Hashtable tempParameters = this.groupingManager.addSequence(seq.getSequence(), seq.getName(), acID, source); + if (tempParameters != null && tempParameters.size()>0) + { + this.logger.sessionDebug("parameter count "+parameters.size()); + String pdbids = (String) tempParameters.remove(this.groupingManager.getPdbidsproperty()); + + if(pdbids!=null && pdbids.length()>0) + { + //TODO check if the ref does not have already the new DB reference + this.logger.sessionDebug("Adding pdb IDs to doc "+pdbids ); + DbRef dbref = new DbRef(); + dbref.setSource("PDB"); + dbref.setAccessionId(pdbids); + seq.addDbRef(dbref); + //seq.setRefid(ref) + } + parameters = addParameters(tempParameters, parameters); + this.logger.sessionDebug("end add sequence "+(parameters==null?0:parameters.size())); + idFound = true; + this.hasAlignmentSequences = true; + } + + /*String pdbids = (String) tempParameters.remove(this.groupingManager.getPdbidsproperty()); + String id = ref.getAccessionId(); + if(id == null || id.length()<1 ) continue; + //suppose it is a PDB ID (should be like PDBID:CHAIN) + //We don t handle chain name , remove id + int pos = id.indexOf(":"); + if (pos>=0) + {//there is a match + id = id.substring(0,pos); + } + PDBEntry entry = SequenceToPDB_MSDLite.getPDBFileFromPDBID(id); + if( entry != null) + { + idFound = true; + if( !parameters.containsValue(entry)) + /*parameters.add(entry);*/ + /* { + parameters.put("molecule"+moleculeNumber,entry); + parameters.put("name"+moleculeNumber, entry.getPdbID()); + moleculeNumber++; + } + Grouping.addSequenceToGroup(entry.getPdbID(), seq);*/ + + } + } + if (!idFound) + { + HashtabletempParameters = this.processSequence(seq); + if (tempParameters != null) + { + //parameters = this.addParameters(this.processSequence(seq), parameters); + String pdbids = (String) tempParameters.remove(this.groupingManager.getPdbidsproperty()); + if(pdbids!=null && pdbids.length()>0) + { + //TODO check if the ref does not have already the new DB reference + this.logger.sessionDebug("Adding pdb IDs to doc "+pdbids ); + DbRef ref = new DbRef(); + ref.setSource("PDB"); + ref.setAccessionId(pdbids); + seq.addDbRef(ref); + //seq.setRefid(ref) + } + parameters = this.addParameters(tempParameters, parameters); + } + } + } + } + this.logger.sessionDebug("ProcessDataSet "+(parameters==null?0:parameters.size())); + return parameters; + } + + + /** + * Process an alignment to extract sequences for grouping + * + * @param align alignment Object to process + */ + private Hashtable ProcessAlignment(Alignment align) throws UnableToGroupSequencesException + { + if (align == null) return null; //should not happen + int seqCount = align.getAlignmentSequenceCount(); + Hashtable parameters = null; + if( seqCount>0 ) + { + parameters = new Hashtable (); + String sequenceName = null; + for (int seqNumber=0; seqNumber< seqCount; seqNumber++) + { + this.logger.sessionDebug("alig seq " +seqNumber ); + AlignmentSequence seq = align.getAlignmentSequence(seqNumber); + if (seq == null) continue; //should not happen + Sequence refSeq = (Sequence) seq.getRefid(); + boolean notFound = true; + if (refSeq != null) + { + if (refSeq.getDbRefCount()>0) + { + int dbRefNumber = 0; + int refCount = refSeq.getDbRefCount(); + while (notFound && dbRefNumber tempParameters = this.groupingManager.addSequence(seq.getSequence(), seq.getName(), acID, source); + + if (tempParameters != null && tempParameters.size()>0) + { + this.logger.sessionDebug("parameter count "+parameters.size()); + String pdbids = (String) tempParameters.remove(this.groupingManager.getPdbidsproperty()); + if(pdbids!=null && pdbids.length()>0) + { + //TODO check if the ref does not have already the new DB reference + this.logger.sessionDebug("Adding pdb IDs to doc "+pdbids ); + DbRef ref = new DbRef(); + ref.setSource("PDB"); + ref.setAccessionId(pdbids); + refSeq.addDbRef(ref); + //seq.setRefid(ref) + } + parameters = addParameters(tempParameters, parameters); + notFound = false; + hasAlignmentSequences = true; + this.logger.sessionDebug("parameter count "+parameters.size()); + } + //if (sequenceName ==null) sequenceName = entry.getPdbID()+"_"; + } + } + else + { /*System.out.println("No DbRef");*/ + } + } + if (notFound) + { + Hashtable tempParameters = processSequence(seq); + if (tempParameters != null) + { + /* String pdbids = (String) tempParameters.remove(this.groupingManager.getPdbidsproperty()); + if(pdbids!=null && pdbids.length()>0) + { + //TODO check if the ref does not have already the new DB reference + this.logger.sessionDebug("Adding pdb IDs to doc "+pdbids ); + DbRef ref = new DbRef(); + ref.setSource("PDB"); + ref.setAccessionId(pdbids); + seq.addDbRef(ref); + //seq.setRefid(ref) + }*/ + parameters = this.addParameters(tempParameters, parameters); + } + } + } + //treat AnnotationElement for highlight + int annotationCount = align.getAlignmentAnnotationsCount(); + this.logger.sessionDebug("annotationCount "+ annotationCount); + for (int annotationNumber = annotationCount-1; annotationNumber>=0; annotationNumber--) + { + this.logger.sessionDebug("annotationNumber "+annotationNumber); + AlignmentAnnotations annotation = align.getAlignmentAnnotations(annotationNumber); + if (annotation == null) continue; + int elementCount = annotation.getAnnotationElementCount(); + for (int elementNumber = elementCount-1; elementNumber>=0; elementNumber--) + { + this.logger.sessionDebug("annotationElement "+elementNumber); + AnnotationElement elt = annotation.getAnnotationElement(elementNumber); + if (elt == null) continue; + parameters = this.addParameters(this.processAnnotationElement(elt), parameters); + } + } + } + this.logger.sessionDebug("ProcessAlignment "+(parameters==null?0:parameters.size())); + return parameters; + } + + private Hashtable processAnnotationElement( AnnotationElement annotation) + { + if (annotation == null) return null; + int secStructure = -1;//unknown + Hashtable parameters = null; + try + { + secStructure = new Integer(annotation.getSecondaryStructure()).intValue(); + } + catch (NumberFormatException nfExcep) + { + this.logger.sessionWarn("Unknown secondary sequence: "+ annotation.getSecondaryStructure()); + secStructure = -1; + } + if (annotation.getDescription().contains("breakpoint") || annotation.getDescription().contains("Breakpoint")) + { + Highlight hgl = new Highlight (annotation.getDisplayCharacter().charAt(0), annotation.getDescription(), secStructure, null, annotation.getPosition()); + //Hashtable temp + parameters = new Hashtable(); + //temp + parameters.put("highlightT0",hgl); + this.groupingManager.addBreakpoint(annotation); + } + //this.groupingManager.addBreakpoint(annotation); + return parameters; + } + + private Hashtable processSequence(SequenceType sequence) throws UnableToGroupSequencesException + { + if (sequence == null) return null; + Hashtable tempParameters = this.groupingManager.addSequence(sequence.getSequence(), sequence.getName()); + + //return null; + + return tempParameters; + } +/** + *

Does ...

+ * + */ + public void updateDocument(Hashtable parameters) + { + this.logger.sessionDebug("Updating Document"); + if( parameters == null || parameters.size()<1) + { + this.logger.sessionWarn("UpdateDocument: no object provided: No update."); + return ; + } + VAMSAS[] roots = null; + try + { + roots = this.client.getClientDocument().getVamsasRoots(); + } + catch (IOException ioe) + { + this.logger.sessionWarn("Add active site: The document does not exist. Can not add Active site."); + return; + + } + if (roots == null || roots.length<1) + { + this.logger.sessionWarn("Add active site: The document is empty. Can not add Active site."); + return; + } + for (int rootNumber = roots.length-1; rootNumber >=0 && parameters != null&& parameters.size()>0; rootNumber-- ) + { + VAMSAS root = roots[rootNumber]; + if (root == null) + { + continue; + } + updateVAMSAS(root,parameters); + } + } + + /** + * Updates a VAMSAS entity with the given parameters + * @param parameters list of objects to update into the VAMSAS tree + */ + private void updateVAMSAS(VAMSAS root, Hashtable parameters) + { + this.logger.sessionDebug("Updating Vamsas"); + if( parameters == null || parameters.size()<1) + { + this.logger.sessionWarn("UpdateVAMSAS: no object provided: No update."); + return ; + } + if(root == null ) + { + this.logger.sessionWarn("UpdateVAMSAS: no VAMSAS XML Entity."); + return ; + } + for (int dataSetNumber = root.getDataSetCount() -1; dataSetNumber>=0&& parameters != null&& parameters.size()>0; dataSetNumber--) + { + DataSet set = root.getDataSet(dataSetNumber); + if( set == null) continue; + updateDataSet(set, parameters); + + } + } + + /** + * Updates a DataSet entity with the given parameters + * @param parameters list of objects to update into the DataSet tree + */ + private void updateDataSet(DataSet root, Hashtable parameters) + { + this.logger.sessionDebug("Updating DataSet"); + if( parameters == null || parameters.size()<1) + { + this.logger.sessionWarn("updateDataSet: no object provided: No update."); + return ; + } + if(root == null ) + { + this.logger.sessionWarn("updateDataSet: no DataSet XML Entity."); + return ; + } + for (int alignmentNumber= root.getAlignmentCount()-1; alignmentNumber>=0&& parameters != null&& parameters.size()>0; alignmentNumber-- ) + { + Alignment align = root.getAlignment(alignmentNumber); + if( align != null) + { + updateAlignment(align, parameters); + } + } + } + + /** + * Updates a Alignment entity with the given parameters + * @param parameters list of objects to update into the Alignment tree + */ + private void updateAlignment(Alignment root, Hashtable parameters) + { + this.logger.sessionDebug("Updating ALignment"); + if( parameters == null || parameters.size()<1) + { + this.logger.sessionWarn("updateAlignment: no object provided: No update."); + return ; + } + if(root == null ) + { + this.logger.sessionWarn("updateAlignment: no DataSet XML Entity."); + return ; + } + this.logger.sessionDebug("list of parameters: "+parameters); + Hashtable> sites = (Hashtable>) parameters.get("MSD.vamav.common.AVActiveSite"); + Hashtable> residueAnnotations = (Hashtable>) parameters.get("MSD.vamav.common.ResidueAnnotation"); + try + { + if ((sites != null && sites.size()>0) || (residueAnnotations!= null && residueAnnotations.size()>0)) + { + boolean hasSitesToUpdate = false; + if (sites!= null && sites.size()>0) + { + hasSitesToUpdate = true; + } + boolean hasAnnotationToUpdate = false; + if (residueAnnotations!= null && residueAnnotations.size()>0) + { + hasAnnotationToUpdate = true; + } + for (int seqNumber = root.getAlignmentSequenceCount() -1; seqNumber>=0; seqNumber --) + { + AlignmentSequence seq = root.getAlignmentSequence(seqNumber); + if( seq == null) continue; + String name = seq.getName(); + if( name == null ) continue; + this.logger.sessionDebug("sequence name "+name); + name = name.trim().toLowerCase().intern(); + if (hasSitesToUpdate) + { + if( sites.containsKey(name) ) + {//found the alignment associated to an Active Site + //add the active site as annotation element + /// AlignmentAnnotations[] annotations = root.getAlignmentAnnotations(); + //if (annotations == null) + // { + this.addActiveSite(root, sites.get(name)); + sites.remove(name); + // } + } + else + { + //look for PDB ID + //usely active sites are associated with PDB chain. + //check any seq has a PDB ID with an active site. + Sequence seqRef = (Sequence)seq.getRefid(); + if( !this.logger.isProduction())this.logger.sessionDebug(" sites "+sites); + // this.logger.sessionDebug(" sites "+sites.keys()); + if (seqRef != null) + { + boolean found = false; + int refNumber = seqRef.getDbRefCount() ; + while (!found && refNumber>0) + { + refNumber --; + DbRef ref = seqRef.getDbRef(refNumber); + if( ref == null ) continue; + String source = ref.getSource(); + this.logger.sessionDebug("DBRef "+ refNumber+ " "+source); + if (source != null && "PDB".equalsIgnoreCase(source)) + { + String accID = ref.getAccessionId(); + if( accID == null || accID.length()<1) continue; + accID = accID.trim().toLowerCase().intern(); + this.logger.sessionDebug("ACCID "+accID); + if( accID != null) + { + for ( Enumeration keys = sites.keys(); keys.hasMoreElements();) + { + String sitePDBID = keys.nextElement(); + if( sitePDBID == null) continue; + + int underPos = sitePDBID.indexOf("_"); + + this.logger.sessionDebug("position underscore "+underPos +" "+sitePDBID.substring(underPos+1, name.length())); + if( underPos>0 && (sitePDBID.substring(underPos+1, sitePDBID.length()).length()==1 || sitePDBID.substring(underPos+1, sitePDBID.length()).length()==0)) + {//remove chain name and leave the PDB ID + sitePDBID = sitePDBID.substring(0, underPos); + } + sitePDBID = sitePDBID.trim().toLowerCase().intern(); + if( sitePDBID.equalsIgnoreCase(accID)) + { + root = this.addActiveSite(root, sites.get(accID)); + } + } + //sites.remove(accID); + } + } + } + } + } + } + if( hasAnnotationToUpdate) + { + this.logger.sessionDebug("Testing "+name+ " for residue annotation."); + if(residueAnnotations.containsKey(name)) + {//found the alignment associated to an Active Site + //add the active site as annotation element + this.logger.sessionDebug("The sequence "+name+" has a residue annotation."); + //AlignmentAnnotations[] annotations = root.getAlignmentAnnotations(); + //if (annotations == null) + // { + this.addResidueAnnotation(root, residueAnnotations.remove(name)); + // } + } + else + { + //look for PDB ID + //usely active sites are associated with PDB chain. + //check any seq has a PDB ID with an active site. + Sequence seqRef = (Sequence)seq.getRefid(); + if (!this.logger.isProduction()) this.logger.sessionDebug(" residueAnnotations "+residueAnnotations); + + if (seqRef != null) + { + boolean found = false; + int refNumber = seqRef.getDbRefCount() ; + while (!found && refNumber>0) + { + refNumber --; + DbRef ref = seqRef.getDbRef(refNumber); + if( ref == null ) continue; + String source = ref.getSource(); + this.logger.sessionDebug("DBRef "+ refNumber+ " "+source); + if (source != null && "PDB".equalsIgnoreCase(source)) + { + String accID = ref.getAccessionId(); + if( accID == null || accID.length()<1) continue; + accID = accID.trim().toLowerCase().intern(); + this.logger.sessionDebug("ACCID "+accID); + if( accID != null && residueAnnotations.containsKey(accID)) + { + root = this.addResidueAnnotation(root, residueAnnotations.get(accID)); + } + } + } + + } + } + + } + } + + } + else + { + this.logger.sessionInfo("Update Alignment: no Residue alignment provided."); + } + }catch (Exception e) + { + this.logger.sessionError("Error during Alignment update ",e); + } + + } + + /** + * add an active site to the document + * @param sites + */ + private Alignment addActiveSite(Alignment align, ArrayList sites ) + { + this.logger.sessionDebug("adding active site"); + if(align == null ) + { + this.logger.sessionWarn("AddActiveSite: no Aligmnemt XML Entity."); + return align; + } + if( sites == null || sites.size()<1) + { + this.logger.sessionDebug("addActiveSite: No site to add."); + return align; + } + Hashtable > orderedSites = new Hashtable >(); + //order site per position + this.logger.sessionDebug(" Ordering sites: "+sites.size()); + for (int siteNumber = sites.size() -1; siteNumber>=0; siteNumber--) + { + AVActiveSite site = sites.get(siteNumber); + if (site == null) continue; + + //we suppose we can have several sites at the same position + //orderedSites.put(Integer.valueOf(siteNumber), site); + Integer position = Integer.valueOf(site.getPosition()); + this.logger.sessionDebug("position: "+position.toString()); + ArrayList s = orderedSites.get(position.toString().intern()); + if(s == null ) + { + s = new ArrayList(); + } + if (!s.contains(site)) s.add(site); + orderedSites.put(position.toString().intern(), s); + //orderedSites. + //site.getPosition(); + }//check if active site are already contained in the Annotation + for (int alignNumber = align.getAlignmentAnnotationsCount() - 1 ; alignNumber>=0; alignNumber--) + { + AlignmentAnnotations annotation= align.getAlignmentAnnotations(alignNumber); + if( annotation == null) continue; + this.logger.sessionDebug("annotation number : "+alignNumber); + this.logger.sessionDebug("Element count "+annotation.getAnnotationElementCount()); + for ( int elementNumber = annotation.getAnnotationElementCount() - 1;elementNumber>=0; elementNumber-- ) + { + AnnotationElement element = annotation.getAnnotationElement(elementNumber); + this.logger.sessionDebug("element "+elementNumber); + if( element == null) continue; + // if(this.activeSiteDescription.equalsIgnoreCase(element.getDescription())&& + // + Integer pos = Integer.valueOf(element.getPosition()); + String desc = element.getDescription(); + this.logger.sessionDebug("element position "+ pos+","); + this.logger.sessionDebug("positions "+orderedSites.keys()); + if(desc != null && desc.startsWith(this.activeSiteDescription) && orderedSites.containsKey(pos.toString().intern())) + { + this.logger.sessionInfo("AddActiveSite: The active site already exists at position: "+element.getPosition()); + ArrayList s = orderedSites.remove(pos.toString().intern()); + + //continue; + } + pos = null; + } + } + //the remaining sites must be added. + if(orderedSites !=null && orderedSites.size()>0 ) + { + AlignmentAnnotations annotation = new AlignmentAnnotations(); + + Collection> s = orderedSites.values(); + if( s != null && s.size()>0) + { + for ( Iterator > iter = s.iterator(); iter.hasNext();) + { + ArrayList list = iter.next(); + if (list == null || list.size()<1) continue; + for (int arrayNumber = list.size()-1; arrayNumber>=0; arrayNumber--) + { + AVActiveSite site = list.get(arrayNumber); + AnnotationElement element = new AnnotationElement(); + if (site == null ) continue; + this.logger.sessionDebug("site : "+site.getSequenceName() + " "+site.getPosition() ); + element.setDescription(this.activeSiteDescription +" "+site.getLigandName()); + element.setPosition(site.getPosition()); + //element.setValue(); + annotation.addAnnotationElement(element); + } + } + } + /*for (Enumeration siteEnum = ; siteEnum.hasMoreElements();) + { + AVActiveSite site = (AVActiveSite)siteEnum.nextElement(); + if (site == null) continue; + logger.Applidebug("site : "+site.getSequenceName()); + element.setDescription(this.activeSiteDescription +" "+site.getLigandName()); + element.setPosition(site.getPosition()); + //element.setValue(); + annotation.addAnnotationElement(element); + }*/ + //adding provenance entry to the annotation + Provenance provenance = annotation.getProvenance(); + Entry provenanceEntry = this.createProvenanceEntry(this.client, "Update - added ActiveSite"); + if(provenanceEntry != null )//otherwise something is wrong + { + if( provenance == null) provenance = new Provenance(); + provenance.addEntry(provenanceEntry); + } + align.addAlignmentAnnotations(annotation); + } + return align; + } + + /** + * add an active site to the document + * @param sites + */ + private Alignment addResidueAnnotation(Alignment align, ArrayList annotations ) + { + this.logger.sessionDebug("adding active site"); + if(align == null ) + { + this.logger.sessionWarn("AddResidueAnnotation: no Aligmnemt XML Entity."); + return align; + } + if( annotations == null || annotations.size()<1) + { + this.logger.sessionDebug("addResidueAnnotation: No annotation to add."); + return align; + } + Hashtable > orderedAnnotation = new Hashtable >(); + //order site per position + this.logger.sessionDebug(" Ordering sites: "+annotations.size()); + for (int siteNumber = annotations.size() -1; siteNumber>=0; siteNumber--) + { + ResidueAnnotation annotation = annotations.get(siteNumber); + if (annotation == null) continue; + + //we suppose we can have several sites at the same position + //orderedSites.put(Integer.valueOf(siteNumber), site); + Integer position = Integer.valueOf(annotation.getResidueNumber()); + this.logger.sessionDebug("position: "+position.toString()); + ArrayList s = orderedAnnotation.get(position.toString().intern()); + if(s == null ) + { + s = new ArrayList(); + } + if (!s.contains(annotation)) s.add(annotation); + orderedAnnotation.put(position.toString().intern(), s); + //orderedSites. + //site.getPosition(); + }//check if active site are already contained in the Annotation + for (int alignNumber = align.getAlignmentAnnotationsCount() - 1 ; alignNumber>=0; alignNumber--) + { + AlignmentAnnotations annotation= align.getAlignmentAnnotations(alignNumber); + if( annotation == null) continue; + this.logger.sessionDebug("annotation number : "+alignNumber); + this.logger.sessionDebug("Element count "+annotation.getAnnotationElementCount()); + for ( int elementNumber = annotation.getAnnotationElementCount() - 1;elementNumber>=0; elementNumber-- ) + { + AnnotationElement element = annotation.getAnnotationElement(elementNumber); + this.logger.sessionDebug("element "+elementNumber); + if( element == null) continue; + // if(this.activeSiteDescription.equalsIgnoreCase(element.getDescription())&& + // + Integer pos = Integer.valueOf(element.getPosition()); + String desc = element.getDescription(); + this.logger.sessionDebug("element position "+ pos+","); + if( !this.logger.isProduction()) this.logger.sessionDebug("positions "+orderedAnnotation.keys()); + if(desc != null && desc.startsWith(this.activeSiteDescription) && orderedAnnotation.containsKey(pos.toString().intern())) + { + this.logger.sessionInfo("AddActiveSite: The active site already exists at position: "+element.getPosition()); + ArrayList s = orderedAnnotation.remove(pos.toString().intern()); + + //continue; + } + pos = null; + } + } + //the remaining sites must be added. + if(orderedAnnotation !=null && orderedAnnotation.size()>0 ) + { + AlignmentAnnotations annots = new AlignmentAnnotations(); + + Collection> s = orderedAnnotation.values(); + if( s != null && s.size()>0) + { + for ( Iterator > iter = s.iterator(); iter.hasNext();) + { + ArrayList list = iter.next(); + if (list == null || list.size()<1) continue; + for (int arrayNumber = list.size()-1; arrayNumber>=0; arrayNumber--) + { + ResidueAnnotation annotation = list.get(arrayNumber); + AnnotationElement element = new AnnotationElement(); + if (annotation == null ) continue; + this.logger.sessionDebug("annotation : "+annotation.getSequenceName() + " "+annotation.getResidueNumber() ); + element.setDescription(annotation.getDescription()); + element.setPosition(annotation.getResidueNumber()); + if (annotation.getDisplayCharacter()!= null && annotation.getDisplayCharacter().length()>0) + element.setDisplayCharacter(annotation.getDisplayCharacter()); + else + element.setDisplayCharacter("?"); + if( annotation.getSecondaryStructure() != null && annotation.getSecondaryStructure().length()>0 ) + { + element.setSecondaryStructure(annotation.getSecondaryStructure()); + } + else + element.setSecondaryStructure("?"); + element.setValue(Float.parseFloat(annotation.getValue())); + //element.setValue(); + annots.addAnnotationElement(element); + } + } + } + /*for (Enumeration siteEnum = ; siteEnum.hasMoreElements();) + { + AVActiveSite site = (AVActiveSite)siteEnum.nextElement(); + if (site == null) continue; + logger.Applidebug("site : "+site.getSequenceName()); + element.setDescription(this.activeSiteDescription +" "+site.getLigandName()); + element.setPosition(site.getPosition()); + //element.setValue(); + annotation.addAnnotationElement(element); + }*/ + //adding provenance entry to the annotation + Provenance provenance = annots.getProvenance(); + Entry provenanceEntry = this.createProvenanceEntry(this.client, "Update - added Residue Annotation"); + if(provenanceEntry != null )//otherwise something is wrong + { + if( provenance == null) provenance = new Provenance(); + provenance.addEntry(provenanceEntry); + } + align.addAlignmentAnnotations(annots); + } + return align; + } + + private Hashtable addParameters(Hashtable newParameters, Hashtable parameters) + { + if (parameters == null) parameters = new Hashtable(); + if (newParameters != null && newParameters.size()>0) + { + boolean found = false; + /*for (Enumeration keys = newParameters.keys(); keys.hasMoreElements();) + { + String key = (String) keys.nextElement(); + if( key == null) continue; + Object value = newParameters.get(key); + if (value == null) continue; + + String newKey = null; + if("molecule".equals(key) ) + { + if( parameters.containsValue(value)) continue; + newKey = "molecule"+this.moleculeNumber; + } + else + if("name".equals(key) ) + { + if( parameters.containsValue(value)) continue; + newKey = "name"+this.moleculeNumber; + } + else newKey = key; + parameters.put(newKey, value); + logger.Applidebug("Adding new parameter "+newKey); + newParameters.remove(key); + key = null; + found = true; + } + found = false; + this.moleculeNumber++;*/ + boolean moreMolecules = true; + int molNumber = -1; + int highlightN= -1; + boolean moreHighlight = true; + if (!this.logger.isProduction() ) + { + for (Enumeration keys = newParameters.keys(); keys.hasMoreElements();) + { + this.logger.sessionDebug("new parameter "+keys.nextElement()); + } + for (Enumeration keys = parameters.keys(); keys.hasMoreElements();) + { + this.logger.sessionDebug("current stored parameter "+keys.nextElement()); + } + } + while (newParameters != null && !newParameters.isEmpty() && (moreMolecules || moreHighlight)) + { + highlightN++; + String currentParameterName = "highlightT"+highlightN; + Object hig = newParameters.remove(currentParameterName); + currentParameterName = null; + if(hig != null) + { + if (!parameters.containsValue(hig)) + { + this.logger.sessionDebug("Highlight found in the document"); + //newParameters.remove("highlight"+highlightNumber); + int currentNumber = this.highlightNumber++; + String newKey = "highlight"+currentNumber; + this.logger.sessionDebug("Adding new parameter "+newKey); + parameters.put(newKey, hig); + } + else + { + this.logger.sessionDebug("the highlight is already contained in the parameter list."); + } + } + else + { + moreHighlight = false; + //continue; + this.logger.sessionDebug("no more highlight"); + } + + molNumber++; + Object mol = newParameters.get("moleculeG"+molNumber); + if (mol == null) + { + moreMolecules = false; + continue; + } + newParameters.remove("moleculeG"+molNumber); + Object name = newParameters.get("nameG"+molNumber); + if (name == null) + { + //moreMolecules = false; + continue; + } + newParameters.remove("nameG"+molNumber); + if( parameters.containsValue(mol)) continue; + int currentNumber = this.moleculeNumber++; + String newKey = "molecule"+currentNumber; + this.logger.sessionDebug("Adding new parameter "+newKey); + parameters.put(newKey, mol); + if( parameters.containsValue(name)) continue; + newKey = "name"+currentNumber; + this.logger.sessionDebug("Adding new parameter "+newKey); + parameters.put(newKey, name); + } + if (newParameters!= null && !newParameters.isEmpty())parameters.putAll(newParameters); + } + if (newParameters != null) + { + newParameters.clear(); + newParameters = null; + } + return parameters; + } + + /** @poseidon-generated */ + public SequenceGrouping getSequenceGrouping() { + return this.groupingManager; + } + /** @poseidon-generated */ + public void setSequenceGrouping(SequenceGrouping sequenceGrouping) { + this.groupingManager = sequenceGrouping; + } + + + private Entry createProvenanceEntry(IClient client, String action) + { + if (client == null) + { + this.logger.sessionError("No vamsas client provided to create provenance entry. The entry object will not be added."); + return null; + } + return this.createProvenanceEntry(client.getUserHandle().getFullName(), action); + } + + private Entry createProvenanceEntry(String user, String action) + { + if( user == null || user.length()<1) + { + this.logger.sessionError("No User name provided to create provenance entry. The entry object will not be added."); + return null; + } + if( action == null || action.length()<1) + { + this.logger.sessionError("No action provided to create provenance entry. The entry object will not be added."); + return null; + } + Entry provenanceEntry = new Entry(); + provenanceEntry.setUser(user); + provenanceEntry.setAction(action); + + /* + ** on some JDK, the default TimeZone is wrong + ** we must set the TimeZone manually!!! + ** Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("EST")); + */ + Calendar cal = Calendar.getInstance(TimeZone.getDefault()); + org.exolab.castor.types.Date date = new org.exolab.castor.types.Date (cal.getTime()); + provenanceEntry.setDate(date); + cal = null; + return provenanceEntry; + } + + public ArrayList getGroupingModes() + { + ArrayList modes = new ArrayList(); + modes.add("structure"); + modes.add("Protein domain"); + return modes; + } + + /** + * Create a document following provided parameters + * + * @param parameters list of parameters, containing objects to map to the document objects/tree + * @return the IClient with the associated newly created document + * @throws IOException if an error occurs during VAMsas document file access + */ + public IClient createDocument(Hashtable parameters) throws IOException + { + if(parameters == null || parameters.size()<1) + { + this.logger.sessionError("No parameter provided to create the VAMSAS document. Abort."); + } + IClientDocument _doc = null; + + VamsasDocument doc = new VamsasDocument(); + VAMSAS root = new VAMSAS(); + doc.addVAMSAS(root); + + + Tree aTree = this.createTree(parameters); + if( aTree != null) root.addTree(aTree); + + DataSet set = this.createDataSet(parameters); + if (set != null) + root.addDataSet(set); + + IdFactory vorba = null; + // TODO: reduce size of vorba ids generated from these parameters to IdFactory (mainly sessionHandle rationalization ?) + try { + vorba= new IdFactory(this.client.getSessionHandle(), + this.client.getClientHandle(), ((VAMAVClient)this.client).getUserHandle());//makeVorbaIdFactory(); + // if session currently holds data - read it in - or get a dummy + this.logger.sessionDebug("Accessing document"); + } + catch (Exception e) { + File sessionDir = ((VAMAVClient)this.client).getVAMAVSession().getSessionDirectory(); + this.logger.sessionError("Failed to get session document for session directory '"+sessionDir.getAbsolutePath()+"'", e); + throw new IOException("Failed to get session document for session directory '"+sessionDir.getAbsolutePath()+"'"); + } + // Construct the IClientDocument instance + ApplicationData appliData = new ApplicationData(); + User user = new User(); + user.setFullname(this.client.getUserHandle().getFullName()); + user.setOrganization(this.client.getUserHandle().getOrganization()); + + appliData.addUser(user); + doc.addApplicationData(appliData); + _doc = new ClientDocument(doc, (VamsasArchive)null, vorba, this.client); + + //_doc = new ClientDocument(doc, new VAMSAS[]{root}, null,this.client); + this.client.updateDocument(_doc); + return this.client; + } + + /** Create Vamsas Tree object + * Currently do nothing + * @return the created tree + * @param parameters a list of parameters from an AstexViewer@MSD-EBI client + */ + private Tree createTree(Hashtable parameters) + { + return null; + } + + + private DataSet createDataSet(Hashtable parameters) + { + if (parameters == null || parameters.size()<1) + { + this.logger.sessionDebug("No parameter provided to create DataSet"); + return null; + } + this.logger.sessionDebug("Create DataSet "); + DataSet set = new DataSet(); + Alignment align = this.createAlignment(parameters); + if (align != null) set.addAlignment(align); + + set = this.createSequences(parameters,set); + + this.logger.sessionDebug("end CreateDataSet "); + return set; + } + + /** + * creates a Alignment entity following the given parameters + * @param parameters list of objects used to create the Alignment tree + */ + private Alignment createAlignment(Hashtable parameters) + { + this.logger.sessionDebug("Create Alignment"); + if( parameters == null || parameters.size()<1) + { + this.logger.sessionWarn("createAlignment: no object provided: Can not create."); + return null; + } + Alignment align = null; + //new Alignment(); + if (!this.logger.isProduction()) this.logger.sessionDebug("list of parameters: "+parameters); + return align; + } + + /** + * creates a Alignment entity following the given parameters + * @param parameters list of objects used to create the Alignment tree + */ + private DataSet createSequences(Hashtable parameters, DataSet set) + { + this.logger.sessionDebug("Create Sequences"); + if( parameters == null || parameters.size()<1) + { + this.logger.sessionWarn("createSequence: no object provided: Can not create."); + return null; + } + ArrayList sequences = (ArrayList) parameters.get("MSD.vamav.common.AVSequence"); + if( sequences != null && sequences.size()>0) + { + Alignment align = new Alignment(); + + for (int sequenceNumber = sequences.size() -1; sequenceNumber >=0; sequenceNumber-- ) + { + AVSequence sequence = sequences.get(sequenceNumber); + + //create sequence object + Sequence seq = new Sequence(); + seq.setName(sequence.getName()); + String sequenceWithoutGap = sequence.getSequence(); + if( sequenceWithoutGap != null && sequenceWithoutGap.length()>0) + { + sequenceWithoutGap = sequenceWithoutGap.replaceAll("-", ""); + } + seq.setSequence(sequenceWithoutGap); + set.addSequence(seq); + + //create Alignment object relative to thie Sequence object + + AlignmentSequence alignmSeq = new AlignmentSequence(); + alignmSeq.setName(sequence.getName()); + alignmSeq.setSequence(sequence.getSequence()); + alignmSeq.setRefid(seq); + align.addAlignmentSequence(alignmSeq); + } + set.addAlignment(align); + } + + if (!this.logger.isProduction()) this.logger.sessionDebug("list of parameters: "+parameters); + return set; + } + + + } diff --git a/src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/exceptions/IncorrectDocumentException.java b/src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/exceptions/IncorrectDocumentException.java new file mode 100755 index 0000000..3b81398 --- /dev/null +++ b/src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/exceptions/IncorrectDocumentException.java @@ -0,0 +1,61 @@ +/* Created on 14 nov. 2005 + * * EMBL-EBI + * MSD Group + * VAMSAS Project + * VAMAV + * @author Pierre MARGUERITE + * @version 1 + * @since 14 nov. 2005 + */ +package uk.ac.ebi.msd.vamsas.vamav.documentmanagement.exceptions; + +/** + * Exception raises if the a Vamsas document is considered as incorrect + * @author Pierre MARGUERITE + * @version 1 + * @since 14 nov. 2005 + * + */ +public class IncorrectDocumentException extends Exception + { + + /** + * Constructor + * + */ + public IncorrectDocumentException() + { + super(); + } + + /** + * Constructor + * + * @param arg0 + */ + public IncorrectDocumentException(String arg0) + { + super(arg0); + } + + /** + * Constructor + * + * @param arg0 + * @param arg1 + */ + public IncorrectDocumentException(String arg0, Throwable arg1) + { + } + + /** + * Constructor + * + * @param arg0 + */ + public IncorrectDocumentException(Throwable arg0) + { + super(arg0); + } + + } diff --git a/src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/exceptions/UnableToProcessException.java b/src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/exceptions/UnableToProcessException.java new file mode 100755 index 0000000..0454e0f --- /dev/null +++ b/src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/exceptions/UnableToProcessException.java @@ -0,0 +1,63 @@ +/* Created on 12 janv. 2006 + * * EMBL-EBI + * MSD Group + * VAMSAS Project + * VAMAV + * @author Pierre MARGUERITE + * @version 1 + * @since 12 janv. 2006 + */ +package uk.ac.ebi.msd.vamsas.vamav.documentmanagement.exceptions; + +/** + * Exception raised when the application is unable to process a document + * or a session + * @author Pierre MARGUERITE + * @version 1 + * @since 12 janv. 2006 + * + */ +public class UnableToProcessException extends Exception + { + + /** + * Constructor + * + */ + public UnableToProcessException() + { + super(); + } + + /** + * Constructor + * + * @param arg0 + */ + public UnableToProcessException(String arg0) + { + super(arg0); + } + + /** + * Constructor + * + * @param arg0 + * @param arg1 + */ + public UnableToProcessException(String arg0, Throwable arg1) + { + super(arg0, arg1); + } + + /** + * Constructor + * + * @param arg0 + */ + public UnableToProcessException(Throwable arg0) + { + super(arg0); + } + + } diff --git a/src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/grouping/SequenceGrouping.java b/src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/grouping/SequenceGrouping.java new file mode 100755 index 0000000..43f5184 --- /dev/null +++ b/src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/grouping/SequenceGrouping.java @@ -0,0 +1,1169 @@ +/* * EMBL-EBI +* MSD Group +* VAMSAS Project +* VAMAV +* * @author Pierre MARGUERITE + * @version 1 +*/ +package uk.ac.ebi.msd.vamsas.vamav.documentmanagement.grouping; + +import uk.ac.ebi.msd.vamsas.vamav.documentmanagement.grouping.exceptions.UnableToGroupSequencesException; +import uk.ac.ebi.msd.vamsas.vamav.exceptions.IncorrectVamavModuleInitialisation; +import uk.ac.ebi.msd.vamsas.vamav.util.data.DataBuffer; +import uk.ac.ebi.msd.vamsas.vamav.util.logger.VAMAVLogger; +import uk.ac.ebi.msd.vamsas.vamav.util.logger.VAMAVLoggerImpl; +import uk.ac.ebi.msd.vamsas.vamav.util.mapping.MappingManager; +import uk.ac.ebi.msd.vamsas.vamav.util.mapping.exceptions.MappingException; +import uk.ac.ebi.msd.vamsas.vamav.util.mapping.matrixrotation.RotationTranslationMatrix; +import uk.ac.ebi.msd.vamsas.vamav.util.multiplealignment.AlignmentManager; +import uk.ac.ebi.msd.vamsas.vamav.util.multiplealignment.ClustalW_EBIWSClient; +import uk.ac.ebi.msd.vamsas.vamav.util.multiplealignment.MultipleAlignmentIntf; +import uk.ac.ebi.msd.vamsas.vamav.util.multiplealignment.exceptions.AlignmentException; +import uk.ac.ebi.msd.vamsas.vamav.util.pool.DataBufferPool; +import uk.ac.ebi.msd.vamsas.vamav.util.pool.StringBufferPool; +import uk.ac.ebi.msd.vamsas.vamav.util.properties.PropertyManager; +import org.vamsas.objects.core.AnnotationElement; +import org.vamsas.objects.core.SequenceType; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.io.Writer; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Properties; + +/** +* Abstract class for defining Structure grouping methods. +* +* Grouping mode should implement these methods +* +* Providing method definitions and code for atribute file generation + * @author Pierre MARGUERITE + * @version 1 +*/ + +public abstract class SequenceGrouping implements uk.ac.ebi.msd.vamsas.vamav.VamaVModule{ + + protected final String pdbidsproperty = "pdbids"; + + protected String modulePrefix = "sequence"; + protected final VAMAVLogger logger = new VAMAVLoggerImpl(this.getClass()); + + protected Hashtable > groups = null; + + /** + * List of PDB structures per group + * to allow rotation translation matrix mapping + */ + protected Hashtable > structuresPerGroup = null; + + protected char gapChar = 'X'; + protected Hashtable maxSeqLengthsPerGroup = null; + protected Hashtable fakeSequencePerLength = null; + + protected ArrayList sequenceFile = null; + protected final String atrFilePrefix = "atr"; + protected final String alignmentFilePrefix = ".aln"; + protected String workingDirectory = "atributeFile"; + //protected String atributeFile = this.workingDirectory+File.separator+"vamsas"+"."+this.atrFilePrefix; + protected static String enc = null; + protected static final boolean erase = true; + protected static final boolean append = false; + protected Hashtable> sequenceBreakPoints = null; + protected final boolean deleteOnExit = false; + /** + * Mapping manager to retrieve a mapping between ID for example + * + */ + protected MappingManager mapping = null; + + protected AlignmentManager alignManager = null; + + + /** + *

+ * + */ + // private MultipleAlignmentIntf multipleAlignment; + + + /** + * List of breakpoints for the current alignmentSet + */ + protected ArrayList breakpoints = null; + /** + * Saves adding order of sequences + */ + protected ArrayList groupOrder = null; + + /** + * + * Constructor of the SequenceGrouping class, given a mapping manager + * + * @param _mappingManager the mapping manager to use for mapping + */ + public SequenceGrouping( MappingManager _mappingManager) + { + this.mapping = _mappingManager; + + } + + /** + * Inits the Sequence Grouping sub module, with a list of configuration properties. + */ + public void init (Properties moduleProperties) throws IncorrectVamavModuleInitialisation + { + PropertyManager propManager = new PropertyManager(); + this.alignManager = new AlignmentManager(); + try + { + Properties props = propManager.getModuleProperties(moduleProperties, this.alignManager.getModulePrefix()); + this.alignManager.init(props); + props = null; + } + catch (IncorrectVamavModuleInitialisation ivmie) + { + logger.appliError("Unable to init Alignment Manager."); + throw new IncorrectVamavModuleInitialisation(ivmie); + } + propManager = null; + if (moduleProperties == null || moduleProperties.size()<1) + { + this.logger.appliInfo("SequenceGrouping - No properties provided. Uses default."); + return; + } + String gap = moduleProperties.getProperty("gapcharacter", String.valueOf(this.gapChar)); + if( gap !=null && gap.length()<1) + this.gapChar = gap.charAt(0); + + } + + + + + + + /** + * Retrieves the mapping attribut + * + * @return Returns the mapping. + */ + protected MappingManager getMapping() + { + return this.mapping; + } + + /** + * retrieves the MultipleAlignmentIntf associated to the current object, + * to execute multiple alignment + * @return the MultipleAlignmentIntf object associated to the current object. + */ + /* private MultipleAlignmentIntf getMultipleAlignment() { + return this.multipleAlignment; + }*/ + + /** + * Set the MultipleAlignmentIntf for the current object + * @param multipleAlignmentIntf the MultipleAlignmentIntf object ot associated to the object. + */ + /* private void setMultipleAlignment(MultipleAlignmentIntf _multipleAlignment) + { + this.multipleAlignment = _multipleAlignment; + }*/ + + /** + * Add a sequence for grouping. + * + * @param sequence chain sequence to add + * @param name name of the sequence to add + * @return a list of parameters to call the AstexViewer + * @throws UnableToGroupSequencesException if an error occurs during the adding. + */ + public abstract Hashtable addSequence(String sequence, String name) throws UnableToGroupSequencesException; + + /** + * Add a sequence for grouping, with an associated accessionID and its source. + * + * @param sequence chain sequence to add for grouping + * @param name name of the sequence to add + * @param accessionID accessionId associated to the sequence + * @param source source of the accessionID + * @return list of parameters to call the AstexViewer, if needed. Null, otherwise. + * @throws UnableToGroupSequencesException if an error occurs during the adding. + */ + public abstract Hashtable addSequence(String sequence, String name, String accessionID, String source) throws UnableToGroupSequencesException; + + /** + * Registers a PDB ID as belonging to a group + * @param groupName name of the group to add the structure in it. + * @param pdbID Id of the PDB structure to add + */ + protected void addStructureToGroup(String groupName, String pdbID) + { + if (this.structuresPerGroup == null) + { + this.structuresPerGroup = new Hashtable>(); + } + ArrayList structs= this.structuresPerGroup.get(groupName); + if (structs == null) + {//create new list of the group + structs = new ArrayList (); + } + //add structure + if (!structs.contains(pdbID)) + { + structs.add(pdbID); + logger.sessionDebug("Adding structure"+pdbID+" to group "+groupName); + // readd list to be sure to have the right list in the global list + this.structuresPerGroup.put(groupName, structs); + } + } + /** + * Add a sequence to a group + * @param groupName name of the group to add the sequence into + * @param sequence sequence to add + * @param sequenceName name of the sequence to add + */ + protected void addSequenceToGroup(String groupName, String sequence, String sequenceName) + { + if (groupName == null || groupName.length()<1) + { + this.logger.sessionError("There is no group name. Can not add the sequence to the group."); + return; + } + if (sequence == null || sequence.length()<1) + { + this.logger.sessionError("There is no sequence. Can not add the sequence to the group."); + return; + } + + this.logger.sessionInfo("Adding "+sequenceName+" sequence to "+groupName+" group."); + ArrayList elements = getGroups().get(groupName); + if (elements == null) + { + elements = new ArrayList(); + this.logger.sessionInfo("No previous list, create one"); + } + if (sequence ==null) + this.logger.sessionError("No sequence provided for "+sequenceName+"."); + else + { + if (sequence.length()>0) + { + Integer maxLength = getMaxSeqLengthsPerGroup().get(groupName); + if(maxLength!=null&& maxLength.intValue()>0 ) + { + int maxSeqLength = maxLength.intValue(); + int seqLen = sequence.length(); + if (maxSeqLength < seqLen) + { + maxSeqLength = seqLen; + maxLength = Integer.valueOf(maxSeqLength); + getMaxSeqLengthsPerGroup().put(groupName, maxLength); + } + } + else + { + int seqLen = sequence.length(); + maxLength = Integer.valueOf(seqLen); + getMaxSeqLengthsPerGroup().put(groupName, maxLength); + } + } + SequenceType seq = new SequenceType() ; + seq.setName(sequenceName); + seq.setSequence(sequence); + if( !elements.contains(seq)) + { + if (!this.logger.isProduction()) + { + this.logger.sessionDebug("sequences size before "); + this.logger.sessionDebug(""+elements.size()); + } + elements.add(seq); + } + //else + //seq = null; + if( !this.logger.isProduction()) + { + this.logger.sessionDebug("sequences size after "); + this.logger.sessionDebug("" +elements.size()); + this.logger.sessionDebug("groups size before "); + this.logger.sessionDebug(""+getGroups().size()); + } + getGroups().put(groupName, elements); + if( !this.logger.isProduction()) + { + this.logger.sessionDebug("groups size after "); + this.logger.sessionDebug(""+getGroups().size()); + } + addGroupToOrder(groupName); + } + } + + /** + * Retrieves the groups attribut + * + * @return Returns the groups. + */ + protected Hashtable> getGroups() + { + if (this.groups == null) + this.groups = new Hashtable> (); + return this.groups; + } + + /** + * Retrieves the fakeSequencePerLength attribut + * + * @return Returns the fakeSequencePerLength. + */ + public Hashtable getFakeSequencePerLength() + { + if (this.fakeSequencePerLength == null) + { + this.fakeSequencePerLength = new Hashtable(); + } + return this.fakeSequencePerLength; + } + + /** + * Retrieves the maxSeqLengthsPerGroup attribut + * + * @return Returns the maxSeqLengthsPerGroup. + */ + public Hashtable getMaxSeqLengthsPerGroup() + { + if( this.maxSeqLengthsPerGroup == null) + this.maxSeqLengthsPerGroup = new Hashtable(); + return this.maxSeqLengthsPerGroup; + } + + /** + * Retrieves the sequenceOrder attribut + * + * @return Returns the sequenceOrder. + */ + protected ArrayList getGroupOrder() { + if( this.groupOrder == null) + this.groupOrder = new ArrayList (); + return this.groupOrder; + } + + protected void addGroupToOrder(String groupName) + { + if (!(getGroupOrder().contains(groupName))) + getGroupOrder().add(groupName); + } + + /** + * Clear the sequence order List + */ + public void groupOrderClear() { + if( this.groupOrder != null) + this.groupOrder = null; + } + + /** + * Retrieves the modulePrefix attribut + * + * @return Returns the modulePrefix. + */ + public String getModulePrefix() + { + return this.modulePrefix; + } + + /** + * Add a breakpoint to the grouping + * @param element annotation element associated to a breakpoint. + */ + public void addBreakpoint(AnnotationElement element) + { + if (element == null) + { + this.logger.sessionError("Sequence Grouping addBreakPoint - There is no annotation element. Can not add the breakpoint to groups"); + return; + } + this.logger.sessionDebug("Adding breakpoint"); + getBreakpoints().add(element); + } + + /** + * Retrieves the breakpoints attribut + * + * @return Returns the breakpoints. + */ + protected ArrayList getBreakpoints() + { + if (this.breakpoints == null) + this.breakpoints= new ArrayList(); + return this.breakpoints; + } + + /** + * Create a fake sequence containing provided breakpoints. + * @param breaks list of breakpoints + * @param groupName name of the group the fake sequence will be associated. + * @return the created fake sequence corresponding to the list of breakpoint + */ + protected String createFakeSequence(String groupName, ArrayList breaks) + { + + if(breaks == null || breaks.size()<1) return null; + this.logger.sessionInfo("Creating BreakPoint sequence for "+groupName ); + this.logger.sessionDebug("break points: "+breaks.size()); + String fakeSequence = null; + Integer len = getMaxSeqLengthsPerGroup().get(groupName); + if (len != null) + { + //retrieves store fake sequence: + fakeSequence = getFakeSequencePerLength().get(len); + if( fakeSequence == null || fakeSequence.length()<1) + { + Hashtable positions = new Hashtable (breaks.size()); + StringBuffer sequence = StringBufferPool.getString(); + for (int breakNumber = breaks.size()-1; breakNumber >=0; breakNumber --) + { + AnnotationElement bp = breaks.get(breakNumber); + if (bp == null) continue; + int pos = bp.getPosition()-1;//position in the sequence start at 1 + if (pos >=0) + { + positions.put(new Integer(pos), bp); + //System.out.println("adding position "+pos); + } + } + + int maxSeqLength = len.intValue(); + int size = maxSeqLength -1; + for (int i = 0; i< maxSeqLength; i++ ) + { + int reversePos = i; + //System.out.println("reverse pos "+reversePos); + Integer p = new Integer(reversePos); + if (positions.containsKey(p)) + { + AnnotationElement bp = positions.get(p); + sequence.append(bp.getDisplayCharacter()); + } + else + { + sequence.append(this.gapChar); + //System.out.println("no breakpoint found at pos "+reversePos); + } + } + positions = null; + fakeSequence = sequence.toString(); + StringBufferPool.returnString(sequence); + getFakeSequencePerLength().put(len, fakeSequence); + } + } + else + { + this.logger.sessionDebug("no len"); + } + this.logger.sessionDebug("fake sequence "+fakeSequence); + return fakeSequence; + } + + + /** + * Writes created groups into an atribute file for tha AstexViewer + * + * @throws UnableToGroupSequencesException, if unable to group added sequences + * @return the atribute file corresponding to the grouping of added sequences + * + */ + public File storeGroups() throws UnableToGroupSequencesException + { + int size = this.getGroups().size(); + if (size<1) + { + this.logger.sessionWarn("Sequence Grouping - There is no computed group. Can not store groups."); + // return null; + throw new UnableToGroupSequencesException(); + } + + //test if there is at least a sequence in each group. + boolean correct = true; + for (Enumeration _groups = this.getGroups().keys(); _groups.hasMoreElements() && correct; ) + { + String groupName = _groups.nextElement(); + ArrayList sequences = this.getGroups().get(groupName); + this.logger.sessionDebug("Group "+groupName); + if (sequences == null || sequences.size()<1) + { + correct = false; + } + else + { + this.logger.sessionDebug("group size "+sequences.size()); + } + } + if (!correct) + { + this.logger.sessionWarn("Sequence Grouping - There is no computed group. Can not store groups."); + //return null; + throw new UnableToGroupSequencesException(); + } + if (this.sequenceFile == null) + this.sequenceFile = new ArrayList(); + else + this.sequenceFile.clear(); + File atrFile = null; + try + { + this.workingDirectory = this.getOutputDirectory(); + String atributeFile = this.workingDirectory+File.separator+"vamav-"+this.getSessionID()+"."+this.atrFilePrefix; + logger.sessionInfo("Creating atribute file: "+atributeFile); + //writing Atribute file + if( atributeFile == null) + { + throw new UnableToGroupSequencesException("No atribute file path provided."); + } + if (!atributeFile.endsWith(this.atrFilePrefix)) + { + atributeFile = atributeFile.concat("."+this.atrFilePrefix); + } + atrFile = new File (atributeFile); + //atrFile.mkdirs(); + this.logger.sessionInfo("SequenceGrouping - Writing Atribute File."); + PrintWriter out = openFile(atrFile); + if( out == null) + throw new UnableToGroupSequencesException("Unable to open file to write. "+atrFile.getAbsolutePath());; + //return null; + DataBuffer line = DataBufferPool.getString(); + + //write header + line.setString("Atribute file Version 1.0"); + writeLine(line, out); + line.setString(""); + writeLine(line, out); + /*int groupNumber = 0; + for (Enumeration keys = getGroups().keys(); keys.hasMoreElements();) + {*/ + + this.alignManager.setSession(this.getSessionID()); + for (int groupNumber = 0; groupNumber < getGroupOrder().size() ;groupNumber++ ) + { + + + String groupName = getGroupOrder().get(groupNumber); + getGroups(); + //exporting fasta file + ArrayList sequences = getGroups().get(groupName); + + //generate alignment file name + // MultipleAlignmentIntf + // AlignmentManager clustal = new AlignmentManager();//ClustalW_EBIWSClient(this.getSessionID()); + //clustal.setSession(this.getSessionID()); + String extension = ""; + String alignmentfileExtension = alignManager.getMultipleAligmnentFileExtension(); + if (alignmentfileExtension != null && alignmentfileExtension.length()>0) + if (alignmentfileExtension.startsWith(".")) + extension = alignmentfileExtension; + else + extension = ".".concat(alignmentfileExtension); + + String alignmentFileName = groupName + extension; + if( sequences != null && sequences.size()>0) + { + //(groupName, "atributeFile"); + this.logger.sessionDebug("Preparing multiple alignment "+groupName); + if(getBreakpoints()!=null && getBreakpoints().size()>0) + { + alignManager.HasBreakPoint(); + String sequence = createFakeSequence(groupName,getBreakpoints() ); + if (sequence !=null) + { + String sequenceName = groupName+"Breakpoints_"; + alignManager.addSequence(sequenceName, this.prepareAddSequence(sequence,sequenceName)); + } + } + else + { + alignManager.HasNoBreakPoint(); + } + for (int seqNumber = sequences.size() -1; seqNumber>=0; seqNumber--) + { + SequenceType seq = sequences.get(seqNumber); + if (seq == null) + { + this.logger.sessionWarn("No sequence to add"); + continue; + } + this.logger.sessionDebug("Add sequence for multiple alignment "+seq.getName() + " "+seq.getSequence()); + alignManager.addSequence(seq.getName(), this.prepareAddSequence(seq.getSequence(), seq.getName())); + } + String alignment = alignManager.execMultipleAlignment(); + if (alignment!= null) + { + File alignmentFile = this.unModifieSequences(alignment, groupName,this.workingDirectory + File.separator+alignmentFileName); + if (alignmentFile != null) + this.getSequenceFiles().add(alignmentFile); + } + else + { + logger.sessionDebug("No alignment retrieved."); + } + + // add group + ArrayList structs = null; + DataBuffer ids = DataBufferPool.getString(); + + if( this.structuresPerGroup != null && this.structuresPerGroup.size()>0) + { + structs = this.structuresPerGroup.get(groupName); + + if (structs == null || structs.size()<1) + { + ids.append("groupName"); + + logger.sessionInfo("no pdb structure for the group "+groupName+". No matrix added"); + line.setString(" Molecule "+groupName+" "+groupName+" {\n"); + // writeLine(line, out); + line.append(" }\n"); + //writeLine(line, out); + } + else + { + String primaryID = structs.remove(structs.size()-1); + line.setString(" Molecule "+primaryID+" {\n"); + // writeLine(line, out); + line.append(" }\n"); + //writeLine(line, out); + ids.append(primaryID); + for (int structNumber = structs.size()-1; structNumber>=0; structNumber--) + { + String id = structs.get(structNumber); + line.append(" Molecule "+id+" {\n"); + //writeLine(line, out); + ids.append(" ".concat(id)); + try + { + Collection matrixes = this.mapping.getRotationTranslationMatrix(primaryID, id); + if (matrixes != null) + { + for (RotationTranslationMatrix matrix : matrixes) + { + if( matrix != null) + { + boolean isChain = false; + String chainID = matrix.getPrimaryPDBIDChain(); + if(chainID!= null &&chainID.length()>0 ) + { + isChain = true; + line.append(" Chain "+chainID+ " {\n"); + } + if( matrix != null) + { + line.append(" Matrix "); + line.append(BigDecimal.valueOf(matrix.get(0, 0).doubleValue())+ " "+BigDecimal.valueOf(matrix.get(0,1).doubleValue())+ " "+BigDecimal.valueOf(matrix.get(0,2).doubleValue())+ " "+ + BigDecimal.valueOf(matrix.get(1,0).doubleValue())+ " "+BigDecimal.valueOf(matrix.get(1, 1).doubleValue())+ " "+BigDecimal.valueOf(matrix.get(1, 2).doubleValue())+ " "+ + BigDecimal.valueOf(matrix.get(2,0).doubleValue())+ " "+BigDecimal.valueOf(matrix.get(2, 1).doubleValue())+ " "+BigDecimal.valueOf(matrix.get(2,2).doubleValue())+ " " + + BigDecimal.valueOf(matrix.get(0,3).doubleValue()) + " " + BigDecimal.valueOf(matrix.get(1, 3).doubleValue()) + " " + BigDecimal.valueOf(matrix.get(2, 3).doubleValue()) ); + //writeLine(line, out); + line.append("\n"); + } + if( isChain) + { + line.append("}\n"); + } + } + } + } + } + catch (MappingException mexcep) + { + logger.sessionError("Error during RTM mapping.",mexcep); + } + line.append(" }\n"); + //writeLine(line, out); + } + + } + + } + DataBuffer groupLine = DataBufferPool.getString(); + groupLine.setString("Group \""+groupName+"\" "+ids+" {"); + // groupLine.setString("Group \""+groupName+"\" {"); + writeLine(groupLine, out); + DataBufferPool.returnString(groupLine); + DataBufferPool.returnString(ids); + line.append(" Sequence \""+alignmentFileName+"\" \n");//\""+groupName+".aln"+"\" "); + //writeLine(line, out); + line.append(" Text \"This is a group "+groupName+"\"\n"); + //writeLine(line, out); + writeLine(line, out); + //Group "dfr" 7dfr 8dfr { + + line.setString("}\n"); + writeLine(line, out); + + + + } + else + this.logger.sessionWarn("No sequence to add to group "+ groupName); + } + line.setString("}\n"); + writeLine(line, out); + closeFile(out); + alignManager = null; + } + catch (AlignmentException ae ) + { + atrFile = null; + throw new UnableToGroupSequencesException(); + } + catch (IOException ioe) + { + this.logger.sessionError("Error during Atribute file writing "+atrFile+". ",ioe); + //ioe.printStackTrace(System.out); + atrFile = null; + } + return atrFile; + } + + /** + * Readds breakpoints after the multiple alignment ( as display character for breakpoint, are not supported by multiple alignment tools + * + * @param alignment alignment String + * @param alignmentName name of the alignment + * @return the file containing the alignment with breakpoints + */ + protected File unModifieSequences (String alignment, String alignmentName, String masterFileName) + { + if (alignment == null) + { + this.logger.sessionError("UnModifiedSequences - No aligment found. Can not unmodified sequences."); + return null; + } + // logger.Applidebug("Readded breakpoint to sequences "+alignment); + + + // String masterFileName = this.workingDirectory + File.separator+alignmentName+ alignmentfileExtension; + // WORK_ROOT + "/" +sessionId+ "/master_" + i + ".seq"; + //check workingDirectory exists, can be read and is a directory + File workingDir = new File (this.workingDirectory); + if(!(workingDir !=null && workingDir.exists())) + { + if (!workingDir.mkdir()) + { + this.logger.sessionError( "%%% WARNING: couldn't open master " + + "sequence file for writing. Working directory does not exist. Can not be created. "+this.workingDirectory ); + return null; + } + } + if(! (workingDir.isDirectory()&& workingDir.canRead())) + { + logger.sessionError( "%%% WARNING: couldn't open master " + + "sequence file for writing. Working directory does not exist. " ); + return null; + } + File masterFile = new File(masterFileName ); + try + { + Writer masterWriter = new FileWriter( masterFile ); + PrintWriter master = new PrintWriter( masterWriter ); + if(this.deleteOnExit) masterFile.deleteOnExit(); + + //write alignment + boolean endAlignment = false; + int len = 0; + DataBuffer brkSequence = DataBufferPool.getString(); + logger.sessionDebug("Retrieving alignment"); + String[] lines = alignment.split("\n"); + if (lines == null || lines.length<1) + { + logger.sessionError("No line retrieving - something wrong."); + return null; + } + logger.sessionDebug(lines.length+" lines found."); + for ( int lineNumber = 0; lineNumber bkpts = this.getSequenceBreakPoints().get(name); + if (bkpts == null)//no breakpoint associated - write line + { + logger.sessionDebug("No breakpoint export line "+line); + master.println(line); + /*System.out.println("no break point");*/ + } + else + {//modified at positions + //get sequence + /*System.out.println(line);*/ + logger.sessionDebug("No breakpoint found "); + String sequence = line.substring(pos+1,line.length()).trim(); + /*System.out.println("sequence: "+sequence);*/ + int seqPos = line.indexOf(sequence); + /*System.out.println("break point "+bkpts.size());*/ + + char[] chars = sequence.toCharArray(); + int currentResidentNumber = 0; + for (int charNumber = 0; charNumber< chars.length;charNumber++ ) + { + char currentChar = chars[charNumber]; + if (currentChar == '-') + { + //System.out.print(" gap "); + continue; + } + //check if breakpoint + /*System.out.print(" "+currentResidentNumber+" ");*/ + Integer resN = Integer.valueOf(currentResidentNumber++); + StringBuffer displayCharacter = bkpts.get(resN); + len++; + //System.out.print("|"+(currentResidentNumber-1)+"-"+len+"|"); + if (displayCharacter == null ||displayCharacter.length()<1 ) + { + continue; + } + //breakpoint found + chars[charNumber] = displayCharacter.charAt(0); + /*System.out.print(displayCharacter.charAt(0));*/ + bkpts.remove(resN);resN=null; + } + int resCount = currentResidentNumber; + sequence = String.valueOf(chars); + /*System.out.println("new seq: "+sequence);*/ + if (brkSequence.length()<=0) brkSequence.setString(sequence); + else brkSequence.append(sequence); + line = line.substring(0,seqPos).concat(sequence); + master.println(line); + Hashtable newBkpts = new Hashtable (bkpts.size()); + + for (Enumeration positions = bkpts.keys(); positions.hasMoreElements();) + { + Integer position = (Integer) positions.nextElement(); + if (position == null|| position.intValue()<0) continue; + StringBuffer character = bkpts.get(position); + if( character == null || character.length()!=1) + continue; + /*System.out.println("previous breakpoint position "+position.intValue());*/ + bkpts.remove(position); + //position = null; + position = Integer.valueOf(position.intValue() - (resCount)); + /*System.out.println("new breakpoint position "+position.intValue());*/ + //use temporary table to avoid deadlock + newBkpts.put(position, character); + } + /*for (Enumeration positions = bkpts.keys(); positions.hasMoreElements();) + { + Integer position = (Integer) positions.nextElement(); + if (position == null|| position.intValue()<0) continue; + StringBuffer character = bkpts.get(position); + if( character == null || character.length()!=1) + continue; + if( position.intValue()0) + this.getSequenceBreakPoints().put(name, newBkpts); + } + } + + //release unused object + this.clearSequenceBreakPoints(); + //StringBufferPool.returnString(this.sequences); + alignment = null; + master.close(); + master = null; + alignmentName = null; + // System.out.println("new bk seq "+brkSequence); + DataBufferPool.returnString(brkSequence); + } + catch( IOException ioe ) + { + logger.sessionError( "%%% WARNING: couldn't open master "+ "sequence file for writing: " + ioe ); + // ioe.printStackTrace(System.out); + masterFile = null; + } + return masterFile; + } + + /** + * As multiple alignment tools do not support breakpoint display characters, they are removed from the sequence, replaced by 'X' character + * and stored for readding after the multiple alignment (see unModifieSequences method) + * @param sequence sequence to prepare for alignment + * @param name name of the sequence to prepare + * @return the sequence without breakpoint display character + */ + + protected String prepareAddSequence(String sequence, String name) + { +// save position for breakpoint sequences + //modified non expected character ( A R D N B C E Z Q G H I L K M F P S T W Y V X) + //t o the same/unique one ->"|" + // + /*sequences.setLength(0); + sequences.trimToSize(); + sequences.append(sequence);*/ + //System.out.println("current seq "+sequences); + String temp = sequence.replaceAll("[^ARDNBCEZQGHILKMFPSTWYVX-]", "|"); + StringBuffer s = StringBufferPool.getString(); + s.setLength(0); + s.trimToSize(); + s.append(temp); + int pos = s.indexOf("|"); + //System.out.println("tem p seq "+temp); + Hashtable breakpointPositions = null; + while (pos>0) + { + logger.sessionInfo("new breakpoint "+pos); + if (breakpointPositions == null) breakpointPositions = new Hashtable(); + breakpointPositions.put(Integer.valueOf(pos), new StringBuffer(sequence.subSequence(pos, pos+1))); + s.setCharAt(pos, 'X'); + pos = s.indexOf("|"); + } + if(breakpointPositions!=null ) + {//a breakpoint has been found at least + this.getSequenceBreakPoints().put(name.trim().toLowerCase(), breakpointPositions); + } + String seq = s.toString(); + StringBufferPool.returnString(s); + return seq; + } + + /** + * Retrieves the sequenceFile attribut + * + * @return Returns the sequenceFile. + */ + public ArrayList getSequenceFiles() { + if( this.sequenceFile == null) + this.sequenceFile = new ArrayList (); + return this.sequenceFile; + } + + + /** + * Opens a file for writing + * + *@param file file to open. + *@return a printwriter to writer into it + * @exception IOException if an error occurs + */ + protected PrintWriter openFile(File file) throws IOException + { + PrintWriter out = null; + if (file == null) + { + //Application log(no such file) + throw new IOException("Unknown file"); + } + + // check if the current file exists + file = new File(file.getAbsolutePath()); + logger.sessionDebug("atribute file "+file.getAbsolutePath()); + if (!file.exists() ) + { + File directory = new File(file.getParent()); + logger.sessionDebug("parent directory "+ directory.getParent()); + // but first, see if it exists already. If so, we don't need + // to run the groups calculation again, so just return and + // we're done + if( directory.exists() ) { + // + } else { + if( ! directory.mkdirs() ) { + logger.sessionError( "%%% ERROR: Grouping; couldn't create " + + "directory for grouping /atribute file " ); + } + } + if (!file.createNewFile()) + { + throw new IOException("Can't create file: " + + file.getAbsolutePath()); + } + } + // the file will be overwritten, if the file already exists (but it should be indicated in the log) + + if (file.exists() && !erase) + { + throw new IOException("The file already exists: "+ file.getAbsolutePath()+ " Shall we overwrite?"); + } + + + if (!file.canWrite() ) + { + throw new IOException("Can not write in file: " + + file.getAbsolutePath()); + } + + // check possible problem with the reader + // The file is already opened. So, we close the file, before reopening it. + if (out != null) + { + closeFile(out); + logger.sessionWarn("The file "+ file.getName()+" has already been opened."); + } + + if (enc != null) + { + logger.sessionDebug("Opening File: "+file.getName()); + logger.sessionDebug("set output with encoding : "+enc+" "+file.getAbsolutePath()); + FileOutputStream fos = new FileOutputStream(file.getAbsolutePath(), append); + try + { + OutputStreamWriter ow = new OutputStreamWriter(fos, enc); + out = new PrintWriter(ow,true); + logger.sessionDebug("Encoding "+ow.getEncoding()+" support "+java.nio.charset.Charset.isSupported(enc)); + } + catch (java.io.UnsupportedEncodingException ue) + { + logger.sessionError("unsupported encoding ",ue); + } + } + else + { + + logger.sessionDebug("Opening File: "+file.getName()); + FileWriter fw = new FileWriter(file.getAbsolutePath(), append); + out = new PrintWriter(new BufferedWriter(fw),true); + } + return out; + } + + + /** + * Closes a data text file. + * @param out writer of the file to close. + * + */ + protected void closeFile(PrintWriter out) + { + if (out != null) + { + out.flush(); + out.close(); + out = null; + } + } + + + /** + *

+ * Retrieves a line from a data file + * Only when termination requirements have been met, the method should return a + * String object. + *

+ * @param line containing data items in one String + * @param out PrintWriter of the file to write line into. + */ + protected void writeLine(DataBuffer line, PrintWriter out ) + { + /*System.out.println("Writeline ");*/ + if (line != null) + { + if (line.length() == 0) + { + /*System.out.println("line empty");*/ + out.println(""); + } + else + { + out.println(line); + /* System.out.println("Writeline :" + line);*/ + } + } + } + + + /** + * Retrieves the sequenceBreakPoints attribut + * + * @return Returns the sequenceBreakPoints. + */ + protected Hashtable> getSequenceBreakPoints() + { + if(this.sequenceBreakPoints == null) + { + this.sequenceBreakPoints = new Hashtable>(); + } + + return this.sequenceBreakPoints; + } + + /** + * Clears breakpoint lisr + * + */ + protected void clearSequenceBreakPoints() + { + if(this.sequenceBreakPoints != null) + { + this.sequenceBreakPoints.clear(); + this.sequenceBreakPoints = null; + } + } + + /** + * Retrieves the pdbidsproperty attribut + * + * @return Returns the pdbidsproperty. + */ + public String getPdbidsproperty() + { + return this.pdbidsproperty; + } + + /** + * Retrieves the working directory for output file. + * @return the path to the output/working directory + */ + public abstract String getOutputDirectory(); + + /** + * retrieves current sessionID + * @return the ID of the current session for the document grouping. + */ + public abstract String getSessionID(); + } diff --git a/src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/grouping/SequenceGrouping_domain.java b/src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/grouping/SequenceGrouping_domain.java new file mode 100755 index 0000000..9d95fa3 --- /dev/null +++ b/src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/grouping/SequenceGrouping_domain.java @@ -0,0 +1,272 @@ +/* Created on 3 janv. 2006 + * * EMBL-EBI + * MSD Group + * VAMSAS Project + * VAMAV + * @author Pierre MARGUERITE + * @version 1 + * @since 3 janv. 2006 + */ +package uk.ac.ebi.msd.vamsas.vamav.documentmanagement.grouping; + +import uk.ac.ebi.msd.vamsas.vamav.documentmanagement.PDBUtil; +import uk.ac.ebi.msd.vamsas.vamav.documentmanagement.grouping.exceptions.UnableToGroupSequencesException; +import uk.ac.ebi.msd.vamsas.vamav.exceptions.IncorrectVamavModuleInitialisation; +import uk.ac.ebi.msd.vamsas.vamav.session.VAMAVSession; +import uk.ac.ebi.msd.vamsas.vamav.util.data.PDBEntry; +import uk.ac.ebi.msd.vamsas.vamav.util.mapping.MappingManager; +import uk.ac.ebi.msd.vamsas.vamav.util.pool.StringBufferPool; + +import java.io.File; +import java.util.ArrayList; +import java.util.Hashtable; +import java.util.Properties; + +/** + * Groups sequence per PFAM domain. + * + * For each sequence provided, the UniProtID is retrieved (if not provided, as source) by MSD lite. + * Then, the UniProt ID is mapped to PFAM domains, using the sanger web server. + * + * @author Pierre MARGUERITE + * @version 1 + * @since 3 janv. 2006 + * + */ +public class SequenceGrouping_domain extends SequenceGrouping + { + + protected VAMAVSession vamavSession = null; + + + /** + * + * Constructor of the SequenceGrouping class, given a mapping manager + * + * @param _mappingManager the mapping manager to use for mapping + */ + public SequenceGrouping_domain( MappingManager _mappingManager) + { + super(_mappingManager); + } + + /** + * + * Constructor of the SequenceGrouping class, given a mapping manager + * + * @param _mappingManager the mapping manager to use for mapping + * @param sessionID current session for which will be used the current sequence grouping. + */ + public SequenceGrouping_domain(MappingManager _mappingManager, VAMAVSession session ) + { + super(_mappingManager); + this.logger.setSession(session.getSessionID()); + this.vamavSession = session; + } + + /** + * Inits the Sequence Grouping sub module, with a list of configuration properties. + */ + public void init (Properties moduleProperties) throws IncorrectVamavModuleInitialisation + { + super.init(moduleProperties); + } + + + /** + * Adds a sequence to group + * @see uk.ac.ebi.msd.vamsas.vamav.documentmanagement.grouping.SequenceGrouping#addSequence(java.lang.String, java.lang.String) + */ + @Override + public Hashtable addSequence(String sequence, + String name) throws UnableToGroupSequencesException + { + // TODO Auto-generated method stub + return null; + } + /** + * Add a sequence for grouping, with an associated accessionID and its source. + * + * @param sequence chain sequence to add for grouping + * @param name name of the sequence to add + * @param accessionID accessionId associated to the sequence + * @param source source of the accessionID + * @return list of parameters to call the AstexViewer, if needed. Null, otherwise. + * @throws UnableToGroupSequencesException if an error occurs during the adding. + * + * @see uk.ac.ebi.msd.vamsas.vamav.documentmanagement.grouping.SequenceGrouping#addSequence(java.lang.String, java.lang.String, java.lang.String, java.lang.String) + + */ + @Override + public Hashtable addSequence(String sequence, + String name, String accessionID, String source) + throws UnableToGroupSequencesException + { + + if( sequence == null || sequence.length()<1) + { + this.logger.sessionError("SequenceGrouping - addSequence: Can not add sequence / The sequence is unknown."); + return null; + } + if( name == null || name.length()<1) + { + this.logger.sessionError("SequenceGrouping - addSequence: Can not add sequence / The name is unknown."); + return null; + } + if( source == null || source.length()<1) + { + this.logger.sessionWarn("SequenceGrouping - addSequence: the accession ID source is not provided / try to determine PDBID from the sequence."); + return this.addSequence(sequence, name); + } + if( accessionID == null || accessionID.length()<1) + { + this.logger.sessionWarn("SequenceGrouping - addSequence: the accession ID is not provided / try to determine PDBID from the sequence."); + return this.addSequence(sequence, name); + } + Hashtable parameters = null; + try + { + ArrayList entries = null; + + if("PDB".equals(source)) + { + PDBEntry entry = this.getMapping().getPDBEntryFromPDBID(accessionID); + if( entry != null) + { + entries = new ArrayList(1); + entries.add(entry); + } + } + if ("UNIPROT".equalsIgnoreCase(source)) + { + entries = this.getMapping().retrievePDBIDFromUniprotAC(accessionID); + } + if( entries == null || entries.size()<1) + { + this.logger.sessionError("No associated PDB ID to the accessionAC "+ accessionID + " from "+source); + return this.addSequence(sequence, name); + } + +// retrieved associated domains + + + ArrayList domains = this.mapping.retrievePFAMDomain(accessionID); + if (domains == null || domains.isEmpty()) + { + logger.sessionWarn("No domain associated to "+accessionID); + logger.sessionWarn("The sequence can not be grouped."); + return null; + } + + //boolean notFound = false; + //hasAlignmentSequences = true; + parameters = new Hashtable(); + + int molNumber = 0; + StringBuffer pdbIDs = null; + if (entries != null || entries.size()<1) + { +// Retrieves PDB chains, before adding them to group + //add molecule to AV parameters + ArrayList associatedChains = new ArrayList(); + PDBUtil util = new PDBUtil(this.vamavSession); + for (int entryNumber = entries.size() -1; entryNumber >=0; entryNumber --) + { + PDBEntry entry = entries.get(entryNumber); + + parameters.put("moleculeG"+molNumber,entry); + parameters.put("nameG"+molNumber, entry.getPdbID()); + if( !logger.isProduction()) logger.sessionDebug("Adding PDB parameters "+parameters); + ArrayList chains = util.GetChain(entry); + + if( chains != null) + { + this.logger.sessionDebug(" chains found "); + associatedChains.addAll(chains); + } + else + this.logger.sessionDebug("no chains found "); + + + if( pdbIDs == null) pdbIDs = StringBufferPool.getString(); + if(pdbIDs.length()>0)pdbIDs.append(", "+entry.getPdbID()); + else pdbIDs.append(entry.getPdbID()); + //entries.remove(entry); + } + + //treating retrieved domains + for (int domainNumber = domains.size() - 1; domainNumber >=0; domainNumber --) + {//add sequence to the current domain + String domainID = domains.get(domainNumber); + if (domainID == null || domainID.length()<0) + { + logger.sessionDebug("No domain. something wrong, while adding sequence to domain group."); + continue; + } + this.addSequenceToGroup(domainID, sequence, name); + //adding PDB chains to the group + if( associatedChains!=null && !associatedChains.isEmpty()) + { + for (int chainNumber = associatedChains.size()-1; chainNumber>=0; chainNumber--) + { + PDBUtil.Chain chain = associatedChains.get(chainNumber); + if (chain == null) continue; + + this.addSequenceToGroup(domainID, chain.getSequence(), chain.getName()); + } + } + if( entries != null && !entries.isEmpty()) + { + for (int entryNumber = entries.size() -1; entryNumber >=0; entryNumber --) + { + PDBEntry entry = entries.get(entryNumber); + if( entry == null) continue; + + this.addStructureToGroup(domainID, entry.getPdbID()); + //entries.remove(entry); + } + } + } + //this.addSequenceToGroup(entry.getPdbID(), sequence, name); + util = null; + if(!"PDB".equals(source))parameters.put(this.pdbidsproperty,pdbIDs.toString()); + StringBufferPool.returnString(pdbIDs); + entries.clear(); + entries = null; + } + + //} + /*catch (IncorrectVamavModuleInitialisation inE) + { + logger.AppliError("Sequence Grouping addSequence - error during mapping execution. Can not proceed.", inE); + throw new UnableToGroupSequencesException(); + }*/ + } + catch (Exception inE) + { + this.logger.sessionError("Sequence Grouping addSequence - error during mapping execution. Can not proceed.", inE); + throw new UnableToGroupSequencesException(); + } + return parameters; + } + + /** Retrieves the directory to store files in. + * @return the output directory for created file by the sequence grouping processing. + */ + public String getOutputDirectory() + { + File sessionDir = this.vamavSession.getSessionDirectory(); + if( sessionDir != null) + return sessionDir.getAbsolutePath(); + return null; //should not happen, has directory file is attached during object creation. + } + /** + * @see uk.ac.ebi.msd.vamsas.vamav.documentmanagement.grouping.SequenceGrouping#getSessionID() + */ + @Override + public String getSessionID() + { + return this.vamavSession.getSessionID(); + } + + } diff --git a/src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/grouping/SequenceGrouping_structure.java b/src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/grouping/SequenceGrouping_structure.java new file mode 100755 index 0000000..c70ba70 --- /dev/null +++ b/src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/grouping/SequenceGrouping_structure.java @@ -0,0 +1,298 @@ +/* * EMBL-EBI +* MSD Group +* VAMSAS Project +* VAMAV +*/ +package uk.ac.ebi.msd.vamsas.vamav.documentmanagement.grouping; + +import uk.ac.ebi.msd.vamsas.vamav.documentmanagement.PDBUtil; +import uk.ac.ebi.msd.vamsas.vamav.documentmanagement.grouping.exceptions.UnableToGroupSequencesException; +import uk.ac.ebi.msd.vamsas.vamav.exceptions.IncorrectVamavModuleInitialisation; +import uk.ac.ebi.msd.vamsas.vamav.session.VAMAVSession; +import uk.ac.ebi.msd.vamsas.vamav.util.data.PDBEntry; +import uk.ac.ebi.msd.vamsas.vamav.util.mapping.MappingManager; +import uk.ac.ebi.msd.vamsas.vamav.util.pool.StringBufferPool; + + +import java.io.File; +import java.util.ArrayList; +import java.util.Hashtable; +import java.util.Properties; + +/** + *Group sequences per structure + * + * First, add sequences, with DB ref is provided ( addSequence methods) + * then, + *storeGroup Method (To create atribute file and alignment files) + * + *Each time a sequence is added, it is added to the determined grou. + * @version 1 + *@author Pierre MARGUERITE + */ +public class SequenceGrouping_structure extends SequenceGrouping //implements uk.ac.ebi.msd.vamsas.vamav.VamaVModule{ +{ + + + //private final VAMAVLogger logger = new VAMAVLoggerImpl(this.getClass()); + protected VAMAVSession vamavSession = null; + + + /** + * + * Constructor of the SequenceGrouping class, given a mapping manager + * + * @param _mappingManager the mapping manager to use for mapping + */ + public SequenceGrouping_structure( MappingManager _mappingManager) + { + super(_mappingManager); + } + + /** + * + * Constructor of the SequenceGrouping class, given a mapping manager + * + * @param _mappingManager the mapping manager to use for mapping + * @param sessionID current session for which will be used the current sequence grouping. + */ + public SequenceGrouping_structure(MappingManager _mappingManager, VAMAVSession session ) + { + super(_mappingManager); + this.logger.setSession(session.getSessionID()); + this.vamavSession = session; + } + + /** + * Inits the Sequence Grouping sub module, with a list of configuration properties. + */ + public void init (Properties moduleProperties) throws IncorrectVamavModuleInitialisation + { + super.init(moduleProperties); + } + + /** + * Add a sequence for grouping. + * + * @param sequence chain sequence to add + * @param name name of the sequence to add + * @return a list of parameters to call the AstexViewer + * @throws UnableToGroupSequencesException if an error occurs during the adding. + */ + public Hashtable addSequence(String sequence, String name) throws UnableToGroupSequencesException + { + if( sequence == null || sequence.length()<1) + { + this.logger.sessionWarn("SequenceGrouping addSequence - no Sequence Provided. Can not add."); + return null; + } + if( name == null || name.length()<1) + { + this.logger.sessionWarn("SequenceGrouping addSequence - no name Provided. Can not add."); + return null; + } + ArrayList entries = null; + try + { + entries = this.getMapping().retrievePDBIDFromSequence(sequence); + } + catch (IncorrectVamavModuleInitialisation inE) + { + this.logger.sessionError("Sequence Grouping addSequence - error during mapping execution. Can not proceed.", inE); + throw new UnableToGroupSequencesException(); + } + Hashtable parameters = null; + if (entries == null ) return null; + StringBuffer pdbIDs = StringBufferPool.getString(); + for (int entryNumber = entries.size() -1; entryNumber>=0; entryNumber--) + { + PDBEntry entry = entries.get(entryNumber); + if (entry == null) continue; + + parameters = new Hashtable(); + int molNumber = 0; + if( !parameters.containsValue(entry)) + { + parameters.put("moleculeG"+molNumber,entry); + parameters.put("nameG"+molNumber, entry.getPdbID()); + this.logger.sessionDebug("New molecule added "+entry); + + molNumber++; + } + PDBUtil util = new PDBUtil(this.vamavSession); + + ArrayList chains = util.GetChain(entry); + util = null; + if( chains != null) + { + /*System.out.println(" chains found ");*/ + for (int chainN = chains.size()-1; chainN>=0; chainN --) + { + PDBUtil.Chain chain =chains.get(chainN); + if (chain == null)continue; + /*System.out.println("chain "+chain.getName()+ " "+chain.getSequence());*/ + String groupName = chain.getName(); + int pos = groupName.indexOf("_"); + if( pos>0) groupName = groupName.substring(0,pos); + this.addSequenceToGroup(groupName,chain.getSequence(),chain.getName()); + this.addStructureToGroup(groupName, entry.getPdbID()); + } + } + else + this.logger.sessionWarn("no chains found "); + String id = entry.getPdbID(); + this.addSequenceToGroup(id, sequence, name); + if(pdbIDs.length()<1) pdbIDs.append(id); + else pdbIDs.append(", "+id); + } + parameters.put(this.pdbidsproperty,pdbIDs.toString()); + StringBufferPool.returnString(pdbIDs); + return parameters; + } + + /** + * Add a sequence for grouping, with an associated accessionID and its source. + * + * @param sequence chain sequence to add for grouping + * @param name name of the sequence to add + * @param accessionID accessionId associated to the sequence + * @param source source of the accessionID + * @return list of parameters to call the AstexViewer, if needed. Null, otherwise. + * @throws UnableToGroupSequencesException if an error occurs during the adding. + */ + public Hashtable addSequence(String sequence, String name, String accessionID, String source) throws UnableToGroupSequencesException + { + + if( sequence == null || sequence.length()<1) + { + this.logger.sessionError("SequenceGrouping - addSequence: Can not add sequence / The sequence is unknown."); + return null; + } + if( name == null || name.length()<1) + { + this.logger.sessionError("SequenceGrouping - addSequence: Can not add sequence / The name is unknown."); + return null; + } + if( source == null || source.length()<1) + { + this.logger.sessionWarn("SequenceGrouping - addSequence: the accession ID source is not provided / try to determine PDBID from the sequence."); + return this.addSequence(sequence, name); + } + if( accessionID == null || accessionID.length()<1) + { + this.logger.sessionWarn("SequenceGrouping - addSequence: the accession ID is not provided / try to determine PDBID from the sequence."); + return this.addSequence(sequence, name); + } + Hashtable parameters = null; + try + { + ArrayList entries = null; + + if("PDB".equals(source)) + { + PDBEntry entry = this.getMapping().getPDBEntryFromPDBID(accessionID); + if( entry != null) + { + entries = new ArrayList(1); + entries.add(entry); + } + } + if ("UNIPROT".equalsIgnoreCase(source)) + { + entries = this.getMapping().retrievePDBIDFromUniprotAC(accessionID); + } + if( entries == null || entries.size()<1) + { + this.logger.sessionError("No associated PDB ID to the accessionAC "+ accessionID + " from "+source); + return this.addSequence(sequence, name); + } + //boolean notFound = false; + //hasAlignmentSequences = true; + parameters = new Hashtable(); + + //currenty only use the first entry + //for ( int entryNumber = entries.size()-1; entryNumber>=0; entryNumber --) + //{ + int molNumber = 0; + StringBuffer pdbIDs = null; + if (entries != null || entries.size()<1) + { + PDBUtil util = new PDBUtil(this.vamavSession); + for (int entryNumber = entries.size() -1; entryNumber >=0; entryNumber --) + { + PDBEntry entry = entries.get(entryNumber); + parameters.put("moleculeG"+molNumber,entry); + parameters.put("nameG"+molNumber, entry.getPdbID()); + + ArrayList chains = util.GetChain(entry); + + if( chains != null) + { + this.logger.sessionDebug(" chains found "); + // StringBuffer buff = StringBufferPool.getString(); + for (int chainN = chains.size()-1; chainN>=0; chainN --) + { + PDBUtil.Chain chain = chains.get(chainN); + if (chain == null)continue; + String groupName = chain.getName(); + int pos = groupName.indexOf("_"); + if( pos>0) groupName = groupName.substring(0,pos); + this.addSequenceToGroup(groupName, chain.getSequence(),chain.getName()); + this.addStructureToGroup(groupName, entry.getPdbID()); + chain = null; + } + } + else + this.logger.sessionDebug("no chains found "); + + this.addSequenceToGroup(entry.getPdbID(), sequence, name); + if( pdbIDs == null) pdbIDs = StringBufferPool.getString(); + if(pdbIDs.length()>0)pdbIDs.append(", "+entry.getPdbID()); + else pdbIDs.append(entry.getPdbID()); + entries.remove(entry); + } + util = null; + if(!"PDB".equals(source))parameters.put(this.pdbidsproperty,pdbIDs.toString()); + StringBufferPool.returnString(pdbIDs); + } + + //} + /*catch (IncorrectVamavModuleInitialisation inE) + { + logger.AppliError("Sequence Grouping addSequence - error during mapping execution. Can not proceed.", inE); + throw new UnableToGroupSequencesException(); + }*/ + } + catch (Exception inE) + { + this.logger.sessionError("Sequence Grouping addSequence - error during mapping execution. Can not proceed.", inE); + throw new UnableToGroupSequencesException(); + } + return parameters; + } + + /** + * Retrieves the directory to store files in. + * @return the output directory for created file by the sequence grouping processing. + */ + public String getOutputDirectory() + { + File sessionDir = this.vamavSession.getSessionDirectory(); + if( sessionDir != null) + return sessionDir.getAbsolutePath(); + return null; //should not happen, has directory file is attached during object creation. + } + + /** + * Retrieves current sessionID + * @see uk.ac.ebi.msd.vamsas.vamav.documentmanagement.grouping.SequenceGrouping#getSessionID() + */ + @Override + public String getSessionID() + { + + return this.vamavSession.getSessionID(); + } + + + } diff --git a/src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/grouping/exceptions/UnableToGroupSequencesException.java b/src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/grouping/exceptions/UnableToGroupSequencesException.java new file mode 100755 index 0000000..de14afa --- /dev/null +++ b/src/uk/ac/ebi/msd/vamsas/vamav/documentmanagement/grouping/exceptions/UnableToGroupSequencesException.java @@ -0,0 +1,61 @@ +/* Created on 22 nov. 2005 + * * EMBL-EBI + * MSD Group + * VAMSAS Project + * VAMAV + * @author Pierre MARGUERITE + * @version 1 + * @since 22 nov. 2005 + */ +package uk.ac.ebi.msd.vamsas.vamav.documentmanagement.grouping.exceptions; + +/** + * + * @author Pierre MARGUERITE + * @version 1 + * @since 22 nov. 2005 + * + */ +public class UnableToGroupSequencesException extends Exception + { + + /** + * Constructor + * + */ + public UnableToGroupSequencesException() + { + super(); + } + + /** + * Constructor + * + * @param arg0 + */ + public UnableToGroupSequencesException(String arg0) + { + } + + /** + * Constructor + * + * @param arg0 + * @param arg1 + */ + public UnableToGroupSequencesException(String arg0, Throwable arg1) + { + super(arg0, arg1); + } + + /** + * Constructor + * + * @param arg0 + */ + public UnableToGroupSequencesException(Throwable arg0) + { + super(arg0); + } + + } diff --git a/src/uk/ac/ebi/msd/vamsas/vamav/session/SessionManager.java b/src/uk/ac/ebi/msd/vamsas/vamav/session/SessionManager.java new file mode 100755 index 0000000..595c3e7 --- /dev/null +++ b/src/uk/ac/ebi/msd/vamsas/vamav/session/SessionManager.java @@ -0,0 +1,983 @@ +/* + * /* + * EMBL - European Bioinformatics institute + * MSD Group + * VAMSAS Project + * + *Created on 14 d�c. 2005 + * @author Pierre MARGUERITE + * @version 1 + * @since 14 d�c. 2005 + */ +package uk.ac.ebi.msd.vamsas.vamav.session; + +import uk.ac.ebi.msd.vamsas.vamav.VAMAVClient; +import uk.ac.ebi.msd.vamsas.vamav.VamaVModule; +import uk.ac.ebi.msd.vamsas.vamav.exceptions.IncorrectVamavModuleInitialisation; +import uk.ac.ebi.msd.vamsas.vamav.session.exceptions.UnableToOpenSession; +import uk.ac.ebi.msd.vamsas.vamav.util.file.FileCopy; +import uk.ac.ebi.msd.vamsas.vamav.util.file.description.FileFormatDescription; +import uk.ac.ebi.msd.vamsas.vamav.util.file.description.SimpleFileFormatDescription; +import uk.ac.ebi.msd.vamsas.vamav.util.logger.VAMAVLogger; +import uk.ac.ebi.msd.vamsas.vamav.util.logger.VAMAVLoggerImpl; +import uk.ac.ebi.msd.vamsas.vamav.util.properties.PropertyManager; +import uk.ac.ebi.msd.vamsas.vamav.util.properties.exceptions.UnableToStorePropertiesException; + +import org.vamsas.client.ClientHandle; +import org.vamsas.client.IClient; +import org.vamsas.client.IClientFactory; +import org.vamsas.client.InvalidSessionUrnException; +import org.vamsas.client.NoDefaultSessionException; +import org.vamsas.client.UserHandle; +import org.vamsas.client.simpleclient.ArchiveUrn; +import org.vamsas.client.simpleclient.SessionUrn; +import org.vamsas.client.simpleclient.VamsasArchiveReader; +import org.vamsas.client.simpleclient.VamsasSession; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Array; +import java.net.MalformedURLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Properties; + +/** + * Manager for VAMSAS session. + * Creates Session to which is attached clients + * + * Avoid to reinit a session previously treated. + * + * @author Pierre MARGUERITE + * @version 1 + * @since 14 d�c. 2005 + * + */ +public class SessionManager implements VamaVModule, IClientFactory + { + +/** + * Definition string for the VAMAV client + */ + private final String clientName = "VAMSAS - AstexViewer@MSD-EBI"; + private final String clientVersion = "0.6"; + + /** + * List of session ID and the associated session + * + */ + private Hashtable sessions = null; + + /** + * Property names + */ + private final String modulePrefix = "sessionmanager"; + + private final String sessionarenaProperty = "sessionarena"; + + private final String sessiondirectoryProperty = "sessiondirectory"; + private final String sessionLogFileProperty = "sessionlogfile"; + private final String appletFileProperty = "appletfile"; + private final String sessionDocumentFileNameProperty = "sessiondocumentfilename"; + + /*private VAMAVClientFactory clientfactory = null;*/ + + /** + * Logger to report messages + */ + private final VAMAVLogger logger = new VAMAVLoggerImpl(this.getClass()); + + /** + * Tags to replace at run-time from rules + */ + private final String temporaryTag = "@temp@"; + private final String sessionIDTag = "@sessionid@"; + private final String sessionDirTag = "@sessiondir@"; + private final String logExtensionTag = "@logfileextension@"; + private final String documentExtensionTag = "@documentextension@"; + + /** + * Rules for runtime variables (directories, files, ..) + */ + + private String sessionArenaRule = this.temporaryTag; + private String sessionDirectoryRule = this.sessionIDTag; + + private String sessionLogFileRule = this.sessionDirTag+File.separator+this.sessionIDTag+"."+this.logExtensionTag; + private String sessionDocumentFileNameRule = this.sessionDirTag+File.separator+"vamsas"+"."+this.documentExtensionTag; + private String appletFile = "index.html"; + + /** + * Keep a track of opened session. + * Stores session + */ + private Properties sessionTrack = null; + private final String trackFileName = "sessions.properties"; + private final String trackDefaultDirectory = "sessions"; + + /** + * root directory of the application + * Can be different of the current directory, in servlet server for example. + */ + private static String baseDirectory = null; + + + private File sessionArena = null; + + /** + * default constructor - called by CreateClientFactory only. + * + */ + public SessionManager() { + sessionArena = null; + } + /** + * Create a SessionManager that works parent directory for all session directories + * @param path + */ + public SessionManager(String path) throws IOException + { + // Check path is valid and read/writeable. + File newarena = new File(path); + if (newarena.exists() && newarena.isDirectory() && newarena.canRead() && newarena.canWrite()) + { + sessionArena = newarena; + } + else + { + sessionArena = null; + throw(new IOException("Cannot read and write to a directory called "+path)); + } + } + + /** + * Retrieves the modulePrefix attribut to init the current VAMAVModule + * + * @return Returns the modulePrefix. + */ + public String getModulePrefix() + { + return this.modulePrefix; + } + + + + /** + * Inits the Session Manager module following given properties + * + * @see uk.ac.ebi.msd.vamsas.vamav.VamaVModule#init(java.util.Properties) + */ + public void init(Properties properties) throws IncorrectVamavModuleInitialisation + { + logger.appliInfo("Init Session Manager: "); + /*/ try + { + this.clientfactory = new VAMAVClientFactory("factory"); + } + catch (IOException e) + { + throw new IncorrectVamavModuleInitialisation("Unable to create client factory"); + }*/ + if (properties != null && properties.size()>0) + { + this.sessionDirectoryRule = properties.getProperty(this.sessiondirectoryProperty, this.sessionDirectoryRule); + + this.sessionLogFileRule = properties.getProperty(this.sessionLogFileProperty, this.sessionLogFileRule); + this.appletFile = properties.getProperty(this.appletFileProperty, this.appletFile); + this.sessionDocumentFileNameRule = properties.getProperty(this.sessionDocumentFileNameProperty, this.sessionDocumentFileNameRule); + this.sessionArenaRule = properties.getProperty(this.sessionarenaProperty, this.sessionArenaRule); + } + if( this.sessionArenaRule.contains(this.temporaryTag)) + { + logger.applidebug("temporary tag found"); + try + { + File tempDir = createTempDir("VAMAV"); + if( !logger.isProduction()) logger.applidebug("temporary directory "+tempDir.getAbsolutePath()); + String preparePath = tempDir.getAbsolutePath().replaceAll("\\\\", "\\\\\\\\"); + this.sessionArenaRule = this.sessionArenaRule.replaceAll(this.temporaryTag,preparePath); + logger.applidebug("session arena rule "+this.sessionArenaRule); + } + catch (IOException exception) + { + this.logger.appliError("Session Manager/init: Unable to create temp directory.", exception); + throw new IncorrectVamavModuleInitialisation(exception); + } + } + else + { logger.applidebug("No temporary tag"); + if (baseDirectory!= null) + this.sessionArenaRule = baseDirectory.concat(File.separator).concat(this.sessionArenaRule); + } + if(this.sessionLogFileRule!=null && this.sessionLogFileRule.length()>0 ) + { + this.sessionLogFileRule = this.sessionLogFileRule.replaceAll(this.logExtensionTag,logger.getLogExtension()); + } + + Hashtable variables = new Hashtable(); + variables.put(this.logExtensionTag, logger.getLogExtension()); + variables.put(this.sessionDirTag, this.sessionDirectoryRule); + variables.put(this.sessionDocumentFileNameRule, this.sessionDirectoryRule); + this.replaceVariable(this.sessionDocumentFileNameRule, variables); + + this.sessionTrack = new Properties(); + PropertyManager propManager = new PropertyManager(); + this.sessionTrack = propManager.loadProperties(this.trackFileName, this.trackDefaultDirectory); + } + + /** + * Variables which can be found in property values, by correct value + * (except sessionId, which is no global to the application.) + * @param rule + * @return + */ + private String replaceVariable(String rule, Hashtable variables) + { + if(rule == null ) + { + logger.appliError("No rule provided to replace variables"); + return null; + } + if( rule.length()<1) + { + return rule; + } + if( variables == null || variables.size()<1) + { + return rule; + } + /** + * Prepare rule, otherwise '\' character is removed by replaceAll + */ + String preparePath = rule.replaceAll("\\\\", "\\\\\\\\"); + for (Enumeration keys = variables.keys(); keys.hasMoreElements();) + { + String var = (String)keys.nextElement(); + rule = rule.replaceAll(var,variables.get(var).replaceAll("\\\\", "\\\\\\\\")); + } + return rule; + + } + + + /** + * Reopens a session following the session ID for the new user + * + * @param firstName firstname of the user to open the session + * @param lastName lastname of the user + * @param sessionID ID of the session to open + * @return the created IClient according to the parameters provided + * @throws UnableToOpenSession if an error occurs while trying to open a session. + */ + public VAMAVClient openSession(String firstName, String lastName, String sessionID) throws UnableToOpenSession + { + if(sessionID == null || sessionID.length()<1 ) + { + this.logger.sessionFatal("Open Session - No sessionID provided: can not open session."); + return null; + } + VAMAVSession session = this.getSessions().get(sessionID); + VAMAVClient vorbaclient = null; + if (session == null) + { + //this.logger.sessionFatal("Open Session - No previous session exists. Can not open session."); + //return null; + this.logger.appliInfo("Opening closed session"); + String sessionDir = this.sessionTrack.getProperty(sessionID); + if( sessionDir == null || sessionDir.length()<1 ) + { + this.logger.appliFatal("Open Session - No previous session exists. Can not open session."); + return null; + } + File dir = new File (sessionDir); + String appletFileName = this.appletFile.replaceAll(this.sessionIDTag, sessionID); + if (dir.exists() && dir.canRead() && dir.isDirectory() && Arrays.asList(dir.list()).contains(appletFileName)) + {//the directory contains some files +// creating VAMSAS CLient + try + { + session = new VAMAVSession(dir); + //session.setSessionDirectory(new File (sessionDir)); + String preparePath = sessionDir.replaceAll("\\\\", "\\\\\\\\"); + session.setSessionLogFile(new File (this.sessionLogFileRule.replaceAll(this.sessionIDTag, sessionID).replaceAll(this.sessionDirTag, preparePath))); + session.setAppletFileName(appletFileName); + session.setClosedSession(true);//.setSessionID( true); + this.getSessions().put(sessionID, session); + } + catch (IOException ioe) + { + this.logger.appliError("unable to access to the session directory.", ioe); + throw new UnableToOpenSession (ioe); + } + } + } + ClientHandle app = new ClientHandle(this.clientName,this.clientVersion); + + if( firstName != null) + { + UserHandle user = new UserHandle(firstName,lastName); + vorbaclient = (VAMAVClient)this.getIClient(app, user, sessionID); + } + else + { + /*try + {*/ + vorbaclient = (VAMAVClient)this.getIClient(app); + /* } + catch (NoDefaultSessionException ndse) + { + this.logger.sessionError("Can not create client: ",ndse); + this.logger.appliError("Can not create client: ",ndse); + throw new UnableToOpenSession(ndse); + }*/ + } + session.addAttachedClient(vorbaclient); + return vorbaclient; + } + + /** + * Opens a new VAMSAS session for the provided VAMSAS document + * + * + * @param firstName firstname of the user to open the session + * @param lastName lastname of the user + * @param sessionID ID of the session to open + * @return the created IClient according to the parameters provided + * @throws UnableToOpenSession if an error occurs while trying to open a session. + */ + public VAMAVClient openSession(String firstName, String lastName, File documentPath) throws UnableToOpenSession + { + /** + * check document path + */ + if(documentPath == null || !documentPath.exists()) + { + this.logger.sessionFatal("No Document path provided or path incorrect. Can not open session."); + return null; + } + + if (!documentPath.canRead() || !documentPath.isFile()) + { + this.logger.sessionFatal("No Document path provided or path incorrect. Can not open session. "+documentPath); + return null; + } + + if ( (firstName == null ||firstName.length()<1 ) + && lastName == null||lastName.length()<1) + { + logger.appliError("No user information provided. Can not open session"); + throw new UnableToOpenSession("No user information provided. Can not open session"); + } + logger.applidebug("Starting new session with data from "+documentPath+"."); + //ArchiveUrn vamdoc = new ArchiveUrn(documentPath); + VamsasArchiveReader archive = new VamsasArchiveReader(documentPath); + // TODO: a real validity test. The below just checks it can be read. + if (!archive.isValid()) + throw new UnableToOpenSession(documentPath+" is not a valid vamsasDocument archive."); + ArchiveUrn vamsasdocument = null; + try + { + vamsasdocument = new ArchiveUrn(documentPath); + } + catch (MalformedURLException mue) + { + throw new UnableToOpenSession(); + } + + + ClientHandle app = new ClientHandle(this.clientName,this.clientVersion); + UserHandle user = new UserHandle(firstName,lastName); + + try + { + this.logger.applidebug("Opening session for "+documentPath + " "+vamsasdocument.asFile() +" "+vamsasdocument.getSessionUrn()); + return (VAMAVClient) this.openSession(app, user, vamsasdocument); + } + catch (IOException ioe) + { + throw new UnableToOpenSession(ioe); + } + } + + + + public IClient openSession(ClientHandle applicationHandle, UserHandle userId, ArchiveUrn vamsasdocument) throws IOException + { + this.logger.applidebug("openSession "+vamsasdocument.asFile()); + if (vamsasdocument == null) + { + return null; + } + + // create new session directory + if (sessionArena==null) + throw new Error("Improperly initialised SimpleClientFactory object - null sessionArena."); + File sessdir = File.createTempFile("sess", ".simpleclient", sessionArena); + if (!(sessdir.delete() && sessdir.mkdir())) + throw new IOException("Could not make session directory "+sessdir); + +// create session + //generate document copy in the session directory + VAMAVSession session = null; + try + {this.logger.applidebug("Creating VAMAVSession for "+sessdir); + session = new VAMAVSession(sessdir); + this.sessionTrack.setProperty(session.getSessionID(), sessdir.getAbsolutePath()); + String preparePath = sessdir.getAbsolutePath().replaceAll("\\\\", "\\\\\\\\"); + + session.setSessionLogFile(new File (this.sessionLogFileRule.replaceAll(this.sessionIDTag, session.getSessionID()).replaceAll(this.sessionDirTag, preparePath))); + session.setAppletFileName(this.appletFile); + this.getSessions().put(session.getSessionID(), session); + // copy document into session directory + File doc = vamsasdocument.asFile(); + this.logger.applidebug("setting document "+doc.getPath()); + this.logger.applidebug("setting document "+doc.getAbsolutePath()); + session.setVamsasDocument(doc); + } + catch (IOException ioe) + { + throw ioe;//new UnableToOpenSession(ioe); + } + IClient vorbaclient = this.getIClient(applicationHandle, userId, session); + session.addAttachedClient((VAMAVClient)vorbaclient); + //process the Vamsas Document to launch AstexViewer with suitable parameters + return vorbaclient; + } + + /** + * make a new vamsas session from the data in the archive vamsasdocument + * @param applicationHandle + * @param userId + * @param vamsasdocument + * @return + */ + /* public IClient openSession(ClientHandle applicationHandle, UserHandle userId, ArchiveUrn vamsasdocument) throws IOException { + // verify applicationHandle and userId + // TODO: verify applicationHandle and userId + // verify vamsasdocument is a valid document. + File vamdoc = vamsasdocument.asFile(); + this.logger.applidebug("Starting new session with data from "+vamsasdocument.getSessionUrn()+"(File is : "+vamdoc+")"); + VamsasArchiveReader archive = new VamsasArchiveReader(vamdoc); + // TODO: a real validity test. The below just checks it can be read. + if (!archive.isValid()) + throw new IOException(vamsasdocument.getSessionUrn()+" is not a valid vamsasDocument archive."); + // create new session directory + if (sessionArena==null) + throw new Error("Improperly initialised SimpleClientFactory object - null sessionArena."); + File sessdir = File.createTempFile("sess", ".simpleclient", sessionArena); + if (!(sessdir.delete() && sessdir.mkdir())) + throw new IOException("Could not make session directory "+sessdir); + VAMAVSession sess = new VAMAVSession(sessdir); + // copy document into session directory + sess.setVamsasDocument(vamsasdocument.asFile()); + // create client instance and return. + VAMAVClient client = new VAMAVClient(userId, applicationHandle, sess); + + return client; + }*/ + + /** + * opens session according to a provided sessionID or reads a provided VAMSAS document + * + * if no sessionID provided, creates a new session and opens the provided document. + * if the session Id is unknown, creates a new session and opens the provided document. + * if the session exists, and the provided document is newer, the provide document will replaced + * the current document in use. + * if the session has ben closed, the document is opened in a new session. + * @param firstName user firstname + * @param lastName user lastname + * @param documentPath path to a VAMSAS document + * @param sessionID ID of the session to open + * @return a VAMAVClient correspoding to the given parameters + * @throws UnableToOpenSession raises if an error during access to the document file + */ + public VAMAVClient openSession(String firstName, String lastName, File documentPath, String sessionID) throws UnableToOpenSession + { + if(sessionID == null || sessionID.length()<1 ) + { + logger.sessionWarn("Open Session - No sessionID provided: can not open session."); + return this.openSession(firstName, lastName, documentPath); + } + VAMAVSession session = this.getSessions().get(sessionID); + if (session == null) + { + return this.openSession(firstName, lastName, documentPath); + } + + /* + VAMAVSession session = null; + try + { + session = new VAMAVSession(new File(sessionDir)); + } + catch (IOException ioe) + { + throw new UnableToOpenSession(ioe); + }*/ + + + VAMAVClient newClient = null; + if (session.isOpen() && !session.isClosed()) + { + FileFormatDescription description = new SimpleFileFormatDescription(documentPath); + Hashtable variables = new Hashtable(); + variables.put(this.documentExtensionTag, description.getFileExtension()); + // String sessionDocumentPath = this.replaceVariable(this.sessionDocumentFileNameRule, variables); + File sessionDoc = session.getVamsasDocumentFile(); + //File sessionDoc = new File (sessionDocumentPath); + if (documentPath != null && documentPath.canRead() && documentPath.isFile() && documentPath.lastModified()< sessionDoc.lastModified()) + {//the provided document is newer than the document in the session directory. + logger.sessionInfo("The provided document is newer than the previously treated document. Proceed new document."); + return this.openSession(firstName, lastName, documentPath); + } + newClient = (VAMAVClient)session.getAttachedClient(0).clone(); + if( firstName != null && firstName.length()<1 && lastName!=null && lastName.length()<1) + { + UserHandle user = new UserHandle(firstName,lastName); + newClient.setUser(user); + } + try + { + FileCopy copyManager = new FileCopy(session.getSessionID()); + File newDoc = sessionDoc; + copyManager.copy(documentPath, newDoc); + documentPath = newDoc; + copyManager = null; + session.setVamsasDocumentFile(newDoc); + } + catch (IOException ioe) + { + logger.appliError("Unable to copy VAMSAS Document.", ioe); + } + } + else + newClient = this.openSession(firstName, lastName, documentPath); + /*String sessionID = vorbaclient.getSessionUrn(); + // String sessionDir = this.sessionDirectoryRule.replaceAll(this.sessionIDTag, sessionID); + // String preparePath = sessionDir.replaceAll("\\\\", "\\\\\\\\"); + // logger.applidebug("session directory "+sessionDir); + String appletFileName = this.appletFile.replaceAll(this.sessionIDTag, sessionID); + + // this.sessionTrack.setProperty(sessionID, sessionDir); + // session.setSessionDirectory(new File (sessionDir)); + // session.setSessionLogFile(new File (this.sessionLogFileRule.replaceAll(this.sessionIDTag, sessionID).replaceAll(this.sessionDirTag, preparePath))); + // session.setSessionID(sessionID,false); + session.addAttachedClient(vorbaclient); + session.setAppletFileName(appletFileName); + this.getSessions().put(sessionID, session); + + //Copying vamsas document file to session directory + FileFormatDescription description = new SimpleFileFormatDescription(documentPath); + Hashtable variables = new Hashtable(); + variables.put(this.documentExtensionTag, description.getFileExtension()); + variables.put(this.sessionDirTag, session.getSessionDirectory().getAbsolutePath()); + String sessionDocumentPath = this.replaceVariable(this.sessionDocumentFileNameRule, variables); + logger.sessionDebug("Session document "+ sessionDocumentPath); + //String sessionDocumentPath = this.sessionDocumentFileNameRule.replaceAll(preparePath, appletFileName);//sessionDir+File.separator+"vamsas"+"."+description.getFileExtension(); + try + { + FileCopy copyManager = new FileCopy(sessionID); + File newDoc = new File(sessionDocumentPath); + copyManager.copy(documentPath, newDoc); + documentPath = newDoc; + copyManager = null; + session.setVamsasDocumentFile(newDoc); + } + catch (IOException ioe) + { + logger.appliError("Unable to copy VAMSAS Document.", ioe); + } + */ + session.addAttachedClient(newClient); + return newClient; + } + + + /** + * Creates a new session of a given user. + * + * @param firstName first name of the user to open the session for + * @param lastName lastname of the user + * @return the created IClient according to the parameters provided + * @throws UnableToOpenSession raises if an error occurs during the accessing to the VAMSAS document. + *///DONE 14/03/2006 + public VAMAVClient createSession(String firstName, String lastName) throws UnableToOpenSession + { + // create new session directory + if (sessionArena==null) + throw new Error("Improperly initialised SimpleClientFactory object - null sessionArena."); + File sessdir = null; + try + { + sessdir = File.createTempFile("sess", ".simpleclient", sessionArena); + if (!(sessdir.delete() && sessdir.mkdir())) + throw new UnableToOpenSession("Could not make session directory "+sessdir); + } + catch (IOException ioe) + { + throw new UnableToOpenSession("Could not make session directory."); + + } + +// create session + //generate document copy in the session directory + VAMAVSession session = null; + //VAMAVClient vorbaclient = null; + try + { + session = new VAMAVSession(sessdir); + this.sessionTrack.setProperty(session.getSessionID(), sessdir.getAbsolutePath()); + String preparePath = sessdir.getAbsolutePath().replaceAll("\\\\", "\\\\\\\\"); + + session.setSessionLogFile(new File (this.sessionLogFileRule.replaceAll(this.sessionIDTag, session.getSessionID()).replaceAll(this.sessionDirTag, preparePath))); + session.setAppletFileName(this.appletFile); + this.getSessions().put(session.getSessionID(), session); + } + catch (IOException ioe) + { + throw new UnableToOpenSession(ioe); + } + ClientHandle app = new ClientHandle(this.clientName,this.clientVersion); + UserHandle user = new UserHandle(firstName,lastName); + IClient vorbaclient = this.getIClient(app, user, session); + session.addAttachedClient((VAMAVClient)vorbaclient); + //process the Vamsas Document to launch AstexViewer with suitable parameters + return (VAMAVClient) vorbaclient; + + } + + + + /** + * Create a new VAMAVCLient for a given clientHandle + * + * @see org.vamsas.client.IClientFactory#getIClient(org.vamsas.client.ClientHandle) + */ + public IClient getIClient(ClientHandle applicationHandle) //throws NoDefaultSessionException + { + try + { + return new VAMAVClient(applicationHandle); + } + catch (InvalidSessionUrnException isue) + { + this.logger.appliError("Unable to get client ",isue); + this.logger.sessionError("Unable to get client ",isue); + // throw new NoDefaultSessionException(isue); + } + return null; + } + + /** + * + * Retrieves a client of a given session URN. + * If does not exist, create a new one. + * + * @param applicationHandle client handle object + * @param sessionUrn URN of the session to attach the client + * @see org.vamsas.client.IClientFactory#getIClient(org.vamsas.client.ClientHandle, java.lang.String) + */ + //done 14 03 06 + public IClient getIClient(ClientHandle applicationHandle, String sessionUrn) + { + // applicationHandle also contains sessionURN + // applicationHandle.getClientUrn() + + /*VAMAVClient client = null; /* this.getClient(sessionUrn); + if (client == null) + { + client = new VAMAVClient(applicationHandle); + }*/ + VAMAVClient client = null; + try + { + VAMAVSession session = this.getSessions().get(sessionUrn); + client = new VAMAVClient(applicationHandle); + session.addAttachedClient(client); + client.setVAMAVSession(session); + } + catch (InvalidSessionUrnException isUExc) + { + this.logger.sessionError("The provided Session URN is incorrect.", isUExc); + this.logger.appliError("The provided Session URN is incorrect.", isUExc); + client = null; + } + return client; + } + + /** + * DONE 14/03/2006 + * @see org.vamsas.client.IClientFactory#getIClient(org.vamsas.client.ClientHandle, org.vamsas.client.UserHandle, java.lang.String) + */ + public IClient getIClient(ClientHandle applicationHandle, UserHandle userId, + String sessionUrn) + { + /* VAMAVClient client = this.getClient(sessionUrn); + if (client == null) + { + client = new VAMAVClient(applicationHandle); + client.setUser(userId); + } + if (userId == null) + { + logger.appliError("There is non userID provided."); + } + else + { + /*this.addUser(sessionUrn,userId);*/ + /*}*/ + VAMAVClient client = null; + try + { + VAMAVSession session = this.getSessions().get(sessionUrn); + client = new VAMAVClient(userId, applicationHandle, session); + session.addAttachedClient(client); + client.setVAMAVSession(session); + } + catch (InvalidSessionUrnException isUExc) + { + this.logger.sessionError("The provided Session URN is incorrect.", isUExc); + this.logger.appliError("The provided Session URN is incorrect.", isUExc); + client = null; + } + return client; + } + + /** + * DONE + * @see org.vamsas.client.IClientFactory#getIClient(org.vamsas.client.ClientHandle, org.vamsas.client.UserHandle) + */ + public VAMAVClient getIClient(ClientHandle applicationHandle, UserHandle userId, VAMAVSession session) + { + if (userId == null) + { + logger.appliInfo("There is non userID provided."); + } + else + { + /* String clientUrn = applicationHandle.getClientUrn(); + if (clientUrn != null && clientUrn.length()>0) + this.addUser(clientUrn, userId);*/ + } + if (session == null) + { + this.logger.appliError("No session provided. Can not create client if not associated to a session."); + return null; + } + + VAMAVClient client = null; + try + { + // String sessionID = new SessionHandle().generateSessionID(); + client = new VAMAVClient(userId, applicationHandle, session); + client.setUser(userId); + } + catch (InvalidSessionUrnException isUExc) + { + this.logger.sessionError("Unable to create session due to incorrect session.", isUExc); + this.logger.appliError("Unable to create session due to incorrect session.", isUExc); + + client = null; + } + // this.addClient(client.getSessionUrn(), client ); + // applicationHandle.setClientUrn(sessionID); + logger.appliInfo("generated sessionID "+client.getSessionUrn()); + return client; + } + + /** + * Remove a client + * + * Do nothing WHY? + * at a later stage? + * @param client the client to remove + */ + public void RemoveClient(VAMAVClient client) + { + if (client == null) + { + this.logger.appliError("SessionManager - Can not remove client. Client is null"); + return; + } + + } + + /** + * + * Finalize the current manager + */ + @Override + protected void finalize()throws Throwable + { + try + { + this.kill(); + } finally { + super.finalize(); + } + } + + /** + * Kill the current manager + * + */ + private void kill() + { + this.close(); + } + + +/** + * Closes the current manager. + * registers required data + * + */ +public void close() + { + if( this.sessionTrack != null && !this.sessionTrack.isEmpty()) + { + PropertyManager propManager = new PropertyManager(); + try + { + propManager.storeProperties(trackFileName, sessionTrack, "", trackDefaultDirectory); + } + catch (UnableToStorePropertiesException utspe) + { + logger.appliWarn("Unable to store session track"); + } + this.sessionTrack.clear(); + } + this.sessionTrack = null; + if (this.sessions!= null) + { + this.sessions.clear(); + this.sessions = null; + } + } + + /** + * Retrieves the sessions attribut + * + * @return Returns the sessions. + */ + private Hashtable getSessions() + { + if( this.sessions == null) + this.sessions = new Hashtable(); + return this.sessions; + } + + /** + * Creates a temp directory in a given directory. + * + * @param prefix prefix of the directory to create + * @param directory + * @throws IOException if an error occurs during file creation + * @return the temporary directory + */ + public File createTempDir(String prefix, File directory) throws IOException + { + if( prefix == null) + { + logger.sessionError("Error: no prefix provided to create temp file."); + throw new IOException(); + } + File tempFile = null; + if( directory == null ) + tempFile = File.createTempFile(prefix, ""); + else + tempFile = File.createTempFile(prefix, "", directory); + if (!tempFile.delete()) + throw new IOException(); + if (!tempFile.mkdir()) + throw new IOException(); + return tempFile; + } + + /** + * Creates a temp directory in the System temp directory. + * @param prefix prefix of the temp directory name + * @return the create file + * @throws IOException if an error during file creation + * + */ + public File createTempDir(String prefix) throws IOException + { + return this.createTempDir(prefix, null); + } + + /** + * Close the current session manager + * + */ + public void closeManager() + { + if (this.sessions != null) + { + for ( Enumeration ids = this.sessions.keys() ; ids.hasMoreElements();) + { + String sessionID = (String)ids.nextElement(); + if( sessionID == null || sessionID.length()<1)continue; + VAMAVSession session = this.sessions.remove(sessionID); + if (session != null) + { + session.close(); + session = null; + } + } + this.sessions.clear(); + this.sessions = null; + } + + } + /**Sets baseDirectory attribut + * + * @param _baseDirectory The baseDirectory to set. + */ + public static void setBaseDirectory(String _baseDirectory) + { + baseDirectory = _baseDirectory; + if( baseDirectory != null && baseDirectory.length()>0 && !baseDirectory.endsWith(File.separator)) + { + baseDirectory = baseDirectory.concat(File.separator); + } + } + + /** + * Retrieves the list of available sessions for the current session manager + */ + public ArrayList getAvailableSessions() + { + ArrayList sessionList = null; + for (Enumeration sessionIDs = sessions.keys();sessionIDs.hasMoreElements();) + { + String sessionID = sessionIDs.nextElement(); + if (sessionID == null || sessionID.length()<1) + { + continue; + } + if (sessionList == null) sessionList = new ArrayList(); + sessionList.add(sessionID); + } + return sessionList; + } + /* (non-Javadoc) + * @see org.vamsas.client.IClientFactory#getIClient(org.vamsas.client.ClientHandle, org.vamsas.client.UserHandle) + */ + public IClient getIClient( + ClientHandle applicationHandle, + UserHandle userId) { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.vamsas.client.IClientFactory#getCurrentSessions() + */ + public String[] getCurrentSessions() { + // TODO look in the arena and enumerate session handles for return. + return new String[] {}; + } + } diff --git a/src/uk/ac/ebi/msd/vamsas/vamav/session/VAMAVSession.java b/src/uk/ac/ebi/msd/vamsas/vamav/session/VAMAVSession.java new file mode 100755 index 0000000..edd4c33 --- /dev/null +++ b/src/uk/ac/ebi/msd/vamsas/vamav/session/VAMAVSession.java @@ -0,0 +1,462 @@ +/* + * + * * EMBL - European Bioinformatics institute + * MSD Group + * VAMSAS Project + * + * Created on Feb 22, 2006 + * + * @author Pierre MARGUERITE + * @version 2 + * @since 22 Feb. 2006 + */ +package uk.ac.ebi.msd.vamsas.vamav.session; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; + +import org.vamsas.client.simpleclient.SessionUrn; +import org.vamsas.client.simpleclient.VamsasSession; + +import uk.ac.ebi.msd.vamsas.vamav.VAMAVClient; +import uk.ac.ebi.msd.vamsas.vamav.util.logger.VAMAVLogger; +import uk.ac.ebi.msd.vamsas.vamav.util.logger.VAMAVLoggerImpl; + +/** + * This class represents a VAMSAS session, + * with a session ID, which can be opened and closed. + * @author Pierre MARGUERITE + * @since 22 Feb. 2006 + * @version 2 + * + */ +public class VAMAVSession extends VamsasSession { + + /** + * ID of the current session + */ + //private String sessionID = null; + + /** + * if the session is opened + */ + private boolean open = false; + + /** + * if the current session has been initialised. + */ + private boolean init = false; + + /** + * log file containing session messages + * TODO merge with VAMSAS session log ? + */ + private File sessionLogFile = null; + + /** + * Path to the HTML page used to call the AstexViewer@MSD- + * EBI as applet + */ + private String appletFileName = null; + + /** + * Path to the Vamsas document file + */ + private File vamsasDocumentFile = null; + + /** + * Logger to report messages + */ + private VAMAVLogger logger = new VAMAVLoggerImpl(this.getClass()); + + /** + * Structure grouping mode in use + */ + private int groupingMode = -1; + + /** + * List of attached VAMAV Client + * + */ + private ArrayList attachedClients = null; + + private SessionUrn sessionURN = null; + + /** + * Constructor specifying the session Directory + * + * @param sessionDir session directory containing all information relatives to the session + * @throws IOException if an error occurs during accessing to the session directory + */ + public VAMAVSession(File sessionDir) throws IOException + { + super(sessionDir); + sessionURN = new SessionUrn(this); + this.logger.applidebug("setting logger seession"); + this.logger.setSession(this); + } + + + /** + * Retrieves the sessionID attribut + * + * ID of the current session + * + * @return Returns the sessionID. + */ + public String getSessionID() + { + String id = null; + if (this.sessionURN != null) + { + String urn = this.sessionURN.asFile().getAbsolutePath(); + //this.logger.applidebug("session urn "+urn); + + if ("\\".equals(File.separator)) + { + //remove last separator at last position if found + if (urn.charAt(urn.length() - 1) == '/')urn = urn.substring(0, urn.length() - 1); + urn = urn.replaceAll("/", "\\\\"); + //this.logger.applidebug("session urn "+urn); + } + int index = urn.lastIndexOf(File.separator); + + if (index >-1) + {//separator found, keep last part of the urn - filename + id = urn.substring(index+1, urn.length()); + } + else + id = urn; + //this.logger.applidebug("session ID "+urn); + } + return id; + } + + + /** + * Sets sessionID attribut, ID of the current sesssion + * + * @param sessionID The sessionID to set. + */ + /* public void setSessionID(String sessionID) + { + //this.sessionID = sessionID; + this.logger.applidebug("setting logger seession"); + this.logger.setSession(this); + } +*/ + + /** + *specifies if the session + *has been closed. + * + * @param sessionID The sessionID to set. + */ + public void setClosedSession( boolean closedSession) + { + //this.sessionID = sessionID; + this.logger.applidebug("setting logger session"); + this.logger.setSession(this, closedSession); + } + + + /** + * Retrieves the open attribut + *Indicates if the session has been opened. + * + * @return Returns the open. + */ + public boolean isOpen() + { + return this.open; + } + + + /** + *Sets open attribut + * + * @param open The open to set. + */ + public void sessionOpen() + { + this.open = true; + this.init = true; + } + + /** + *Sets open attribut + * + * @return true if the session has been opened then closed. false, otherwise. + */ + public boolean isClosed() + { + return !this.open; + } + + /** + * finalize the object + */ + protected void finalize() throws Throwable + { + try + { + this.kill(); + } finally { + super.finalize(); + } + } + + /** + * kills the current session + * Stores required information + * + */ + private void kill() + { + if (this.attachedClients!= null) + { + for (int clientNumber = this.attachedClients.size() -1;clientNumber>=0; clientNumber-- ) + { + VAMAVClient client = this.attachedClients.get(clientNumber) ; + client = null; + } + this.attachedClients.clear(); + this.attachedClients = null; + } + /*if( this.sessionID != null) + { + this.sessionID = this.sessionID.replaceAll(this.sessionID, ""); + this.sessionID = null; + }*/ + } + + /** + * Retrieves the attachedClients attribut, list of client + * associated to the current session + * + * @return Returns the attachedClients. + */ + private ArrayList getAttachedClients() + { + return this.attachedClients; + } + + /** + * Retrieves an attachedClient at a given index + * + * + * @param index index of the client to retrieved + * @return the attached client at the given index, if found. null otherwise. + */ + public VAMAVClient getAttachedClient(int index ) + { + if (this.getAttachedClients() == null || index<0 || index>this.getAttachedClients().size()) + return null; + return this.getAttachedClients().get(index); + } + + /** + * Attached the client to a VAMAV Session + * + * @param client client to add the current session. + */ + public void addAttachedClient(VAMAVClient client) + { + if( this.getAttachedClients() == null) + { + this.attachedClients = new ArrayList(); + } + this.getAttachedClients().add(client); + client.setVAMAVSession(this); + } + + /** + * removes a client from the current session + * + * @param client client to remove + */ + public void removeClient(VAMAVClient client) + { + if( this.getAttachedClients() == null ) + { + logger.appliError("Unable to remove client. There is no client attached."); + } + this.getAttachedClients().remove(client); + if ( this.getAttachedClients().size()<1) + { + this.close(); + } + } + + /** + * Retrieves the sessionDirectory attribut + * + * retrieves the session directory containing files relatives to the session + * + * @return Returns the sessionDirectory. + */ + public File getSessionDirectory() + { + return this.sessionDir; + } + + + /** + *Sets sessionDirectory attribut + * + *Sets the path to the session directory + * + * @param sessionDirectory The sessionDirectory to set. + */ + public void setSessionDirectory(File sessionDirectory) + { + if( sessionDirectory!= null) + { + if(!sessionDirectory.exists()) + if( !sessionDirectory.mkdirs()) + { + logger.sessionError("Unable to create session directory."); + } + this.sessionDir = sessionDirectory; + if (!this.logger.isProduction()) this.logger.applidebug("session directory "+sessionDirectory.getAbsolutePath()); + + } + } + + /** + * Retrieves the sessionLogFile attribut + * + *Path the session log file containing reported messages relatives + *to the session + * + * @return Returns the sessionLogFile. + */ + public File getSessionLogFile() + { + return this.sessionLogFile; + } + + + /** + *Sets sessionLogFile attribut + * + *Sets the file containing all reported session messages + * + * @param sessionLogFile The sessionLogFile to set. + */ + public void setSessionLogFile(File sessionLogFile) + { + this.sessionLogFile = sessionLogFile; + if (sessionLogFile != null && !this.logger.isProduction()) + { + this.logger.applidebug(sessionLogFile.getAbsolutePath()); + } + + } + + /** + * Closes the current session + *Clears client list //TODO close attached clients + * + */ + public void close () + { + logger.sessionInfo("Closing session "+this.getSessionID() ); + this.open = false; + if (this.getAttachedClients() != null) + { + this.getAttachedClients().clear(); + this.attachedClients = null; + } + } + + + /** + * Retrieves the appletFileName attribut + *name of the file containing html page to call the AstexViewer@MSD-EBI + * + * @return Returns the appletFileName. + */ + public String getAppletFileName() + { + return this.appletFileName; + } + + /** + * Retrieves the appletFile object + * + * @return Returns the appletFile object + */ + public File getAppletFile() + { + return new File (this.getSessionDirectory().getAbsolutePath()+File.separator+this.appletFileName); + } + + + /** + *Sets appletFileName attribut + * + * @param appletFileName The appletFileName to set. + */ + public void setAppletFileName(String appletFileName) + { + this.appletFileName = appletFileName; + } + + + /** + * Retrieves the vamsasDocument File + * + * @return Returns the vamsasDocumentFile. + */ + public File getVamsasDocumentFile() + { + return this.vamsasDocumentFile; + } + + + /** + *Sets vamsasDocumentFile associated to /treated in the session + * + * @param vamsasDocumentFile The vamsasDocumentFile to set. + */ + public void setVamsasDocumentFile(File vamsasDocumentFile) + { + this.vamsasDocumentFile = vamsasDocumentFile; + } + + + /** + * Retrieves the groupingMode currently used in the + * session for process data + * + * @return Returns the groupingMode. + */ + public int getGroupingMode() + { + return this.groupingMode; + } + + + /** + *Sets groupingMode attribut + * + * @param groupingMode The groupingMode to set. + */ + public void setGroupingMode(int groupingMode) + { + this.groupingMode = groupingMode; + } + + + /** + * Retrieves the init attribut + * Indicates if the current session has been initialised + * @return Returns the init. + */ + public boolean isInit() + { + return this.init; + } +} diff --git a/src/uk/ac/ebi/msd/vamsas/vamav/session/exceptions/UnableToOpenSession.java b/src/uk/ac/ebi/msd/vamsas/vamav/session/exceptions/UnableToOpenSession.java new file mode 100755 index 0000000..5156c5f --- /dev/null +++ b/src/uk/ac/ebi/msd/vamsas/vamav/session/exceptions/UnableToOpenSession.java @@ -0,0 +1,50 @@ +/* + * Created on Mar 9, 2006 + * + * To change the template for this generated file go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +package uk.ac.ebi.msd.vamsas.vamav.session.exceptions; + +/** + * @author pierre + * + * To change the template for this generated type comment go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +public class UnableToOpenSession extends Exception { + + /** + * + */ + public UnableToOpenSession() { + super(); + // TODO Auto-generated constructor stub + } + + /** + * @param message + */ + public UnableToOpenSession(String message) { + super(message); + // TODO Auto-generated constructor stub + } + + /** + * @param message + * @param cause + */ + public UnableToOpenSession(String message, Throwable cause) { + super(message, cause); + // TODO Auto-generated constructor stub + } + + /** + * @param cause + */ + public UnableToOpenSession(Throwable cause) { + super(cause); + // TODO Auto-generated constructor stub + } + +} -- 1.7.10.2