Ejemplo n.º 1
0
  void ResidueDB::readResiduesFromFile_(const String& file_name)
  {
    String file = File::find(file_name);

    Param param;
    ParamXMLFile paramFile;
    paramFile.load(file, param);

    if (!param.begin().getName().hasPrefix("Residues"))
    {
      throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "", "");
    }

    try
    {
      vector<String> split;
      param.begin().getName().split(':', split);
      String prefix = split[0] + split[1];
      Residue* res_ptr = nullptr;

      Map<String, String> values;

      for (Param::ParamIterator it = param.begin(); it != param.end(); ++it)
      {
        it.getName().split(':', split);
        if (prefix != split[0] + split[1])
        {
          // add residue
          res_ptr = parseResidue_(values);
          values.clear();
          residues_.insert(res_ptr);
          const_residues_.insert(res_ptr);
          prefix = split[0] + split[1];
        }

        String value = it->value;
        String key = it.getName();
        values[key] = value;

      }

      // add last residue
      res_ptr = parseResidue_(values);
      residues_.insert(res_ptr);
      const_residues_.insert(res_ptr);
    }
    catch (Exception::BaseException& e)
    {
      throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, e.what(), "");
    }
  }
Ejemplo n.º 2
0
  void EnzymesDB::readEnzymesFromFile_(const String& file_name)
  {
    String file = File::find(file_name);

    Param param;
    ParamXMLFile paramFile;
    paramFile.load(file, param);

    if (!param.begin().getName().hasPrefix("Enzymes"))
    {
      throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "", "");
    }

    try
    {
      vector<String> split;
      param.begin().getName().split(':', split);
      String prefix = split[0] + split[1];
 
      Map<String, String> values;

      for (Param::ParamIterator it = param.begin(); it != param.end(); ++it)
      {
        it.getName().split(':', split);
        if (prefix != split[0] + split[1])
        {
          // add enzyme
          addEnzyme_(parseEnzyme_(values));
          prefix = split[0] + split[1];
          values.clear();
        }
        values[it.getName()] = it->value;
      }

      // add last enzyme
      addEnzyme_(parseEnzyme_(values));
    }
    catch (Exception::BaseException& e)
    {
      throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, e.what(), "");
    }
  }
Ejemplo n.º 3
0
  StringList INIUpdater::getToolNamesFromINI(const Param & ini) const
  {
    StringList tool_names;

    for (Param::ParamIterator it = ini.begin(); it != ini.end(); ++it)
    {
      if (it.getName().toQString().count(':') == 1 && it.getName().hasSuffix(":version"))
      {
        tool_names.push_back(it.getName().prefix(':'));
      }
    }
    return tool_names;
  }
