text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.IO.Packaging;
using System.Linq;
using System.Reflection;
using System.Security.Principal;
using System.Text;
using System.Xml.Linq;
using System.Xml;

namespace Novacode
{
    internal static class HelperFunctions
    {
        public const string DOCUMENT_DOCUMENTTYPE = "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml";
        public const string TEMPLATE_DOCUMENTTYPE = "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml";

            public static bool IsNullOrWhiteSpace(this string value)
            {
                if (value == null) return true;
                return string.IsNullOrEmpty(value.Trim());
            }

        /// <summary>
        /// Checks whether 'toCheck' has all children that 'desired' has and values of 'val' attributes are the same
        /// </summary>
        /// <param name="desired"></param>
        /// <param name="toCheck"></param>
        /// <param name="fo">Matching options whether check if desired attributes are inder a, or a has exactly and only these attributes as b has.</param>
        /// <returns></returns>
        internal static bool ContainsEveryChildOf(XElement desired, XElement toCheck, MatchFormattingOptions fo)
        {
            foreach (XElement e in desired.Elements())
            {
                // If a formatting property has the same name and 'val' attribute's value, its considered to be equivalent.
                if (!toCheck.Elements(e.Name).Where(bElement => bElement.GetAttribute(XName.Get("val", DocX.w.NamespaceName)) == e.GetAttribute(XName.Get("val", DocX.w.NamespaceName))).Any())
                    return false;
            }

            // If the formatting has to be exact, no additionaly formatting must exist.
            if (fo == MatchFormattingOptions.ExactMatch)
                return desired.Elements().Count() == toCheck.Elements().Count();

            return true;
        }
        internal static void CreateRelsPackagePart(DocX Document, Uri uri)
        {
            PackagePart pp = Document.package.CreatePart(uri, "application/vnd.openxmlformats-package.relationships+xml", CompressionOption.Maximum);
            using (TextWriter tw = new StreamWriter(pp.GetStream()))
            {
                XDocument d = new XDocument
                (
                    new XDeclaration("1.0", "UTF-8", "yes"),
                    new XElement(XName.Get("Relationships", DocX.rel.NamespaceName))
                );
                var root = d.Root;
                d.Save(tw);
            }
        }

        internal static int GetSize(XElement Xml)
        {
            switch (Xml.Name.LocalName)
            {
                case "tab":
                    return 1;
                case "br":
                    return 1;
                case "t":
                    goto case "delText";
                case "delText":
                    return Xml.Value.Length;
                case "tr":
                    goto case "br";
                case "tc":
                    goto case "br";
                default:
                    return 0;
            }
        }

        internal static string GetText(XElement e)
        {
            StringBuilder sb = new StringBuilder();
            GetTextRecursive(e, ref sb);
            return sb.ToString();
        }

        internal static void GetTextRecursive(XElement Xml, ref StringBuilder sb)
        {
            sb.Append(ToText(Xml));

            if (Xml.HasElements)
                foreach (XElement e in Xml.Elements())
                    GetTextRecursive(e, ref sb);
        }

        internal static List<FormattedText> GetFormattedText(XElement e)
        {
            List<FormattedText> alist = new List<FormattedText>();
            GetFormattedTextRecursive(e, ref alist);
            return alist;
        }

        internal static void GetFormattedTextRecursive(XElement Xml, ref List<FormattedText> alist)
        {
            FormattedText ft = ToFormattedText(Xml);
            FormattedText last = null;

            if (ft != null)
            {
                if (alist.Count() > 0)
                    last = alist.Last();

                if (last != null && last.CompareTo(ft) == 0)
                {
                    // Update text of last entry.
                    last.text += ft.text;
                }
                else
                {
                    if (last != null)
                        ft.index = last.index + last.text.Length;

                    alist.Add(ft);
                }
            }

            if (Xml.HasElements)
                foreach (XElement e in Xml.Elements())
                    GetFormattedTextRecursive(e, ref alist);
        }

        internal static FormattedText ToFormattedText(XElement e)
        {
            // The text representation of e.
            String text = ToText(e);
            if (text == String.Empty)
                return null;

            // e is a w:t element, it must exist inside a w:r element or a w:tabs, lets climb until we find it.
            while (!e.Name.Equals(XName.Get("r", DocX.w.NamespaceName)) &&
                   !e.Name.Equals(XName.Get("tabs", DocX.w.NamespaceName)))
                e = e.Parent;

            // e is a w:r element, lets find the rPr element.
            XElement rPr = e.Element(XName.Get("rPr", DocX.w.NamespaceName));

            FormattedText ft = new FormattedText();
            ft.text = text;
            ft.index = 0;
            ft.formatting = null;

            // Return text with formatting.
            if (rPr != null)
                ft.formatting = Formatting.Parse(rPr);

            return ft;
        }

        internal static string ToText(XElement e)
        {
            switch (e.Name.LocalName)
            {
                case "tab":
                    return "\t";
                case "br":
                    return "\n";
                case "t":
                    goto case "delText";
                case "delText":
                    {
                        if (e.Parent != null && e.Parent.Name.LocalName == "r")
                        {
                            XElement run = e.Parent;
                            var rPr = run.Elements().FirstOrDefault(a => a.Name.LocalName == "rPr");
                            if (rPr != null)
                            {
                                var caps = rPr.Elements().FirstOrDefault(a => a.Name.LocalName == "caps");

                                if (caps != null)
                                    return e.Value.ToUpper();
                            }
                        }

                        return e.Value;
                    }
                case "tr":
                    goto case "br";
                case "tc":
                    goto case "tab";
                default: return "";
            }
        }

        internal static XElement CloneElement(XElement element)
        {
            return new XElement
            (
                element.Name,
                element.Attributes(),
                element.Nodes().Select
                (
                    n =>
                    {
                        XElement e = n as XElement;
                        if (e != null)
                            return CloneElement(e);
                        return n;
                    }
                )
            );
        }

