New Linux binaries for ViennaRNA
[jabaws.git] / webservices / compbio / ws / server / WSUtil.java
1 /* Copyright (c) 2011 Peter Troshin\r
2  *  \r
3  *  JAva Bioinformatics Analysis Web Services (JABAWS) @version: 2.0     \r
4  * \r
5  *  This library is free software; you can redistribute it and/or modify it under the terms of the\r
6  *  Apache License version 2 as published by the Apache Software Foundation\r
7  * \r
8  *  This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without\r
9  *  even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Apache \r
10  *  License for more details.\r
11  * \r
12  *  A copy of the license is in apache_license.txt. It is also available here:\r
13  * @see: http://www.apache.org/licenses/LICENSE-2.0.txt\r
14  * \r
15  * Any republication or derived work distributed in source code form\r
16  * must include this copyright and license notice.\r
17  */\r
18 package compbio.ws.server;\r
19 \r
20 import java.security.InvalidParameterException;\r
21 import java.util.ArrayList;\r
22 import java.util.HashSet;\r
23 import java.util.List;\r
24 import java.util.Set;\r
25 \r
26 import org.apache.log4j.Logger;\r
27 \r
28 import compbio.data.sequence.FastaSequence;\r
29 import compbio.data.sequence.ScoreManager;\r
30 import compbio.engine.AsyncExecutor;\r
31 import compbio.engine.Configurator;\r
32 import compbio.engine.ProgressGetter;\r
33 import compbio.engine.client.ConfiguredExecutable;\r
34 import compbio.metadata.ChunkHolder;\r
35 import compbio.metadata.JobStatus;\r
36 import compbio.metadata.JobSubmissionException;\r
37 import compbio.metadata.Limit;\r
38 import compbio.metadata.LimitExceededException;\r
39 import compbio.metadata.Option;\r
40 import compbio.metadata.ResultNotAvailableException;\r
41 import compbio.ws.client.Services;\r
42 import compbio.ws.client.ServicesUtil;\r
43 \r
44 public final class WSUtil {\r
45 \r
46         public static final void validateJobId(String jobId)\r
47                         throws InvalidParameterException {\r
48                 if (!compbio.engine.client.Util.isValidJobId(jobId)) {\r
49                         throw new InvalidParameterException(\r
50                                         "JobId is not provided or cannot be recognised! Given value: "\r
51                                                         + jobId);\r
52                 }\r
53         }\r
54 \r
55         public static final void validateFastaInput(List<FastaSequence> sequences)\r
56                         throws JobSubmissionException {\r
57                 if (sequences == null || sequences.isEmpty()) {\r
58                         throw new JobSubmissionException(\r
59                                         "List of fasta sequences required but not provided! ");\r
60                 }\r
61                 Set<String> names = new HashSet<String>();\r
62                 for (FastaSequence fs : sequences) {\r
63                         boolean unique = names.add(fs.getId());\r
64                         if (!unique) {\r
65                                 throw new JobSubmissionException(\r
66                                                 "Input sequences must have unique names! \n"\r
67                                                                 + "Sequence " + fs.getId() + " is a duplicate!");\r
68                         }\r
69                         if (fs.getLength() == 0) {\r
70                                 throw new JobSubmissionException(\r
71                                                 "Sequence must not be empty! Sequence: " + fs.getId()\r
72                                                                 + " was empty");\r
73                         }\r
74                 }\r
75         }\r
76 \r
77         public static JobStatus getJobStatus(String jobId) {\r
78                 AsyncExecutor asyncEngine = Configurator.getAsyncEngine(jobId);\r
79                 return asyncEngine.getJobStatus(jobId);\r
80         }\r
81 \r
82         public static ChunkHolder pullFile(String file, long position) {\r
83                 return ProgressGetter.pull(file, position);\r
84         }\r
85 \r
86         public static byte getProgress(String jobId) {\r
87                 throw new UnsupportedOperationException();\r
88         }\r
89 \r
90         public static AsyncExecutor getEngine(ConfiguredExecutable<?> confClustal) {\r
91                 assert confClustal != null;\r
92                 return Configurator.getAsyncEngine(confClustal);\r
93         }\r
94 \r
95         public static boolean cancelJob(String jobId) {\r
96                 AsyncExecutor asyncEngine = Configurator.getAsyncEngine(jobId);\r
97                 return asyncEngine.cancelJob(jobId);\r
98         }\r
99 \r
100         public static <T> String align(List<FastaSequence> sequences,\r
101                         ConfiguredExecutable<T> confExec, Logger logger,\r
102                         String callingMethod, Limit<T> limit)\r
103                         throws LimitExceededException, JobSubmissionException {\r
104 \r
105                 if (limit != null && limit.isExceeded(sequences)) {\r
106                         throw LimitExceededException.newLimitExceeded(limit, sequences);\r
107                 }\r
108                 compbio.runner.Util.writeInput(sequences, confExec);\r
109                 AsyncExecutor engine = Configurator.getAsyncEngine(confExec);\r
110                 String jobId = engine.submitJob(confExec);\r
111                 reportUsage(confExec, logger);\r
112                 return jobId;\r
113         }\r
114         \r
115 \r
116         static <T> void reportUsage(ConfiguredExecutable<T> confExec, Logger logger) {\r
117                 if (GAUtils.IS_GA_ENABLED) {\r
118                         Services service = ServicesUtil.getServiceByRunner(confExec\r
119                                         .getExecutable().getClass());\r
120                         GAUtils.reportUsage(service);\r
121                         logger.info("Reporting GA usage for " + service);\r
122                 }\r
123         }\r
124 \r
125         public static <T> String analize(List<FastaSequence> sequences,\r
126                         ConfiguredExecutable<T> confExec, Logger log, String method,\r
127                         Limit<T> limit) throws JobSubmissionException {\r
128                 if (limit != null && limit.isExceeded(sequences)) {\r
129                         throw LimitExceededException.newLimitExceeded(limit, sequences);\r
130                 }\r
131                 log.debug("Method: " + method + " with task: " + confExec.getTaskId());\r
132                 compbio.runner.Util.writeInput(sequences, confExec);\r
133                 AsyncExecutor engine = Configurator.getAsyncEngine(confExec);\r
134                 String jobId = engine.submitJob(confExec);\r
135                 reportUsage(confExec, log);\r
136                 return jobId;\r
137         }\r
138         \r
139         // Same as analize but Alifold takes clustal input not fasta\r
140         // An if condition in the above method might be a better solution but \r
141         // you need a way of finding out the type of confExec at runtime\r
142         \r
143         public static <T> String fold(List<FastaSequence> sequences,\r
144                         ConfiguredExecutable<T> confExec, Logger log, String method,\r
145                         Limit<T> limit) throws JobSubmissionException {\r
146                 if (limit != null && limit.isExceeded(sequences)) {\r
147                         throw LimitExceededException.newLimitExceeded(limit, sequences);\r
148                 }\r
149                 log.debug("Method: " + method + " with task: " + confExec.getTaskId());\r
150                 // This line is different from the above method\r
151                 compbio.runner.Util.writeClustalInput(sequences, confExec, '-');\r
152                 AsyncExecutor engine = Configurator.getAsyncEngine(confExec);\r
153                 String jobId = engine.submitJob(confExec);\r
154                 reportUsage(confExec, log);\r
155                 return jobId;\r
156         }\r
157 \r
158         /*\r
159          * TODO Rewrite using purely CommandBuilder. This is breaking encapsulation\r
160          */\r
161         public static final <T> List<String> getCommands(List<Option<T>> options,\r
162                         String keyValueSeparator) {\r
163                 List<String> oList = new ArrayList<String>();\r
164                 for (Option<T> o : options) {\r
165                         oList.add(o.toCommand(keyValueSeparator));\r
166                 }\r
167                 return oList;\r
168         }\r
169 \r
170         public static void validateAAConInput(List<FastaSequence> sequences)\r
171                         throws JobSubmissionException {\r
172                 validateFastaInput(sequences);\r
173                 int len = 0;\r
174                 for (FastaSequence fs : sequences) {\r
175                         if (len == 0) {\r
176                                 len = fs.getLength();\r
177                                 continue;\r
178                         }\r
179                         if (fs.getLength() != len) {\r
180                                 throw new JobSubmissionException(\r
181                                                 "All sequences must be of the same length. Please align the sequences " + \r
182                                                 " prior to submission! The first sequence length is : " + len + \r
183                                                 " but the sequence '" + fs.getId() + "' length is " + fs.getLength());\r
184                         }\r
185                 }\r
186         }\r
187 \r
188         public static void validateJpredInput(List<FastaSequence> sequences)\r
189                         throws JobSubmissionException {\r
190                 validateFastaInput(sequences);\r
191                 int len = 0;\r
192                 for (FastaSequence fs : sequences) {\r
193                         if (len == 0) {\r
194                                 len = fs.getLength();\r
195                                 continue;\r
196                         }\r
197                         if (fs.getLength() != len) {\r
198                                 System.out.println("FASTA rec: id = " + fs.getId() + ": seq = " + fs.getSequence());\r
199                                 throw new JobSubmissionException(\r
200                                                 "All sequences must be of the same length. Please align the sequences " + \r
201                                                 " prior to submission! The first sequence length is : " + len + \r
202                                                 " but the sequence '" + fs.getId() + "' length is " + fs.getLength());\r
203                         }\r
204                 }\r
205         }\r
206 \r
207         public static <T> ScoreManager getAnnotation(String jobId, Logger log)\r
208                         throws ResultNotAvailableException {\r
209                 WSUtil.validateJobId(jobId);\r
210                 AsyncExecutor asyncEngine = Configurator.getAsyncEngine(jobId);\r
211                 ConfiguredExecutable<T> aacon = (ConfiguredExecutable<T>) asyncEngine.getResults(jobId);\r
212                 ScoreManager mas = aacon.getResults();\r
213                 \r
214                 log.trace(jobId + " getConservation : " + mas);\r
215                 return mas;\r
216         }\r
217         \r
218 \r
219         /*\r
220          * UNUSED\r
221          * \r
222          * @SuppressWarnings("unchecked") static <T> LimitsManager<T>\r
223          * getLimits(Class<? extends Executable<T>> clazz, WebServiceContext\r
224          * wsContext) {\r
225          * \r
226          * String LIMIT_KEY = CACHE_KEY + clazz.getCanonicalName(); LimitsManager<T>\r
227          * limit = (LimitsManager<T>) getObjectFromApplContext( LIMIT_KEY,\r
228          * wsContext); if (limit == null) { synchronized (WSUtil.class) { limit =\r
229          * (LimitsManager<T>) getObjectFromApplContext(LIMIT_KEY, wsContext); if\r
230          * (limit == null) { limit = compbio.runner.Util\r
231          * .getLimits((Class<Executable<T>>) clazz);\r
232          * addObjectToApplContext(wsContext, LIMIT_KEY, limit); } } } return limit;\r
233          * }\r
234          * \r
235          * static void addObjectToApplContext(WebServiceContext wsContext, String\r
236          * objKey, Object obj) { assert !Util.isEmpty(objKey) :\r
237          * "Key for the object must not be empty! "; assert wsContext != null;\r
238          * \r
239          * ServletContext ctx = ((javax.servlet.ServletContext) wsContext\r
240          * .getMessageContext().get(MessageContext. SERVLET_CONTEXT)); assert ctx !=\r
241          * null; log.debug("Adding object with key '" + objKey + "' and value '" +\r
242          * obj + "' to the application context"); ctx.setAttribute(objKey, obj); }\r
243          * static Object getObjectFromApplContext(String objKey, WebServiceContext\r
244          * wsContext) { assert !Util.isEmpty(objKey) :\r
245          * "Key for the object must not be empty! "; assert wsContext != null;\r
246          * \r
247          * ServletContext ctx = ((javax.servlet.ServletContext) wsContext\r
248          * .getMessageContext().get(MessageContext. SERVLET_CONTEXT)); Object obj =\r
249          * ctx.getAttribute(objKey); log.trace("Retrieving object with key '" +\r
250          * objKey + "' and value '" + obj + "' from the application context");\r
251          * return obj; }\r
252          */\r
253 }\r