Ejemplo n.º 4
0
  void ElementDB::readFromFile_(const String& file_name)
  {
    String file = File::find(file_name);

    // load elements into param object
    Param param;
    ParamXMLFile paramFile;
    paramFile.load(file, param);

    UInt an(0);
    String name, symbol;

    // determine prefix
    vector<String> split;
    param.begin().getName().split(':', split);
    String prefix("");
    for (Size i = 0; i < split.size() - 1; ++i)
    {
      prefix += split[i] + ":";
    }
    //cout << "first element prefix=" << prefix << endl;

    Map<UInt, double> Z_to_abundancy;
    Map<UInt, double> Z_to_mass;

    for (Param::ParamIterator it = param.begin(); it != param.end(); ++it)
    {
      // new element started?
      if (!it.getName().hasPrefix(prefix))
      {
        // update prefix
        it.getName().split(':', split);
        prefix = "";
        for (Size i = 0; i < split.size() - 1; ++i)
        {
          prefix += split[i] + ":";
        }
        // cout << "new element prefix=" << prefix << endl;

        // Parsing of previous element is finished. Now store data in Element object
        IsotopeDistribution isotopes = parseIsotopeDistribution_(Z_to_abundancy);
        double avg_weight = calculateAvgWeight_(Z_to_abundancy, Z_to_mass);
        double mono_weight = calculateMonoWeight_(Z_to_mass);

        /*
        // print information about elements
        cout << "Name: " << name << " AtomicNumber: " << an << " Symbol: " << symbol << " AvgWeight: " << avg_weight
             << " MonoWeight: " << mono_weight << " NIsotopes: " << isotopes.size() << endl;

        */
        Element* e = new Element(name, symbol, an, avg_weight, mono_weight, isotopes);
        names_[name] = e;
        symbols_[symbol] = e;
        atomic_numbers_[an] = e;

        // add all the individual isotopes as separat elements
        for (IsotopeDistribution::ConstIterator iit = isotopes.begin(); iit != isotopes.end(); ++iit)
        {
          String iso_name = "(" + String(iit->first) + ")" + name;
          String iso_symbol = "(" + String(iit->first) + ")" + symbol;

          // set avg and mono to same value for isotopes (old hack...)
          DoubleReal iso_avg_weight = Z_to_mass[(UInt) iit->first];
          DoubleReal iso_mono_weight = iso_avg_weight;
          IsotopeDistribution iso_isotopes;
          vector<pair<Size, double> > iso_container;
          iso_container.push_back(make_pair(iit->first, 1.0));
          iso_isotopes.set(iso_container);

          /*
          // print name, symbal and atomic mass of the current isotope
          cout << "Isotope Name: " << iso_name << " Symbol: " << iso_symbol << " AtomicMass: " << iso_mono_weight << endl;
          */

          Element* iso_e = new Element(iso_name, iso_symbol, an, iso_avg_weight, iso_mono_weight, iso_isotopes);
          names_[iso_name] = iso_e;
          names_[iso_symbol] = iso_e;
        }

        Z_to_abundancy.clear();
        Z_to_mass.clear();
      }

      // top level: read the contents of the element section
      it.getName().split(':', split);
      String key = split[2];
      String value = it->value;
      value.trim();

      // cout << "Key=" << key << endl;

      if (key == "AtomicNumber")
      {
        an = (UInt)value.toInt();
      }
      else
      {
        if (key == "Isotopes")
        {
          UInt Z = UInt(split[3].toInt());
          String item = split[4];
          if (item == "RelativeAbundance")
          {
            Z_to_abundancy[Z] = double(value.toDouble() / 100.0);
          }
          else if (item == "AtomicMass")
          {
            Z_to_mass[Z] = double(value.toDouble());
          }
          else
          {
            cerr << "read unknown item in Isotopes: " << item << endl;
          }
        }
        else
        {
          if (key == "Name")
          {
            name = value;
          }
          else
          {
            if (key == "Symbol")
            {
              symbol = value;
            }
            else
            {
              cerr << "read unknown tag: " << key << endl;
            }
          }
        }
      }
    }

    // build last element
    double avg_weight(0), mono_weight(0);
    IsotopeDistribution isotopes = parseIsotopeDistribution_(Z_to_abundancy);
    Element* e = new Element(name, symbol, an, avg_weight, mono_weight, isotopes);
    names_[name] = e;
    symbols_[symbol] = e;
    atomic_numbers_[an] = e;
  }
  ExitCodes main_(int, const char **)
  {
    // find the config for the tool:
    String type = getStringOption_("type");


    Param tool_param = this->getParam_();

    // check required parameters (TOPPBase does not do this as we did not use registerInputFile_(...) etc)
    Param p = tool_param.copy("ETool:", true);
    for (Param::ParamIterator it = p.begin(); it != p.end(); ++it)
    {
      if ((it->tags).count("required") > 0)
      {
        if (it->value.toString().trim().empty())    // any required parameter should have a value
        {
          LOG_ERROR << "The INI-parameter '" + it->name + "' is required, but was not given! Aborting ...";
          return wrapExit(CANNOT_WRITE_OUTPUT_FILE);
        }
        else if ((it->tags).count("input file") > 0) // any required input file should exist
        {
          if (!File::exists(it->value))
          {
            LOG_ERROR << "Input file '" + String(it->value) + "' does not exist! Aborting ...";
            return wrapExit(INPUT_FILE_NOT_FOUND);
          }
        }
      }
    }

    Internal::ToolDescription gw = ToolHandler::getTOPPToolList(true)[toolName_()];
    for (Size i = 0; i < gw.types.size(); ++i)
    {
      if (type == gw.types[i])
      {
        tde_ = gw.external_details[i];
        if (tde_.working_directory.trim() == "") tde_.working_directory = ".";
        break;
      }
    }

    LOG_INFO << tde_.text_startup << "\n";

    String command_args = tde_.commandline;
    // check for double spaces and warn
    if (command_args.hasSubstring("  "))
    {
      LOG_WARN << "Commandline contains double spaces, which is not allowed. Condensing...\n";
      while (command_args.hasSubstring("  "))
      {
        command_args.substitute("  ", " ");
      }
      LOG_WARN << "result: " << command_args << std::endl;
    }

    writeDebug_("CommandLine from ttd (unprocessed): " + command_args, 1);

    // do "pre" moves (e.g. if the wrapped tool works on its data in-place (overwrites) it - we need to make a copy first
    // - we copy the file
    // - we set the value of the affected parameter to the copied tmp file, such that subsequent calls target the tmp file
    for (Size i = 0; i < tde_.tr_table.pre_moves.size(); ++i)
    {
      const Internal::FileMapping & fm = tde_.tr_table.pre_moves[i];
      // find target param:
      Param p = tool_param.copy("ETool:", true);
      String target = fm.target;
      if (!p.exists(target)) throw Exception::InvalidValue(__FILE__, __LINE__, __PRETTY_FUNCTION__, "Cannot find target parameter '" + target + "' being mapped from external tools output!", target);
      String tmp_location = fm.location;
      // fragment's placeholder evaluation:

      createFragment_(tmp_location, p);

      // check if target already exists:
      String target_file = (String)p.getValue(target);
      if (File::exists(tmp_location))
      {
        if (!File::remove(tmp_location))
        {
          LOG_ERROR << "While writing a tmp file: Cannot remove conflicting file '" + tmp_location + "'. Check permissions! Aborting ...";
          return wrapExit(CANNOT_WRITE_OUTPUT_FILE);
        }
      }
      // create the temp file  tmp_location target_file
      writeDebug_(String("Copying '") + target_file + "' to '" + tmp_location + "'", 1);
      bool move_ok = QFile::copy(target_file.toQString(), tmp_location.toQString());
      if (!move_ok)
      {
        LOG_ERROR << "Copying the target file '" + tmp_location + "' from '" + target_file + "' failed! Aborting ...";
        return wrapExit(CANNOT_WRITE_OUTPUT_FILE);
      }
      // set the input file's value to the temp file
      tool_param.setValue(String("ETool:") + target, tmp_location);
    }

    ///// construct the command line:
    // go through mappings (reverse because replacing %10 must come before %1):
    for (std::map<Int, String>::reverse_iterator it = tde_.tr_table.mapping.rbegin(); it != tde_.tr_table.mapping.rend(); ++it)
    {
      //std::cout << "mapping #" << it->first << "\n";
      String fragment = it->second;
      // fragment's placeholder evaluation:
      createFragment_(fragment, tool_param.copy("ETool:", true));

      // replace fragment in cl
      //std::cout << "replace : " << "%"+String(it->first) << " with '" << fragment << "\n";
      command_args.substitute("%" + String(it->first), fragment);
    }

    QProcess builder;
    builder.setProcessChannelMode(QProcess::MergedChannels);
    String call = tde_.path + " " + command_args;

    writeDebug_("call command: " + call, 1);

    builder.setWorkingDirectory(tde_.working_directory.toQString());
    builder.start(call.toQString());

    if (!builder.waitForFinished(-1) || builder.exitStatus() != 0 || builder.exitCode() != 0)
    {
      LOG_ERROR << ("External tool returned with non-zero exit code (" + String(builder.exitCode()) + "), exit status (" + String(builder.exitStatus()) + ") or timed out. Aborting ...\n");
      LOG_ERROR << ("External tool output:\n" + String(QString(builder.readAll())));
      return wrapExit(EXTERNAL_PROGRAM_ERROR);
    }

    LOG_INFO << ("External tool output:\n" + String(QString(builder.readAll())));


    // post processing (file moving via 'file' command)
    for (Size i = 0; i < tde_.tr_table.post_moves.size(); ++i)
    {
      const Internal::FileMapping & fm = tde_.tr_table.post_moves[i];
      // find target param:
      Param p = tool_param.copy("ETool:", true);
      String target = fm.target;
      if (!p.exists(target)) throw Exception::InvalidValue(__FILE__, __LINE__, __PRETTY_FUNCTION__, "Cannot find target parameter '" + target + "' being mapped from external tools output!", target);
      String source = fm.location;
      // fragment's placeholder evaluation:
      createFragment_(source, p);
      // check if target already exists:
      String target_file = (String)p.getValue(target);

      if (target_file.trim().empty())   // if target was not given, we skip the copying step (usually for optional parameters)
      {
        LOG_INFO << "Parameter '" + target + "' not given. Skipping forwarding of files.\n";
        continue;
      }
      if (File::exists(target_file))
      {
        if (!File::remove(target_file))
        {
          LOG_ERROR << "Cannot remove conflicting file '" + target_file + "'. Check permissions! Aborting ..." << std::endl;
          return wrapExit(CANNOT_WRITE_OUTPUT_FILE);
        }
      }
      // move to target
      writeDebug_(String("moving '") + source + "' to '" + target_file + "'", 1);
      bool move_ok = QFile::rename(source.toQString(), target_file.toQString());
      if (!move_ok)
      {
        LOG_ERROR << "Moving the target file '" + target_file + "' from '" + source + "' failed! Aborting ..." << std::endl;
        return wrapExit(CANNOT_WRITE_OUTPUT_FILE);
      }
    }

    LOG_INFO << tde_.text_finish << "\n";

    return wrapExit(EXECUTION_OK);
  }
  void createFragment_(String & fragment, const Param & param)
  {

    //std::cerr << "FRAGMENT: " << fragment << "\n\n";

    // e.g.:  -input %BASENAME[%%in].mzML

    // we have to make this little detour param -> vector<String>
    // to sort the param names by length, otherwise we have a
    // problem with parameter substitution
    // i.e., if A is a prefix of B and gets replaced first, the
    // suffix of B remains and will cause trouble!
    vector<String> param_names;
    param_names.reserve(param.size());
    for (Param::ParamIterator it = param.begin(); it != param.end(); ++it)
    {
      param_names.push_back(it->name);
    }
    // sort by length
    std::sort(param_names.begin(), param_names.end(), reverseComparator(StringSizeLess()));

    // iterate through all input params and replace with values:
    SignedSize allowed_percent(0); // filenames might contain '%', which are allowed to remain there (and even must remain)
    for (vector<String>::iterator it = param_names.begin(); it != param_names.end(); ++it)
    {
      if (!fragment.hasSubstring("%%" + *it)) continue;

      String s_new = paramToString_(param.getEntry(*it));
      allowed_percent += s_new.length() - String(s_new).substitute("%", "").length();
      //std::cerr << "IN: " << s_new << "(" << allowed_percent << "\n";
      fragment.substitute("%%" + *it, s_new);
    }
    if (fragment.hasSubstring("%%")) throw Exception::InvalidValue(__FILE__, __LINE__, __PRETTY_FUNCTION__, "Invalid '%%' found in '" + fragment + "' after replacing all parameters!", fragment);

    // %TMP replace:
    fragment.substitute("%TMP", File::getTempDirectory());

    // %RND replace:
    fragment.substitute("%RND", String(UniqueIdGenerator::getUniqueId()));

    // %WORKINGDIR replace:
    fragment.substitute("%WORKINGDIR", tde_.working_directory);

    // %DIR% replace
    {
      QRegExp rx("%DIR\\[(.*)\\]");
      rx.setMinimal(true);
      int pos = 0;
      QString t_tmp = fragment.toQString();
      //std::cout << "fragment is:" << fragment << std::endl;
      while ((pos = rx.indexIn(t_tmp, pos)) != -1)
      {
        String value = rx.cap(1);   // param name (hopefully)
        // replace in fragment:
        QFileInfo qfi(value.toQString());
        //std::cout << "match @ " << pos << " " << value << " --> " << qfi.canonicalPath() << "\n";
        t_tmp = t_tmp.replace(String("%DIR[" + value + "]").toQString(), qfi.canonicalPath());
      }
      fragment = String(t_tmp);
      //std::cout << "NEW fragment is:" << fragment << std::endl;
    }

    // %BASENAME% replace
    {
      QRegExp rx("%BASENAME\\[(.*)\\]");
      rx.setMinimal(true);
      int pos = 0, count = 0;
      QString t_tmp = fragment.toQString();
      while ((pos = rx.indexIn(t_tmp, pos)) != -1)
      {
        //std::cout << "match @ " << pos << "\n";
        String value = rx.cap(1);   // param name (hopefully)
        // replace in fragment:
        QFileInfo qfi(value.toQString());
        //std::cout << "match @ " << pos << " " << value << " --> " << qfi.completeBaseName() << "\n";
        t_tmp = t_tmp.replace(String("%BASENAME[" + value + "]").toQString(), qfi.completeBaseName());
        ++count;
      }
      // update expected count of valid '%'
      allowed_percent -= (fragment.length() - String(fragment).substitute("%", "").length()) // original # of %
                         - (t_tmp.length() - String(t_tmp).substitute("%", "").length()) // new # of %
                         - count; // expected # of % due to %BASENAME
      fragment = String(t_tmp);
    }

    SignedSize diff = (fragment.length() - String(fragment).substitute("%", "").length()) - allowed_percent;
    //std::cerr << "allowed: " << allowed_percent << "\n" << "diff: " << diff << " in: " << fragment << "\n";
    if (diff > 0) throw Exception::InvalidValue(__FILE__, __LINE__, __PRETTY_FUNCTION__, "Mapping still contains '%' after substitution! Did you use % instead of %%?", fragment);
    else if (diff < 0) throw Exception::InvalidValue(__FILE__, __LINE__, __PRETTY_FUNCTION__, "Error: '%' from a filename where accidentally considered command tags! "
                                                                                              "This is a bug! Remove '%' from input filesnames to fix, but please report this as well!", fragment);

    //std::cout << fragment << "'\n";
  }