        internal static PackagePart CreateOrGetSettingsPart(Package package)
        {
            PackagePart settingsPart;

            Uri settingsUri = new Uri("/word/settings.xml", UriKind.Relative);
            if (!package.PartExists(settingsUri))
            {
                settingsPart = package.CreatePart(settingsUri, "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml", CompressionOption.Maximum);

                PackagePart mainDocumentPart = package.GetParts().Single(p => p.ContentType.Equals(DOCUMENT_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase) ||
                                                                              p.ContentType.Equals(TEMPLATE_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase));

                mainDocumentPart.CreateRelationship(settingsUri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings");

                XDocument settings = XDocument.Parse
                (@"<?xml version='1.0' encoding='utf-8' standalone='yes'?>
                <w:settings xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:r='http://schemas.openxmlformats.org/officeDocument/2006/relationships' xmlns:m='http://schemas.openxmlformats.org/officeDocument/2006/math' xmlns:v='urn:schemas-microsoft-com:vml' xmlns:w10='urn:schemas-microsoft-com:office:word' xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' xmlns:sl='http://schemas.openxmlformats.org/schemaLibrary/2006/main'>
                  <w:zoom w:percent='100' />
                  <w:defaultTabStop w:val='720' />
                  <w:characterSpacingControl w:val='doNotCompress' />
                  <w:compat />
                  <w:rsids>
                    <w:rsidRoot w:val='00217F62' />
                    <w:rsid w:val='001915A3' />
                    <w:rsid w:val='00217F62' />
                    <w:rsid w:val='00A906D8' />
                    <w:rsid w:val='00AB5A74' />
                    <w:rsid w:val='00F071AE' />
                  </w:rsids>
                  <m:mathPr>
                    <m:mathFont m:val='Cambria Math' />
                    <m:brkBin m:val='before' />
                    <m:brkBinSub m:val='--' />
                    <m:smallFrac m:val='off' />
                    <m:dispDef />
                    <m:lMargin m:val='0' />
                    <m:rMargin m:val='0' />
                    <m:defJc m:val='centerGroup' />
                    <m:wrapIndent m:val='1440' />
                    <m:intLim m:val='subSup' />
                    <m:naryLim m:val='undOvr' />
                  </m:mathPr>
                  <w:themeFontLang w:val='en-IE' w:bidi='ar-SA' />
                  <w:clrSchemeMapping w:bg1='light1' w:t1='dark1' w:bg2='light2' w:t2='dark2' w:accent1='accent1' w:accent2='accent2' w:accent3='accent3' w:accent4='accent4' w:accent5='accent5' w:accent6='accent6' w:hyperlink='hyperlink' w:followedHyperlink='followedHyperlink' />
                  <w:shapeDefaults>
                    <o:shapedefaults v:ext='edit' spidmax='2050' />
                    <o:shapelayout v:ext='edit'>
                      <o:idmap v:ext='edit' data='1' />
                    </o:shapelayout>
                  </w:shapeDefaults>
                  <w:decimalSymbol w:val='.' />
                  <w:listSeparator w:val=',' />
                </w:settings>"
                );

                XElement themeFontLang = settings.Root.Element(XName.Get("themeFontLang", DocX.w.NamespaceName));
                themeFontLang.SetAttributeValue(XName.Get("val", DocX.w.NamespaceName), CultureInfo.CurrentCulture);

                // Save the settings document.
                using (TextWriter tw = new StreamWriter(settingsPart.GetStream()))
                    settings.Save(tw);
            }
            else
                settingsPart = package.GetPart(settingsUri);
            return settingsPart;
        }

        internal static void CreateCustomPropertiesPart(DocX document)
        {
            PackagePart customPropertiesPart = document.package.CreatePart(new Uri("/docProps/custom.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.custom-properties+xml", CompressionOption.Maximum);

            XDocument customPropDoc = new XDocument
            (
                new XDeclaration("1.0", "UTF-8", "yes"),
                new XElement
                (
                    XName.Get("Properties", DocX.customPropertiesSchema.NamespaceName),
                    new XAttribute(XNamespace.Xmlns + "vt", DocX.customVTypesSchema)
                )
            );

            using (TextWriter tw = new StreamWriter(customPropertiesPart.GetStream(FileMode.Create, FileAccess.Write)))
                customPropDoc.Save(tw, SaveOptions.None);

            document.package.CreateRelationship(customPropertiesPart.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties");
        }

        internal static XDocument DecompressXMLResource(string manifest_resource_name)
        {
            // XDocument to load the compressed Xml resource into.
            XDocument document;

            // Get a reference to the executing assembly.
            Assembly assembly = Assembly.GetExecutingAssembly();

            // Open a Stream to the embedded resource.
            Stream stream = assembly.GetManifestResourceStream(manifest_resource_name);

            // Decompress the embedded resource.
            using (GZipStream zip = new GZipStream(stream, CompressionMode.Decompress))
            {
                // Load this decompressed embedded resource into an XDocument using a TextReader.
                using (TextReader sr = new StreamReader(zip))
                {
                    document = XDocument.Load(sr);
                }
            }

            // Return the decompressed Xml as an XDocument.
            return document;
        }

        /// <summary>
        /// If this document does not contain a /word/numbering.xml add the default one generated by Microsoft Word
        /// when the default bullet, numbered and multilevel lists are added to a blank document
        /// </summary>
        /// <param name="package"></param>
        /// <param name="mainDocumentPart"></param>
        /// <returns></returns>
        internal static XDocument AddDefaultNumberingXml(Package package)
        {
            XDocument numberingDoc;
            // Create the main document part for this package
            PackagePart wordNumbering = package.CreatePart(new Uri("/word/numbering.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml", CompressionOption.Maximum);

            numberingDoc = DecompressXMLResource("Novacode.Resources.numbering.xml.gz");

            // Save /word/numbering.xml
            using (TextWriter tw = new StreamWriter(wordNumbering.GetStream(FileMode.Create, FileAccess.Write)))
                numberingDoc.Save(tw, SaveOptions.None);

            PackagePart mainDocumentPart = package.GetParts().Single(p => p.ContentType.Equals(DOCUMENT_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase) ||
                                                                          p.ContentType.Equals(TEMPLATE_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase));

            mainDocumentPart.CreateRelationship(wordNumbering.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering");
            return numberingDoc;
        }

        /// <summary>
        /// If this document does not contain a /word/styles.xml add the default one generated by Microsoft Word.
        /// </summary>
        /// <param name="package"></param>
        /// <param name="mainDocumentPart"></param>
        /// <returns></returns>
        internal static XDocument AddDefaultStylesXml(Package package)
        {
            XDocument stylesDoc;
            // Create the main document part for this package
            PackagePart word_styles = package.CreatePart(new Uri("/word/styles.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml", CompressionOption.Maximum);

            stylesDoc = HelperFunctions.DecompressXMLResource("Novacode.Resources.default_styles.xml.gz");
            XElement lang = stylesDoc.Root.Element(XName.Get("docDefaults", DocX.w.NamespaceName)).Element(XName.Get("rPrDefault", DocX.w.NamespaceName)).Element(XName.Get("rPr", DocX.w.NamespaceName)).Element(XName.Get("lang", DocX.w.NamespaceName));
            lang.SetAttributeValue(XName.Get("val", DocX.w.NamespaceName), CultureInfo.CurrentCulture);

            // Save /word/styles.xml
            using (TextWriter tw = new StreamWriter(word_styles.GetStream(FileMode.Create, FileAccess.Write)))
                stylesDoc.Save(tw, SaveOptions.None);

            PackagePart mainDocumentPart = package.GetParts().Where
            (
                p => p.ContentType.Equals(DOCUMENT_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase)||p.ContentType.Equals(TEMPLATE_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase)
            ).Single();

            mainDocumentPart.CreateRelationship(word_styles.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles");
            return stylesDoc;
        }

        internal static XElement CreateEdit(EditType t, DateTime edit_time, object content)
        {
            if (t == EditType.del)
            {
                foreach (object o in (IEnumerable<XElement>)content)
                {
                    if (o is XElement)
                    {
                        XElement e = (o as XElement);
                        IEnumerable<XElement> ts = e.DescendantsAndSelf(XName.Get("t", DocX.w.NamespaceName));

                        for (int i = 0; i < ts.Count(); i++)
                        {
                            XElement text = ts.ElementAt(i);
                            text.ReplaceWith(new XElement(DocX.w + "delText", text.Attributes(), text.Value));
                        }
                    }
                }
            }

            return
            (
                new XElement(DocX.w + t.ToString(),
                    new XAttribute(DocX.w + "id", 0),
                    new XAttribute(DocX.w + "author", WindowsIdentity.GetCurrent().Name),
                    new XAttribute(DocX.w + "date", edit_time),
                content)
            );
        }

        internal static XElement CreateTable(int rowCount, int columnCount)
		{
			int[] columnWidths = new int[columnCount];
			for (int i = 0; i < columnCount; i++)
			{
				columnWidths[i] = 2310;
			}
			return CreateTable(rowCount, columnWidths);
		}

		internal static XElement CreateTable(int rowCount, int[] columnWidths)
        {
            XElement newTable =
            new XElement
            (
                XName.Get("tbl", DocX.w.NamespaceName),
                new XElement
                (
                    XName.Get("tblPr", DocX.w.NamespaceName),
                        new XElement(XName.Get("tblStyle", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), "TableGrid")),
                        new XElement(XName.Get("tblW", DocX.w.NamespaceName), new XAttribute(XName.Get("w", DocX.w.NamespaceName), "5000"), new XAttribute(XName.Get("type", DocX.w.NamespaceName), "auto")),
                        new XElement(XName.Get("tblLook", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), "04A0"))
                )
            );

            XElement tableGrid = new XElement(XName.Get("tblGrid", DocX.w.NamespaceName));
            for (int i = 0; i < columnWidths.Length; i++)
                tableGrid.Add(new XElement(XName.Get("gridCol", DocX.w.NamespaceName), new XAttribute(XName.Get("w", DocX.w.NamespaceName), XmlConvert.ToString(columnWidths[i]))));

            newTable.Add(tableGrid);

            for (int i = 0; i < rowCount; i++)
            {
                XElement row = new XElement(XName.Get("tr", DocX.w.NamespaceName));

                for (int j = 0; j < columnWidths.Length; j++)
                {
                    XElement cell = CreateTableCell();
                    row.Add(cell);
                }

                newTable.Add(row);
            }
            return newTable;
        }

        /// <summary>
        /// Create and return a cell of a table
        /// </summary>
        internal static XElement CreateTableCell()
        {
            return new XElement
                    (
                        XName.Get("tc", DocX.w.NamespaceName),
                            new XElement(XName.Get("tcPr", DocX.w.NamespaceName),
                            new XElement(XName.Get("tcW", DocX.w.NamespaceName),
                                    new XAttribute(XName.Get("w", DocX.w.NamespaceName), "2310"),
                                    new XAttribute(XName.Get("type", DocX.w.NamespaceName), "dxa"))),
                            new XElement(XName.Get("p", DocX.w.NamespaceName),
                                new XElement(XName.Get("pPr", DocX.w.NamespaceName)))
                    );
        }

        internal static List CreateItemInList(List list, string listText, int level = 0, ListItemType listType = ListItemType.Numbered, int? startNumber = null, bool trackChanges = false)
        {
            if (list.NumId == 0)
            {
                list.CreateNewNumberingNumId(level, listType);
            }

            if (!string.IsNullOrEmpty(listText))
            {
                var newParagraphSection = new XElement
                    (
                    XName.Get("p", DocX.w.NamespaceName),
                    new XElement(XName.Get("pPr", DocX.w.NamespaceName),
                                 new XElement(XName.Get("numPr", DocX.w.NamespaceName),
                                              new XElement(XName.Get("ilvl", DocX.w.NamespaceName), new XAttribute(DocX.w + "val", level)),
                                              new XElement(XName.Get("numId", DocX.w.NamespaceName), new XAttribute(DocX.w + "val", list.NumId)))),
                    new XElement(XName.Get("r", DocX.w.NamespaceName), new XElement(XName.Get("t", DocX.w.NamespaceName), listText))
                    );

                if (trackChanges)
                    newParagraphSection = CreateEdit(EditType.ins, DateTime.Now, newParagraphSection);

                if (startNumber == null)
                {
                    list.AddItem(new Paragraph(list.Document, newParagraphSection, 0, ContainerType.Paragraph));
                }
                else
                {
                    list.AddItemWithStartValue(new Paragraph(list.Document, newParagraphSection, 0, ContainerType.Paragraph), (int)startNumber);
                }
            }

            return list;
        }

        internal static void RenumberIDs(DocX document)
        {
            IEnumerable<XAttribute> trackerIDs =
                            (from d in document.mainDoc.Descendants()
                             where d.Name.LocalName == "ins" || d.Name.LocalName == "del"
                             select d.Attribute(XName.Get("id", "http://schemas.openxmlformats.org/wordprocessingml/2006/main")));

            for (int i = 0; i < trackerIDs.Count(); i++)
                trackerIDs.ElementAt(i).Value = i.ToString();
        }

        internal static Paragraph GetFirstParagraphEffectedByInsert(DocX document, int index)
        {
            // This document contains no Paragraphs and insertion is at index 0
            if (document.paragraphLookup.Keys.Count() == 0 && index == 0)
                return null;

            foreach (int paragraphEndIndex in document.paragraphLookup.Keys)
            {
                if (paragraphEndIndex >= index)
                    return document.paragraphLookup[paragraphEndIndex];
            }

            throw new ArgumentOutOfRangeException();
        }

        internal static List<XElement> FormatInput(string text, XElement rPr)
        {
            List<XElement> newRuns = new List<XElement>();
            XElement tabRun = new XElement(DocX.w + "tab");
            XElement breakRun = new XElement(DocX.w + "br");

            StringBuilder sb = new StringBuilder();

            if (string.IsNullOrEmpty(text))
            {
                return newRuns; //I dont wanna get an exception if text == null, so just return empy list
            }

            foreach (char c in text)
            {
                switch (c)
                {
                    case '\t':
                        if (sb.Length > 0)
                        {
                            XElement t = new XElement(DocX.w + "t", sb.ToString());
                            Novacode.Text.PreserveSpace(t);
                            newRuns.Add(new XElement(DocX.w + "r", rPr, t));
                            sb = new StringBuilder();
                        }
                        newRuns.Add(new XElement(DocX.w + "r", rPr, tabRun));
                        break;
                    case '\n':
                        if (sb.Length > 0)
                        {
                            XElement t = new XElement(DocX.w + "t", sb.ToString());
                            Novacode.Text.PreserveSpace(t);
                            newRuns.Add(new XElement(DocX.w + "r", rPr, t));
                            sb = new StringBuilder();
                        }
                        newRuns.Add(new XElement(DocX.w + "r", rPr, breakRun));
                        break;

                    default:
                        sb.Append(c);
                        break;
                }
            }

            if (sb.Length > 0)
            {
                XElement t = new XElement(DocX.w + "t", sb.ToString());
                Novacode.Text.PreserveSpace(t);
                newRuns.Add(new XElement(DocX.w + "r", rPr, t));
            }

            return newRuns;
        }

        internal static XElement[] SplitParagraph(Paragraph p, int index)
        {
            // In this case edit dosent really matter, you have a choice.
            Run r = p.GetFirstRunEffectedByEdit(index, EditType.ins);

            XElement[] split;
            XElement before, after;

            if (r.Xml.Parent.Name.LocalName == "ins")
            {
                split = p.SplitEdit(r.Xml.Parent, index, EditType.ins);
                before = new XElement(p.Xml.Name, p.Xml.Attributes(), r.Xml.Parent.ElementsBeforeSelf(), split[0]);
                after = new XElement(p.Xml.Name, p.Xml.Attributes(), r.Xml.Parent.ElementsAfterSelf(), split[1]);
            }
            else if (r.Xml.Parent.Name.LocalName == "del")
            {
                split = p.SplitEdit(r.Xml.Parent, index, EditType.del);

                before = new XElement(p.Xml.Name, p.Xml.Attributes(), r.Xml.Parent.ElementsBeforeSelf(), split[0]);
                after = new XElement(p.Xml.Name, p.Xml.Attributes(), r.Xml.Parent.ElementsAfterSelf(), split[1]);
            }
            else
            {
                split = Run.SplitRun(r, index);

                before = new XElement(p.Xml.Name, p.Xml.Attributes(), r.Xml.ElementsBeforeSelf(), split[0]);
                after = new XElement(p.Xml.Name, p.Xml.Attributes(), split[1], r.Xml.ElementsAfterSelf());
            }

            if (before.Elements().Count() == 0)
                before = null;

            if (after.Elements().Count() == 0)
                after = null;

            return new XElement[] { before, after };
        }

        /// <!--
        /// Bug found and fixed by trnilse. To see the change,
        /// please compare this release to the previous release using TFS compare.
        /// -->
        internal static bool IsSameFile(Stream streamOne, Stream streamTwo)
        {
            int file1byte, file2byte;

            if (streamOne.Length != streamOne.Length)
            {
                // Return false to indicate files are different
                return false;
            }

            // Read and compare a byte from each file until either a
            // non-matching set of bytes is found or until the end of
            // file1 is reached.
            do
            {
                // Read one byte from each file.
                file1byte = streamOne.ReadByte();
                file2byte = streamTwo.ReadByte();
            }
            while ((file1byte == file2byte) && (file1byte != -1));

            // Return the success of the comparison. "file1byte" is
            // equal to "file2byte" at this point only if the files are
            // the same.

            streamOne.Position = 0;
            streamTwo.Position = 0;

            return ((file1byte - file2byte) == 0);
        }

      internal static UnderlineStyle GetUnderlineStyle(string underlineStyle)
      {
        switch (underlineStyle)
        {
          case "single":
            return UnderlineStyle.singleLine;
          case "double":
            return UnderlineStyle.doubleLine;
          case "thick":
            return UnderlineStyle.thick;
          case "dotted":
            return UnderlineStyle.dotted;
          case "dottedHeavy":
            return UnderlineStyle.dottedHeavy;
          case "dash":
            return UnderlineStyle.dash;
          case "dashedHeavy":
            return UnderlineStyle.dashedHeavy;
          case "dashLong":
            return UnderlineStyle.dashLong;
          case "dashLongHeavy":
            return UnderlineStyle.dashLongHeavy;
          case "dotDash":
            return UnderlineStyle.dotDash;
          case "dashDotHeavy":
            return UnderlineStyle.dashDotHeavy;
          case "dotDotDash":
            return UnderlineStyle.dotDotDash;
          case "dashDotDotHeavy":
            return UnderlineStyle.dashDotDotHeavy;
          case "wave":
            return UnderlineStyle.wave;
          case "wavyHeavy":
            return UnderlineStyle.wavyHeavy;
          case "wavyDouble":
            return UnderlineStyle.wavyDouble;
          case "words":
            return UnderlineStyle.words;
          default:
            return UnderlineStyle.none;
        }
      }

    }
}


text:
<?php
/**
 * If you need an environment-specific system or application configuration,
 * there is an example in the documentation
 * @see https://docs.zendframework.com/tutorials/advanced-config/#environment-specific-system-configuration
 * @see https://docs.zendframework.com/tutorials/advanced-config/#environment-specific-application-configuration
 *
 * @see https://github.com/zendframework/ZendSkeletonApplication/blob/master/config/application.config.php
 */
return [
    // Retrieve list of modules used in this application.
    'modules' => require __DIR__ . '/modules.config.php',
    // These are various options for the listeners attached to the ModuleManager
    'module_listener_options' => [
        'config_cache_enabled' => false,
        'module_map_cache_enabled' => false,
        'check_dependencies' => true,

        'config_glob_paths' => [
            realpath(__DIR__) . '/test/*.php',
        ],
    ],
];

redpajama_set_name: RedPajamaGithub


text:
package org.jboss.pnc.dto.requests;

import org.jboss.pnc.dto.validation.constraints.SCMUrl;

import javax.validation.constraints.NotBlank;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;

import lombok.Builder;
import lombok.Data;
import org.jboss.pnc.dto.validation.groups.WhenCreatingNew;

/**
 * Request to create new SCM repository config with given URL.
 *
 * @author Honza Brázdil <jbrazdil@redhat.com>
 */
@Data
@Builder(builderClassName = "Builder")
@JsonDeserialize(builder = CreateAndSyncSCMRequest.Builder.class)
public class CreateAndSyncSCMRequest {

    /**
     * The SCM repository URL. The URL can be internal or external.
     */
    @NotBlank(groups = { WhenCreatingNew.class })
    @SCMUrl(groups = { WhenCreatingNew.class })
    private final String scmUrl;

    /**
     * Pre-builds sync enablement flag. Is taken into account only when scmUrl contains an external URL. Defaults to
     * true.
     */
    private final Boolean preBuildSyncEnabled;

    @JsonPOJOBuilder(withPrefix = "")
    public static final class Builder {
    }
}


text:
package blackdoor.auth;

import java.io.Serializable;

import blackdoor.auth.AuthRequest.Operation;
@Deprecated //See the Portunes project for more features and an SQL user database
public class AuthReply implements Serializable {
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	private boolean operationCompleted;
	private int id;
	private Operation operation;
	public String message;
	AuthReply(boolean operationCompleted, int id, Operation operation){
		this.operationCompleted = operationCompleted;
		this.id = id;
		this.operation = operation;
	}
	/**
	 * @return the operationCompleted
	 */
	public boolean isOperationCompleted() {
		return operationCompleted;
	}
	/**
	 * @param operationCompleted the operationCompleted to set
	 */
	public void setOperationCompleted(boolean operationCompleted) {
		this.operationCompleted = operationCompleted;
	}
	/**
	 * @return the id
	 */
	public int getId() {
		return id;
	}
	/**
	 * @param id the id to set
	 */
	public void setId(int id) {
		this.id = id;
	}
	/**
	 * @return the operation
	 */
	public Operation getOperation() {
		return operation;
	}
	/**
	 * @param operation the operation to set
	 */
	public void setOperation(Operation operation) {
		this.operation = operation;
	}

}


text:
typedef enum {
    BBPRevenueEvent,
    BBPStandardEvent
} BBPEventType;

@interface BBPEvent : NSObject

- (instancetype)initMonetaryEventWithName:(NSString *)name value:(double)value currency:(NSString *)currency;
- (instancetype)initWithName:(NSString *)name keyword:(NSString *)keyword;
- (instancetype)initWithName:(NSString *)name;

@property (assign, readonly) BBPEventType type;

- (NSDictionary *)payloadWithUserId:(NSString *)uuid;

@end


text:
var path = require('path');
var moduleExports = {};

// 源文件目录
moduleExports.staticRootDir = path.resolve(__dirname, '../../'); // 项目根目录
moduleExports.srcRootDir = path.resolve(moduleExports.staticRootDir, './src'); // 项目业务代码根目录
moduleExports.vendorDir = path.resolve(moduleExports.staticRootDir, './vendor'); // 存放所有不能用npm管理的第三方库
moduleExports.dllDir = path.resolve(moduleExports.srcRootDir, './dll'); // 存放由各种不常改变的js/css打包而来的dll
moduleExports.pagesDir = path.resolve(moduleExports.srcRootDir, './pages'); // 存放各个页面独有的部分,如入口文件、只有该页面使用到的css、模板文件等
moduleExports.publicDir = path.resolve(moduleExports.srcRootDir, './public-resource'); // 存放各个页面使用到的公共资源
moduleExports.logicDir = path.resolve(moduleExports.publicDir, './logic'); // 存放公用的业务逻辑
moduleExports.libsDir = path.resolve(moduleExports.publicDir, './libs');  // 与业务逻辑无关的库都可以放到这里
moduleExports.configDir = path.resolve(moduleExports.publicDir, './config'); // 存放各种配置文件
moduleExports.componentsDir = path.resolve(moduleExports.publicDir, './components'); // 存放组件,可以是纯HTML,也可以包含js/css/image等,看自己需要
moduleExports.layoutDir = path.resolve(moduleExports.publicDir, './layout'); // 存放UI布局,组织各个组件拼起来,因应需要可以有不同的布局套路

// 生成文件目录
moduleExports.buildDir = path.resolve(moduleExports.staticRootDir, './build'); // 存放编译后生成的所有代码、资源(图片、字体等,虽然只是简单的从源目录迁移过来)

module.exports = moduleExports;


text:
"use strict";

const serviceConfig = require('../../../app/lib/serviceConfig.js');
const { ServiceBroker } = require("moleculer");
const { ValidationError } = require("moleculer").Errors;
const { MoleculerClientError } = require("moleculer").Errors;
const path = require('path');

const createTestToken = (user) => ({
	id: (user ? user.id : '') || "123456",
	username: (user ? user.username : '') || "amy",
	role: (user ? user.role : '') || "user",
})
describe("Test 'Challenge' service", () => {

	describe("unregistered user", () => {
		let broker;
		beforeEach(async () => {
			serviceConfig.extend({ auth: { admins: [{provider: 'google', username: 'monica83' }] } });
			broker = new ServiceBroker(require('../../utils/getLoggerSettings.js')(path.resolve(__dirname, '..', '..'), __filename, expect.getState()));
			broker.createService({
					name: 'userStore',
					actions: {
						get: () => ({
							registered: false
						})
					}
			})
			const schemaBuilder = require(__dirname + "../../../../app/services/challenges/index.js");
			broker.createService(schemaBuilder(serviceConfig.data));
			await broker.start()
		});
		afterEach(() => broker.stop());

		it('should throw unauthorize error when getting user challenge',  async () => {
			expect(
				broker.call('challenges.getUserChallenge', { challengeId: '878768' }, {meta: {user: createTestToken()}})
			).rejects.toThrow(/must finish registration process/i)
		});

		it('should throw unauthorize error when updateing user challenge',  async () => {
			expect(
				broker.call('challenges.updateUserChallenge', { challengeId: '878768' }, {meta: {user: createTestToken()}})
			).rejects.toThrow(/must finish registration process/i)
		});
	});

	describe("registered user", () => {
		let broker;

		beforeEach(async () => {
			serviceConfig.extend({ auth: { admins: [{provider: 'google', username: 'monica83' }] } });
			broker = new ServiceBroker(require('../../utils/getLoggerSettings.js')(path.resolve(__dirname, '..', '..'), __filename, expect.getState()));
			broker.createService({
					name: 'userStore',
					actions: {
						get: () => ({
							registered: true
						})
					}
			})
			const schemaBuilder = require(__dirname + "../../../../app/services/challenges/index.js");
			broker.createService(schemaBuilder(serviceConfig.data));
			await broker.start();
		});

		afterEach(() => broker.stop());

		it('should return empty list of challenges by default',  async () => {
			const user = {
				username: 'john',
				role: 'user',
				id: '92864'
			}
			let result = await broker.call('challenges.listUserChallenges', {}, {meta: {user: createTestToken(user)}});
			expect(result).toHaveLength(0);
		});

		it('should create new challenge if does not exist on get operation',  async () => {
			const user = {
				username: 'john',
				role: 'user',
				id: '92864'
			}
			const challengeId = 'challenge-123456XYZ';
			let result = await broker.call('challenges.getUserChallenge', {challengeId}, {meta: {user: createTestToken(user)}});
			expect(result).toHaveProperty('id');
			expect(result).toHaveProperty('challengeId', challengeId);
			expect(result).toHaveProperty('userId', user.id);
			expect(result).toHaveProperty('code');
			expect(result).toHaveProperty('completed', false);
			expect(result).toHaveProperty('modifiedAt');
		});

		it('should return existing challenge if possible on get operation',  async () => {
			const user = {
				username: 'john',
				role: 'user',
				id: '92864'
			}
			const challengeId = 'challenge-123456XYZ';
			let challenge = await broker.call('challenges.getUserChallenge', {challengeId}, {meta: {user: createTestToken(user)}});
			let result = await broker.call('challenges.getUserChallenge', {challengeId}, {meta: {user: createTestToken(user)}});
			expect(result).toHaveProperty('id', challenge.id);
			expect(result).toHaveProperty('challengeId', challengeId);
			expect(result).toHaveProperty('userId', user.id);
			expect(result).toHaveProperty('code');
			expect(result).toHaveProperty('completed', false);
			expect(result).toHaveProperty('modifiedAt');
		});

		it('should create new challenge if does not exist on update operation',  async () => {
			const user = {
				username: 'john',
				role: 'user',
				id: '92864'
			}
			const challengeId = 'challenge-123456XYZ';
			const code = '//my sample 736432';
			const completed = true;
			let result = await broker.call('challenges.updateUserChallenge', {challengeId, code, completed}, {meta: {user: createTestToken(user)}});
			expect(result).toHaveProperty('id');
			expect(result).toHaveProperty('challengeId', challengeId);
			expect(result).toHaveProperty('userId', user.id);
			expect(result).toHaveProperty('code', code);
			expect(result).toHaveProperty('completed', completed);
			expect(result).toHaveProperty('modifiedAt');
		});

		it('should return existing challenge if possible on update operation',  async () => {
			const user = {
				username: 'john',
				role: 'user',
				id: '92864'
			}
			const challengeId = 'challenge-123456XYZ';
			const code = '//my sample 736432';
			const completed = true;
			let challenge = await broker.call('challenges.updateUserChallenge', {challengeId}, {meta: {user: createTestToken(user)}});
			let result = await broker.call('challenges.updateUserChallenge', {challengeId, code, completed}, {meta: {user: createTestToken(user)}});
			expect(result).toHaveProperty('id', challenge.id);
			expect(result).toHaveProperty('challengeId', challengeId);
			expect(result).toHaveProperty('userId', user.id);
			expect(result).toHaveProperty('code', code);
			expect(result).toHaveProperty('completed', completed);
			expect(result).toHaveProperty('modifiedAt');
		});

	});
});


text:
package com.github.kamekoopa.j8utils.utils;

import java.util.function.Function;

@FunctionalInterface
public interface FE1<A, X> {

	static <A, X> FE1<A, X> from(Function<? super A, ? extends X> f){
		return f::apply;
	}

	X apply(A a) throws Exception;
}


text:
package com.mpush.monitor.quota.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mpush.monitor.quota.MemoryQuota;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryPoolMXBean;
import java.util.List;
import java.util.Map;

public class JVMMemory implements MemoryQuota {

    private final List<String> permGenName = Lists.newArrayList("CMS Perm Gen", "Perm Gen", "PS Perm Gen", "G1 Perm Gen");

    private final List<String> oldGenName = Lists.newArrayList("CMS Old Gen", "Tenured Gen", "PS Old Gen", "G1 Old Gen");

    private final List<String> edenSpaceName = Lists.newArrayList("Par Eden Space", "Eden Space", "PS Eden Space", "G1 Eden");

    private final List<String> psSurvivorName = Lists.newArrayList("Par Survivor Space", "Survivor Space", "PS Survivor Space", "G1 Survivor");

    public static final JVMMemory I = new JVMMemory();

    private MemoryMXBean memoryMXBean;

    private MemoryPoolMXBean permGenMxBean;
    private MemoryPoolMXBean oldGenMxBean;
    private MemoryPoolMXBean edenSpaceMxBean;
    private MemoryPoolMXBean pSSurvivorSpaceMxBean;

    private JVMMemory() {
        memoryMXBean = ManagementFactory.getMemoryMXBean();
        List<MemoryPoolMXBean> list = ManagementFactory.getMemoryPoolMXBeans();
        for (MemoryPoolMXBean item : list) {
            String name = item.getName();
            if (permGenName.contains(name)) {
                permGenMxBean = item;
            } else if (oldGenName.contains(name)) {
                oldGenMxBean = item;
            } else if (edenSpaceName.contains(name)) {
                edenSpaceMxBean = item;
            } else if (psSurvivorName.contains(name)) {
                pSSurvivorSpaceMxBean = item;
            }
        }
    }

    @Override
    public long heapMemoryCommitted() {
        return memoryMXBean.getHeapMemoryUsage().getCommitted();
    }

    @Override
    public long heapMemoryInit() {
        return memoryMXBean.getHeapMemoryUsage().getInit();
    }

    @Override
    public long heapMemoryMax() {
        return memoryMXBean.getHeapMemoryUsage().getMax();
    }

    @Override
    public long heapMemoryUsed() {
        return memoryMXBean.getHeapMemoryUsage().getUsed();
    }

    @Override
    public long nonHeapMemoryCommitted() {
        return memoryMXBean.getNonHeapMemoryUsage().getCommitted();
    }

    @Override
    public long nonHeapMemoryInit() {
        return memoryMXBean.getNonHeapMemoryUsage().getInit();
    }

    @Override
    public long nonHeapMemoryMax() {
        return memoryMXBean.getNonHeapMemoryUsage().getMax();
    }

    @Override
    public long nonHeapMemoryUsed() {
        return memoryMXBean.getNonHeapMemoryUsage().getUsed();
    }

    @Override
    public long permGenCommitted() {
        if (permGenMxBean == null) {
            return 0;
        }
        return permGenMxBean.getUsage().getCommitted();
    }

    @Override
    public long permGenInit() {
        if (permGenMxBean == null) {
            return 0;
        }
        return permGenMxBean.getUsage().getInit();
    }

    @Override
    public long permGenMax() {
        if (permGenMxBean == null) {
            return 0;
        }
        return permGenMxBean.getUsage().getMax();
    }

    @Override
    public long permGenUsed() {
        if (permGenMxBean == null) {
            return 0;
        }
        return permGenMxBean.getUsage().getUsed();
    }

    @Override
    public long oldGenCommitted() {
        if (oldGenMxBean == null) {
            return 0;
        }
        return oldGenMxBean.getUsage().getCommitted();
    }

    @Override
    public long oldGenInit() {
        if (oldGenMxBean == null) {
            return 0;
        }
        return oldGenMxBean.getUsage().getInit();
    }

    @Override
    public long oldGenMax() {
        if (oldGenMxBean == null) {
            return 0;
        }
        return oldGenMxBean.getUsage().getMax();
    }

    @Override
    public long oldGenUsed() {
        if (oldGenMxBean == null) {
            return 0;
        }
        return oldGenMxBean.getUsage().getUsed();
    }

    @Override
    public long edenSpaceCommitted() {
        if (null == edenSpaceMxBean) {
            return 0;
        }
        return edenSpaceMxBean.getUsage().getCommitted();
    }

    @Override
    public long edenSpaceInit() {
        if (null == edenSpaceMxBean) {
            return 0;
        }
        return edenSpaceMxBean.getUsage().getInit();
    }

    @Override
    public long edenSpaceMax() {
        if (null == edenSpaceMxBean) {
            return 0;
        }
        return edenSpaceMxBean.getUsage().getMax();
    }

    @Override
    public long edenSpaceUsed() {
        if (null == edenSpaceMxBean) {
            return 0;
        }
        return edenSpaceMxBean.getUsage().getUsed();
    }

    @Override
    public long survivorCommitted() {
        if (null == pSSurvivorSpaceMxBean) {
            return 0;
        }
        return pSSurvivorSpaceMxBean.getUsage().getCommitted();
    }

    @Override
    public long survivorInit() {
        if (null == pSSurvivorSpaceMxBean) {
            return 0;
        }
        return pSSurvivorSpaceMxBean.getUsage().getInit();
    }

    @Override
    public long survivorMax() {
        if (null == pSSurvivorSpaceMxBean) {
            return 0;
        }
        return pSSurvivorSpaceMxBean.getUsage().getMax();
    }

    @Override
    public long survivorUsed() {
        if (null == pSSurvivorSpaceMxBean) {
            return 0;
        }
        return pSSurvivorSpaceMxBean.getUsage().getUsed();
    }

    @Override
    public Object monitor(Object... args) {
        Map<String, Object> map = Maps.newHashMap();
        map.put("heapMemoryCommitted", heapMemoryCommitted());
        map.put("heapMemoryInit", heapMemoryInit());
        map.put("heapMemoryMax", heapMemoryMax());
        map.put("heapMemoryUsed", heapMemoryUsed());
        map.put("nonHeapMemoryCommitted", nonHeapMemoryCommitted());
        map.put("nonHeapMemoryInit", nonHeapMemoryInit());
        map.put("nonHeapMemoryMax", nonHeapMemoryMax());
        map.put("nonHeapMemoryUsed", nonHeapMemoryUsed());
        map.put("permGenCommitted", permGenCommitted());
        map.put("permGenInit", permGenInit());
        map.put("permGenMax", permGenMax());
        map.put("permGenUsed", permGenUsed());
        map.put("oldGenCommitted", oldGenCommitted());
        map.put("oldGenInit", oldGenInit());
        map.put("oldGenMax", oldGenMax());
        map.put("oldGenUsed", oldGenUsed());
        map.put("edenSpaceCommitted", edenSpaceCommitted());
        map.put("edenSpaceInit", edenSpaceInit());
        map.put("edenSpaceMax", edenSpaceMax());
        map.put("edenSpaceUsed", edenSpaceUsed());
        map.put("survivorCommitted", survivorCommitted());
        map.put("survivorInit", survivorInit());
        map.put("survivorMax", survivorMax());
        map.put("survivorUsed", survivorUsed());
        return map;
    }
}


text:
package com.helger.as4.server.servlet;

import static org.junit.Assert.assertTrue;

import org.apache.http.HttpEntity;
import org.junit.Test;
import org.w3c.dom.Document;

import com.helger.as4.AS4TestConstants;
import com.helger.as4.crypto.AS4SigningParams;
import com.helger.as4.error.EEbmsError;
import com.helger.as4.http.HttpXMLEntity;
import com.helger.as4.messaging.crypto.AS4Signer;
import com.helger.as4.messaging.domain.AS4PullRequestMessage;
import com.helger.as4.messaging.domain.MessageHelperMethods;
import com.helger.as4.mgr.MetaAS4Manager;
import com.helger.as4.model.mpc.MPC;
import com.helger.as4.server.spi.MockMessageProcessorSPI;
import com.helger.as4.soap.ESOAPVersion;
import com.helger.as4.util.AS4ResourceHelper;
import com.helger.commons.collection.impl.CommonsArrayList;
import com.helger.commons.collection.impl.ICommonsList;
import com.helger.commons.io.resource.ClassPathResource;
import com.helger.xml.serialize.read.DOMReader;

public final class PullRequestTest extends AbstractUserMessageTestSetUpExt
{
  private final ESOAPVersion m_eSOAPVersion = ESOAPVersion.AS4_DEFAULT;

  @Test
  public void sendPullRequestSuccess () throws Exception
  {
    final AS4PullRequestMessage aPullReqMsg = AS4PullRequestMessage.create (m_eSOAPVersion,
                                                                            MessageHelperMethods.createEbms3MessageInfo (),
                                                                            AS4TestConstants.DEFAULT_MPC,
                                                                            null);
    Document aDoc = aPullReqMsg.getAsSOAPDocument ();

    final boolean bMustUnderstand = true;
    aDoc = AS4Signer.createSignedMessage (m_aCryptoFactory,
                                          aDoc,
                                          m_eSOAPVersion,
                                          aPullReqMsg.getMessagingID (),
                                          null,
                                          new AS4ResourceHelper (),
                                          bMustUnderstand,
                                          AS4SigningParams.createDefault ());

    final HttpEntity aEntity = new HttpXMLEntity (aDoc, m_eSOAPVersion);
    final String sResponse = sendPlainMessage (aEntity, true, null);

    assertTrue (sResponse.contains (AS4TestConstants.USERMESSAGE_ASSERTCHECK));
  }

  @Test
  public void sendPullRequestEmpty () throws Exception
  {
    // Special MPC name handled in MockMessageProcessorSPI
    final String sFailure = MockMessageProcessorSPI.MPC_EMPTY;
    final MPC aMPC = new MPC (sFailure);
    if (MetaAS4Manager.getMPCMgr ().getMPCOfID (sFailure) == null)
      MetaAS4Manager.getMPCMgr ().createMPC (aMPC);

    final Document aDoc = AS4PullRequestMessage.create (m_eSOAPVersion,
                                                        MessageHelperMethods.createEbms3MessageInfo (),
                                                        sFailure,
                                                        null)
                                               .getAsSOAPDocument ();

    final HttpEntity aEntity = new HttpXMLEntity (aDoc, m_eSOAPVersion);
    sendPlainMessage (aEntity, false, EEbmsError.EBMS_EMPTY_MESSAGE_PARTITION_CHANNEL.getErrorCode ());
  }

  @Test
  public void sendPullRequestFailure () throws Exception
  {
    // Special MPC name handled in MockMessageProcessorSPI
    final String sFailure = MockMessageProcessorSPI.MPC_FAILURE;
    final MPC aMPC = new MPC (sFailure);
    if (MetaAS4Manager.getMPCMgr ().getMPCOfID (sFailure) == null)
      MetaAS4Manager.getMPCMgr ().createMPC (aMPC);

    final Document aDoc = AS4PullRequestMessage.create (m_eSOAPVersion,
                                                        MessageHelperMethods.createEbms3MessageInfo (),
                                                        sFailure,
                                                        null)
                                               .getAsSOAPDocument ();
    final HttpEntity aEntity = new HttpXMLEntity (aDoc, m_eSOAPVersion);
    sendPlainMessage (aEntity, false, EEbmsError.EBMS_OTHER.getErrorCode ());
  }

  @Test
  public void sendPullRequestTwoSPIsFailure () throws Exception
  {
    final String sMPC = "TWO-SPI";
    final MPC aMPC = new MPC (sMPC);
    if (MetaAS4Manager.getMPCMgr ().getMPCOfID (sMPC) == null)
      MetaAS4Manager.getMPCMgr ().createMPC (aMPC);

    final Document aDoc = AS4PullRequestMessage.create (m_eSOAPVersion,
                                                        MessageHelperMethods.createEbms3MessageInfo (),
                                                        sMPC,
                                                        null)
                                               .getAsSOAPDocument ();
    final HttpEntity aEntity = new HttpXMLEntity (aDoc, m_eSOAPVersion);
    sendPlainMessage (aEntity, false, EEbmsError.EBMS_VALUE_INCONSISTENT.getErrorCode ());
  }

  @Test
  public void sendPullRequestSuccessTwoWayPushPull () throws Exception
  {
    // Depending on the payload a different EMEPBinding get chosen by
    // @MockPullRequestProcessorSPI
    // To Test the pull request part of the EMEPBinding
    final Document aPayload = DOMReader.readXMLDOM (new ClassPathResource ("testfiles/PushPull.xml"));
    final ICommonsList <Object> aAny = new CommonsArrayList <> ();
    aAny.add (aPayload.getDocumentElement ());

    final Document aDoc = AS4PullRequestMessage.create (m_eSOAPVersion,
                                                        MessageHelperMethods.createEbms3MessageInfo (),
                                                        AS4TestConstants.DEFAULT_MPC,
                                                        aAny)
                                               .getAsSOAPDocument ();
    final HttpEntity aEntity = new HttpXMLEntity (aDoc, m_eSOAPVersion);
    final String sResponse = sendPlainMessage (aEntity, true, null);

    assertTrue (sResponse.contains (AS4TestConstants.USERMESSAGE_ASSERTCHECK));
  }

  @Test
  public void sendPullRequestSuccessTwoWayPullPush () throws Exception
  {
    // Depending on the payload a different EMEPBinding get chosen by
    // @MockPullRequestProcessorSPI
    // To Test the pull request part of the EMEPBinding
    final Document aPayload = DOMReader.readXMLDOM (new ClassPathResource ("testfiles/PullPush.xml"));
    final ICommonsList <Object> aAny = new CommonsArrayList <> ();
    aAny.add (aPayload.getDocumentElement ());

    final Document aDoc = AS4PullRequestMessage.create (m_eSOAPVersion,
                                                        MessageHelperMethods.createEbms3MessageInfo (),
                                                        AS4TestConstants.DEFAULT_MPC,
                                                        aAny)
                                               .getAsSOAPDocument ();
    final HttpEntity aEntity = new HttpXMLEntity (aDoc, m_eSOAPVersion);
    final String sResponse = sendPlainMessage (aEntity, true, null);

    assertTrue (sResponse.contains (AS4TestConstants.USERMESSAGE_ASSERTCHECK));
  }

  @Test
  public void sendPullRequestWithNoMPC () throws Exception
  {
    final Document aDoc = AS4PullRequestMessage.create (m_eSOAPVersion,
                                                        MessageHelperMethods.createEbms3MessageInfo (),
                                                        null,
                                                        null)
                                               .getAsSOAPDocument ();
    final HttpEntity aEntity = new HttpXMLEntity (aDoc, m_eSOAPVersion);
    sendPlainMessage (aEntity, false, EEbmsError.EBMS_VALUE_NOT_RECOGNIZED.getErrorCode ());
  }
}


text:
package semanticsco.compositionandexecutioncontext;

import semanticsco.servicecomposition.CLMManager;
import semanticsco.extra.DataElement;
import semanticsco.extra.Service;
import semanticsco.servicecomposition.ServiceComposer;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.francetelecom.fl.causalLinkMatrix.entry.FT_SetOfTriples;
import org.francetelecom.fl.causalLinkMatrix.entry.FT_Triple;
import org.francetelecom.fl.causalLinkMatrix.label.FT_RowAndColumnLabel;

public class CompositionAndExecutionContext {

    //contextID = userID + sessionID (This allows to identify the user)
    public String contextID;

    //Store all details of all discovered services (it contains more info than the CLMManager)
    private HashMap<String,Service> discServices;

    //Store all details of services selected by user (it contains more info than the CLMManager)
    private HashMap<String,Service> selectedServices;

    //Causal Link Matrix (Keep track of discovered services, and their outputs)
    private CLMManager clm;

    //Store all service outputs IDs and service IDs to which the outputs belong to
    private HashMap<String,String> servOutputs;

    //Graph Composition (composition of services). Keep track of services that were executed and need to be executed
    private ServiceComposer graphComposition;

    //Store user-provided inputs for services - HashMap <SemanticType,ValidID_InAvailableValues>
    private HashMap<String, List<String>> userInputs;

    //Store context information = user profile/context info + executed services outputs
    private HashMap<String,DataElement> availableValues;

    //Store user context/profile information - <SemanticType, LIST{ValidID_InAvailableValues}>
    private HashMap<String, List<String>> userContextInfo;

    //Store services from the GraphComposition that are ready to be executed or being executed
    private List<String> activeServices;

    //Store services from the GraphComposition that have already been executed
    private List<String> executedServices;

    //Empty Constructor
    public CompositionAndExecutionContext() {

        //Initialize lists
        this.discServices = new HashMap<>();
        this.selectedServices = new HashMap<>();
        this.servOutputs = new HashMap<>();
        this.graphComposition = new ServiceComposer();
        this.userInputs = new HashMap<>();
        this.availableValues = new HashMap<>();
        this.userContextInfo = new HashMap<>();
        this.activeServices = new LinkedList<>();
        this.executedServices = new LinkedList<>();
    }

    //Change discovered services to cope with multiple instances
    public List<Service> changeDiscServices(List<Service> services){

        //For each discovered service
        for(int i=0; i<services.size(); i++){

            //For each previously selected service
            int count = 0;
            for (Map.Entry<String,Service> entry : selectedServices.entrySet()){
                if(entry.getKey().contains(services.get(i).getIdentifier()))
                    count++;
            }

            //Set service ID
            services.get(i).setIdentifier("inst" + (count+1) + services.get(i).getIdentifier());

            //Set service input IDs
            LinkedList<DataElement> inputs = services.get(i).getInputs();
            for(Iterator it=inputs.iterator();it.hasNext();){
                DataElement element = (DataElement) it.next();
                element.setServiceID(services.get(i).getIdentifier());
                element.setIdentifier("inst" + (count+1)+element.getIdentifier());
            }

            //Set service output IDs
            LinkedList<DataElement> outputs = services.get(i).getOutputs();
            for(Iterator it=outputs.iterator();it.hasNext();){
                DataElement element = (DataElement) it.next();
                element.setServiceID(services.get(i).getIdentifier());
                element.setIdentifier("inst" + (count+1)+element.getIdentifier());
            }

        }

        return services;

    }

    //Change discovered services to cope with multiple instances during ResolveServ invocation
    public List<Service> changeDiscServicesForResolve(List<Service> services){

        List<Service> changedServices = new LinkedList<>();

        //For each discovered service
        for(int i=0; i<services.size(); i++){

            //For each previously selected service
            int count = 0;
            for(Map.Entry<String,Service> entry : selectedServices.entrySet()){

                if(entry.getKey().contains(services.get(i).getIdentifier())){

                    Service previouslySelectedService = (Service)entry.getValue();

                    Service newService = new Service();
                    newService.setIdentifier(previouslySelectedService.getIdentifier());
                    newService.setName(services.get(i).getName());
                    newService.setDescription(services.get(i).getDescription());
                    newService.setLocation(services.get(i).getLocation());
                    newService.setNamespace(services.get(i).getNamespace());
                    newService.setInterfaces(services.get(i).getInterfaces());
                    newService.setFunctionValue(services.get(i).getFunctionValue());
                    newService.setInputValue(services.get(i).getInputValue());
                    newService.setOutputValue(services.get(i).getOutputValue());
                    newService.setFunctions(services.get(i).getFunctions());

                    String number = newService.getIdentifier().split("uddi:")[0];

                    LinkedList<DataElement> originalInputs = services.get(i).getInputs();
                    LinkedList<DataElement> newInputs = new LinkedList<>();
                    for(Iterator it=originalInputs.iterator();it.hasNext();){
                        DataElement originalElement = (DataElement) it.next();
                        DataElement newElement = new DataElement(number+originalElement.getIdentifier(),originalElement.getName(),originalElement.getSemanticConcept(),originalElement.getSyntacticalType(),newService.getIdentifier());
                        newInputs.add(newElement);
                    }
                    newService.setInputs(newInputs);

                    LinkedList<DataElement> originalOutputs = services.get(i).getOutputs();
                    LinkedList<DataElement> newOutputs = new LinkedList<>();
                    for(Iterator it=originalOutputs.iterator();it.hasNext();){
                        DataElement originalElement = (DataElement) it.next();
                        DataElement newElement = new DataElement(number+originalElement.getIdentifier(),originalElement.getName(),originalElement.getSemanticConcept(),originalElement.getSyntacticalType(),newService.getIdentifier());
                        newOutputs.add(newElement);
                    }
                    newService.setOutputs(newOutputs);

                    changedServices.add(newService);

                    count++;
                }
            }

            //Do this part if count == 0 or other value -------------------------------------------

            //Set service ID
            services.get(i).setIdentifier("inst" + (count+1) + services.get(i).getIdentifier());

            //Set service input IDs
            LinkedList<DataElement> inputs = services.get(i).getInputs();
            for(Iterator it=inputs.iterator();it.hasNext();){
                DataElement element = (DataElement) it.next();
                element.setServiceID(services.get(i).getIdentifier());
                element.setIdentifier("inst" + (count+1)+element.getIdentifier());
            }

            //Set service output IDs
            LinkedList<DataElement> outputs = services.get(i).getOutputs();
            for(Iterator it=outputs.iterator();it.hasNext();){
                DataElement element = (DataElement) it.next();
                element.setServiceID(services.get(i).getIdentifier());
                element.setIdentifier("inst" + (count+1)+element.getIdentifier());
            }
            changedServices.add(services.get(i));

            //-------------------------------------------------------------------------------------
        }

        return changedServices;

    }

    //Add discovered services to HashMap "DiscServices"
    public void addToDiscServices(List<Service> services){

        for(int i=0; i<services.size(); i++){
            if(!discServices.containsKey(services.get(i).getIdentifier()))
                discServices.put(services.get(i).getIdentifier(),services.get(i));
        }

    }

    //Return a service from the list of discovered services by its service ID
    public Service getDiscService(String serviceID){

	return discServices.get(serviceID);

    }

    //Add services to CLMManager
    public void addServCLM(List<Service> servicesToAdd){

        //Store services to be added to the CLMManager
        List<Service> listServices = new LinkedList<>();

	//Add all existing selected services to the list of services to be considered in the creation of the CLMManager
	Collection<Service> selecServs = this.selectedServices.values();

	//If some selected service was not previously selected
	if(!selecServs.containsAll(servicesToAdd)){

            //For each selected service
            for(Iterator it = servicesToAdd.iterator();it.hasNext();){

                Service s = (Service) it.next();

                //If selected service was not previously selected, add to list "listServices"
                if(!selecServs.contains(s))
                    listServices.add(s);
            }

            //Add all previously selected services to list "listServices"
            listServices.addAll(selecServs);

            //Create CLMManager with 1 row and 1 column, and no services
            CLMManager clmConstruction = new CLMManager(1, 1, null);

            //Compute the Causal Link Matrix with the list of selected services
            this.clm = clmConstruction.ComputeCLM(listServices);

        }

        //Else, if all selected services were previously selected, do nothing -> the CLMManager is not re-computed!

    }

    public boolean hasSelectedServiceKey(String serviceID){

        return this.selectedServices.containsKey(serviceID);

    }

    //Add service output ID and service ID to the servOutputs Hash, ensuring no duplicates
    public void addServOutput(String serviceId, String serviceOuputId) {

        if(!this.servOutputs.containsKey(serviceOuputId))
            this.servOutputs.put(serviceOuputId, serviceId);

    }

    /**
     * Add a service to the graph composition
     *
     * @param serviceID - the service to be added to the ServCompGraph
     *
    */
    public void addServToGraph(String serviceID) {

        //Add service to the ServCompGraph
	graphComposition.addServiceToGraph(discServices.get(serviceID),null,false);

    }

    /**
     * Add a service to the graph composition - Forward Composition!
     *
     * @param serviceID - the service to be added to the ServCompGraph, which has outputs to resolve
     * services (inputs) that are already in the service composition
     * @param composingServicesIDs - services to be composed with the new service
     *
    */
    public void addServToGraph(String serviceID, List<String> composingServicesIDs) {

        //Add service to the ServCompGraph
	if(serviceID != null)
            graphComposition.addServiceToGraph(discServices.get(serviceID),composingServicesIDs,true);

	//Close open nodes (services that had inputs composed after insertion of the newly added service)
	for(int i=0; i<composingServicesIDs.size(); i++)
            graphComposition.closeOpenNode(selectedServices.get(composingServicesIDs.get(i)));

    }

    /**
     * Close a service input (matched with a given service output)
     * It also checks if the node (service) can be closed, i.e., if all service inputs were resolved!
     *
     * @param service
     * @param inputID
     * @param outputID
    */
    public void closeInput(Service service, String inputID, String outputID) {

        //Add the outputID (a given service output) to the ExecutionValue of the Service Input
        //This allows to find the correct value in the CompositionAndExecutionContext.AvailableValues at execution time
	for(int i=0; i<service.getInputs().size(); i++){
            if(service.getInputs().get(i).getIdentifier().equals(inputID))
		service.getInputs().get(i).setExecutionValue(outputID);
	}

	//Tries to close the open node
	graphComposition.closeOpenNode(service);

    }

    //Check if a given input (inputConcept) has some user-provided value
    public boolean hasUserProvidedInput(String inputConcept){
        return this.userInputs.containsKey(inputConcept);
    }

    //Return user-provided values for a given input (inputConcept)
    public List<String> getUserProvidedInputs(String inputConcept){
        return this.userInputs.get(inputConcept);
    }

    //Return data element of a given service input/ouput
    public DataElement getAvailableValue(String elementID){
	return this.availableValues.get(elementID);
    }

    //Check if a given input (inputConcept) has some user-context info
    public boolean hasUserContextInfo(String inputConcept){
        return this.userContextInfo.containsKey(inputConcept);
    }

    //Return user-context info for a given input (inputConcept)
    public List<String> getUserContextInfo(String inputConcept){
        return this.userContextInfo.get(inputConcept);
    }

    /**
     * Find services whose outputs semantically match the requested input concepts.
     * It returns only the data element IDs, which allow to access the values using the getAvailableValue method
     *
     * @param serviceID
     * @param inputConcept input semantic concept
     * @return List of data element IDs that match the requested input concept
    */
    public List<String> findMatchingValues(String serviceID, String inputConcept){

	//Query CLMManager for all services whose outputs match the input semantic concept
	List<String> elementIDs = queriesCLMforOutput(serviceID,inputConcept);

	return elementIDs;
    }

    /**
     * Check if a given input concept is an output concept in the CLMManager. In case a given output
 (or similar concept) exists in the CLMManager, retrieve the services IDs that provide the outputs and
 the output IDs ("ServiceID;ElementID").
     * @param serviceID
     * @param inputConcept
     * @return
    */
    public List<String> queriesCLMforOutput(String serviceID, String inputConcept) {

        List<String> result = new LinkedList<>();

        //Get CLMManager rows and columns labels
	FT_RowAndColumnLabel RCLabel = clm.ft_getRcLabel();

	//For each CLMManager column (output concept)
	for (int i=0; i<clm.ft_getColumn(); i++) {

            //If there is some CLMManager output concept that match the given input concept
            if(((String)RCLabel.ft_getConcept(i)).compareTo(inputConcept) == 0) {

                //For each CLMManager row -> saves{ServiceID of matching services}
		for (int j=0; j<clm.ft_getRow(); j++) {

                    //Get set of triples of the CLMManager entry (j,i)
                    FT_SetOfTriples triples = clm.ft_getCellTriplets(j,i);

                    //If the set of triples is not empty
                    if (!(triples.isEmpty())) {

                        String tempServiceOutputID;
			String tempService;

                        //For each set of triples of the CLMManager entry (j,i)
                        FT_SetOfTriples setOftriple = (FT_SetOfTriples)clm.ft_getMatrix()[j][i];
			for(Iterator it= setOftriple.iterator();it.hasNext();) {

                            //Get triple
                            FT_Triple triple = (FT_Triple) it.next();

                            //Extract service properties
                            tempService = triple.ft_getFirst().toString();

                            //Extract service ID and ouput ID of the service
                            int beginIndex = tempService.indexOf("(");
                            int endIndexOfServ = tempService.indexOf(";");
                            String clmServiceID = tempService.substring(beginIndex + 1, endIndexOfServ);
                            int endIndexOutputID = tempService.indexOf(";", endIndexOfServ + 2);
                            tempServiceOutputID = tempService.substring(beginIndex+1, endIndexOutputID);

                            //If found service ID is not the given service ID
                            if(!clmServiceID.equals(serviceID)){

                                //Add service output ID to list servicesToRetrieveCheck, ensuring no duplicates
                                boolean exists = false;
                                for (int k=0; k<result.size(); k++) {
                                    if (result.get(k).equals(tempServiceOutputID))
                                        exists = true;
                                }
                                if (!exists)
                                    result.add(tempServiceOutputID);
                            }
                        }
                    }
                }
            }
        }

        return result;
    }

    //Return a service from the list of selected services by its service ID.
    public Service getSelectedService(String serviceID){

        return this.selectedServices.get(serviceID);
    }

    /**
     * Checks if in the GraphComposition the targetService is a children node of the
     * sourceService, i.e. there is a deadlock
     *
     * @param sourceService - active service.
     * @param targetService - service that may be composed with the active service.
     * @return true if deadlock is found, false otherwise
     */
    public boolean checkForDeadlock(Service sourceService, Service targetService) {

        //If source and target services are the same, deadlock is detected
        if(sourceService.getIdentifier().equals(targetService.getIdentifier()))
            return true;

        //Otherwise, check for deadlocks
        return graphComposition.checkDeadlocks(sourceService.getIdentifier(), targetService.getIdentifier());
    }

    //Add services to the list of selected services
    public void addToSeleServices(List<Service> services){

        //For each service to be added
        for(int i=0; i<services.size(); i++){

            //If the service was not already selected, add it to selected services
            if(!selectedServices.containsKey(services.get(i).getIdentifier()))
                selectedServices.put(services.get(i).getIdentifier(),services.get(i));
	}

    }

    /**
     * Stores the input ID of an available value provided by the user
     *
     * Each userInput element has a unique ID, which consists of the InputID + index.
     * Then, in case a service has several values provided for the same input, we can grant
 that all of the values can be used as suggestionValues, and can be correctly referred
 into the CompositionAndExecutionContext.AvailableValues.
     * @param serviceID
     * @param inputID
     * @return
    */
    public String addToUserInputs(String serviceID, String inputID) {

	String elementID = inputID;

	//Get input semantic concept
	String semanticConcept = "";
	for(int i=0; i<selectedServices.get(serviceID).getInputs().size(); i++){
            if (selectedServices.get(serviceID).getInputs().get(i).getIdentifier().equals(inputID))
                semanticConcept = selectedServices.get(serviceID).getInputs().get(i).getSemanticConcept();
	}

        //If input ID already exist in list "availableValues" (context info), add a random value to input ID
        if(this.getAvailableValue(inputID) != null)
            elementID = inputID +"-" + (int) (Math.random() * 10000);

	//If input concept is not already in the list "userInputs", add it to the list
        if(!userInputs.containsKey(semanticConcept))
            userInputs.put(semanticConcept, new LinkedList<String>());

        //Add input ID to the list "userInputs"
        userInputs.get(semanticConcept).add(elementID);

	return elementID;
    }

    //Store the values provided for service parameters or user information/context.
    public void addToAvailableValues(String serviceID, String elementID, String elemValue, String elemDescription){

	//Create new data element and store info provided by parameters (not all information need to be stored)
        DataElement de = new DataElement();
        de.setIdentifier(elementID); //Set ID
        de.setExecutionValue(elemValue); //Set execution value
        de.setName(elemDescription); //Set name
        de.setServiceID(serviceID); //Set service ID associated to this data element

        //Add data element to list "availableValues" (context info)
        availableValues.put(elementID,de);

    }

    /**
     * Add an execution value (user-provided or selected) to a selected service input.
     * In fact, do not add the value itself, but a reference to the value (Data Element ID)
     * Thus, when we want to execute this service we know which input value has to be used for its execution.
     * @param serviceID
     * @param inputID
     * @param inputValueID
    */
    public void addInputValueToSeleServ(String serviceID, String inputID, String inputValueID) {

        //Add/Overwrite execution value of service input
	for(int i=0; i<selectedServices.get(serviceID).getInputs().size(); i++){
            if(selectedServices.get(serviceID).getInputs().get(i).getIdentifier().equals(inputID))
            	selectedServices.get(serviceID).getInputs().get(i).setExecutionValue(inputValueID);
	}
    }

    //Return the service ID of the service associated to a given output
    public String getServiceIdOfOutput(String outputID) {

	return servOutputs.get(outputID);

    }

    /**
     * Tries to close a node (service) in the GraphComposition.
     *
     * @param service - the service to be closed
     * @return true if it closes the open node, or false if it cannot be closed (still require inputs)
     *
    */
    public boolean closeOpenNode(Service service) {

        //Tries to close the open node
	return graphComposition.closeOpenNode(service);

    }

    //Return the syntactical type of a selected service input
    public String getInputSyntacticalType(String serviceID, String inputID){

	String syntacticalType = "";
	for(int i=0; i<selectedServices.get(serviceID).getInputs().size(); i++){
            if (selectedServices.get(serviceID).getInputs().get(i).getIdentifier().equals(inputID))
                syntacticalType = selectedServices.get(serviceID).getInputs().get(i).getSyntacticalType();
	}

        return syntacticalType;
    }

    //Return the semantic type of a selected service input
    public String getInputSemanticType(String serviceID, String inputID){

	String semanticType = "";
	for(int i=0; i<selectedServices.get(serviceID).getInputs().size(); i++){
            if (selectedServices.get(serviceID).getInputs().get(i).getIdentifier().equals(inputID))
                semanticType = selectedServices.get(serviceID).getInputs().get(i).getSemanticConcept();
	}

        return semanticType;
    }

    //Return the syntactical type of a selected service output
    public String getOutputSyntacticalType(String serviceID, String outputID){

        String syntacticalType = "";
	for(int i=0; i<selectedServices.get(serviceID).getOutputs().size(); i++){
            if (selectedServices.get(serviceID).getOutputs().get(i).getIdentifier().equals(outputID))
                syntacticalType = selectedServices.get(serviceID).getOutputs().get(i).getSyntacticalType();
	}

        return syntacticalType;
    }

    //Return the open nodes (services)  from the graphComposition
    public List<String> getOpenNodes() {

	return graphComposition.getOpenNodes();

    }

    /**
     * Return the next services (IDs) from the service composition that are ready
     * to be executed.
     * @return
    */
    public List<String> nextServsToExec() {

    	//If the sets of active and executed services (nodes) are empty, i.e., the execution is going to start
	if(activeServices.isEmpty() && executedServices.isEmpty()){

            //Find the "root" nodes (with no incoming edges), which are the first nodes to be executed
            List<String> rootNodes = graphComposition.findRootNodes();

            //For each "root" node
            for(int i=0; i<rootNodes.size(); i++){

                //If service (node) is not opened, add it to list "activeServices"
		if(!getOpenNodes().contains(rootNodes.get(i)))
                    activeServices.add(rootNodes.get(i));

            }

	}//Else, if the execution already started, find the next services to be executed...
	else{

            //Gets all nodes (services) from graphComposition
            Set<String> graphNodes = graphComposition.getAllNodes();

            //For each node (service)
            Iterator it = graphNodes.iterator();
            while(it.hasNext()){

		//Get node ID of service to be analysed
		String nodeID = (String) it.next();

                //If the service was not already executed, is not opened and is not active
                //Removi esta parte do if p/ permitir que msm q 1 serviço tenha sido executado, ele pode ser de novo:
                // !executedServices.contains(nodeID) &&
                if(!graphComposition.getOpenNodes().contains(nodeID) && !activeServices.contains(nodeID)){

                    //Get all parent nodes (previous services) of service to be analysed
                    List<String> parentNodes = graphComposition.findParentNodes(nodeID);

                    //If its parent nodes were already executed or it has no parent nodes, add it to list "activeServices" (it can be executed)
                    if(executedServices.containsAll(parentNodes) || parentNodes.isEmpty())
                        activeServices.add(nodeID);

                }
            }
        }

        return activeServices;
    }

    //Move an executed service from the list "activeServices" to the list "executedServices"
    public void moveFromActiveToExecuted(String serviceID){

        //Remove service from list "activeServices"
        this.activeServices.remove(serviceID);

        //Add service to list "executedServices"
        this.executedServices.add(serviceID);
    }

    /**
     * Stores the ID of an available value from the user context information.
     *
     * It stores based on the semantic type of the user context info value, i.e., a
     * semantic type may have several context values (IDs) associate to them. The
     * IDs must be unique, so that the correct value can be accessed in the list
     * "availableValues".
     *
     * @param elementID
     * @param semtype
    */
    public void addToUserContextInfo(String elementID,String semtype) {

        //If semantic concept is not already contained in HashTable "userContextInfo", add it
        if(!userContextInfo.containsKey(semtype))
            userContextInfo.put(semtype, new LinkedList<String>());

        //Add elementID to list associated with the semtype
        userContextInfo.get(semtype).add(elementID);

    }

    //Clear user session context
    public void cleanContext() {

	this.contextID = null;
	this.clm = new CLMManager(1, 1, null);
	this.userContextInfo.clear();
	this.userInputs.clear();
	this.discServices.clear();
	this.selectedServices.clear();
	this.availableValues.clear();
	this.graphComposition = new ServiceComposer();
	this.activeServices = new LinkedList<>();

    }

}


text:
from enum import Enum, unique
from django.core.files.uploadedfile import InMemoryUploadedFile

# a decorator for converting a singular type into the array version
def array(cls):

	old_valid = cls.is_valid
	old_cast = cls.cast

	def new_valid(value):
		return all(map(old_valid, value))

	def new_cast(value):
		return list(map(old_cast, value))

	cls.is_valid = new_valid
	cls.cast = new_cast

	return cls

class ParamTypeBase(object):

	representation = ''

	@staticmethod
	def is_valid(value):
		raise NotImplementedError

	@staticmethod
	def cast(value):
		raise NotImplementedError

class Blob(ParamTypeBase):

	representation = 'blob'

	def is_valid(value):
		return isinstance(value, InMemoryUploadedFile)

	def cast(value):
		return value

class File(ParamTypeBase):

	representation = 'file'

	def is_valid(value):
		return True

	def cast(value):
		return value

class Float(ParamTypeBase):

	representation = 'float'

	def is_valid(value):
		return isinstance(value, float) or isinstance(value, int)

	def cast(value):
		return float(value)

@array
class FloatArray(Float):
	representation = 'float[]'

class Integer(ParamTypeBase):
	representation = 'integer'

	def is_valid(value):
		return isinstance(value, int)

	def cast(value):
		return value

@array
class IntegerArray(Integer):
	representation = 'integer[]'

class String(ParamTypeBase):
	representation = 'string'

	def is_valid(value):
		return isinstance(value, str)

	def cast(value):
		return value

@array
class StringArray(String):
	representation = 'string[]'

class Object(ParamTypeBase):
	representation = 'object'

	def is_valid(value):
		return isinstance(value, dict)

	def cast(value):
		return value

@array
class ObjectArray(Object):
	representation = 'object[]'

class Boolean(ParamTypeBase):
	representation = 'boolean'

	def is_valid(value):
		return isinstance(value, bool)

	def cast(value):
		return value

@array
class BooleanArray(Boolean):
	representation = 'boolean[]'

@unique
class Types(Enum):
	BLOB = Blob
	FILE = File
	BOOLEAN = Boolean
	BOOLEAN_ARRAY = BooleanArray
	FLOAT = Float
	FLOAT_ARRAY = FloatArray
	INTEGER = Integer
	INTEGER_ARRAY = IntegerArray
	STRING = String
	STRING_ARRAY = StringArray
	OBJECT = Object
	OBJECT_ARRAY = ObjectArray


text:
require 'spec_helper'

describe 'tripleo::profile::base::swift::ringbuilder' do
  shared_examples_for 'tripleo::profile::base::swift::ringbuilder' do

    let :pre_condition do
      "class { 'swift':
         swift_hash_path_prefix => 'foo',
       }"
    end

    context 'with step 2 and swift_ring_get_tempurl set' do
      let(:params) { {
        :step => 2,
        :replicas => 1,
        :swift_ring_get_tempurl=> 'http://something'
      } }

      it 'should fetch and extract swift rings' do
        is_expected.to contain_exec('fetch_swift_ring_tarball')
        is_expected.to contain_exec('extract_swift_ring_tarball')
      end
    end

    context 'with step 5 and swift_ring_put_tempurl set' do
      let(:params) { {
        :step => 5,
        :replicas => 1,
        :swift_ring_put_tempurl=> 'http://something'
      } }

      it 'should pack and upload swift rings' do
        is_expected.to contain_exec('create_swift_ring_tarball')
        is_expected.to contain_exec('upload_swift_ring_tarball')
      end
    end

  end

  on_supported_os.each do |os, facts|
    context "on #{os}" do
      let(:facts) do
        facts.merge(OSDefaults.get_facts({ :hostname => 'node.example.com' }))
      end

      it_behaves_like 'tripleo::profile::base::swift::ringbuilder'
    end
  end
end


text:
/*
 * $Id$
 */

/*

Copyright (c) 2000-2003 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.

*/

package org.lockss.poller;

import java.io.*;
import java.util.*;
import java.net.*;
import org.lockss.app.*;
import org.lockss.config.ConfigManager;
import org.lockss.daemon.*;
import org.lockss.plugin.*;
import org.lockss.protocol.*;
import org.lockss.util.*;
import org.lockss.test.*;
import org.lockss.repository.LockssRepositoryImpl;

/** JUnitTest case for class: org.lockss.poller.Poll */
public class TestV1PollTally extends LockssTestCase {
  private static Logger log = Logger.getLogger("TestV1PollTally");

  public void testConcatenateNullNameSubPollLists() {
    V1PollTally t1 = new MockV1PollTally();
    V1PollTally t2 = new MockV1PollTally();
    t1.localEntries = null;
    t2.localEntries = ListUtil.list("three", "fore");
    t2.setPreviousNamePollTally(t1);
    V1PollTally concatTally = t2.concatenateNameSubPollLists();
    assertSame(t1, concatTally);
    assertEquals(ListUtil.list("three", "fore"), t1.localEntries);

    t1.localEntries = ListUtil.list("three", "fore");
    t2.localEntries = null;
    t2.setPreviousNamePollTally(t1);
    concatTally = t2.concatenateNameSubPollLists();
    assertSame(t1, concatTally);
    assertEquals(ListUtil.list("three", "fore"), t1.localEntries);
  }

  public void testConcatenateNameSubPollLists() {
    V1PollTally t1 = new MockV1PollTally();
    V1PollTally t2 = new MockV1PollTally();
    V1PollTally t3 = new MockV1PollTally();
    t1.localEntries = ListUtil.list("one", "two");
    t2.localEntries = ListUtil.list("three", "fore");
    t3.localEntries = ListUtil.list("five", "sicks");
    t2.setPreviousNamePollTally(t1);
    t3.setPreviousNamePollTally(t2);
    V1PollTally concatTally = t3.concatenateNameSubPollLists();
    assertSame(t1, concatTally);
    assertEquals(ListUtil.list("one", "two", "three", "fore", "five", "sicks"),
		 t1.localEntries);
  }

  class MockV1PollTally extends V1PollTally {
    MockV1PollTally() {
      super(Poll.V1_NAME_POLL, 0, 4, 0, 0, 0, 0, 3, null);
    }
  }

}