seqan::ArgumentParser::ParseResult parseCommandLine(ModifyStringOptions & options, int argc, char const ** argv) { seqan::ArgumentParser parser("fixed_len_trim"); addOption(parser, seqan::ArgParseOption("i", "input-file", "Path to the input file. Supported input: fq, fq.gz, fastq, fastq.gz, fasta, fasta.gz, fa and fa.gz.", seqan::ArgParseArgument::INPUT_FILE, "IN")); setRequired(parser, "input-file"); setShortDescription(parser, "Methylation Tools"); setVersion(parser, "0.0.1"); setDate(parser, "July 2016"); addUsageLine(parser, "-i [input file] -o [output file] -l [trim length]"); addOption(parser, seqan::ArgParseOption("l", "length", "Length to trim to.",seqan::ArgParseArgument::INTEGER, "INT")); setRequired(parser, "l"); addOption(parser, seqan::ArgParseOption("o", "output-file", "Path to the output file. You must include a file extension. Supported output types: fq, fastq, fasta and fa.", seqan::ArgParseArgument::OUTPUT_FILE, "OUT")); setRequired(parser, "o"); addDescription(parser, "Trims your fasta files to a fixed length."); seqan::ArgumentParser::ParseResult res = seqan::parse(parser, argc, argv); // Extract options ONLY if the args are parsed correctly if (res != seqan::ArgumentParser::PARSE_OK) return res; getOptionValue(options.inputFileName, parser, "input-file"); getOptionValue(options.length, parser, "length"); getOptionValue(options.outputFileName, parser, "output-file"); return seqan::ArgumentParser::PARSE_OK; }
seqan::ArgumentParser::ParseResult parseCommandLine(ModifyStringOptions & options, int argc, char const ** argv) { seqan::ArgumentParser parser("w1/(soon w50)_creator"); addOption(parser, seqan::ArgParseOption("i", "input-file", "Path to the input file", seqan::ArgParseArgument::INPUT_FILE, "IN")); setRequired(parser, "input-file"); setShortDescription(parser, "Methylation Tools"); setVersion(parser, "0.0.6"); setDate(parser, "November 2017"); addUsageLine(parser, "-i CX_report.txt [\\fIOPTIONS\\fP] "); addOption(parser, seqan::ArgParseOption("l", "window-length", "Size of window",seqan::ArgParseArgument::INTEGER, "INT")); setDefaultValue(parser, "window-length", "50"); addDescription(parser, "Create a w1 (and soon w50) file from a CX report."); seqan::ArgumentParser::ParseResult res = seqan::parse(parser, argc, argv); // If parsing was not successful then exit with code 1 if there were errors. // Otherwise, exit with code 0 (e.g. help was printed). if (res != seqan::ArgumentParser::PARSE_OK) return res; getOptionValue(options.inputFileName, parser, "input-file"); getOptionValue(options.window_length, parser, "window-length"); return seqan::ArgumentParser::PARSE_OK; }
bool RequestAction_LoadPlaylist::executeAction() { auto id = getOptionValue("id"); auto value = getOptionValue("value"); auto trackIndexString = getOptionValue("trackIndex"); std::int32_t trackIndex = 0; if (!trackIndexString.empty()) trackIndex = Raumkernel::Tools::CommonUtil::toInt32(trackIndexString); if (trackIndex < 0) trackIndex = 0; // if we got an id we try to stop the playing for the id (which may be a roomUDN, a zoneUDM or a roomName) if (!id.empty()) { auto mediaRenderer = getVirtualMediaRenderer(id); if (!mediaRenderer) { logError("Room or Zone with ID: " + id + " not found!", CURRENT_FUNCTION); return false; } mediaRenderer->loadPlaylist(value, trackIndex, sync); } return true; }
bool RequestAction_VolumeUp::executeAction() { auto id = getOptionValue("id"); auto scope = getOptionValue("scope"); auto value = Raumkernel::Tools::StringUtil::tolower(getOptionValue("value")); auto valueChange = Raumkernel::Tools::CommonUtil::toInt32(value); auto zoneScope = isZoneScope(scope); std::int32_t newVolumeValue = 0; // we have got an id that might be a room or a zone. we have to get the scope to know what we should mute if (!id.empty()) { auto mediaRenderer = getVirtualMediaRenderer(id); if (!mediaRenderer) { logError("Room or Zone with ID: " + id + " not found!", CURRENT_FUNCTION); return false; } if (zoneScope) { newVolumeValue = mediaRenderer->getVolume(true) + valueChange; if (newVolumeValue > 100) newVolumeValue = 100; if (newVolumeValue < 0) newVolumeValue = 0; mediaRenderer->setVolume(newVolumeValue, sync); } else { newVolumeValue = mediaRenderer->getRoomVolume(getRoomUDNFromId(id), true) + valueChange; if (newVolumeValue > 100) newVolumeValue = 100; if (newVolumeValue < 0) newVolumeValue = 0; mediaRenderer->setRoomVolume(getRoomUDNFromId(id), newVolumeValue, sync); } } // if we have no id provided, we mute all renderers else { auto zoneInfoMap = getManagerEngineer()->getZoneManager()->getZoneInformationMap(); for (auto it : zoneInfoMap) { auto rendererUDN = getManagerEngineer()->getZoneManager()->getRendererUDNForZoneUDN(it.first); auto mediaRenderer = getVirtualMediaRendererFromUDN(rendererUDN); if (mediaRenderer) { newVolumeValue = mediaRenderer->getVolume(true) + valueChange; if (newVolumeValue > 100) newVolumeValue = 100; if (newVolumeValue < 0) newVolumeValue = 0; mediaRenderer->setVolume(newVolumeValue, sync); } } } return true; }
seqan::ArgumentParser::ParseResult parseCommandLine(ModifyStringOptions & options, int argc, char const ** argv) { // Setup ArgumentParser. seqan::ArgumentParser parser("modify_string"); // We require one argument. addArgument(parser, seqan::ArgParseArgument( seqan::ArgParseArgument::STRING, "TEXT")); // Define Options addOption(parser, seqan::ArgParseOption( "i", "period", "Period to use for the index.", seqan::ArgParseArgument::INTEGER, "INT")); setMinValue(parser, "period", "1"); setDefaultValue(parser, "period", "1"); addOption(parser, seqan::ArgParseOption( "r", "range", "Range of the text to modify.", seqan::ArgParseArgument::INTEGER, "INT", false, 2)); addOption(parser, seqan::ArgParseOption( "U", "uppercase", "Select to-uppercase as operation.")); addOption(parser, seqan::ArgParseOption( "L", "lowercase", "Select to-lowercase as operation.")); // Parse command line. seqan::ArgumentParser::ParseResult res = seqan::parse(parser, argc, argv); // Only extract options if the program will continue after parseCommandLine() if (res != seqan::ArgumentParser::PARSE_OK) return res; // Extract option values. getOptionValue(options.period, parser, "period"); getOptionValue(options.rangeBegin, parser, "range", 0); getOptionValue(options.rangeEnd, parser, "range", 1); options.toUppercase = isSet(parser, "uppercase"); options.toLowercase = isSet(parser, "lowercase"); seqan::getArgumentValue(options.text, parser, 0); // If both to-uppercase and to-lowercase were selected then this is an error. if (options.toUppercase && options.toLowercase) { std::cerr << "ERROR: You cannot specify both to-uppercase and to-lowercase!\n"; return seqan::ArgumentParser::PARSE_ERROR; } return seqan::ArgumentParser::PARSE_OK; }
bool RequestAction_EnterAutomaticStandby::executeAction() { auto id = getOptionValue("id"); if (!id.empty()) { auto mediaRenderer = std::dynamic_pointer_cast<Raumkernel::Devices::MediaRenderer_Raumfeld>(getMediaRenderer(id)); if (!mediaRenderer) { logError("Room with ID: " + id + " not found!", CURRENT_FUNCTION); return false; } mediaRenderer->enterAutomaticStandby(sync); } else { auto mediaRendererMap = getManagerEngineer()->getDeviceManager()->getMediaRenderers(); for (auto it : mediaRendererMap) { if (!it.second->isZoneRenderer()) { auto mediaRenderer = std::dynamic_pointer_cast<Raumkernel::Devices::MediaRenderer_Raumfeld>(it.second); if (mediaRenderer) mediaRenderer->enterAutomaticStandby(sync); } } } return true; }
bool RequestAction_VolumeUp::isValid() { bool isValid = RequestAction::isValid(); // examples for valid requests: // raumserver/controller/volumeUp?value=2 // raumserver/controller/volumeUp?id=Schlafzimmer&value=2 // raumserver/controller/volumeUp?id=Schlafzimmer&value=2&scope=zone // raumserver/controller/volumeUp?id=uuid:3f68f253-df2a-4474-8640-fd45dd9ebf88&value=1 // raumserver/controller/volumeUp?id=uuid:3f68f253-df2a-4474-8640-fd45dd9ebf88&value=1&scope=zone auto value = getOptionValue("value"); if (value.empty()) { logError("'value' option is needed to execute 'volumeUp' command!", CURRENT_FUNCTION); isValid = false; } auto valueChange = Raumkernel::Tools::CommonUtil::toInt32(value); if (valueChange <= 0) { logError("'value' has to be greater than '0'", CURRENT_FUNCTION); isValid = false; } return isValid; }
std::string RequestActionReturnableLongPolling_GetZoneMediaList::getLastUpdateId() { auto id = getOptionValue("id"); auto mediaRenderer = getVirtualMediaRenderer(id); if (!mediaRenderer) return ""; std::string zonePlaylistId = Raumkernel::Manager::LISTID_ZONEIDENTIFIER + mediaRenderer->getUDN(); auto lastUpdateId = getManagerEngineer()->getMediaListManager()->getLastUpdateIdForList(zonePlaylistId); return lastUpdateId; }
seqan::ArgumentParser::ParseResult parseArgs(FxSamCoverageOptions & options, int argc, char const ** argv) { seqan::ArgumentParser parser("fx_sam_coverage"); setShortDescription(parser, "Read Coverage Computation."); setVersion(parser, "0.1"); setDate(parser, "August 2012"); addUsageLine(parser, "[\\fIOPTIONS\\fP] \\fB-o\\fP \\fIOUT.tsv\\fP \\fIGENOME.fa\\fP \\fIMAPPING.sam\\fP"); addDescription(parser, "Compute read coverage and C+G content for a genome."); // Two input files: Genome, and mapping. addArgument(parser, seqan::ArgParseArgument(seqan::ArgParseArgument::INPUTFILE)); setValidValues(parser, 0, "fasta fa"); addArgument(parser, seqan::ArgParseArgument(seqan::ArgParseArgument::INPUTFILE)); setValidValues(parser, 1, "sam"); // TODO(holtgrew): I want a custom help text! // addOption(parser, seqan::ArgParseOption("h", "help", "This helpful screen.")); addOption(parser, seqan::ArgParseOption("v", "verbose", "Verbose, log to STDERR.")); hideOption(parser, "verbose"); addOption(parser, seqan::ArgParseOption("vv", "very-verbose", "Very verbose, log to STDERR.")); hideOption(parser, "very-verbose"); addSection(parser, "Main Options"); addOption(parser, seqan::ArgParseOption("w", "window-size", "Set the size of the non-overlapping windows in base pairs.", seqan::ArgParseArgument::INTEGER, "NUM")); setDefaultValue(parser, "window-size", "10000"); addSection(parser, "Output Options"); addOption(parser, seqan::ArgParseOption("o", "out-path", "Path to the resulting file. If omitted, result is printed to stdout.", seqan::ArgParseArgument::OUTPUTFILE, "TSV")); setRequired(parser, "out-path"); setValidValues(parser, "out-path", "sam.coverage.tsv"); seqan::ArgumentParser::ParseResult res = parse(parser, argc, argv); if (res == seqan::ArgumentParser::PARSE_OK) { getArgumentValue(options.inGenomePath, parser, 0); getArgumentValue(options.inSamPath, parser, 1); getOptionValue(options.outPath, parser, "out-path"); if (isSet(parser, "verbose")) options.verbosity = 2; if (isSet(parser, "very-verbose")) options.verbosity = 3; } return res; }
String ProgramOptions::getOptionValueOrDefault(const String& optionName, const String& defaultValue) const { String value; try { value = getOptionValue(optionName); } catch (BaseException& ) { value = defaultValue; } return value; }
bool RequestAction_Mute::executeAction() { auto id = getOptionValue("id"); auto scope = getOptionValue("scope"); auto value = Raumkernel::Tools::StringUtil::tolower(getOptionValue("value")); auto zoneScope = isZoneScope(scope); bool mute = (value == "true" || value == "1" || value.empty()) ? true : false; // we have got an id that might be a room or a zone. we have to get the scope to know what we should mute if (!id.empty()) { auto mediaRenderer = getVirtualMediaRenderer(id); if (!mediaRenderer) { logError("Room or Zone with ID: " + id + " not found!", CURRENT_FUNCTION); return false; } if (zoneScope) mediaRenderer->setMute(true, sync); else mediaRenderer->setRoomMute(getRoomUDNFromId(id), mute, sync); } // if we have no id provided, we mute all renderers else { auto zoneInfoMap = getManagerEngineer()->getZoneManager()->getZoneInformationMap(); for (auto it : zoneInfoMap) { auto rendererUDN = getManagerEngineer()->getZoneManager()->getRendererUDNForZoneUDN(it.first); auto mediaRenderer = getVirtualMediaRendererFromUDN(rendererUDN); if (mediaRenderer) mediaRenderer->setMute(mute, sync); } } return true; }
bool RequestActionReturnableLongPolling_GetZoneMediaList::executeActionLongPolling() { auto id = getOptionValue("id"); std::vector<std::shared_ptr<Raumkernel::Media::Item::MediaItem>> mediaList; rapidjson::StringBuffer jsonStringBuffer; rapidjson::Writer<rapidjson::StringBuffer> jsonWriter(jsonStringBuffer); jsonWriter.StartArray(); // if we got an id we get the list if (!id.empty()) { auto mediaRenderer = getVirtualMediaRenderer(id); if (!mediaRenderer) { logError("Room or Zone with ID: " + id + " not found!", CURRENT_FUNCTION); return false; } std::string zonePlaylistId = Raumkernel::Manager::LISTID_ZONEIDENTIFIER + mediaRenderer->getUDN(); // zone playlists do not have to be extra read, they are always up to date! // So we do only get a copy of the list with shared pointers to media items mediaList = managerEngineer->getMediaListManager()->getList(zonePlaylistId); // add the list items to the jsonWriter // we do not have to lock when we are reading the copied list of the media items because they are shared pointers // and media items only will be created once and will never be updated! addMediaListToJson(mediaRenderer->getUDN(), mediaList, jsonWriter); } // if we have no id provided, then we get the playlist for all virtual renderers else { auto zoneInfoMap = getManagerEngineer()->getZoneManager()->getZoneInformationMap(); for (auto it : zoneInfoMap) { std::string zonePlaylistId = Raumkernel::Manager::LISTID_ZONEIDENTIFIER + it.second.UDN; mediaList = managerEngineer->getMediaListManager()->getList(zonePlaylistId); addMediaListToJson(it.second.UDN, mediaList, jsonWriter); } } jsonWriter.EndArray(); setResponseData(jsonStringBuffer.GetString()); return true; }
bool RequestAction_LoadPlaylist::isValid() { bool isValid = RequestAction::isValid(); // examples for valid requests: // raumserver/controller/loadPlaylist?id=Schlafzimmer&value=[urlencoded playlist id] // raumserver/controller/loadPlaylist?id=uuid:3f68f253-df2a-4474-8640-fd45dd9ebf88&value=[urlencoded playlist id] auto id = getOptionValue("id"); auto value = getOptionValue("value"); if (id.empty()) { logError("'id' option is needed to execute 'loadPlaylist' command!", CURRENT_FUNCTION); isValid = false; } if (value.empty()) { logError("'value' option is needed to execute 'loadPlaylist' command!", CURRENT_FUNCTION); isValid = false; } return isValid; }
int main(int argc, char const ** argv) { //![object] // Setup ArgumentParser. seqan::ArgumentParser parser("modify_string"); //![object] //![argument] addArgument(parser, seqan::ArgParseArgument( seqan::ArgParseArgument::STRING, "TEXT")); //![argument] //![option] addOption(parser, seqan::ArgParseOption( "i", "period", "Period to use for the index.", seqan::ArgParseArgument::INTEGER, "INT")); addOption(parser, seqan::ArgParseOption( "U", "uppercase", "Select to-uppercase as operation.")); //![option] //![parse] // Parse command line. seqan::ArgumentParser::ParseResult res = seqan::parse(parser, argc, argv); //![parse] // If parsing was not successful then exit with code 1 if there were errors. // Otherwise, exit with code 0 (e.g. help was printed). //![check] if (res != seqan::ArgumentParser::PARSE_OK) return res == seqan::ArgumentParser::PARSE_ERROR; //![check] //![print] // Extract option values and print them. unsigned period = 0; getOptionValue(period, parser, "period"); bool toUppercase = isSet(parser, "uppercase"); seqan::CharString text; getArgumentValue(text, parser, 0); std::cout << "period \t" << period << '\n' << "uppercase\t" << toUppercase << '\n' << "text \t" << text << '\n'; //![print] return 0; }
int RegularExpression::parseOptions(const XMLCh* const options) { if (options == 0) return 0; int opts = 0; int length = XMLString::stringLen(options); for (int i=0; i < length; i++) { int v = getOptionValue(options[i]); if (v == 0) ThrowXMLwithMemMgr1(ParseException, XMLExcepts::Regex_UnknownOption, options, fMemoryManager); opts |= v; } return opts; }
double SingleOptionContract::getValue(boost::shared_ptr<RatesEnvironment> re) { if (valueCalcuated && (re == cachedRE)) { return cachedContractValue; } Date valueDate = (re->getAnchorDate()); if (valueDate > getSettlementDate()) { return 0; } double premium = getOptionValue(re); if (valueDate <= getPremiumPaymentDate()) { double df = (re->getDRS())->getDiscountFactor(getPremiumPaymentDate()); premium -= getPremiumAmount() * getVolume() * df; } cachedRE = re; valueCalcuated = true; cachedContractValue = getBuySellAsDouble() * premium; return cachedContractValue; }
int main(int argc, char const ** argv) { // Setup ArgumentParser. seqan::ArgumentParser parser("modify_string"); addArgument(parser, seqan::ArgParseArgument( seqan::ArgParseArgument::STRING, "TEXT")); addOption(parser, seqan::ArgParseOption( "i", "period", "Period to use for the index.", seqan::ArgParseArgument::INTEGER, "INT")); setDefaultValue(parser, "period", "1"); addOption(parser, seqan::ArgParseOption( "U", "uppercase", "Select to-uppercase as operation.")); addOption(parser, seqan::ArgParseOption( "L", "lowercase", "Select to-lowercase as operation.")); // Parse command line. seqan::ArgumentParser::ParseResult res = seqan::parse(parser, argc, argv); // If parsing was not successful then exit with code 1 if there were errors. // Otherwise, exit with code 0 (e.g. help was printed). if (res != seqan::ArgumentParser::PARSE_OK) return res == seqan::ArgumentParser::PARSE_ERROR; // Extract option values and print them. ModifyStringOptions options; getOptionValue(options.period, parser, "period"); options.toUppercase = isSet(parser, "uppercase"); options.toLowercase = isSet(parser, "lowercase"); getArgumentValue(options.text, parser, 0); std::cout << "period \t" << options.period << '\n' << "uppercase\t" << options.toUppercase << '\n' << "lowercase\t" << options.toLowercase << '\n' << "text \t" << options.text << '\n'; return 0; }
seqan::ArgumentParser::ParseResult parseCommandLine(ModifyStringOptions & options, int argc, char const ** argv) { // Setup ArgumentParser. seqan::ArgumentParser parser("modify_string"); // Set short description, version, and date. setShortDescription(parser, "String Modifier"); setVersion(parser, "1.0"); setDate(parser, "July 2012"); // Define usage line and long description. addUsageLine(parser, "[\\fIOPTIONS\\fP] \"\\fITEXT\\fP\""); addDescription(parser, "This program allows simple character modifications to " "each i-th character."); // We require one argument. addArgument(parser, seqan::ArgParseArgument( seqan::ArgParseArgument::STRING, "TEXT")); // Define Options -- Section Modification Options addSection(parser, "Modification Options"); addOption(parser, seqan::ArgParseOption( "i", "period", "Period to use for the index.", seqan::ArgParseArgument::INTEGER, "INT")); setDefaultValue(parser, "period", "1"); addOption(parser, seqan::ArgParseOption( "U", "uppercase", "Select to-uppercase as operation.")); addOption(parser, seqan::ArgParseOption( "L", "lowercase", "Select to-lowercase as operation.")); // Add Examples Section. addTextSection(parser, "Examples"); addListItem(parser, "\\fBmodify_string\\fP \\fB-U\\fP \\fIveryverylongword\\fP", "Print upper case version of \"veryverylongword\""); addListItem(parser, "\\fBmodify_string\\fP \\fB-L\\fP \\fB-i\\fP \\fI3\\fP " "\\fIveryverylongword\\fP", "Print \"veryverylongword\" with every third character " "converted to upper case."); // Parse command line. seqan::ArgumentParser::ParseResult res = seqan::parse(parser, argc, argv); // Only extract options if the program will continue after parseCommandLine() if (res != seqan::ArgumentParser::PARSE_OK) return res; // Extract option values. getOptionValue(options.period, parser, "period"); options.toUppercase = isSet(parser, "uppercase"); options.toLowercase = isSet(parser, "lowercase"); seqan::getArgumentValue(options.text, parser, 0); // If both to-uppercase and to-lowercase were selected then this is an error. if (options.toUppercase && options.toLowercase) { std::cerr << "ERROR: You cannot specify both to-uppercase and to-lowercase!\n"; return seqan::ArgumentParser::PARSE_ERROR; } return seqan::ArgumentParser::PARSE_OK; }
seqan::ArgumentParser::ParseResult parseArgs(FxFaidxOptions & options, int argc, char const ** argv) { seqan::ArgumentParser parser("fx_faidx"); setShortDescription(parser, "Indexing FASTA and indexed FASTA access."); setVersion(parser, "0.1"); setDate(parser, "May 2012"); addUsageLine(parser, "[\\fIOPTIONS\\fP] [\\fB-f\\fP \\fIFASTA\\fP] [\\fB-r\\fP \\fIREGION\\fP]+"); addDescription(parser, "Equivalent program to samtools faidx."); // TODO(holtgrew): I want a custom help text! // addOption(parser, seqan::ArgParseOption("h", "help", "This helpful screen.")); addOption(parser, seqan::ArgParseOption("v", "verbose", "Verbose, log to STDERR.")); addOption(parser, seqan::ArgParseOption("vv", "very-verbose", "Very verbose, log to STDERR.")); hideOption(parser, "very-verbose"); addSection(parser, "FASTA / FAIDX Files"); addOption(parser, seqan::ArgParseOption("f", "fasta-file", "Path to the FASTA file.", seqan::ArgParseArgument::STRING, false, "FASTA")); setRequired(parser, "fasta-file"); addOption(parser, seqan::ArgParseOption("i", "index-file", "Path to the .fai index file. Defaults to FASTA.fai", seqan::ArgParseArgument::STRING, false, "FASTA")); addOption(parser, seqan::ArgParseOption("o", "out-file", "Path to the resulting file. If omitted, result is printed to stdout.", seqan::ArgParseArgument::STRING, false, "FASTA")); addSection(parser, "Regions"); addOption(parser, seqan::ArgParseOption("r", "region", "Region to retrieve from FASTA file. You can specify multiple regions with multiple \\fB-r\\fP \\fIREGION\\fP. Note that regions are one-based, see below for detailed information about the format.", seqan::ArgParseArgument::STRING, true, "REGION")); addTextSection(parser, "Regions"); addText(parser, "Regions can be specified in the formats \\fICHR\\fP, \\fICHR\\fP:\\fISTART\\fP, \\fICHR\\fP:\\fISTART\\fP:\\fIEND\\fP. \\fICHR\\fP is the id of the reference sequence in the FASTA file, \\fISTART\\fP and \\fIEND\\fP are the start end end positions of the region. These positions are one-based."); addTextSection(parser, "Region Examples"); addListItem(parser, "\\fIchr1\\fP", "All of the sequence with the identifier \"chr1\"."); addListItem(parser, "\\fIchrX\\fP:\\fI1,000\\fP", "The characters in the X chromsome, starting with the 1,000th base."); addListItem(parser, "\\fIchr2\\fP:\\fI1,500,000\\fP-\\fI2,000,000\\fP", "The character 1,500,000 up to and including character 2,000,000 in the same chromosome."); addTextSection(parser, "Usage Examples"); addListItem(parser, "\\fBfx_faidx\\fP \\fB-f\\fP \\fIREF.fa\\fP", "Create index for file \\fIREF.fa\\fP, index is written to \\fIREF.fa.fai\\fP"); addListItem(parser, "\\fBfx_faidx\\fP \\fB-f\\fP \\fIREF.fa\\fP \\fB-i\\fP \\fIINDEX.fai\\fP", "Create index for file \\fIREF.fa\\fP, index is written to \\fIINDEX.fai\\fP"); addListItem(parser, "\\fBfx_faidx\\fP \\fB-f\\fP \\fIREF.fa\\fP \\fB-r\\fP \\fIchr1\\fP", "Retrieve sequence named \"chr1\" from file \\fIREF.fa\\fP using the index with the default name \\fIREF.fa.fai\\fP. The index file name is created if it does not exist."); addListItem(parser, "\\fBfx_faidx\\fP \\fB-f\\fP \\fIREF.fa\\fP \\fB-r\\fP \\fIchr1:100-1100\\fP", "Retrieve characters 100 to 1,100 from the sequence named \"chr1\" from file \\fIREF.fa\\fP using the index with the default name \\fIREF.fa.fai\\fP."); addListItem(parser, "\\fBfx_faidx\\fP \\fB-f\\fP \\fIREF.fa\\fP \\fB-r\\fP \\fIchr1:100-1100\\fP \\fB-r\\fP \\fIchr2:2,000\\fP", "Retrieve characters 100-1,000 from \"chr1\" and all characters from 2,000 of \"chr2\"."); seqan::ArgumentParser::ParseResult res = parse(parser, argc, argv); if (res == seqan::ArgumentParser::PARSE_OK) { getOptionValue(options.inFastaPath, parser, "fasta-file"); // Set default FAI file name. options.inFaiPath = options.inFastaPath; append(options.inFaiPath, ".fai"); // Get FAI file name from parser if set. if (isSet(parser, "index-file")) getOptionValue(options.inFaiPath, parser, "index-file"); if (isSet(parser, "region")) options.regions = getOptionValues(parser, "region"); if (isSet(parser, "out-file")) getOptionValue(options.outFastaPath, parser, "out-file"); if (isSet(parser, "verbose")) options.verbosity = 2; if (isSet(parser, "very-verbose")) options.verbosity = 3; } return res; }
seqan::ArgumentParser::ParseResult parseArgs(SakOptions & options, int argc, char ** argv) { seqan::ArgumentParser parser("sak"); setShortDescription(parser, "Slicing and dicing of FASTA/FASTQ files.."); setVersion(parser, SEQAN_APP_VERSION " [" SEQAN_REVISION "]"); setDate(parser, SEQAN_DATE); setCategory(parser, "Utilities"); addUsageLine(parser, "[\\fIOPTIONS\\fP] [\\fB-o\\fP \\fIOUT.{fa,fq}\\fP] \\fIIN.{fa,fq}\\fP"); addDescription(parser, "\"It slices, it dices and it makes the laundry!\""); addDescription(parser, "Original SAK tool by David Weese. Rewrite by Manuel Holtgrewe."); // The only argument is the input file. addArgument(parser, seqan::ArgParseArgument(seqan::ArgParseArgument::INPUT_FILE, "IN")); // Only FASTA and FASTQ files are allowed as input. setValidValues(parser, 0, seqan::SeqFileIn::getFileExtensions()); // TODO(holtgrew): I want a custom help text! // addOption(parser, seqan::ArgParseOption("h", "help", "This helpful screen.")); addOption(parser, seqan::ArgParseOption("v", "verbose", "Verbose, log to STDERR.")); hideOption(parser, "verbose"); addOption(parser, seqan::ArgParseOption("vv", "very-verbose", "Very verbose, log to STDERR.")); hideOption(parser, "very-verbose"); addSection(parser, "Output Options"); addOption(parser, seqan::ArgParseOption("o", "out-path", "Path to the resulting file. If omitted, result is printed to stdout in FastQ format.", seqan::ArgParseOption::OUTPUT_FILE, "FASTX")); setValidValues(parser, "out-path", seqan::SeqFileOut::getFileExtensions()); addOption(parser, seqan::ArgParseOption("rc", "revcomp", "Reverse-complement output.")); addOption(parser, seqan::ArgParseOption("l", "max-length", "Maximal number of sequence characters to write out.", seqan::ArgParseOption::INTEGER, "LEN")); addSection(parser, "Filter Options"); addOption(parser, seqan::ArgParseOption("s", "sequence", "Select the given sequence for extraction by 0-based index.", seqan::ArgParseOption::INTEGER, "NUM", true)); addOption(parser, seqan::ArgParseOption("sn", "sequence-name", "Select sequence with name prefix being \\fINAME\\fP.", seqan::ArgParseOption::STRING, "NAME", true)); addOption(parser, seqan::ArgParseOption("ss", "sequences", "Select sequences \\fIfrom\\fP-\\fIto\\fP where \\fIfrom\\fP and \\fIto\\fP " "are 0-based indices.", seqan::ArgParseArgument::STRING, "RANGE", true)); addOption(parser, seqan::ArgParseOption("i", "infix", "Select characters \\fIfrom\\fP-\\fIto\\fP where \\fIfrom\\fP and \\fIto\\fP " "are 0-based indices.", seqan::ArgParseArgument::STRING, "RANGE", true)); addOption(parser, seqan::ArgParseOption("ll", "line-length", "Set line length in output file. See section \\fILine Length\\fP for details.", seqan::ArgParseArgument::INTEGER, "LEN", false)); setMinValue(parser, "line-length", "-1"); addTextSection(parser, "Line Length"); addText(parser, "You can use the setting \\fB--line-length\\fP for setting the resulting line length. By default, " "sequences in FASTA files are written with at most 70 characters per line and sequences in FASTQ files are " "written without any line breaks. The quality sequence in FASTQ file is written in the same way as the " "residue sequence."); addText(parser, "The default is selected with a \\fB--line-length\\fP value of \\fI-1\\fP and line breaks can be disabled " "with a value of \\fI0\\fP."); addTextSection(parser, "Usage Examples"); addListItem(parser, "\\fBsak\\fP \\fB-s\\fP \\fI10\\fP \\fIIN.fa\\fP", "Cut out 11th sequence from \\fIIN.fa\\fP and write to stdout as FASTA."); addListItem(parser, "\\fBsak\\fP \\fB-ss\\fP \\fI10-12\\fP \\fB-ss\\fP \\fI100-200\\fP \\fIIN.fq\\fP", "Cut out 11th up to and including 12th and 101th up to and including 199th sequence from \\fIIN.fq\\fP " "and write to stdout as FASTA."); seqan::ArgumentParser::ParseResult res = parse(parser, argc, argv); if (res != seqan::ArgumentParser::PARSE_OK) return res; getArgumentValue(options.inFastxPath, parser, 0); seqan::CharString tmp; getOptionValue(tmp, parser, "out-path"); if (isSet(parser, "out-path")) getOptionValue(options.outPath, parser, "out-path"); if (isSet(parser, "verbose")) options.verbosity = 2; if (isSet(parser, "very-verbose")) options.verbosity = 3; if (isSet(parser, "sequence")) { std::vector<std::string> sequenceIds = getOptionValues(parser, "sequence"); for (unsigned i = 0; i < seqan::length(sequenceIds); ++i) { unsigned idx = 0; if (!seqan::lexicalCast(idx, sequenceIds[i])) { std::cerr << "ERROR: Invalid sequence index " << sequenceIds[i] << "\n"; return seqan::ArgumentParser::PARSE_ERROR; } appendValue(options.seqIndices, idx); } } if (isSet(parser, "sequences")) { std::vector<std::string> sequenceRanges = getOptionValues(parser, "sequences"); seqan::CharString buffer; for (unsigned i = 0; i < seqan::length(sequenceRanges); ++i) { seqan::Pair<uint64_t> range; if (!parseRange(range.i1, range.i2, sequenceRanges[i])) { std::cerr << "ERROR: Invalid range " << sequenceRanges[i] << "\n"; return seqan::ArgumentParser::PARSE_ERROR; } appendValue(options.seqIndexRanges, range); } } if (isSet(parser, "infix")) { seqan::CharString buffer; getOptionValue(buffer, parser, "infix"); if (!parseRange(options.seqInfixBegin, options.seqInfixEnd, buffer)) { std::cerr << "ERROR: Invalid range " << buffer << "\n"; return seqan::ArgumentParser::PARSE_ERROR; } } options.reverseComplement = isSet(parser, "revcomp"); if (isSet(parser, "max-length")) getOptionValue(options.maxLength, parser, "max-length"); if (isSet(parser, "sequence-name")) getOptionValue(options.readPattern, parser, "sequence-name"); getOptionValue(options.seqOutOptions.lineLength, parser, "line-length"); return res; }
seqan::ArgumentParser::ParseResult parseCommandLine(Options & options, int argc, char const ** argv) { // Setup ArgumentParser. seqan::ArgumentParser parser("roiGFF"); // Set short description, version, and date. setShortDescription(parser, "get ROIs based on GFF annotation"); setVersion(parser, VERSION); setDate(parser, "March 2013"); // Define usage line and long description. addUsageLine(parser, "[\\fIOPTIONS\\fP] \\fB-if\\fP \\fIIN.roi\\fP" "\\fB-ig\\fP \\fIIN.gff\fP" "\\fB-of\\fP \\fIOUT.roi\\fP" "[\\fB-ss\\fP] [\\fB-t\\fP \\fItype\\fP] " "[\\fB-p\\fP \\fIparent attribute\\fP]]"); addDescription(parser, "Takes regions from GFF file, calculates the overlap with the ROI file" "and creates a new ROI file based on the GFF regions."); // General Options addOption(parser, seqan::ArgParseOption("v", "verbose", "Verbose mode.")); addOption(parser, seqan::ArgParseOption("vv", "vverbose", "Very verbose mode.")); // Input / Output Options addSection(parser, "Input / Output Parameters"); addOption(parser, seqan::ArgParseOption("if", "roi-file", "roi file", seqan::ArgParseOption::INPUTFILE)); setValidValues(parser, "roi-file", "roi"); setRequired(parser, "roi-file"); addOption(parser, seqan::ArgParseOption("ig", "gff-file", "gff file", seqan::ArgParseOption::INPUTFILE)); setValidValues(parser, "gff-file", "gff"); setRequired(parser, "gff-file"); addOption(parser, seqan::ArgParseOption("of", "output-file", "Output file", seqan::ArgParseOption::OUTPUTFILE)); setValidValues(parser, "output-file", "roi"); setRequired(parser, "output-file"); // Optional Parameter addOption(parser, seqan::ArgParseOption("ss", "strandspecific", "calculate strandspecific stats (only position sorted)")); addOption(parser, seqan::ArgParseOption("t", "type", "Type to used (3. column in GFF file). If not set all types will be used." "There can only be one or none set.", seqan::ArgParseOption::STRING)); setDefaultValue(parser, "type", ""); addOption(parser, seqan::ArgParseOption("p", "parent", "tag to used to identify regions that should be concatednated." "They are sorted by start position and then concatenated. If empty/not set" "there will be no concatenation performed", seqan::ArgParseOption::STRING)); setDefaultValue(parser, "parent", ""); // Parse command line. seqan::ArgumentParser::ParseResult res = seqan::parse(parser, argc, argv); // Extract option values. if (isSet(parser, "verbose")) options.verbosity = 1; if (isSet(parser, "vverbose")) options.verbosity = 2; getOptionValue(options.roiFileName, parser, "roi-file"); getOptionValue(options.gffFileName, parser, "gff-file"); getOptionValue(options.outputFileName, parser, "output-file"); getOptionValue(options.strandSpecific, parser, "strandspecific"); getOptionValue(options.type, parser, "type"); getOptionValue(options.parent, parser, "parent"); return seqan::ArgumentParser::PARSE_OK; }
int main(int argc, char const * argv[]) { // Additional checks seqan::ArgumentParser parser = buildParser(); seqan::ArgumentParser::ParseResult res = seqan::parse(parser, argc, argv); // Check if input was successfully parsed. if (res != seqan::ArgumentParser::PARSE_OK) return res == seqan::ArgumentParser::PARSE_ERROR; // Check if one or two input files (single or paired-end) were given. int fileCount = getArgumentValueCount(parser, 0); if (fileCount < 1) { printShortHelp(parser); return 1; } unsigned int radius = 1; getOptionValue(radius, parser, "r"); seqan::CharString readsFileName; getOptionValue(readsFileName, parser, "i"); // Open input file, BamFileIn can read SAM and BAM files. seqan::BamFileIn bamFileIn(seqan::toCString(readsFileName)); seqan::CharString _filterChromosomes; seqan::getOptionValue(_filterChromosomes, parser, "fc"); std::string filterChromosomes = seqan::toCString(_filterChromosomes); OccurenceMap occurenceMap; Statistics stats; std::cout << "read bam file... "; auto t1 = std::chrono::steady_clock::now(); seqan::BamAlignmentRecord record; seqan::BamHeader header; readHeader(header, bamFileIn); const auto chromosomeFilterSet = calculateChromosomeFilter(filterChromosomes, contigNames(context(bamFileIn))); const auto chromosomes = contigNames(context(bamFileIn)); processBamFile(bamFileIn, chromosomeFilterSet, occurenceMap, stats); auto t2 = std::chrono::steady_clock::now(); std::cout << std::chrono::duration_cast<std::chrono::duration<float>>(t2 - t1).count() << "s" << std::endl; std::vector<std::pair<unsigned int, unsigned int>> hits(radius * 2 + 1); t1 = std::chrono::steady_clock::now(); std::cout << "calculating 5'-ends around peaks... "; for (unsigned int fileIndex = 0;fileIndex < static_cast<unsigned int>(fileCount); ++fileIndex) { seqan::CharString fileName_; getArgumentValue(fileName_, parser, fileIndex, 0); const std::string fileName = seqan::toCString(fileName_); std::ifstream infile(fileName); std::string chromosome, dummy; unsigned int start, end; while (infile >> chromosome >> start >> end >> dummy) { int rID = -1; for (unsigned int i = 0;i < length(chromosomes);++i) if (chromosomes[i] == chromosome) { rID = i; break; } if (rID == -1) { std::cout << "invalid chromosome name: " << chromosome << " in file " << fileName << std::endl; return -1; } seqan::BamAlignmentRecord record; record.beginPos = std::max<int>(start - radius, 0); record.rID = rID; record.flag = 0; unsigned int index = 0; if (start < radius) index += radius - start; while (record.beginPos <= static_cast<__int32>(start + radius)) { BamRecordKey<NoBarcode> pos(record); auto el = occurenceMap.find(pos); if(el != occurenceMap.end()) hits[index].first += el->second; pos.init(pos.getRID(), pos.get5EndPosition(), true); el = occurenceMap.find(pos); if (el != occurenceMap.end()) hits[index].second += el->second; ++record.beginPos; ++index; } } std::string outFilename = getFilePrefix(fileName) + std::string("_5PrimeEnds.tab"); if (seqan::isSet(parser, "o")) { seqan::CharString outFileName_; getOptionValue(outFileName_, parser, "o"); outFilename = seqan::toCString(outFileName_); } std::fstream fs; std::cout << "writing " << outFilename << std::endl; #ifdef _MSC_VER fs.open(outFilename, std::fstream::out, _SH_DENYNO); #else fs.open(outFilename, std::fstream::out); #endif int i = - static_cast<int>(radius); for (const auto& hit : hits) fs << i++ << "\t" << hit.first << "\t" << hit.second << std::endl; fs.close(); } t2 = std::chrono::steady_clock::now(); std::cout << std::chrono::duration_cast<std::chrono::duration<float>>(t2 - t1).count() << "s" << std::endl; return 0; }
seqan::ArgumentParser::ParseResult parseCommandLine(SeqConsOptions & options, int argc, char const ** argv) { // Setup ArgumentParser. seqan::ArgumentParser parser("seqcons2"); // Set short description, version, and date. setShortDescription(parser, "Compute consensus from sequences."); setVersion(parser, SEQAN_APP_VERSION " [" SEQAN_REVISION "]"); setDate(parser, SEQAN_DATE); // Define usage line and long description. addUsageLine(parser, "\\fB-i\\fP \\fIINPUT.{fa,sam}\\fP [\\fB-oa\\fP \\fIOUT_ALIGN.{fa,sam}\\fP] " "[\\fB-oc\\fP \\fIOUT_CONSENSUS.fa\\fP]"); addDescription(parser, "Compute consensus from sequences with and without approximate alignment information."); // Overall Program Options addOption(parser, seqan::ArgParseOption("q", "quiet", "Set verbosity to a minimum.")); addOption(parser, seqan::ArgParseOption("v", "verbose", "Enable verbose output.")); addOption(parser, seqan::ArgParseOption("vv", "very-verbose", "Enable very verbose output.")); addOption(parser, seqan::ArgParseOption("m", "method", "Method to perform. See section \\fIMethods\\fP " "below for details.", seqan::ArgParseOption::STRING, "METHOD")); setValidValues(parser, "method", "nop realign align_consensus overlap_consensus contig_consensus pos_consensus"); setDefaultValue(parser, "method", "pos_consensus"); // I/O Options addSection(parser, "I/O Options"); addOption(parser, seqan::ArgParseOption("i", "input-file", "Input file.", seqan::ArgParseOption::INPUT_FILE, "INPUT")); setRequired(parser, "input-file", true); setValidValues(parser, "input-file", "sam fa fasta"); addOption(parser, seqan::ArgParseOption("oa", "output-alignment-file", "Output file with alignment.", seqan::ArgParseOption::OUTPUT_FILE, "OUT_ALIGNMENT")); setRequired(parser, "output-alignment-file", false); setValidValues(parser, "output-alignment-file", "sam txt"); addOption(parser, seqan::ArgParseOption("oc", "output-consensus-file", "Output file with consensus sequence.", seqan::ArgParseOption::OUTPUT_FILE, "OUT_CONSENSUS")); setRequired(parser, "output-consensus-file", false); setValidValues(parser, "output-consensus-file", "fa fasta"); // Alignment Quality Filter Options addSection(parser, "Alignment Quality Filter Options"); addOption(parser, seqan::ArgParseOption("", "overlap-min-length", "Minimal overlap length.", seqan::ArgParseOption::INTEGER, "LENGTH")); setMinValue(parser, "overlap-min-length", "0"); setDefaultValue(parser, "overlap-min-length", "20"); addOption(parser, seqan::ArgParseOption("", "overlap-max-error", "Maximal error rate in overlap as percentage.", seqan::ArgParseOption::DOUBLE, "RATE")); setMinValue(parser, "overlap-max-error", "0.0"); setDefaultValue(parser, "overlap-max-error", "5.0"); addOption(parser, seqan::ArgParseOption("", "overlap-min-count", "Minimal overlap count.", seqan::ArgParseOption::INTEGER, "COUNT")); setMinValue(parser, "overlap-min-count", "0"); setDefaultValue(parser, "overlap-min-count", "3"); addOption(parser, seqan::ArgParseOption("", "overlap-window-size", "Window size to look for alignments.", seqan::ArgParseOption::INTEGER, "SIZE")); setMinValue(parser, "overlap-window-size", "0"); setDefaultValue(parser, "overlap-window-size", "20"); // K-mer Filter Options addSection(parser, "K-Mer Filter Options"); addOption(parser, seqan::ArgParseOption("", "k-mer-size", "The k-mer size to use.", seqan::ArgParseOption::INTEGER, "LENGTH")); setMinValue(parser, "k-mer-size", "5"); setDefaultValue(parser, "k-mer-size", "20"); addOption(parser, seqan::ArgParseOption("", "k-mer-max-occ", "Ignore k-mer with higher occurence count, 0 to disable.", seqan::ArgParseOption::INTEGER, "COUNT")); setMinValue(parser, "k-mer-max-occ", "0"); setDefaultValue(parser, "k-mer-max-occ", "200"); // Realignment Options addSection(parser, "Realignment Options"); addOption(parser, seqan::ArgParseOption("", "realign-bandwidth", "Bandwidth to use for pairwise alignments in realignment.", seqan::ArgParseOption::INTEGER, "LENGTH")); setMinValue(parser, "realign-bandwidth", "5"); setDefaultValue(parser, "realign-bandwidth", "10"); addOption(parser, seqan::ArgParseOption("", "realign-environment", "Environment for extraction in realignment.", seqan::ArgParseOption::INTEGER, "COUNT")); setMinValue(parser, "realign-environment", "5"); setDefaultValue(parser, "realign-environment", "20"); // Add Methods Section addTextSection(parser, "Methods"); addListItem(parser, "\\fBnop\\fP", "Perform no action, just perform file conversion if possible."); addListItem(parser, "\\fBrealign\\fP", "Perform realignment, requires input to be a SAM file to provide approximate position " "information, creates consensus sequence after realignment."); addListItem(parser, "\\fBoverlap_consensus\\fP", "Perform MSA with overlap alignments of the input ignoring any given coordinates, then realign. " "This is most suited when computing the consensus of reads where the underlying sequence is very " "similar and most differences stem from sequencing errors and not genomic variation. All " "pairwise alignments computed here are banded."); addListItem(parser, "\\fBalign_consensus\\fP", "Perform MSA with global alignments of the input ignoring any given coordinates, then realign. " "This will computed unbanded global ends-gap free pairwise alignments. This is also suitable " "when aligning different sequences, e.g. clustered transcripts. Using this method, seqcons " "will be similar to calling SeqAn::T-Coffee, followed by realignment and consensus computation."); addListItem(parser, "\\fBcontig_consensus\\fP", "Perform MSA of the input, contig by contig, requires contig information, then realign. Input " "must be SAM."); addListItem(parser, "\\fBpos_consensus\\fP", "Perform consensus of the input, then realign. Requires approximate coordinate information in " "SAM file."); // Add Output Section addTextSection(parser, "Output Formats"); addText(parser, "The program can write out the consensus sequence in FASTA format and optionally the alignment of the " "input sequences against the consensus in SAM/BAM format. When using the extension \\fI.txt\\fP, seqcons " "will write out the MSA as a plain text visualization."); // Add Examples Section addTextSection(parser, "Examples"); addListItem(parser, "\\fBseqcons\\fP \\fB-m\\fP \\fIovl_consensus\\fP \\fB-i\\fP \\fIreads.fa\\fP \\fB-oa\\fP " "\\fIout.sam\\fP \\fB-oc\\fP \\fIcons.fa\\fP", "Compute MSA of the sequences in \\fIreads.fa\\fP. The consensus sequence is written to " "\\fIcons.fa\\fP and the alignment of the sequences in \\fIreads.fa\\fP is written to " "\\fIout.sam\\fP."); addListItem(parser, "\\fBseqcons\\fP \\fB-m\\fP \\fIrealign\\fP \\fB-i\\fP \\fIin.sam\\fP \\fB-oa\\fP \\fIout.sam\\fP", "Read in multi-read alignment from \\fIin.sam\\fP, refine it using Anson-Myers realignment and " "write out the refined alignment to \\fIout.sam\\fP"); // Parse command line. seqan::ArgumentParser::ParseResult res = seqan::parse(parser, argc, argv); // Only extract options if the program will continue after parseCommandLine() if (res != seqan::ArgumentParser::PARSE_OK) return res; // Extract option values. if (isSet(parser, "quiet")) options.verbosity = 0; if (isSet(parser, "verbose")) options.verbosity = 2; if (isSet(parser, "very-verbose")) options.verbosity = 3; std::string opStr; getOptionValue(opStr, parser, "method"); options.operation = strToMethod(opStr.c_str()); getOptionValue(options.inputFile, parser, "input-file"); getOptionValue(options.outputFileAlignment, parser, "output-alignment-file"); getOptionValue(options.outputFileConsensus, parser, "output-consensus-file"); getOptionValue(options.overlapMinLength, parser, "overlap-min-length"); getOptionValue(options.overlapMaxErrorRate, parser, "overlap-max-error"); getOptionValue(options.overlapWindowSize, parser, "overlap-window-size"); getOptionValue(options.kMerSize, parser, "k-mer-size"); getOptionValue(options.kMerMaxOcc, parser, "k-mer-max-occ"); getOptionValue(options.reAlignmentBandwidth, parser, "realign-bandwidth"); getOptionValue(options.reAlignmentEnvironment, parser, "realign-environment"); return seqan::ArgumentParser::PARSE_OK; }
seqan::ArgumentParser::ParseResult parseCommandLine(MasonGenomeOptions & options, int argc, char const ** argv) { // Setup ArgumentParser. seqan::ArgumentParser parser("mason_genome"); // Set short description, version, and date. setShortDescription(parser, "Random Genome Simulation"); setVersion(parser, "2.1"); setDate(parser, "March 2013"); setCategory(parser, "Simulators"); // Define usage line and long description. addUsageLine(parser, "[\\fIOPTIONS\\fP] [\\fB-l\\fP \\fILEN\\fP]+ \\fB-o\\fP \\fIOUT.fa\\fP"); addDescription(parser, "Simulate a random genome to the output file. For each \\fB-l\\fP/\\fB--contig-length\\fP " "entry, a contig with the given length will be simulated."); // We require one argument. addOption(parser, seqan::ArgParseOption("q", "quiet", "Set verbosity to a minimum.")); addOption(parser, seqan::ArgParseOption("v", "verbose", "Enable verbose output.")); addOption(parser, seqan::ArgParseOption("vv", "very-verbose", "Enable very verbose output.")); addSection(parser, "Simulation Configuration"); addOption(parser, seqan::ArgParseOption("l", "contig-length", "Length of the contig to simulate. Give one \\fB-l\\fP " "value for each contig to simulate.", seqan::ArgParseOption::INTEGER, "LENGTH", true)); setMinValue(parser, "contig-length", "1"); setRequired(parser, "contig-length"); addOption(parser, seqan::ArgParseOption("s", "seed", "The seed to use for the random number generator.", seqan::ArgParseOption::INTEGER, "INT")); setDefaultValue(parser, "seed", 0); addSection(parser, "Output Options"); addOption(parser, seqan::ArgParseOption("o", "out-file", "Output file.", seqan::ArgParseOption::OUTPUTFILE, "FILE")); setValidValues(parser, "out-file", "fa fasta"); setRequired(parser, "out-file"); // Add Examples Section. addTextSection(parser, "Examples"); addListItem(parser, "\\fBmason_genome\\fP \\fB-l\\fP 1000 \\fB-l\\fP 4000 \\fB-o\\fP \\fIgenome.fa\\fP", "Simulate a genome with two contigs of lengths 1000 and 4000 and write it to genome.fa."); // Parse command line. seqan::ArgumentParser::ParseResult res = seqan::parse(parser, argc, argv); // Only extract options if the program will continue after parseCommandLine() if (res != seqan::ArgumentParser::PARSE_OK) return res; // Extract option values. if (isSet(parser, "quiet")) options.verbosity = 0; if (isSet(parser, "verbose")) options.verbosity = 2; if (isSet(parser, "very-verbose")) options.verbosity = 3; getOptionValue(options.outputFilename, parser, "out-file"); getOptionValue(options.seed, parser, "seed"); for (unsigned i = 0; i < getOptionValueCount(parser, "contig-length"); ++i) { int len = 0; getOptionValue(len, parser, "contig-length", i); appendValue(options.contigLengths, len); } return seqan::ArgumentParser::PARSE_OK; }
void run(int argc, char* argv[], char* env[]) { U_TRACE(5, "Application::run(%d,%p,%p)", argc, argv, env) UApplication::run(argc, argv, env); U_SYSCALL_VOID_NO_PARAM(xmlInitParser); // init libxml LIBXML_TEST_VERSION // manage options num_args = (argc - optind); U_INTERNAL_DUMP("optind = %d num_args = %d", optind, num_args) if (UApplication::isOptions()) cfg_str = opt['c']; // manage file configuration if (cfg_str.empty()) cfg_str = U_STRING_FROM_CONSTANT("XAdES.ini"); // ---------------------------------------------------------------------------------------------------------------------------------- // XAdES signature - configuration parameters // ---------------------------------------------------------------------------------------------------------------------------------- // DigestAlgorithm md2 | md5 | sha | sha1 | sha224 | sha256 | sha384 | sha512 | mdc2 | ripmed160 // // SigningTime this property contains the time at which the signer claims to have performed the signing process (yes/no) // ClaimedRole this property contains claimed or certified roles assumed by the signer in creating the signature // // this property contains the indication of the purported place where the signer claims to have produced the signature // ------------------------------------------------------------------------------------------------------------------- // ProductionPlaceCity // ProductionPlaceStateOrProvince // ProductionPlacePostalCode // ProductionPlaceCountryName // ------------------------------------------------------------------------------------------------------------------- // // DataObjectFormatMimeType this property identifies the format of a signed data object (when electronic signatures // are not exchanged in a restricted context) to enable the presentation to the verifier or // use by the verifier (text, sound or video) in exactly the same way as intended by the signer // // CAStore // ArchiveTimeStamp the time-stamp token within this property covers the archive validation data // // SignatureTimeStamp the time-stamp token within this property covers the digital signature value element // Schema the pathname XML Schema of XAdES // ---------------------------------------------------------------------------------------------------------------------------------- cfg.UFile::setPath(cfg_str); UString x(U_CAPACITY); UServices::readEOF(STDIN_FILENO, x); if (x.empty()) U_ERROR("cannot read data from <stdin>"); (void) document.reserve(x.size()); UBase64::decode(x, document); if (document.empty()) U_ERROR("decoding data read failed"); // manage arguments... if ( U_DATA_URI && *U_DATA_URI == '\0') { U_ERROR("DATA_URI is mandatory"); } if ( U_X509 && *U_X509 == '\0') { U_ERROR("X509 is mandatory"); } if ( U_KEY_HANDLE && *U_KEY_HANDLE == '\0') { U_ERROR("KEY_HANDLE is mandatory"); } UCertificate cert(UString(U_X509)); if (cert.isValid() == false) U_ERROR("certificate not valid"); U_INTERNAL_DUMP("U_CA_STORE = %S", U_CA_STORE) xades_c = (U_CA_STORE != U_NULLPTR); digest_algorithm = getOptionValue(U_DIGEST_ALGORITHM, "DigestAlgorithm"); alg = u_dgst_get_algoritm(digest_algorithm.c_str()); if (alg == -1) U_ERROR("I can't find the digest algorithm for: %s", digest_algorithm.data()); signing_time = getOptionValue(U_SIGNING_TIME, "SigningTime").strtol(); claimed_role = getOptionValue(U_CLAIMED_ROLE, "ClaimedRole"); production_place_city = getOptionValue(U_PRODUCTION_PLACE_CITY, "ProductionPlaceCity"); production_place_state_or_province = getOptionValue(U_PRODUCTION_PLACE_STATE_OR_PROVINCE, "ProductionPlaceStateOrProvince"); production_place_postal_code = getOptionValue(U_PRODUCTION_PLACE_POSTAL_CODE, "ProductionPlacePostalCode"); production_place_country_name = getOptionValue(U_PRODUCTION_PLACE_COUNTRY_NAME, "ProductionPlaceCountryName"); data_object_format_mimetype = getOptionValue("", "DataObjectFormatMimeType"); if (xades_c == false) num_ca = 0; else { // XAdES-C // ------------------------------------------------------------------------------------------------------------- str_CApath = getOptionValue(U_CA_STORE, "CAStore"); signature_timestamp = getOptionValue(U_SIGNATURE_TIMESTAMP, "SignatureTimeStamp"); if (str_CApath.empty() || UServices::setupOpenSSLStore(U_NULLPTR, str_CApath.c_str()) == false) { U_ERROR("error on setting CA Store: %S", str_CApath.data()); } num_ca = cert.getSignerCertificates(vec_ca, U_NULLPTR, 0); if (UCertificate::verify_result == false) { UServices::setVerifyStatus(); U_ERROR("error on verifying the certificate: %.*s", u_buffer_len, u_buffer); } // ------------------------------------------------------------------------------------------------------------- } u_base64_max_columns = U_OPENSSL_BASE64_MAX_COLUMN; U_line_terminator_len = 2; UString modulus = cert.getModulus(), exponent = cert.getExponent(); X509IssuerName = cert.getIssuerForLDAP(), X509SubjectName = cert.getSubjectForLDAP(), X509Certificate = cert.getEncoded("DER"); X509SerialNumber = cert.getSerialNumber(); UString X509CertificateValue(U_CAPACITY), KeyInfo(U_CAPACITY); UBase64::encode(X509Certificate, X509CertificateValue); u_base64_max_columns = 0; KeyInfo.snprintf(U_CONSTANT_TO_PARAM(U_XMLDSIG_KEYINFO_TEMPLATE), U_STRING_TO_TRACE(modulus), U_STRING_TO_TRACE(exponent), U_STRING_TO_TRACE(X509SubjectName), U_STRING_TO_TRACE(X509IssuerName), X509SerialNumber, U_STRING_TO_TRACE(X509CertificateValue)); UString ObjectDigestValue(200U), Reference(U_CAPACITY), dataObjectFormat(U_CAPACITY), XMLDSIGReference(U_CAPACITY), XMLDSIGReferenceC14N(U_CAPACITY); // --------------------------------------------------------------------------------------------------------------- // check for OOffice or MS-Word document... // --------------------------------------------------------------------------------------------------------------- utility.handlerConfig(cfg); (void) utility.checkDocument(document, U_DATA_URI, true); // --------------------------------------------------------------------------------------------------------------- for (uint32_t i = 0, n = utility.vdocument.size(); i < n; ++i) { uri = utility.vuri[i]; to_digest = utility.vdocument[i]; // --------------------------------------------------------------------------------------------------------------- // 2. Compute the message digest of the text, m = Hash(C). // --------------------------------------------------------------------------------------------------------------- ObjectDigestValue.setEmpty(); UServices::generateDigest(alg, 0, to_digest, ObjectDigestValue, true); // --------------------------------------------------------------------------------------------------------------- Reference.snprintf(U_CONSTANT_TO_PARAM(U_XMLDSIG_REFERENCE_TEMPLATE), uri.c_str(), U_STRING_TO_TRACE(digest_algorithm), U_STRING_TO_TRACE(ObjectDigestValue)); XMLDSIGReference += Reference; XMLDSIGReferenceC14N += UXML2Document::xmlC14N(Reference); if (data_object_format_mimetype.empty() == false) { dataObjectFormat.snprintf(U_CONSTANT_TO_PARAM(U_XADES_DATA_OBJECT_FORMAT_TEMPLATE), uri.c_str(), U_STRING_TO_TRACE(data_object_format_mimetype)); DataObjectFormat += dataObjectFormat; } } setXAdESReference(); // XAdES management // --------------------------------------------------------------------------------------------------------------- // 3. Encapsulate the message digest in an XML <SignedInfo> element, SI, in canonicalized form. // --------------------------------------------------------------------------------------------------------------- UString SignedInfo(U_CONSTANT_SIZE(U_XMLDSIG_SIGNED_INFO_TEMPLATE) + XMLDSIGReference.size() + XAdESReference.size()); SignedInfo.snprintf(U_CONSTANT_TO_PARAM(U_XMLDSIG_SIGNED_INFO_TEMPLATE), U_STRING_TO_TRACE(digest_algorithm), U_STRING_TO_TRACE(XMLDSIGReference), U_STRING_TO_TRACE(XAdESReference)); UString to_sign = UXML2Document::xmlC14N(SignedInfo); // --------------------------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------------------------- // 4. Compute the RSA signatureValue of the canonicalized <SignedInfo> element, SV = RsaSign(Ks, SI). // --------------------------------------------------------------------------------------------------------------- UString SignatureValue(U_CAPACITY), signatureTimeStamp(U_CAPACITY), archiveTimeStamp(U_CAPACITY); u_base64_max_columns = U_OPENSSL_BASE64_MAX_COLUMN; ENGINE* e; # ifdef _MSWINDOWS_ e = UServices::loadEngine("HCSP", ENGINE_METHOD_RSA); x = U_KEY_HANDLE; # else e = U_NULLPTR; x = UFile::contentOf(UString(U_KEY_HANDLE)); if (x.empty() || (u_pkey = UServices::loadKey(x, U_NULLPTR, true, U_NULLPTR, e)) == U_NULLPTR) { U_ERROR("I can't load the private key: %S", U_KEY_HANDLE); } # ifdef HAVE_OPENSSL_98 if (cert.matchPrivateKey(u_pkey) == false) U_ERROR("the private key doesn't matches the public key of the certificate"); # endif x.clear(); # endif UString sign = UServices::getSignatureValue(alg, to_sign, x, UString::getStringNull(), true, e); u_base64_max_columns = 0; SignatureValue.snprintf(U_CONSTANT_TO_PARAM(U_XMLDSIG_SIGNATURE_VALUE_TEMPLATE), U_STRING_TO_TRACE(sign)); if (signature_timestamp.empty() == false) { to_digest = UXML2Document::xmlC14N(SignatureValue); UString token = getTimeStampToken(to_digest, signature_timestamp); signatureTimeStamp.snprintf(U_CONSTANT_TO_PARAM(U_XADES_SIGNATURE_TIMESTAMP_TEMPLATE), U_STRING_TO_TRACE(token)); } // XAdES-C // ------------------------------------------------------------------------------------------------------------- if (xades_c) setXAdESUnsignedSignatureProperties(); // ------------------------------------------------------------------------------------------------------------- (void) XAdESObject.reserve(U_CONSTANT_SIZE(U_XADES_TEMPLATE) + signedProperties.size() + unsignedSignatureProperties.size() + archiveTimeStamp.size() + signatureTimeStamp.size()); XAdESObject.snprintf(U_CONSTANT_TO_PARAM(U_XADES_TEMPLATE), U_STRING_TO_TRACE(signedProperties), U_STRING_TO_TRACE(unsignedSignatureProperties), U_STRING_TO_TRACE(archiveTimeStamp), U_STRING_TO_TRACE(signatureTimeStamp)); // --------------------------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------------------------- // 5. Compose the final XML document including the signatureValue, this time in non-canonicalized form. // --------------------------------------------------------------------------------------------------------------- UString output(U_CONSTANT_SIZE(U_XMLDSIG_TEMPLATE) + 8192U + SignedInfo.size() + SignatureValue.size() + XAdESObject.size()); if (utility.ooffice) { OpenDocumentStart = U_STRING_FROM_CONSTANT("<document-signatures xmlns=\"urn:oasis:names:tc:opendocument:xmlns:digitalsignature:1.0\">"); OpenDocumentEnd = U_STRING_FROM_CONSTANT("</document-signatures>"); } output.snprintf(U_CONSTANT_TO_PARAM(U_XMLDSIG_TEMPLATE), U_STRING_TO_TRACE(OpenDocumentStart), U_STRING_TO_TRACE(SignedInfo), U_STRING_TO_TRACE(SignatureValue), U_STRING_TO_TRACE(KeyInfo), U_STRING_TO_TRACE(XAdESObject), U_STRING_TO_TRACE(OpenDocumentEnd)); // --------------------------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------------------------- // check for OOffice or MS-Word document... // --------------------------------------------------------------------------------------------------------------- utility.outputDocument(output); // --------------------------------------------------------------------------------------------------------------- }