Ejemplo n.º 7
0
  ExitCodes main_(int, const char **) override
  {
    // find the config for the tool:
    String type = getStringOption_("type");


    Param tool_param = this->getParam_();

    // check required parameters (TOPPBase does not do this as we did not use registerInputFile_(...) etc)
    Param p = tool_param.copy("ETool:", true);
    for (Param::ParamIterator it = p.begin(); it != p.end(); ++it)
    {
      if ((it->tags).count("required") > 0)
      {
        String in = it->value.toString().trim(); // will give '[]' for empty lists (hack, but DataValue class does not offer a convenient query)
        if (in.empty() || in == "[]") // any required parameter should have a value
        {
          LOG_ERROR << "The INI-parameter 'ETool:" << it->name << "' is required, but was not given! Aborting ..." << std::endl;
          return wrapExit(CANNOT_WRITE_OUTPUT_FILE);
        }
        else if ((it->tags).count("input file") > 0) // any required input file should exist
        {
          StringList ifs;
          switch (it->value.valueType())
          {
            case DataValue::STRING_VALUE:
              ifs.push_back(it->value); 
              break;
            case DataValue::STRING_LIST:
              ifs = it->value;
              break;
            default:
              LOG_ERROR << "The INI-parameter 'ETool:" << it->name << "' is tagged as input file and thus must be a string! Aborting ...";
              return wrapExit(ILLEGAL_PARAMETERS);
          }
          for (StringList::const_iterator itf = ifs.begin(); itf != ifs.end(); ++itf)
          {
            if (!File::exists(*itf))
            {
              LOG_ERROR << "Input file '" << *itf << "' does not exist! Aborting ...";
              return wrapExit(INPUT_FILE_NOT_FOUND);
            }
          }
        }
      }
    }

    Internal::ToolDescription gw = ToolHandler::getTOPPToolList(true)[toolName_()];
    for (Size i = 0; i < gw.types.size(); ++i)
    {
      if (type == gw.types[i])
      {
        tde_ = gw.external_details[i];
        if (tde_.working_directory.trim() == "") tde_.working_directory = ".";
        break;
      }
    }

    LOG_INFO << tde_.text_startup << "\n";

    String command_args = tde_.commandline;
    // check for double spaces and warn
    if (command_args.hasSubstring("  "))
    {
      LOG_WARN << "Command line contains double spaces, which is not allowed. Condensing...\n";
      while (command_args.hasSubstring("  "))
      {
        command_args.substitute("  ", " ");
      }
      LOG_WARN << "result: " << command_args << std::endl;
    }

    writeDebug_("CommandLine from ttd (unprocessed): " + command_args, 1);

    // do "pre" moves (e.g. if the wrapped tool works on its data in-place (overwrites) it - we need to make a copy first
    // - we copy the file
    // - we set the value of the affected parameter to the copied tmp file, such that subsequent calls target the tmp file
    for (Size i = 0; i < tde_.tr_table.pre_moves.size(); ++i)
    {
      const Internal::FileMapping & fm = tde_.tr_table.pre_moves[i];
      // find target param:
      Param p = tool_param.copy("ETool:", true);
      String target = fm.target;
      if (!p.exists(target)) throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Cannot find target parameter '" + target + "' being mapped from external tools output!", target);
      String tmp_location = fm.location;
      // fragment's placeholder evaluation:

      createFragment_(tmp_location, p);

      // check if target already exists:
      String target_file = (String)p.getValue(target);
      if (File::exists(tmp_location))
      {
        if (!File::remove(tmp_location))
        {
          LOG_ERROR << "While writing a tmp file: Cannot remove conflicting file '" + tmp_location + "'. Check permissions! Aborting ...";
          return wrapExit(CANNOT_WRITE_OUTPUT_FILE);
        }
      }
      // create the temp file  tmp_location target_file
      writeDebug_(String("Copying '") + target_file + "' to '" + tmp_location + "'", 1);
      bool move_ok = QFile::copy(target_file.toQString(), tmp_location.toQString());
      if (!move_ok)
      {
        LOG_ERROR << "Copying the target file '" + tmp_location + "' from '" + target_file + "' failed! Aborting ...";
        return wrapExit(CANNOT_WRITE_OUTPUT_FILE);
      }
      // set the input file's value to the temp file
      tool_param.setValue(String("ETool:") + target, tmp_location);
    }

    ///// construct the command line:
    std::map<int, std::string> mappings;  // remember the values for each mapping (for file_post substitution later on)
    // go through mappings (reverse because replacing %10 must come before %1):
    for (std::map<Int, String>::reverse_iterator it = tde_.tr_table.mapping.rbegin(); it != tde_.tr_table.mapping.rend(); ++it)
    {
      //std::cout << "mapping #" << it->first << "\n";
      String fragment = it->second;
      // fragment's placeholder evaluation:
      createFragment_(fragment, tool_param.copy("ETool:", true));

      // replace fragment in cl
      //std::cout << "replace : " << "%"+String(it->first) << " with '" << fragment << "\n";
      command_args.substitute("%" + String(it->first), fragment);

      // cache mapping
      mappings[it->first] = fragment;
    }

    QProcess builder;
    builder.setProcessChannelMode(QProcess::MergedChannels);
    String call = tde_.path + " " + command_args;

    writeDebug_("call command: " + call, 1);

    builder.setWorkingDirectory(tde_.working_directory.toQString());
    builder.start(call.toQString());

    if (!builder.waitForFinished(-1) || builder.exitStatus() != 0 || builder.exitCode() != 0)
    {
      LOG_ERROR << ("External tool returned with exit code (" + String(builder.exitCode()) + "), exit status (" + String(builder.exitStatus()) + ") or timed out. Aborting ...\n");
      LOG_ERROR << ("External tool output:\n" + String(QString(builder.readAll())));
      return wrapExit(EXTERNAL_PROGRAM_ERROR);
    }

    LOG_INFO << ("External tool output:\n" + String(QString(builder.readAll())));


    // post processing (file moving via 'file_post' command)
    for (Size i = 0; i < tde_.tr_table.post_moves.size(); ++i)
    {
      const Internal::FileMapping & fm = tde_.tr_table.post_moves[i];
      // find target param:
      Param p = tool_param.copy("ETool:", true);
      String source_file = fm.location;
      // fragment's placeholder evaluation:
      createFragment_(source_file, p, mappings);
      // check if target already exists:
      String target = fm.target;
      if (!p.exists(target)) throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Cannot find target parameter '" + target + "' being mapped from external tools output!", target);
      String target_file = (String)p.getValue(target);

      if (target_file.trim().empty())   // if target was not given, we skip the copying step (usually for optional parameters)
      {
        LOG_INFO << "Parameter '" + target + "' not given. Skipping forwarding of files.\n";
        continue;
      }
      // check if the target exists already (should not; if yes, delete it before overwriting it)
      if (File::exists(target_file))
      {
        if (!File::remove(target_file))
        {
          LOG_ERROR << "Cannot remove conflicting file '" + target_file + "'. Check permissions! Aborting ..." << std::endl;
          return wrapExit(CANNOT_WRITE_OUTPUT_FILE);
        }
      }
      // move to target
      writeDebug_(String("<file_post>: moving '") + source_file + "' to '" + target_file + "'", 1);
      if (!File::exists(source_file))
      {
        LOG_ERROR << "Moving the source file '" + source_file + "' during <file_post> failed, since it does not exist!\n"
                  << "Make sure the external program created the file and its filename is either\n"
                  << "unique or you only run one GenericWrapper at a time to avoid overwriting of files!\n"
                  << "Ideally, (if the external program allows to specify output filenames directly) avoid <file_post>\n"
                  << "in the TTD and request the output file directly. Aborting ..." << std::endl;
        return wrapExit(CANNOT_WRITE_OUTPUT_FILE);
      }
      bool move_ok = QFile::rename(source_file.toQString(), target_file.toQString());
      if (!move_ok)
      {
        LOG_ERROR << "Moving the target file '" + target_file + "' from '" + source_file + "' failed!\n"
                  << "This file exists, but is either currently open for writing or otherwise blocked (concurrent process?). Aborting ..." << std::endl;
        return wrapExit(CANNOT_WRITE_OUTPUT_FILE);
      }
    }

    LOG_INFO << tde_.text_finish << "\n";

    return wrapExit(EXECUTION_OK);
  }
