Code development platform for open source projects from the European Union institutions

Skip to content
Snippets Groups Projects
Commit 08e3f4ab authored by Markus Quaritsch's avatar Markus Quaritsch
Browse files

Merge pull request #443 in VECTO/vecto-sim from...

Merge pull request #443 in VECTO/vecto-sim from ~EMKRISPMI/vecto-sim:bugfix/VECTO-425-vectocmd-invalid-handle-progress to develop

* commit '8a46ab53':
  corrected error with joining paths of BaseDirectory
parents 905e4a1a 8a46ab53
No related branches found
No related tags found
No related merge requests found
......@@ -29,28 +29,28 @@
* Martin Rexeis, rexeis@ivt.tugraz.at, IVT, Graz University of Technology
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using TUGraz.VectoCore.Utils;
using TUGraz.VectoHashing;
namespace HashingCmd
{
class Program
{
public delegate void HashingAction(string filename, VectoHash h);
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using TUGraz.VectoCore.Utils;
using TUGraz.VectoHashing;
namespace HashingCmd
{
class Program
{
public delegate void HashingAction(string filename, VectoHash h);
private const string Usage = @"
hashingcmd.exe (-h | [-v] [[-s] -x] [-c] [-r]) <file.xml> <file2.xml> <file3.xml>
";
";
private const string Help = @"
hashingcmd.exe
......@@ -60,234 +60,235 @@ hashingcmd.exe
-x: validate generated XML against VECTO XML schema
-c: compute hash and write to stdout
-r: read hash from file and write to stdout
";
private static readonly Dictionary<string, HashingAction> Actions = new Dictionary<string, HashingAction> {
{ "-v", VerifyHashAction },
{ "-c", ComputeHashAction },
{ "-r", ReadHashAction },
{ "-s", CreateHashedFileAction }
};
static bool _validateXML;
private static bool xmlValid = true;
static int Main(string[] args)
{
try {
if (args.Contains("-h")) {
ShowVersionInformation();
Console.Write(Help);
return 0;
}
if (args.Contains("-x")) {
_validateXML = true;
}
var fileList = args.Except(Actions.Keys.Concat(new[] { "-x" })).ToArray();
if (fileList.Length == 0 || !args.Intersect(Actions.Keys.ToArray()).Any()) {
ShowVersionInformation();
Console.Write(Usage);
return 0;
}
foreach (var file in fileList) {
Console.Error.WriteLine("processing " + Path.GetFileName(file));
if (!File.Exists(Path.GetFullPath(file))) {
Console.Error.WriteLine("file " + Path.GetFullPath(file) + " not found!");
continue;
}
foreach (var arg in args) {
if (Actions.ContainsKey(arg)) {
try {
var h = VectoHash.Load(file);
Actions[arg](Path.GetFullPath(file), h);
} catch (Exception e) {
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine(e.Message);
if (e.InnerException != null) {
Console.Error.WriteLine(e.InnerException.Message);
}
Console.ResetColor();
}
}
}
}
} catch (Exception e) {
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine(e.Message);
Console.ResetColor();
//Console.Error.WriteLine("Please see log-file for further details (logs/log.txt)");
Environment.ExitCode = Environment.ExitCode != 0 ? Environment.ExitCode : 1;
}
#if DEBUG
Console.Error.WriteLine("done.");
if (!Console.IsInputRedirected)
Console.ReadKey();
#endif
return Environment.ExitCode;
}
private static void CreateHashedFileAction(string filename, VectoHash h)
{
var destination = Path.Combine(Path.GetDirectoryName(filename),
Path.GetFileNameWithoutExtension(filename) + "_hashed.xml");
if (File.Exists(destination)) {
Console.Error.WriteLine("hashed file already exists. overwrite? (y/n) ");
var key = Console.ReadKey(true);
while (!(key.KeyChar == 'y' || key.KeyChar == 'n')) {
Console.Error.WriteLine("overwrite? (y/n) ");
key = Console.ReadKey(true);
}
if (key.KeyChar == 'n') {
return;
}
Console.Error.WriteLine("overwriting file " + Path.GetFileName(destination));
} else {
Console.Error.WriteLine("creating file " + Path.GetFileName(destination));
}
var result = h.AddHash();
var writer = new XmlTextWriter(destination, Encoding.UTF8) {
Formatting = Formatting.Indented,
Indentation = 4
};
result.WriteTo(writer);
writer.Flush();
writer.Close();
if (_validateXML) {
ValidateXML(destination);
}
}
private static void ValidateXML(string filename)
{
try {
var settings = new XmlReaderSettings {
ValidationType = ValidationType.Schema,
ValidationFlags = //XmlSchemaValidationFlags.ProcessInlineSchema |
//XmlSchemaValidationFlags.ProcessSchemaLocation |
XmlSchemaValidationFlags.ReportValidationWarnings
};
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
settings.Schemas.Add(GetXMLSchema(""));
var vreader = XmlReader.Create(filename, settings);
var doc = new XmlDocument();
doc.Load(vreader);
doc.Validate(ValidationCallBack);
//while (vreader.Read()) {
// Console.WriteLine(vreader.Value);
//}
if (xmlValid) {
WriteLine("Valid", ConsoleColor.Green);
}
} catch (Exception e) {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Failed to validate hashed XML file!");
Console.Error.WriteLine(e.Message);
if (e.InnerException != null) {
Console.Error.WriteLine(e.InnerException.Message);
}
Console.ResetColor();
}
}
private static void ValidationCallBack(object sender, ValidationEventArgs args)
{
xmlValid = false;
if (args.Severity == XmlSeverityType.Error) {
throw new Exception(string.Format("Validation error: {0}" + Environment.NewLine +
"Line: {1}", args.Message, args.Exception.LineNumber));
} else {
Console.Error.WriteLine(string.Format("Validation warning: {0}" + Environment.NewLine +
"Line: {1}", args.Message, args.Exception.LineNumber));
}
}
private static XmlSchemaSet GetXMLSchema(string version)
{
var resource = RessourceHelper.LoadResourceAsStream(RessourceHelper.ResourceType.XMLSchema, "VectoComponent.xsd");
var xset = new XmlSchemaSet() { XmlResolver = new XmlResourceResolver() };
var reader = XmlReader.Create(resource, new XmlReaderSettings(), "schema://");
xset.Add(XmlSchema.Read(reader, null));
xset.Compile();
return xset;
}
private static void ReadHashAction(string filename, VectoHash h)
{
WriteLine("reading hashes");
var components = h.GetContainigComponents().GroupBy(s => s)
.Select(g => new { Entry = g.Key, Count = g.Count() });
foreach (var component in components) {
if (component.Entry == VectoComponents.Vehicle) {
continue;
}
for (var i = 0; i < component.Count; i++) {
var readHash = h.ReadHash(component.Entry, i);
WriteLine(" " + component.Entry.XMLElementName() + "\t ... " + readHash + "");
}
}
}
private static void ComputeHashAction(string filename, VectoHash h)
{
WriteLine("computing hashes");
var components = h.GetContainigComponents();
if (components.Count > 1) {
var grouped = components.GroupBy(s => s)
.Select(g => new { Entry = g.Key, Count = g.Count() });
foreach (var component in grouped) {
if (component.Entry == VectoComponents.Vehicle) {
continue;
}
for (var i = 0; i < component.Count; i++) {
var computedHash = h.ComputeHash(component.Entry, i);
WriteLine(" " + component.Entry.XMLElementName() + "\t ... " + computedHash + "");
}
}
var jobHash = h.ComputeHash();
WriteLine(" job file\t ... " + jobHash + "");
} else {
var hash = h.ComputeHash();
WriteLine(" computed hash: " + hash + "");
}
}
private static void VerifyHashAction(string filename, VectoHash h)
{
WriteLine("validating hashes");
var components = h.GetContainigComponents().GroupBy(s => s)
.Select(g => new { Entry = g.Key, Count = g.Count() });
foreach (var component in components) {
if (component.Entry == VectoComponents.Vehicle) {
continue;
}
for (var i = 0; i < component.Count; i++) {
var result = h.ValidateHash(component.Entry, i);
WriteLine(" " + component.Entry.XMLElementName() + "\t ... " + (result ? "valid" : "invalid"),
result ? ConsoleColor.Green : ConsoleColor.Red);
}
}
}
private static void WriteLine(string message, ConsoleColor foregroundColor = ConsoleColor.Gray)
{
Console.ForegroundColor = foregroundColor;
Console.WriteLine(message);
Console.ResetColor();
}
private static void ShowVersionInformation()
{
var hashingLib = Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + "VectoHashing.dll").GetName();
WriteLine(string.Format(@"HashingLibrary: {0}", hashingLib.Version));
}
}
";
private static readonly Dictionary<string, HashingAction> Actions = new Dictionary<string, HashingAction> {
{ "-v", VerifyHashAction },
{ "-c", ComputeHashAction },
{ "-r", ReadHashAction },
{ "-s", CreateHashedFileAction }
};
static bool _validateXML;
private static bool xmlValid = true;
static int Main(string[] args)
{
try {
if (args.Contains("-h")) {
ShowVersionInformation();
Console.Write(Help);
return 0;
}
if (args.Contains("-x")) {
_validateXML = true;
}
var fileList = args.Except(Actions.Keys.Concat(new[] { "-x" })).ToArray();
if (fileList.Length == 0 || !args.Intersect(Actions.Keys.ToArray()).Any()) {
ShowVersionInformation();
Console.Write(Usage);
return 0;
}
foreach (var file in fileList) {
Console.Error.WriteLine("processing " + Path.GetFileName(file));
if (!File.Exists(Path.GetFullPath(file))) {
Console.Error.WriteLine("file " + Path.GetFullPath(file) + " not found!");
continue;
}
foreach (var arg in args) {
if (Actions.ContainsKey(arg)) {
try {
var h = VectoHash.Load(file);
Actions[arg](Path.GetFullPath(file), h);
} catch (Exception e) {
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine(e.Message);
if (e.InnerException != null) {
Console.Error.WriteLine(e.InnerException.Message);
}
Console.ResetColor();
}
}
}
}
} catch (Exception e) {
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine(e.Message);
Console.ResetColor();
//Console.Error.WriteLine("Please see log-file for further details (logs/log.txt)");
Environment.ExitCode = Environment.ExitCode != 0 ? Environment.ExitCode : 1;
}
#if DEBUG
Console.Error.WriteLine("done.");
if (!Console.IsInputRedirected)
Console.ReadKey();
#endif
return Environment.ExitCode;
}
private static void CreateHashedFileAction(string filename, VectoHash h)
{
var destination = Path.Combine(Path.GetDirectoryName(filename),
Path.GetFileNameWithoutExtension(filename) + "_hashed.xml");
if (File.Exists(destination)) {
Console.Error.WriteLine("hashed file already exists. overwrite? (y/n) ");
var key = Console.ReadKey(true);
while (!(key.KeyChar == 'y' || key.KeyChar == 'n')) {
Console.Error.WriteLine("overwrite? (y/n) ");
key = Console.ReadKey(true);
}
if (key.KeyChar == 'n') {
return;
}
Console.Error.WriteLine("overwriting file " + Path.GetFileName(destination));
} else {
Console.Error.WriteLine("creating file " + Path.GetFileName(destination));
}
var result = h.AddHash();
var writer = new XmlTextWriter(destination, Encoding.UTF8) {
Formatting = Formatting.Indented,
Indentation = 4
};
result.WriteTo(writer);
writer.Flush();
writer.Close();
if (_validateXML) {
ValidateXML(destination);
}
}
private static void ValidateXML(string filename)
{
try {
var settings = new XmlReaderSettings {
ValidationType = ValidationType.Schema,
ValidationFlags = //XmlSchemaValidationFlags.ProcessInlineSchema |
//XmlSchemaValidationFlags.ProcessSchemaLocation |
XmlSchemaValidationFlags.ReportValidationWarnings
};
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
settings.Schemas.Add(GetXMLSchema(""));
var vreader = XmlReader.Create(filename, settings);
var doc = new XmlDocument();
doc.Load(vreader);
doc.Validate(ValidationCallBack);
//while (vreader.Read()) {
// Console.WriteLine(vreader.Value);
//}
if (xmlValid) {
WriteLine("Valid", ConsoleColor.Green);
}
} catch (Exception e) {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Failed to validate hashed XML file!");
Console.Error.WriteLine(e.Message);
if (e.InnerException != null) {
Console.Error.WriteLine(e.InnerException.Message);
}
Console.ResetColor();
}
}
private static void ValidationCallBack(object sender, ValidationEventArgs args)
{
xmlValid = false;
if (args.Severity == XmlSeverityType.Error) {
throw new Exception(string.Format("Validation error: {0}" + Environment.NewLine +
"Line: {1}", args.Message, args.Exception.LineNumber));
} else {
Console.Error.WriteLine(string.Format("Validation warning: {0}" + Environment.NewLine +
"Line: {1}", args.Message, args.Exception.LineNumber));
}
}
private static XmlSchemaSet GetXMLSchema(string version)
{
var resource = RessourceHelper.LoadResourceAsStream(RessourceHelper.ResourceType.XMLSchema, "VectoComponent.xsd");
var xset = new XmlSchemaSet() { XmlResolver = new XmlResourceResolver() };
var reader = XmlReader.Create(resource, new XmlReaderSettings(), "schema://");
xset.Add(XmlSchema.Read(reader, null));
xset.Compile();
return xset;
}
private static void ReadHashAction(string filename, VectoHash h)
{
WriteLine("reading hashes");
var components = h.GetContainigComponents().GroupBy(s => s)
.Select(g => new { Entry = g.Key, Count = g.Count() });
foreach (var component in components) {
if (component.Entry == VectoComponents.Vehicle) {
continue;
}
for (var i = 0; i < component.Count; i++) {
var readHash = h.ReadHash(component.Entry, i);
WriteLine(" " + component.Entry.XMLElementName() + "\t ... " + readHash + "");
}
}
}
private static void ComputeHashAction(string filename, VectoHash h)
{
WriteLine("computing hashes");
var components = h.GetContainigComponents();
if (components.Count > 1) {
var grouped = components.GroupBy(s => s)
.Select(g => new { Entry = g.Key, Count = g.Count() });
foreach (var component in grouped) {
if (component.Entry == VectoComponents.Vehicle) {
continue;
}
for (var i = 0; i < component.Count; i++) {
var computedHash = h.ComputeHash(component.Entry, i);
WriteLine(" " + component.Entry.XMLElementName() + "\t ... " + computedHash + "");
}
}
var jobHash = h.ComputeHash();
WriteLine(" job file\t ... " + jobHash + "");
} else {
var hash = h.ComputeHash();
WriteLine(" computed hash: " + hash + "");
}
}
private static void VerifyHashAction(string filename, VectoHash h)
{
WriteLine("validating hashes");
var components = h.GetContainigComponents().GroupBy(s => s)
.Select(g => new { Entry = g.Key, Count = g.Count() });
foreach (var component in components) {
if (component.Entry == VectoComponents.Vehicle) {
continue;
}
for (var i = 0; i < component.Count; i++) {
var result = h.ValidateHash(component.Entry, i);
WriteLine(" " + component.Entry.XMLElementName() + "\t ... " + (result ? "valid" : "invalid"),
result ? ConsoleColor.Green : ConsoleColor.Red);
}
}
}
private static void WriteLine(string message, ConsoleColor foregroundColor = ConsoleColor.Gray)
{
Console.ForegroundColor = foregroundColor;
Console.WriteLine(message);
Console.ResetColor();
}
private static void ShowVersionInformation()
{
var hashingLib = Assembly.LoadFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "VectoHashing.dll"))
.GetName();
WriteLine(string.Format(@"HashingLibrary: {0}", hashingLib.Version));
}
}
}
\ No newline at end of file
This diff is collapsed.
......@@ -29,158 +29,158 @@
* Martin Rexeis, rexeis@ivt.tugraz.at, IVT, Graz University of Technology
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using System.Xml.Linq;
using TUGraz.IVT.VectoXML.Writer;
using TUGraz.VectoCommon.Models;
using TUGraz.VectoCommon.Resources;
using TUGraz.VectoCommon.Utils;
using TUGraz.VectoCore.Models.Declaration;
using TUGraz.VectoCore.Models.Simulation.Data;
using TUGraz.VectoCore.Models.Simulation.Impl;
using TUGraz.VectoHashing;
namespace TUGraz.VectoCore.OutputData.XML
{
public class XMLCustomerReport
{
protected readonly XElement VehiclePart;
protected XElement InputDataIntegrity;
protected readonly XElement Results;
protected readonly XNamespace tns;
protected readonly XNamespace di;
private bool allSuccess = true;
public XMLCustomerReport()
{
di = "http://www.w3.org/2000/09/xmldsig#";
tns = "urn:tugraz:ivt:VectoAPI:COCOutput:v0.4";
VehiclePart = new XElement(tns + XMLNames.Component_Vehicle);
Results = new XElement(tns + "Results");
}
public void Initialize(VectoRunData modelData, Segment segment)
{
VehiclePart.Add(
new XElement(tns + XMLNames.Component_Model, modelData.VehicleData.ModelName),
new XElement(tns + XMLNames.Component_Manufacturer, modelData.VehicleData.Manufacturer),
new XElement(tns + XMLNames.Component_ManufacturerAddress, modelData.VehicleData.ManufacturerAddress),
new XElement(tns + XMLNames.Vehicle_VIN, modelData.VehicleData.VIN),
new XElement(tns + XMLNames.Vehicle_VehicleCategory, modelData.VehicleData.LegislativeClass),
new XElement(tns + "VehicleGroup", segment.VehicleClass.GetClassNumber()),
new XElement(tns + XMLNames.Vehicle_AxleConfiguration, modelData.VehicleData.AxleConfiguration.GetName()),
new XElement(tns + XMLNames.Vehicle_GrossVehicleMass, modelData.VehicleData.GrossVehicleWeight.ToXMLFormat(0)),
new XElement(tns + XMLNames.Vehicle_CurbMassChassis, modelData.VehicleData.CurbWeight.ToXMLFormat(0)),
new XElement(tns + "EngineRatedPower", modelData.EngineData.RatedPowerDeclared.ToXMLFormat(0)),
new XElement(tns + "EngineDisplacement",
modelData.EngineData.Displacement.ConvertTo().Cubic.Centi.Meter.ToXMLFormat(0)),
new XElement(tns + XMLNames.Engine_FuelType, modelData.EngineData.FuelType.ToXMLFormat()),
new XElement(tns + "TransmissionMainCertificationMethod", modelData.GearboxData.CertificationMethod.ToXMLFormat()),
new XElement(tns + XMLNames.Gearbox_TransmissionType, modelData.GearboxData.Type.ToXMLFormat()),
new XElement(tns + "GearsCount", modelData.GearboxData.Gears.Count),
new XElement(tns + "Retarder", modelData.Retarder.Type.IsDedicatedComponent()),
new XElement(tns + "AxleRatio", modelData.AxleGearData.AxleGear.Ratio.ToXMLFormat(3))
);
InputDataIntegrity = new XElement(tns + "InputDataSignature",
modelData.InputDataHash == null ? CreateDummySig() : new XElement(modelData.InputDataHash));
}
private XElement CreateDummySig()
{
return new XElement(di + XMLNames.DI_Signature_Reference,
new XElement(di + XMLNames.DI_Signature_Reference_DigestMethod,
new XAttribute(XMLNames.DI_Signature_Algorithm_Attr, "null")),
new XElement(di + XMLNames.DI_Signature_Reference_DigestValue, "NOT AVAILABLE")
);
}
public void AddResult(
DeclarationReport<XMLDeclarationReport.ResultEntry>.ResultContainer<XMLDeclarationReport.ResultEntry> entry)
{
foreach (var resultEntry in entry.ModData) {
allSuccess &= resultEntry.Value.Status == VectoRun.Status.Success;
Results.Add(new XElement(tns + "Result",
new XAttribute("status", resultEntry.Value.Status.ToString().ToLower()),
new XElement(tns + "Mission", entry.Mission.ToXMLFormat()),
GetResults(resultEntry)));
}
}
private object[] GetResults(KeyValuePair<LoadingType, XMLDeclarationReport.ResultEntry> resultEntry)
{
switch (resultEntry.Value.Status) {
case VectoRun.Status.Pending:
case VectoRun.Status.Running:
return null; // should not happen!
case VectoRun.Status.Success:
return GetSuccessResultEntry(resultEntry.Value);
case VectoRun.Status.Canceled:
case VectoRun.Status.Aborted:
return new object[] {
new XElement("Error", resultEntry.Value.Error)
};
default:
throw new ArgumentOutOfRangeException();
}
}
private object[] GetSuccessResultEntry(XMLDeclarationReport.ResultEntry result)
{
return new object[] {
new XElement(tns + "Payload", new XAttribute("unit", "kg"), result.Payload.ToXMLFormat(0)),
new XElement(tns + "FuelType", result.FuelType.ToXMLFormat()),
new XElement(tns + "AverageSpeed", new XAttribute("unit", "km/h"), result.AverageSpeed.AsKmph.ToXMLFormat(1)),
XMLDeclarationReport.GetResults(result, tns, false).Cast<object>().ToArray()
};
}
private XElement GetApplicationInfo()
{
var vectodll = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + "VectoCore.dll").GetName();
return new XElement(tns + "ApplicationInformation",
new XElement(tns + "SimulationToolVersion", vectodll.Version),
new XElement(tns + "Date", XmlConvert.ToString(DateTime.Now, XmlDateTimeSerializationMode.Utc)));
}
public void GenerateReport(XElement resultSignature)
{
var xsi = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");
var retVal = new XDocument();
var results = new XElement(Results);
results.AddFirst(new XElement(tns + "Status", allSuccess ? "success" : "error"));
var vehicle = new XElement(VehiclePart);
vehicle.Add(InputDataIntegrity);
retVal.Add(new XElement(tns + "VectoCustomerInformation",
new XAttribute("schemaVersion", "0.4"),
new XAttribute(XNamespace.Xmlns + "xsi", xsi.NamespaceName),
new XAttribute("xmlns", tns),
new XAttribute(XNamespace.Xmlns + "di", di),
new XAttribute(xsi + "schemaLocation",
string.Format("{0} {1}VectoCOC.xsd", tns, AbstractXMLWriter.SchemaLocationBaseUrl)),
new XElement(tns + "Data",
vehicle,
new XElement(tns + "ResultDataSignature", resultSignature),
results,
GetApplicationInfo())
)
);
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(retVal);
writer.Flush();
stream.Seek(0, SeekOrigin.Begin);
var h = VectoHash.Load(stream);
Report = h.AddHash();
}
public XDocument Report { get; private set; }
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using System.Xml.Linq;
using TUGraz.IVT.VectoXML.Writer;
using TUGraz.VectoCommon.Models;
using TUGraz.VectoCommon.Resources;
using TUGraz.VectoCommon.Utils;
using TUGraz.VectoCore.Models.Declaration;
using TUGraz.VectoCore.Models.Simulation.Data;
using TUGraz.VectoCore.Models.Simulation.Impl;
using TUGraz.VectoHashing;
namespace TUGraz.VectoCore.OutputData.XML
{
public class XMLCustomerReport
{
protected readonly XElement VehiclePart;
protected XElement InputDataIntegrity;
protected readonly XElement Results;
protected readonly XNamespace tns;
protected readonly XNamespace di;
private bool allSuccess = true;
public XMLCustomerReport()
{
di = "http://www.w3.org/2000/09/xmldsig#";
tns = "urn:tugraz:ivt:VectoAPI:COCOutput:v0.4";
VehiclePart = new XElement(tns + XMLNames.Component_Vehicle);
Results = new XElement(tns + "Results");
}
public void Initialize(VectoRunData modelData, Segment segment)
{
VehiclePart.Add(
new XElement(tns + XMLNames.Component_Model, modelData.VehicleData.ModelName),
new XElement(tns + XMLNames.Component_Manufacturer, modelData.VehicleData.Manufacturer),
new XElement(tns + XMLNames.Component_ManufacturerAddress, modelData.VehicleData.ManufacturerAddress),
new XElement(tns + XMLNames.Vehicle_VIN, modelData.VehicleData.VIN),
new XElement(tns + XMLNames.Vehicle_VehicleCategory, modelData.VehicleData.LegislativeClass),
new XElement(tns + "VehicleGroup", segment.VehicleClass.GetClassNumber()),
new XElement(tns + XMLNames.Vehicle_AxleConfiguration, modelData.VehicleData.AxleConfiguration.GetName()),
new XElement(tns + XMLNames.Vehicle_GrossVehicleMass, modelData.VehicleData.GrossVehicleWeight.ToXMLFormat(0)),
new XElement(tns + XMLNames.Vehicle_CurbMassChassis, modelData.VehicleData.CurbWeight.ToXMLFormat(0)),
new XElement(tns + "EngineRatedPower", modelData.EngineData.RatedPowerDeclared.ToXMLFormat(0)),
new XElement(tns + "EngineDisplacement",
modelData.EngineData.Displacement.ConvertTo().Cubic.Centi.Meter.ToXMLFormat(0)),
new XElement(tns + XMLNames.Engine_FuelType, modelData.EngineData.FuelType.ToXMLFormat()),
new XElement(tns + "TransmissionMainCertificationMethod", modelData.GearboxData.CertificationMethod.ToXMLFormat()),
new XElement(tns + XMLNames.Gearbox_TransmissionType, modelData.GearboxData.Type.ToXMLFormat()),
new XElement(tns + "GearsCount", modelData.GearboxData.Gears.Count),
new XElement(tns + "Retarder", modelData.Retarder.Type.IsDedicatedComponent()),
new XElement(tns + "AxleRatio", modelData.AxleGearData.AxleGear.Ratio.ToXMLFormat(3))
);
InputDataIntegrity = new XElement(tns + "InputDataSignature",
modelData.InputDataHash == null ? CreateDummySig() : new XElement(modelData.InputDataHash));
}
private XElement CreateDummySig()
{
return new XElement(di + XMLNames.DI_Signature_Reference,
new XElement(di + XMLNames.DI_Signature_Reference_DigestMethod,
new XAttribute(XMLNames.DI_Signature_Algorithm_Attr, "null")),
new XElement(di + XMLNames.DI_Signature_Reference_DigestValue, "NOT AVAILABLE")
);
}
public void AddResult(
DeclarationReport<XMLDeclarationReport.ResultEntry>.ResultContainer<XMLDeclarationReport.ResultEntry> entry)
{
foreach (var resultEntry in entry.ModData) {
allSuccess &= resultEntry.Value.Status == VectoRun.Status.Success;
Results.Add(new XElement(tns + "Result",
new XAttribute("status", resultEntry.Value.Status.ToString().ToLower()),
new XElement(tns + "Mission", entry.Mission.ToXMLFormat()),
GetResults(resultEntry)));
}
}
private object[] GetResults(KeyValuePair<LoadingType, XMLDeclarationReport.ResultEntry> resultEntry)
{
switch (resultEntry.Value.Status) {
case VectoRun.Status.Pending:
case VectoRun.Status.Running:
return null; // should not happen!
case VectoRun.Status.Success:
return GetSuccessResultEntry(resultEntry.Value);
case VectoRun.Status.Canceled:
case VectoRun.Status.Aborted:
return new object[] {
new XElement("Error", resultEntry.Value.Error)
};
default:
throw new ArgumentOutOfRangeException();
}
}
private object[] GetSuccessResultEntry(XMLDeclarationReport.ResultEntry result)
{
return new object[] {
new XElement(tns + "Payload", new XAttribute("unit", "kg"), result.Payload.ToXMLFormat(0)),
new XElement(tns + "FuelType", result.FuelType.ToXMLFormat()),
new XElement(tns + "AverageSpeed", new XAttribute("unit", "km/h"), result.AverageSpeed.AsKmph.ToXMLFormat(1)),
XMLDeclarationReport.GetResults(result, tns, false).Cast<object>().ToArray()
};
}
private XElement GetApplicationInfo()
{
var vectodll = Assembly.LoadFrom(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "VectoCore.dll")).GetName();
return new XElement(tns + "ApplicationInformation",
new XElement(tns + "SimulationToolVersion", vectodll.Version),
new XElement(tns + "Date", XmlConvert.ToString(DateTime.Now, XmlDateTimeSerializationMode.Utc)));
}
public void GenerateReport(XElement resultSignature)
{
var xsi = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");
var retVal = new XDocument();
var results = new XElement(Results);
results.AddFirst(new XElement(tns + "Status", allSuccess ? "success" : "error"));
var vehicle = new XElement(VehiclePart);
vehicle.Add(InputDataIntegrity);
retVal.Add(new XElement(tns + "VectoCustomerInformation",
new XAttribute("schemaVersion", "0.4"),
new XAttribute(XNamespace.Xmlns + "xsi", xsi.NamespaceName),
new XAttribute("xmlns", tns),
new XAttribute(XNamespace.Xmlns + "di", di),
new XAttribute(xsi + "schemaLocation",
string.Format("{0} {1}VectoCOC.xsd", tns, AbstractXMLWriter.SchemaLocationBaseUrl)),
new XElement(tns + "Data",
vehicle,
new XElement(tns + "ResultDataSignature", resultSignature),
results,
GetApplicationInfo())
)
);
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(retVal);
writer.Flush();
stream.Seek(0, SeekOrigin.Begin);
var h = VectoHash.Load(stream);
Report = h.AddHash();
}
public XDocument Report { get; private set; }
}
}
\ No newline at end of file
This diff is collapsed.
......@@ -29,217 +29,217 @@
* Martin Rexeis, rexeis@ivt.tugraz.at, IVT, Graz University of Technology
*/
using Microsoft.VisualBasic.FileIO;
using System;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using TUGraz.VectoCommon.Exceptions;
using TUGraz.VectoCommon.InputData;
using TUGraz.VectoCommon.Models;
using TUGraz.VectoCommon.Utils;
namespace TUGraz.VectoCore.Utils
{
/// <summary>
/// Class for Reading and Writing VECTO CSV Files.
/// </summary>
/// <remarks>
/// The following format applies to all CSV (Comma-separated values) Input Files used in VECTO:
/// List DELIMITER: Comma ","
/// Decimal-Mark: Dot "."
/// Comments: "#" at the beginning of the comment line. Number and position of comment lines is not limited.
/// Header: One header line (not a comment line) at the beginning of the file.
/// All Combinations between max-format and min-format possible. Only "id"-field is used.
/// max: id (name) [unit], id (name) [unit], ...
/// min: id,id,...
/// </remarks>
public static class VectoCSVFile
{
private static readonly Regex HeaderFilter = new Regex(@"\[.*?\]|\<|\>", RegexOptions.Compiled);
private const string Delimiter = ",";
private const string Comment = "#";
/// <summary>
/// Reads a CSV file which is stored in Vecto-CSV-Format.
/// </summary>
/// <param name="fileName">the filename</param>
/// <param name="ignoreEmptyColumns">set true, if empty columns should be ignored. default: false.</param>
/// <param name="fullHeader">set true is column names should be preserved. Otherwise units are trimed away. default: false.</param>
/// <returns>A DataTable which represents the CSV File.</returns>
public static TableData Read(string fileName, bool ignoreEmptyColumns = false, bool fullHeader = false)
{
try {
using (var fs = new FileStream(fileName, FileMode.Open)) {
var retVal = new TableData(fileName);
ReadCSV(retVal, fs, ignoreEmptyColumns, fullHeader);
return retVal;
}
} catch (Exception e) {
LogManager.GetLogger(typeof(VectoCSVFile).FullName).Error(e);
throw new VectoException("Error reading file {0}: {1}", fileName, e.Message);
}
}
/// <summary>
/// Reads a CSV file which is stored in Vecto-CSV-Format.
/// </summary>
/// <param name="stream">the stream to read</param>
/// <param name="ignoreEmptyColumns">set true, if empty columns should be ignored. default: false.</param>
/// <param name="fullHeader">set true is column names should be preserved. Otherwise units are trimed away. default: false.</param>
/// <param name="source"></param>
/// <returns>A DataTable which represents the CSV File.</returns>
public static TableData ReadStream(Stream stream, bool ignoreEmptyColumns = false, bool fullHeader = false,
string source = null)
{
var retVal = new TableData(source, DataSourceType.Embedded);
ReadCSV(retVal, stream, ignoreEmptyColumns, fullHeader);
return retVal;
}
private static void ReadCSV(DataTable table, Stream stream, bool ignoreEmptyColumns, bool fullHeader)
{
var p = new TextFieldParser(stream) {
TextFieldType = FieldType.Delimited,
Delimiters = new[] { Delimiter },
CommentTokens = new[] { Comment },
HasFieldsEnclosedInQuotes = true,
TrimWhiteSpace = true
};
string[] colsWithoutComment = { };
try {
var fields = p.ReadFields();
if (fields == null) {
throw new CSVReadException("CSV Read Error: File was empty.");
}
colsWithoutComment = fields
.Select(l => l.Contains(Comment) ? l.Substring(0, l.IndexOf(Comment, StringComparison.Ordinal)) : l)
.ToArray();
} catch (ArgumentNullException) {
throw new CSVReadException("CSV Read Error: File was empty.");
}
double tmp;
var columns = colsWithoutComment
.Select(l => fullHeader ? l : HeaderFilter.Replace(l, ""))
.Select(l => l.Trim())
.Where(col => !double.TryParse(col, NumberStyles.Any, CultureInfo.InvariantCulture, out tmp))
.Distinct()
.ToList();
var firstLineIsData = columns.Count == 0;
if (firstLineIsData) {
LogManager.GetLogger(typeof(VectoCSVFile).FullName)
.Warn("No valid Data Header found. Interpreting the first line as data line.");
// set the validColumns to: {"0", "1", "2", "3", ...} for all columns in first line.
columns = colsWithoutComment.Select((_, i) => i.ToString()).ToList();
}
//var table = new DataTable();
foreach (var col in columns) {
table.Columns.Add(col);
}
if (p.EndOfData) {
return;
}
var lineNumber = 1;
do {
string[] cells = { };
if (firstLineIsData) {
cells = colsWithoutComment;
} else {
var fields = p.ReadFields();
if (fields != null) {
cells = fields.Select(l => l.Contains(Comment) ? l.Substring(0, l.IndexOf(Comment, StringComparison.Ordinal)) : l)
.Select(s => s.Trim())
.ToArray();
}
}
firstLineIsData = false;
if (table.Columns.Count != cells.Length && !ignoreEmptyColumns) {
throw new CSVReadException(
string.Format("Line {0}: The number of values is not correct. Expected {1} Columns, Got {2} Columns",
lineNumber, table.Columns.Count, cells.Length));
}
try {
// ReSharper disable once CoVariantArrayConversion
table.Rows.Add(cells);
} catch (InvalidCastException e) {
throw new CSVReadException(
string.Format("Line {0}: The data format of a value is not correct. {1}", lineNumber, e.Message), e);
}
lineNumber++;
} while (!p.EndOfData);
}
/// <summary>
/// Writes the datatable to the csv file.
/// Uses the column caption as header (with fallback to column name) for the csv header.
/// </summary>
/// <param name="fileName">Path to the file.</param>
/// <param name="table">The Datatable.</param>
/// <param name="addVersionHeader"></param>
public static void Write(string fileName, DataTable table, bool addVersionHeader = false)
{
using (var sw = new StreamWriter(new FileStream(fileName, FileMode.Create), Encoding.UTF8)) {
Write(sw, table, addVersionHeader);
}
}
/// <summary>
/// writes the datatable to a csv file.
/// Uses the column caption as header (with fallback to column name) for the csv header.
/// <remarks>Note: the callee has to make suree to close the stream after use.</remarks>
/// </summary>
/// <param name="writer"></param>
/// <param name="table"></param>
/// <param name="addVersionHeader"></param>
public static void Write(StreamWriter writer, DataTable table, bool addVersionHeader = false)
{
if (writer == null) {
return;
}
if (addVersionHeader) {
var vectodll = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + "VectoCore.dll").GetName();
writer.WriteLine("# VECTO {0} - {1}", vectodll.Version, DateTime.Now.ToString("dd.MM.yyyy HH:mm"));
}
var header = table.Columns.Cast<DataColumn>().Select(col => col.Caption ?? col.ColumnName);
writer.WriteLine(string.Join(Delimiter, header));
var columnFormatter = new Func<SI, string>[table.Columns.Count];
for (var i = 0; i < table.Columns.Count; i++) {
var col = table.Columns[i];
var decimals = (uint?)col.ExtendedProperties["decimals"];
var outputFactor = (double?)col.ExtendedProperties["outputFactor"];
var showUnit = (bool?)col.ExtendedProperties["showUnit"];
columnFormatter[i] = item => item.ToOutputFormat(decimals, outputFactor, showUnit);
}
foreach (DataRow row in table.Rows) {
var items = row.ItemArray;
var formattedList = new string[items.Length];
for (var i = 0; i < items.Length; i++) {
var si = items[i] as SI;
formattedList[i] = si != null
? columnFormatter[i](si)
: formattedList[i] = string.Format(CultureInfo.InvariantCulture, "{0}", items[i]);
if (formattedList[i].Contains(Delimiter)) {
formattedList[i] = string.Format("\"{0}\"", formattedList[i]);
}
}
writer.WriteLine(string.Join(Delimiter, formattedList));
}
}
}
using Microsoft.VisualBasic.FileIO;
using System;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using TUGraz.VectoCommon.Exceptions;
using TUGraz.VectoCommon.InputData;
using TUGraz.VectoCommon.Models;
using TUGraz.VectoCommon.Utils;
namespace TUGraz.VectoCore.Utils
{
/// <summary>
/// Class for Reading and Writing VECTO CSV Files.
/// </summary>
/// <remarks>
/// The following format applies to all CSV (Comma-separated values) Input Files used in VECTO:
/// List DELIMITER: Comma ","
/// Decimal-Mark: Dot "."
/// Comments: "#" at the beginning of the comment line. Number and position of comment lines is not limited.
/// Header: One header line (not a comment line) at the beginning of the file.
/// All Combinations between max-format and min-format possible. Only "id"-field is used.
/// max: id (name) [unit], id (name) [unit], ...
/// min: id,id,...
/// </remarks>
public static class VectoCSVFile
{
private static readonly Regex HeaderFilter = new Regex(@"\[.*?\]|\<|\>", RegexOptions.Compiled);
private const string Delimiter = ",";
private const string Comment = "#";
/// <summary>
/// Reads a CSV file which is stored in Vecto-CSV-Format.
/// </summary>
/// <param name="fileName">the filename</param>
/// <param name="ignoreEmptyColumns">set true, if empty columns should be ignored. default: false.</param>
/// <param name="fullHeader">set true is column names should be preserved. Otherwise units are trimed away. default: false.</param>
/// <returns>A DataTable which represents the CSV File.</returns>
public static TableData Read(string fileName, bool ignoreEmptyColumns = false, bool fullHeader = false)
{
try {
using (var fs = new FileStream(fileName, FileMode.Open)) {
var retVal = new TableData(fileName);
ReadCSV(retVal, fs, ignoreEmptyColumns, fullHeader);
return retVal;
}
} catch (Exception e) {
LogManager.GetLogger(typeof(VectoCSVFile).FullName).Error(e);
throw new VectoException("Error reading file {0}: {1}", fileName, e.Message);
}
}
/// <summary>
/// Reads a CSV file which is stored in Vecto-CSV-Format.
/// </summary>
/// <param name="stream">the stream to read</param>
/// <param name="ignoreEmptyColumns">set true, if empty columns should be ignored. default: false.</param>
/// <param name="fullHeader">set true is column names should be preserved. Otherwise units are trimed away. default: false.</param>
/// <param name="source"></param>
/// <returns>A DataTable which represents the CSV File.</returns>
public static TableData ReadStream(Stream stream, bool ignoreEmptyColumns = false, bool fullHeader = false,
string source = null)
{
var retVal = new TableData(source, DataSourceType.Embedded);
ReadCSV(retVal, stream, ignoreEmptyColumns, fullHeader);
return retVal;
}
private static void ReadCSV(DataTable table, Stream stream, bool ignoreEmptyColumns, bool fullHeader)
{
var p = new TextFieldParser(stream) {
TextFieldType = FieldType.Delimited,
Delimiters = new[] { Delimiter },
CommentTokens = new[] { Comment },
HasFieldsEnclosedInQuotes = true,
TrimWhiteSpace = true
};
string[] colsWithoutComment = { };
try {
var fields = p.ReadFields();
if (fields == null) {
throw new CSVReadException("CSV Read Error: File was empty.");
}
colsWithoutComment = fields
.Select(l => l.Contains(Comment) ? l.Substring(0, l.IndexOf(Comment, StringComparison.Ordinal)) : l)
.ToArray();
} catch (ArgumentNullException) {
throw new CSVReadException("CSV Read Error: File was empty.");
}
double tmp;
var columns = colsWithoutComment
.Select(l => fullHeader ? l : HeaderFilter.Replace(l, ""))
.Select(l => l.Trim())
.Where(col => !double.TryParse(col, NumberStyles.Any, CultureInfo.InvariantCulture, out tmp))
.Distinct()
.ToList();
var firstLineIsData = columns.Count == 0;
if (firstLineIsData) {
LogManager.GetLogger(typeof(VectoCSVFile).FullName)
.Warn("No valid Data Header found. Interpreting the first line as data line.");
// set the validColumns to: {"0", "1", "2", "3", ...} for all columns in first line.
columns = colsWithoutComment.Select((_, i) => i.ToString()).ToList();
}
//var table = new DataTable();
foreach (var col in columns) {
table.Columns.Add(col);
}
if (p.EndOfData) {
return;
}
var lineNumber = 1;
do {
string[] cells = { };
if (firstLineIsData) {
cells = colsWithoutComment;
} else {
var fields = p.ReadFields();
if (fields != null) {
cells = fields.Select(l => l.Contains(Comment) ? l.Substring(0, l.IndexOf(Comment, StringComparison.Ordinal)) : l)
.Select(s => s.Trim())
.ToArray();
}
}
firstLineIsData = false;
if (table.Columns.Count != cells.Length && !ignoreEmptyColumns) {
throw new CSVReadException(
string.Format("Line {0}: The number of values is not correct. Expected {1} Columns, Got {2} Columns",
lineNumber, table.Columns.Count, cells.Length));
}
try {
// ReSharper disable once CoVariantArrayConversion
table.Rows.Add(cells);
} catch (InvalidCastException e) {
throw new CSVReadException(
string.Format("Line {0}: The data format of a value is not correct. {1}", lineNumber, e.Message), e);
}
lineNumber++;
} while (!p.EndOfData);
}
/// <summary>
/// Writes the datatable to the csv file.
/// Uses the column caption as header (with fallback to column name) for the csv header.
/// </summary>
/// <param name="fileName">Path to the file.</param>
/// <param name="table">The Datatable.</param>
/// <param name="addVersionHeader"></param>
public static void Write(string fileName, DataTable table, bool addVersionHeader = false)
{
using (var sw = new StreamWriter(new FileStream(fileName, FileMode.Create), Encoding.UTF8)) {
Write(sw, table, addVersionHeader);
}
}
/// <summary>
/// writes the datatable to a csv file.
/// Uses the column caption as header (with fallback to column name) for the csv header.
/// <remarks>Note: the callee has to make suree to close the stream after use.</remarks>
/// </summary>
/// <param name="writer"></param>
/// <param name="table"></param>
/// <param name="addVersionHeader"></param>
public static void Write(StreamWriter writer, DataTable table, bool addVersionHeader = false)
{
if (writer == null) {
return;
}
if (addVersionHeader) {
var vectodll = Assembly.LoadFrom(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "VectoCore.dll")).GetName();
writer.WriteLine("# VECTO {0} - {1}", vectodll.Version, DateTime.Now.ToString("dd.MM.yyyy HH:mm"));
}
var header = table.Columns.Cast<DataColumn>().Select(col => col.Caption ?? col.ColumnName);
writer.WriteLine(string.Join(Delimiter, header));
var columnFormatter = new Func<SI, string>[table.Columns.Count];
for (var i = 0; i < table.Columns.Count; i++) {
var col = table.Columns[i];
var decimals = (uint?)col.ExtendedProperties["decimals"];
var outputFactor = (double?)col.ExtendedProperties["outputFactor"];
var showUnit = (bool?)col.ExtendedProperties["showUnit"];
columnFormatter[i] = item => item.ToOutputFormat(decimals, outputFactor, showUnit);
}
foreach (DataRow row in table.Rows) {
var items = row.ItemArray;
var formattedList = new string[items.Length];
for (var i = 0; i < items.Length; i++) {
var si = items[i] as SI;
formattedList[i] = si != null
? columnFormatter[i](si)
: formattedList[i] = string.Format(CultureInfo.InvariantCulture, "{0}", items[i]);
if (formattedList[i].Contains(Delimiter)) {
formattedList[i] = string.Format("\"{0}\"", formattedList[i]);
}
}
writer.WriteLine(string.Join(Delimiter, formattedList));
}
}
}
}
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment