Changeset 6198


Ignore:
Timestamp:
Apr 7, 2021, 7:52:23 AM (2 years ago)
Author:
Nicklas Nordborg
Message:

References #1295: Registration of specimen handled by external lab

Re-factoring to prepare for better error handling.

Location:
extensions/net.sf.basedb.reggie/trunk
Files:
5 edited

Legend:

Unmodified
Added
Removed
  • extensions/net.sf.basedb.reggie/trunk/resources/batch/import-external-specimen.js

    r6178 r6198  
    1212    Events.addEventHandler('step-1', 'wizard-validate', specimen.validateStep1);
    1313   
    14         // Step 2
     14    // Step 2
    1515    Events.addEventHandler('step-2', 'wizard-initialize', specimen.initializeStep2);
    1616    Events.addEventHandler('step-2', 'wizard-validate', specimen.validateStep2);
     
    5050    html += '<th class="dottedleft">Item</th>';
    5151    html += '<th class="dottedleft">JSON file</th>'
    52     html += '<th>Valid</th>';
    5352    html += '<th>FASTQ files</th>';
    54     html += '<th>Import</th>';
     53    html += '<th class="icon"></th>'
     54    html += '<th class="dottedleft"></th>';
     55    html += '<th class="dottedleft">Import</th>';
    5556    html += '</tr>';
    5657    html += '</thead>';
     
    6061    {
    6162      var item = importItems[itemNo];
    62       var canImport = item.name && item.jsonFile;
     63      var jsonFile = item.jsonFile;
     64      var canImport = item.name && jsonFile && !jsonFile.errors;
     65     
     66      var icon = null;
     67      if (jsonFile)
     68      {
     69        icon = 'ok.png';
     70        if (jsonFile.warnings) icon = 'warning.png';
     71        if (jsonFile.errors) icon = 'error.png';
     72      }
    6373
    6474      html += '<tr class="highlight ' + (itemNo % 4 < 2 ? 'evenrow' : 'oddrow') + '">';
    65       html += '<td>'+(Strings.encodeTags(item.itemType) || '<i>unknown</i>')+'</td>';
    66       html += '<td>'+(Strings.encodeTags(item.name) || '<i>unkown</i>')+'</td>';
    67       html += '<td>'+(Strings.encodeTags(item.jsonFile) || '<i>no file</i>')+'</td>';
    68       html += '<td></td>';
    69       html += '<td></td>';
    70       html += '<td>';
     75      html += '<td>'+(Strings.encodeTags(item.itemType) || '-')+'</td>';
     76      html += '<td class="dottedleft">'+(Strings.encodeTags(item.name) || '-')+'</td>';
     77      html += '<td class="dottedleft">'+(jsonFile ? Strings.encodeTags(jsonFile.name) : '-')+'</td>';
     78      html += '<td class="fastq">';
     79      if (jsonFile && jsonFile.fastq)
     80      {
     81        for (var fqNo = 0; fqNo < jsonFile.fastq.length; fqNo++)
     82        {
     83          var fq = jsonFile.fastq[fqNo];
     84          html += Strings.encodeTags(fq.name) + '; ' + Numbers.formatBytes(fq.size)+'; '+Reggie.reformatDate(fq.lastModified)+'<br>';
     85        }
     86      }
     87      html += '</td>';
     88      html += '<td class="icon">';
     89      if (icon) html+= '<img src="../images/'+icon+'">';
     90      html += '</td>';
     91      html += '<td class="valid dottedleft">';
     92      if (jsonFile && jsonFile.errors)
     93      {
     94        html += '<div class="messagecontainer error">'+Strings.encodeTags(jsonFile.errors.join('\n'))+'</div>';
     95      }
     96      else if (jsonFile && jsonFile.warnings)
     97      {
     98        html += '<div">'+Strings.encodeTags(jsonFile.warnings.join('<br>'))+'</div>';
     99      }
     100      html += '</td>';
     101      html += '<td class="dottedleft">';
    71102      html += '<input type="checkbox" id="import.'+itemNo+'" '+(canImport?'checked':'disabled')+'>';
    72103      html += '</td>';
     
    178209      if (frm['import.'+itemNo].checked)
    179210      {
    180         items[items.length] = importItems[itemNo];
     211        var item = importItems[itemNo]
     212        var tmp = {};
     213        tmp.id = item.id;
     214        tmp.jsonFile = item.jsonFile.name;
     215        items[items.length] = tmp;
    181216      }
    182217    }
  • extensions/net.sf.basedb.reggie/trunk/resources/batch/import-external-specimen.jsp

    r6178 r6198  
    5757#importItemsTable tbody td
    5858{
    59   padding-top: 1px;
    60   padding-bottom: 1px;
     59  padding: 1px 2px;
     60}
     61
     62#importItemsTable td.icon
     63{
     64  width: 20px;
     65  min-width: 20px;
     66}
     67
     68#importItemsTable td.valid
     69{
     70  text-align: left;
    6171}
    6272
  • extensions/net.sf.basedb.reggie/trunk/src/net/sf/basedb/reggie/counter/CounterService.java

    r6187 r6198  
    4949import net.sf.basedb.reggie.dao.Subtype;
    5050import net.sf.basedb.reggie.pdf.GeneReportWorker;
     51import net.sf.basedb.reggie.plugins.FutureSpecimenImporter;
     52import net.sf.basedb.reggie.plugins.FutureSpecimenImporter.JsonFile;
    5153import net.sf.basedb.reggie.query.AnyToAnyRestriction;
    5254import net.sf.basedb.reggie.servlet.AdminServlet;
    5355import net.sf.basedb.reggie.servlet.AdminServlet.RemoteFolder;
    54 import net.sf.basedb.reggie.servlet.FutureSpecimenServlet;
    5556import net.sf.basedb.util.Values;
    5657import net.sf.basedb.util.extensions.Extension;
     
    14701471  private void countImportFiles(DbControl dc, JSONObject json)
    14711472  {
    1472     List<String> importFiles = new ArrayList<>();
     1473    List<JsonFile> importFiles = new ArrayList<>();
    14731474    try
    14741475    {
    1475       importFiles = FutureSpecimenServlet.getJSONFiles(dc);
     1476      importFiles = FutureSpecimenImporter.getJSONFiles(dc, Fileserver.IMPORT_ARCHIVE.load(dc), false);
    14761477    }
    14771478    catch (RuntimeException ex)
  • extensions/net.sf.basedb.reggie/trunk/src/net/sf/basedb/reggie/plugins/FutureSpecimenImporter.java

    r6197 r6198  
    22
    33
     4import java.io.InputStream;
     5import java.util.ArrayList;
     6import java.util.Date;
    47import java.util.HashMap;
    58import java.util.List;
     
    1013import org.json.simple.JSONArray;
    1114import org.json.simple.JSONObject;
     15import org.json.simple.parser.JSONParser;
    1216
    1317import net.sf.basedb.core.BioMaterialEvent;
     
    1721import net.sf.basedb.core.DerivedBioAssay;
    1822import net.sf.basedb.core.Extract;
     23import net.sf.basedb.core.FileServer;
    1924import net.sf.basedb.core.ItemQuery;
    2025import net.sf.basedb.core.PhysicalBioAssay;
     
    2429import net.sf.basedb.core.query.Hql;
    2530import net.sf.basedb.core.query.Restrictions;
     31import net.sf.basedb.opengrid.CmdResult;
     32import net.sf.basedb.opengrid.OpenGrid;
     33import net.sf.basedb.opengrid.RemoteHost;
     34import net.sf.basedb.opengrid.RemoteSession;
     35import net.sf.basedb.opengrid.config.ConnectionInfo;
     36import net.sf.basedb.opengrid.filetransfer.ByteArrayDownloadTarget;
     37import net.sf.basedb.opengrid.filetransfer.FileMetaData;
    2638import net.sf.basedb.reggie.Reggie;
    2739import net.sf.basedb.reggie.dao.Annotationtype;
     
    3749import net.sf.basedb.reggie.dao.SpecimenTube;
    3850import net.sf.basedb.reggie.dao.Subtype;
     51import net.sf.basedb.reggie.grid.ScriptUtil;
    3952import net.sf.basedb.util.Coordinate;
     53import net.sf.basedb.util.FileUtil;
    4054
    4155/**
     
    5569{
    5670 
    57   private JSONArray jsonMessages;
     71  public static List<JsonFile> getJSONFiles(DbControl dc, FileServer fs, boolean downloadAndParse)
     72  {
     73    List<JsonFile> importFiles = new ArrayList<>();
     74
     75    // Get the import archive and connect to it via SSH
     76    RemoteHost host = new RemoteHost(new ConnectionInfo(fs));
     77    String rootPath = ScriptUtil.checkValidPath(fs.getRootPath(), true, false);
     78    RemoteSession session = null;
     79    try
     80    {
     81
     82      session = host.connect(5);
     83      // The 'find' command will find all *.json files. Output:
     84      // 0: filename without path
     85     
     86      String findCmd = "find " + rootPath + " -maxdepth 1 -type f -name *.json -printf '%f\\n'";
     87      CmdResult<String> find = session.executeCmd(findCmd, 60);
     88      find.throwExceptionIfNonZeroExitStatus();
     89     
     90      String[] lines = find.getStdout().split("\\n");
     91     
     92      for (String line : lines)
     93      {
     94        JsonFile file = new JsonFile(line);
     95       
     96        if (downloadAndParse)
     97        {
     98          file.downloadAndParse(session, rootPath);
     99        }
     100       
     101        importFiles.add(file);
     102      }
     103    }
     104    finally
     105    {
     106      OpenGrid.close(session);
     107    }
     108   
     109    return importFiles;
     110  }
     111
     112  private JsonFile currentFile;
     113 
    58114  private Map<String, Extract> poolCache;
    59115  private Map<String, PhysicalBioAssay> flowCellCache;
     
    70126    this.libPlateCache = new HashMap<>();
    71127  }
    72  
    73   public void setMessages(JSONArray jsonMessages)
    74   {
    75     this.jsonMessages = jsonMessages;
     128
     129
     130  void addWarningMessage(String msg)
     131  {
     132    this.currentFile.addWarningMessage("[Warning] " + msg);
     133  }
     134 
     135  void addErrorMessage(String msg)
     136  {
     137    this.currentFile.addErrorMessage("[Error] " + msg);
     138  }
     139
     140  void addDebugMessage(String msg)
     141  {
     142    this.currentFile.addDebugMessage("[Debug] "+msg);
    76143  }
    77144 
     
    79146    Import to a Specimen or FutureSpecimen item.
    80147  */
    81   public void doImport(DbControl dc, Sample sample, JSONObject json)
    82   {
     148  public void doImport(DbControl dc, Sample sample, JsonFile jsonFile)
     149  {
     150    this.currentFile = jsonFile;
     151   
     152    JSONObject json = jsonFile.getJSON();
    83153   
    84154    JSONObject jsonSpecimen = (JSONObject)json.get("specimen");
     
    132202      specimen.setItemSubtype(Subtype.SPECIMEN.get(dc));
    133203   
    134       jsonMessages.add("FutureSpecimen changed to Specimen: "+specimen.getName());
     204      addDebugMessage("FutureSpecimen changed to Specimen: "+specimen.getName());
    135205    }
    136206    else
    137207    {
    138       jsonMessages.add("Importing to existing Specimen: "+specimen.getName());
     208      addDebugMessage("Importing to existing Specimen: "+specimen.getName());
    139209    }
    140210   
     
    152222    dc.saveItem(lysate);
    153223   
    154     jsonMessages.add("Created: "+ lysate.getName());
     224    addDebugMessage("Created: "+ lysate.getName());
    155225    return Lysate.get(lysate);
    156226  }
     
    166236    dc.saveItem(rna);
    167237   
    168     jsonMessages.add("Created: "+ rna.getName());
     238    addDebugMessage("Created: "+ rna.getName());
    169239    return Rna.get(rna);
    170240  }
     
    199269        {
    200270          lib.setBioWell(well);
    201           jsonMessages.add("Using well: " + pos);
     271          addDebugMessage("Using well: " + pos);
    202272        }
    203273        else
    204274        {
    205           jsonMessages.add("Well is not empty: " + pos);
     275          addErrorMessage("Well is not empty: " + pos);
    206276          // ERROR
    207277        }
     
    209279      else
    210280      {
    211         jsonMessages.add("Invalid well: " + pos);
     281        addErrorMessage("Invalid well: " + pos);
    212282        // ERROR
    213283      }
    214284    }
    215285   
    216     jsonMessages.add("Created: "+ lib.getName());
     286    addDebugMessage("Created: "+ lib.getName());
    217287    return Library.get(lib);
    218288  }
     
    230300      dc.saveItem(plate);
    231301      libPlateCache.put(plateId, plate);
    232       jsonMessages.add("Created: "+ plate.getName() + "[ref="+plateId+"]");
     302      addDebugMessage("Created: "+ plate.getName() + "[ref="+plateId+"]");
    233303    }
    234304    else
    235305    {
    236       jsonMessages.add("Found: "+plate.getName());
     306      addDebugMessage("Found: "+plate.getName());
    237307    }
    238308   
     
    278348      poolCache.put(poolId, pool);
    279349     
    280       jsonMessages.add("Created: "+ pool.getName() + "[ref="+poolId+"]");
     350      addDebugMessage("Created: "+ pool.getName() + "[ref="+poolId+"]");
    281351    }
    282352    else
    283353    {
    284       jsonMessages.add("Found: "+pool.getName());
     354      addDebugMessage("Found: "+pool.getName());
    285355    }
    286356   
     
    339409        createEvent.addSource(poolA).setPosition(laneNo);
    340410        dc.saveItem(poolA);
    341         jsonMessages.add("Created: "+ poolA.getName());
    342       }
    343       jsonMessages.add("Created: "+ flowCell.getName());
     411        addDebugMessage("Created: "+ poolA.getName());
     412      }
     413      addDebugMessage("Created: "+ flowCell.getName());
    344414     
    345415    }
    346416    else
    347417    {
    348       jsonMessages.add("Found: "+flowCell.getName());
     418      addDebugMessage("Found: "+flowCell.getName());
    349419      // TODO -- It should be linked with POOL already -- verify this??
    350420    }
     
    361431     
    362432      seqRunCache.put(flowCellId, seqRun);
    363       jsonMessages.add("Created: "+ seqRun.getName());
     433      addDebugMessage("Created: "+ seqRun.getName());
    364434    }
    365435    else
    366436    {
    367       jsonMessages.add("Found: "+seqRun.getName());
     437      addDebugMessage("Found: "+seqRun.getName());
    368438      // verify settings ??
    369439    }
     
    431501      dc.saveItem(demux);
    432502      demuxCache.put(seqRun.getName(), demux);
    433       jsonMessages.add("Created: "+ demux.getName());
     503      addDebugMessage("Created: "+ demux.getName());
    434504    }
    435505    else
    436506    {
    437       jsonMessages.add("Found: "+demux.getName());
     507      addDebugMessage("Found: "+demux.getName());
    438508    }
    439509   
     
    444514    merged.setExtract(lib.getItem());
    445515    dc.saveItem(merged);
    446     jsonMessages.add("Created: "+ merged.getName());
     516    addDebugMessage("Created: "+ merged.getName());
    447517   
    448518    return MergedSequences.get(merged);
     
    459529  }
    460530
     531 
     532  public static class JsonFile
     533  {
     534
     535    private final String name;
     536    private final List<String> errorMessages;
     537    private final List<String> warningMessages;
     538    private final List<String> debugMessages;
     539
     540    private JSONObject json;
     541    private FastqFile[] fastq;
     542
     543    public JsonFile(String name)
     544    {
     545      this.name = name;
     546      this.errorMessages = new ArrayList<String>();
     547      this.warningMessages = new ArrayList<String>();
     548      this.debugMessages = new ArrayList<String>();
     549    }
     550   
     551    public String getName()
     552    {
     553      return name;
     554    }
     555   
     556    public boolean hasWarning()
     557    {
     558      return warningMessages.size() > 0;
     559    }
     560    public List<String> getWarningMessages()
     561    {
     562      return warningMessages;
     563    }
     564    public void addWarningMessage(String msg)
     565    {
     566      this.warningMessages.add(msg);
     567    }
     568   
     569    public boolean hasError()
     570    {
     571      return errorMessages.size() > 0;
     572    }
     573    public List<String> getErrorMessages()
     574    {
     575      return errorMessages;
     576    }
     577    public void addErrorMessage(String msg)
     578    {
     579      this.errorMessages.add(msg);
     580    }
     581
     582    public boolean hasDebug()
     583    {
     584      return debugMessages.size() > 0;
     585    }
     586    public List<String> getDebugMessages()
     587    {
     588      return debugMessages;
     589    }
     590    public void addDebugMessage(String msg)
     591    {
     592      this.debugMessages.add(msg);
     593    }
     594   
     595    public JSONObject asJSONObject()
     596    {
     597      JSONObject j = new JSONObject();
     598      j.put("name", name);
     599     
     600      if (fastq != null)
     601      {
     602        JSONArray jsonFq = new JSONArray();
     603        j.put("fastq", jsonFq);
     604        for (FastqFile fq : fastq)
     605        {
     606          jsonFq.add(fq.asJSONObject());
     607        }
     608      }
     609     
     610      if (hasError())
     611      {
     612        JSONArray jsonErrors = new JSONArray();
     613        jsonErrors.addAll(errorMessages);
     614        j.put("errors", jsonErrors);
     615      }
     616      if (hasWarning())
     617      {
     618        JSONArray jsonWarnings = new JSONArray();
     619        jsonWarnings.addAll(warningMessages);
     620        j.put("warnings", jsonWarnings);
     621      }
     622     
     623      return j;
     624    }
     625   
     626    public JSONObject getJSON()
     627    {
     628      return json;
     629    }
     630   
     631    public void downloadAndParse(RemoteSession session, String rootDir)
     632    {
     633      if (!rootDir.endsWith("/")) rootDir += "/";
     634      String path = rootDir + name;
     635
     636      ByteArrayDownloadTarget download = new ByteArrayDownloadTarget(path);
     637      try
     638      {
     639        session.downloadFile(path, download);
     640      }
     641      catch (Exception ex)
     642      {
     643        addErrorMessage("Could not download '"+ name + "': " + ex.getMessage());
     644        return;
     645      }
     646      try
     647      {
     648        String data = download.getString("UTF-8");
     649        if (data == null || data.length() == 0)
     650        {
     651          addErrorMessage("Could not parse '"+name+"': File is empty");
     652          return;
     653        }
     654        json = (JSONObject)new JSONParser().parse(data);
     655       
     656        JSONObject jsonFastq = (JSONObject)json.get("fastq");
     657        if (jsonFastq == null)
     658        {
     659          addErrorMessage("No 'fastq' section in file '"+name+"'");
     660          return;
     661        }
     662       
     663        String r1 = (String)jsonFastq.get("R1");
     664        String r2 = (String)jsonFastq.get("R2");
     665        if (r1 == null) addErrorMessage("No 'fastq.R1' entry in file '"+name+"'");
     666        if (r2 == null) addErrorMessage("No 'fastq.R2' entry in file '"+name+"'");
     667        if (hasError()) return;
     668       
     669        fastq = new FastqFile[2];
     670        fastq[0] = getFastqFile(session, rootDir, r1);
     671        fastq[1] = getFastqFile(session, rootDir, r2);
     672       
     673      }
     674      catch (Exception ex)
     675      {
     676        addErrorMessage("Could not parse '"+name+"': " + ex.getMessage());
     677        return;
     678      }
     679    }
     680   
     681   
     682    FastqFile getFastqFile(RemoteSession session, String rootDir, String name)
     683    {
     684      FastqFile fq = new FastqFile(name);
     685      InputStream tmp = null;
     686      try
     687      {
     688        FileMetaData info = new FileMetaData();
     689        tmp = session.readFile(rootDir+name, info);
     690        fq.setSize(info.getSize());
     691        fq.setLastModified(info.getLastModifiedTime());
     692      }
     693      catch (Exception ex)
     694      {
     695        addErrorMessage("Could not stat FASTQ file '"+name+"': " + ex.getMessage());
     696      }
     697      finally
     698      {
     699        FileUtil.close(tmp);
     700      }
     701      return fq;
     702    }
     703  }
     704 
     705  public static class FastqFile
     706  {
     707   
     708    private final String name;
     709    private long size;
     710    private long lastModified;
     711   
     712    public FastqFile(String name)
     713    {
     714      this.name = name;
     715    }
     716   
     717    public String getName()
     718    {
     719      return name;
     720    }
     721
     722    public long getSize()
     723    {
     724      return size;
     725    }
     726   
     727    public long getLastModified()
     728    {
     729      return lastModified;
     730    }
     731   
     732    void setSize(long size)
     733    {
     734      this.size = size;
     735    }
     736   
     737    void setLastModified(long lastModified)
     738    {
     739      this.lastModified = lastModified;
     740    }
     741   
     742    public JSONObject asJSONObject()
     743    {
     744      JSONObject j = new JSONObject();
     745      j.put("name", name);
     746      j.put("size", size);
     747      j.put("lastModified", Reggie.CONVERTER_DATETIME_TO_STRING_WITH_SEPARATOR.convert(new Date(lastModified)));
     748      return j;
     749    }
     750
     751  }
    461752}
  • extensions/net.sf.basedb.reggie/trunk/src/net/sf/basedb/reggie/servlet/FutureSpecimenServlet.java

    r6193 r6198  
    22
    33import java.io.IOException;
    4 import java.util.ArrayList;
    54import java.util.List;
    65
     
    1211import org.json.simple.JSONArray;
    1312import org.json.simple.JSONObject;
    14 import org.json.simple.parser.JSONParser;
    15 import org.json.simple.parser.ParseException;
    1613
    1714import net.sf.basedb.core.DbControl;
     
    2118import net.sf.basedb.core.Sample;
    2219import net.sf.basedb.core.SessionControl;
    23 import net.sf.basedb.opengrid.CmdResult;
    2420import net.sf.basedb.opengrid.OpenGrid;
    2521import net.sf.basedb.opengrid.OpenGridCluster;
     
    2723import net.sf.basedb.opengrid.RemoteSession;
    2824import net.sf.basedb.opengrid.config.ConnectionInfo;
    29 import net.sf.basedb.opengrid.filetransfer.ByteArrayDownloadTarget;
    3025import net.sf.basedb.opengrid.service.OpenGridService;
    3126import net.sf.basedb.reggie.JsonUtil;
     
    3934import net.sf.basedb.reggie.grid.ScriptUtil;
    4035import net.sf.basedb.reggie.plugins.FutureSpecimenImporter;
     36import net.sf.basedb.reggie.plugins.FutureSpecimenImporter.JsonFile;
    4137import net.sf.basedb.util.error.ThrowableUtil;
    4238
     
    7167        dc = sc.newDbControl();
    7268       
    73         List<String> files = getJSONFiles(dc);
     69        List<JsonFile> files = FutureSpecimenImporter.getJSONFiles(dc, Fileserver.IMPORT_ARCHIVE.load(dc), true);
    7470       
    7571        ItemQuery<Sample> query = Sample.getQuery();
     
    8076        {
    8177          fs.setAnnotation("itemType", "FutureSpecimen");
    82           int index = files.indexOf(fs.getName().substring(0,  7)+".json");
    83           if (index >= 0)
     78          String filenameToMatch = fs.getName().substring(0,  7)+".json";
     79          for (int index = 0; index < files.size(); index++)
    8480          {
    85             fs.setAnnotation("jsonFile", files.remove(index));
     81            JsonFile file = files.get(index);
     82            if (file.getName().equals(filenameToMatch))
     83            {
     84              fs.setAnnotation("jsonFile", file.asJSONObject());
     85              files.remove(index);
     86              break;
     87            }
    8688          }
     89         
    8790          jsonImportItems.add(fs.asJSONObject());
    8891        }
    8992       
    9093       
    91         for (String importFile : files)
     94        for (JsonFile importFile : files)
    9295        {
    9396          JSONObject jsonFile = new JSONObject();
    94           jsonFile.put("jsonFile", importFile);
     97          jsonFile.put("jsonFile", importFile.asJSONObject());
    9598         
    96           SpecimenTube specimen = SpecimenTube.findByTubeName(dc, importFile.replace(".json", ""));
     99          SpecimenTube specimen = SpecimenTube.findByTubeName(dc, importFile.getName().replace(".json", ""));
    97100          if (specimen != null)
    98101          {
     
    163166        try
    164167        {
    165           session = connect(fs);
     168          RemoteHost host = new RemoteHost(new ConnectionInfo(fs));
     169          session = host.connect(5);
    166170          FutureSpecimenImporter importer = new FutureSpecimenImporter();
    167           importer.setMessages(jsonMessages);
    168171         
    169172          for (int itemNo = 0; itemNo < jsonItems.size(); itemNo++)
     
    171174            JSONObject jsonItem = (JSONObject)jsonItems.get(itemNo);
    172175            Number itemId = (Number)jsonItem.get("id");
    173             String jsonFile = (String)jsonItem.get("jsonFile");
     176            JsonFile jsonFile = new JsonFile((String)jsonItem.get("jsonFile"));
     177            jsonFile.downloadAndParse(session, rootPath);
    174178           
    175179            Sample specimen = Sample.getById(dc, itemId.intValue());
    176             JSONObject jsonIn = getJSONFile(session, rootPath+"/"+jsonFile);
    177            
    178             importer.doImport(dc, specimen, jsonIn);
    179            
    180             jsonMessages.add("Imported " + jsonItem.get("name"));
     180           
     181            if (!jsonFile.hasError())
     182            {
     183              importer.doImport(dc, specimen, jsonFile);
     184            }
     185           
     186            if (jsonFile.hasError())
     187            {
     188              jsonMessages.add("[Error] Import failed. See below for more information.");
     189              jsonMessages.addAll(jsonFile.getErrorMessages());
     190            }
     191            else
     192            {
     193              jsonMessages.add("Imported " + specimen.getName());
     194            }
     195           
     196            jsonMessages.addAll(jsonFile.getWarningMessages());
     197            jsonMessages.addAll(jsonFile.getDebugMessages());
    181198          }
    182199
     
    206223      if (dc != null) dc.close();
    207224      json.writeJSONString(resp.getWriter());
    208     }
    209    
     225    }   
    210226  }
    211227 
    212  
    213   private RemoteSession connect(FileServer fs)
    214   {
    215     RemoteHost host = new RemoteHost(new ConnectionInfo(fs));
    216     return host.connect(5);
    217   }
    218  
    219   private JSONObject getJSONFile(RemoteSession session, String path)
    220     throws ParseException
    221   {
    222     ByteArrayDownloadTarget download = new ByteArrayDownloadTarget(path);
    223     session.downloadFile(path, download);
    224     return (JSONObject)new JSONParser().parse(download.getString("UTF-8"));
    225   }
    226  
    227   public static List<String> getJSONFiles(DbControl dc)
    228   {
    229     List<String> importFiles = new ArrayList<>();
    230 
    231     // Get the import archive and connect to it via SSH
    232     FileServer fs = Fileserver.IMPORT_ARCHIVE.load(dc);
    233     RemoteHost host = new RemoteHost(new ConnectionInfo(fs));
    234     String rootPath = ScriptUtil.checkValidPath(fs.getRootPath(), true, false);
    235     RemoteSession session = null;
    236     try
    237     {
    238 
    239       session = host.connect(5);
    240       // The 'find' command will find all *.json files. Output:
    241       // 0: filename without path
    242      
    243       String findCmd = "find " + rootPath + " -maxdepth 1 -type f -name *.json -printf '%f\\n'";
    244       CmdResult<String> find = session.executeCmd(findCmd, 60);
    245       find.throwExceptionIfNonZeroExitStatus();
    246      
    247       String[] lines = find.getStdout().split("\\n");
    248      
    249       for (String line : lines)
    250       {
    251         importFiles.add(line);
    252       }
    253     }
    254     finally
    255     {
    256       OpenGrid.close(session);
    257     }
    258    
    259     return importFiles;
    260   }
    261 
    262 
    263228}
Note: See TracChangeset for help on using the changeset viewer.