Ejemplo n.º 8
0
int main(int argc, const char** argv)
{
#if  defined(__APPLE__)
  // we do not want to load plugins as this leads to serious problems
  // when shipping on mac os x
  QApplication::setLibraryPaths(QStringList());
#endif

  // ensure correct encoding of paths
  QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));

  Map<String, String> option_lists;
  Map<String, String> options;
  options["-print"] = "print";
  Map<String, String> flags;
  flags["--help"] = "help";
  Param param;
  param.parseCommandLine(argc, argv, options, flags, option_lists);

  //catch command line errors
  if (param.exists("help") //help requested
     || argc > 3 //too many arguments
     || (argc == 3 && !param.exists("print")) //three argument but no -print
     || (param.exists("print") && param.getValue("print") == "") //-print but no file given
      )
  {
    cerr << endl
         << "INIFileEditor -- An editor for OpenMS configuration files." << endl
         << endl
         << "Usage:" << endl
         << " INIFileEditor [options] [file]" << endl
         << endl
         << "Options are:" << endl
         << " --help         Shows this help and exits" << endl
         << " -print <file>  Prints the content of the file to the command line and exits" << endl
         << endl;
    return 0;
  }

  //print a ini file as text
  if (param.exists("print"))
  {
    Param data;
    ParamXMLFile paramFile;
    try
    {
      paramFile.load(param.getValue("print"), data);
      for (Param::ParamIterator it = data.begin(); it != data.end(); ++it)
      {
        cout << it.getName() << " = " << it->value << endl;
      }
    }
    catch (Exception::BaseException& e)
    {
      LOG_ERROR << "Error while parsing file '" << param.getValue("print") << "'\n";
      LOG_ERROR << e << "\n";
    }

    return 0;
  }

  //Create window
  QApplicationTOPP app(argc, const_cast<char**>(argv));

  //set plastique style unless windows / mac style is available
  if (QStyleFactory::keys().contains("windowsxp", Qt::CaseInsensitive))
  {
    app.setStyle("windowsxp");
  }
  else if (QStyleFactory::keys().contains("macintosh", Qt::CaseInsensitive))
  {
    app.setStyle("macintosh");
  }
  else if (QStyleFactory::keys().contains("plastique", Qt::CaseInsensitive))
  {
    app.setStyle("plastique");
  }

  INIFileEditorWindow editor_window;

  //Open passed file
  if (argc == 2)
  {
    //cout << "OPEN: "  << argv[1] << endl;
    editor_window.openFile(argv[1]);
  }

