more fixes and extension to allow return data types to be specified JAL-715
[jalview.git] / src / jalview / ws / rest / params / Alignment.java
1 package jalview.ws.rest.params;
2
3 import jalview.datamodel.AlignmentI;
4 import jalview.ws.rest.InputType;
5 import jalview.ws.rest.NoValidInputDataException;
6 import jalview.ws.rest.RestJob;
7 import jalview.ws.rest.InputType.molType;
8
9 import java.io.BufferedOutputStream;
10 import java.io.File;
11 import java.io.FileOutputStream;
12 import java.io.OutputStreamWriter;
13 import java.io.PrintWriter;
14 import java.io.UnsupportedEncodingException;
15 import java.nio.charset.Charset;
16
17 import org.apache.http.entity.mime.content.ContentBody;
18 import org.apache.http.entity.mime.content.FileBody;
19 import org.apache.http.entity.mime.content.StringBody;
20
21 /**
22  * format an alignment for input to rest service.
23  * @author JimP
24  *
25  */
26 public class Alignment extends InputType {
27   public Alignment()
28   {
29     super(new Class[] { AlignmentI.class} );
30   }
31
32   String format="FASTA";
33   molType type;
34   boolean jvsuffix=false;
35   /**
36    * input data as a file upload rather than inline content
37    */
38   public boolean writeAsFile;
39   @Override
40   public ContentBody formatForInput(RestJob rj) throws UnsupportedEncodingException, NoValidInputDataException
41   {
42     AlignmentI alignment = rj.getAlignmentForInput(token,type);
43     if (writeAsFile)
44     {
45     try {
46       File fa = File.createTempFile("jvmime", ".fa");
47       PrintWriter pw = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(fa)), "UTF-8"));
48       pw.append(new jalview.io.FormatAdapter().formatSequences(format, alignment, jvsuffix));
49       pw.close();
50       return new FileBody(fa, "text/plain");
51     } catch (Exception ex)
52     {
53       throw new NoValidInputDataException("Couldn't write out alignment to file.",ex);
54     }
55     } else {
56     StringBody sb = new StringBody(new jalview.io.FormatAdapter().formatSequences(format, alignment, jvsuffix)); // , "text/plain", Charset.forName("UTF-8"));
57     // sb.getContentTypeParameters().put("filename", "alignment.fa");
58     return sb; 
59     }
60   }
61 }