#ifdef OPENMS_WINDOWSPLATFORM
  FreeConsole(); // get rid of console window at this point (we will not see any console output from this point on)
  AttachConsole(-1); // if the parent is a console, reattach to it - so we can see debug output - a normal user will usually not use cmd.exe to start a GUI)
#endif

  editor_window.show();
  return app.exec();
}
Ejemplo n.º 9
0
void convertINI2HTML(const Param & p, ostream & os)
{
  // the .css file is included via the Header.html (see doc/doxygen/common/Header.html)
  os << "<div class=\"ini_global\">\n";
  os << "<div class=\"legend\">\n";
  os << "<b>Legend:</b><br>\n";
  os << " <div class=\"item item_required\">required parameter</div>\n";
  os << " <div class=\"item item_advanced\">advanced parameter</div>\n";
  os << "</div>\n";

  Param::ParamIterator it = p.begin();
  String indentation = "  ";

  while (it != p.end())
  {
    string key = it.getName();

    //write opened/closed nodes
    const std::vector<Param::ParamIterator::TraceInfo> & trace = it.getTrace();
    for (std::vector<Param::ParamIterator::TraceInfo>::const_iterator it2 = trace.begin(); it2 != trace.end(); ++it2)
    {
      if (it2->opened) //opened node
      {
        String d = it2->description;
        d.substitute("\n", "<br>");
        os << indentation  << "<div class=\"node\"><span class=\"node_name\">" << (String().fillLeft('+', (UInt) indentation.size() / 2) + it2->name) << "</span><span class=\"node_description\">" << (d) << "</span></div>" << "\n";
        indentation += "  ";
      }
      else //closed node
      {
        indentation.resize(indentation.size() - 2);
        //os << indentation << "</div>" << "\n";
      }
    }

    //write item
    String s_attr;
    String s_req;
    if (it->tags.find("advanced") != it->tags.end())
      s_attr += " item_advanced";                                                // optionally add advanced class
    if (it->tags.find("required") != it->tags.end())
      s_req += " item_required";                                                // optionally add required class
    DataValue::DataType value_type = it->value.valueType();
    //write opening tag
    os << indentation << "<div class=\"item" + s_attr + "\"><span class=\"item_name" + s_req + "\" style=\"padding-left:" << indentation.size() * 4 << "px;\">" << (it->name) << "</span><span class=\"item_value\">" << it->value.toString() << "</span>" << "\n";

    //replace all critical characters in description
    String d = it->description;
    d.substitute("\n", "<br>");
    os << "<span class=\"item_description\">" << (d) << "</span>";

    //tags
    String list;
    for (set<String>::const_iterator tag_it = it->tags.begin(); tag_it != it->tags.end(); ++tag_it)
    {
      if (*tag_it == "advanced")
        continue;                        // do not list "advanced" or "required" (this is done by color coding)
      if (*tag_it == "required")
        continue;
      if (!list.empty())
        list += ",";
      list += *tag_it;
    }
    os << "<span class=\"item_tags\">" << (list) << "</span>";

    //restrictions
    String restrictions = "";
    bool escape_restrictions(true);
    switch (value_type)
    {
    case DataValue::INT_VALUE:
    case DataValue::INT_LIST:
    {
      bool min_set = (it->min_int != -numeric_limits<Int>::max());
      bool max_set = (it->max_int != numeric_limits<Int>::max());
      if (max_set || min_set)
      {
        if (min_set)
          restrictions += String(it->min_int);
        else
          restrictions += "-&#8734;";        // infinity symbol
        restrictions += ':';
        if (max_set)
          restrictions += String(it->max_int);
        else
          restrictions += "&#8734;";
      }
      escape_restrictions = false;     // prevent html escape of infinity symbol
    }
    break;

    case DataValue::DOUBLE_VALUE:
    case DataValue::DOUBLE_LIST:
    {
      bool min_set = (it->min_float != -numeric_limits<DoubleReal>::max());
      bool max_set = (it->max_float != numeric_limits<DoubleReal>::max());
      if (max_set || min_set)
      {
        if (min_set)
          restrictions += String(it->min_float);
        else
          restrictions += "-&#8734;";        // infinity symbol
        restrictions += ':';
        if (max_set)
          restrictions += String(it->max_float);
        else
          restrictions += "&#8734;";
      }
      escape_restrictions = false;     // prevent html escape of infinity symbol
    }
    break;

    case DataValue::STRING_VALUE:
    case DataValue::STRING_LIST:
      if (it->valid_strings.size() != 0)
      {
        restrictions.concatenate(it->valid_strings.begin(), it->valid_strings.end(), ",");
      }
      break;

    default:
      break;
    }
    if (restrictions.empty())
      restrictions = " ";                       // create content, such that the cell gets an underline

    os << "<span class=\"item_restrictions\">" << restrictions << "</span>";

    os << "</div>"; // end div item

    ++it;
  }

  os << "</div>\n";  // end global div
}