text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Xml.Linq;
using Microsoft.Extensions.Options;
using NPoco;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.Hosting;
using Umbraco.Cms.Core.IO;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Packaging;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Infrastructure.Persistence.Dtos;
using Umbraco.Extensions;
using File = System.IO.File;

namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement
{
    /// <inheritdoc />
    public class CreatedPackageSchemaRepository : ICreatedPackagesRepository
    {
        private readonly PackageDefinitionXmlParser _xmlParser;
        private readonly IUmbracoDatabase? _umbracoDatabase;
        private readonly IHostingEnvironment _hostingEnvironment;
        private readonly FileSystems _fileSystems;
        private readonly IEntityXmlSerializer _serializer;
        private readonly IDataTypeService _dataTypeService;
        private readonly ILocalizationService _localizationService;
        private readonly IFileService _fileService;
        private readonly IMediaService _mediaService;
        private readonly IMediaTypeService _mediaTypeService;
        private readonly IContentService _contentService;
        private readonly MediaFileManager _mediaFileManager;
        private readonly IMacroService _macroService;
        private readonly IContentTypeService _contentTypeService;
        private readonly string _tempFolderPath;
        private readonly string _createdPackagesFolderPath;

        /// <summary>
        /// Initializes a new instance of the <see cref="CreatedPackageSchemaRepository"/> class.
        /// </summary>
        public CreatedPackageSchemaRepository(
            IUmbracoDatabaseFactory umbracoDatabaseFactory,
            IHostingEnvironment hostingEnvironment,
            IOptions<GlobalSettings> globalSettings,
            FileSystems fileSystems,
            IEntityXmlSerializer serializer,
            IDataTypeService dataTypeService,
            ILocalizationService localizationService,
            IFileService fileService,
            IMediaService mediaService,
            IMediaTypeService mediaTypeService,
            IContentService contentService,
            MediaFileManager mediaFileManager,
            IMacroService macroService,
            IContentTypeService contentTypeService,
            string? mediaFolderPath = null,
            string? tempFolderPath = null)
        {
            _umbracoDatabase = umbracoDatabaseFactory.CreateDatabase();
            _hostingEnvironment = hostingEnvironment;
            _fileSystems = fileSystems;
            _serializer = serializer;
            _dataTypeService = dataTypeService;
            _localizationService = localizationService;
            _fileService = fileService;
            _mediaService = mediaService;
            _mediaTypeService = mediaTypeService;
            _contentService = contentService;
            _mediaFileManager = mediaFileManager;
            _macroService = macroService;
            _contentTypeService = contentTypeService;
            _xmlParser = new PackageDefinitionXmlParser();
            _createdPackagesFolderPath = mediaFolderPath ?? Constants.SystemDirectories.CreatedPackages;
            _tempFolderPath = tempFolderPath ?? Constants.SystemDirectories.TempData + "/PackageFiles";
        }

        public IEnumerable<PackageDefinition> GetAll()
        {
            Sql<ISqlContext> query = new Sql<ISqlContext>(_umbracoDatabase!.SqlContext)
                .Select<CreatedPackageSchemaDto>()
                .From<CreatedPackageSchemaDto>()
                .OrderBy<CreatedPackageSchemaDto>(x => x.Id);

            var packageDefinitions = new List<PackageDefinition>();

            List<CreatedPackageSchemaDto> xmlSchemas = _umbracoDatabase.Fetch<CreatedPackageSchemaDto>(query);
            foreach (CreatedPackageSchemaDto packageSchema in xmlSchemas)
            {
                var packageDefinition = _xmlParser.ToPackageDefinition(XElement.Parse(packageSchema.Value));
                if (packageDefinition is not null)
                {
                    packageDefinition.Id = packageSchema.Id;
                    packageDefinition.Name = packageSchema.Name;
                    packageDefinition.PackageId = packageSchema.PackageId;
                    packageDefinitions.Add(packageDefinition);
                }
            }

            return packageDefinitions;
        }

        public PackageDefinition? GetById(int id)
        {
            Sql<ISqlContext> query = new Sql<ISqlContext>(_umbracoDatabase!.SqlContext)
                .Select<CreatedPackageSchemaDto>()
                .From<CreatedPackageSchemaDto>()
                .Where<CreatedPackageSchemaDto>(x => x.Id == id);
            List<CreatedPackageSchemaDto> schemaDtos = _umbracoDatabase.Fetch<CreatedPackageSchemaDto>(query);

            if (schemaDtos.IsCollectionEmpty())
            {
                return null;
            }

            var packageSchema = schemaDtos.First();
            var packageDefinition = _xmlParser.ToPackageDefinition(XElement.Parse(packageSchema.Value));
            if (packageDefinition is not null)
            {
                packageDefinition.Id = packageSchema.Id;
                packageDefinition.Name = packageSchema.Name;
                packageDefinition.PackageId = packageSchema.PackageId;
            }

            return packageDefinition;
        }

        public void Delete(int id)
        {
            // Delete package snapshot
            var packageDef = GetById(id);
            if (File.Exists(packageDef?.PackagePath))
            {
                File.Delete(packageDef.PackagePath);
            }

            Sql<ISqlContext> query = new Sql<ISqlContext>(_umbracoDatabase!.SqlContext)
                .Delete<CreatedPackageSchemaDto>()
                .Where<CreatedPackageSchemaDto>(x => x.Id == id);

            _umbracoDatabase.Execute(query);
        }

        public bool SavePackage(PackageDefinition definition)
        {
            if (definition == null)
            {
                throw new NullReferenceException("PackageDefinition cannot be null when saving");
            }

            if (definition.Name == null || string.IsNullOrEmpty(definition.Name) || definition.PackagePath == null)
            {
                return false;
            }

            // Ensure it's valid
            ValidatePackage(definition);

            if (definition.Id == default)
            {
                // Create dto from definition
                var dto = new CreatedPackageSchemaDto()
                {
                    Name = definition.Name,
                    Value = _xmlParser.ToXml(definition).ToString(),
                    UpdateDate = DateTime.Now,
                    PackageId = Guid.NewGuid()
                };

                // Set the ids, we have to save in database first to get the Id
                _umbracoDatabase!.Insert(dto);
                definition.Id = dto.Id;
            }

            // Save snapshot locally, we do this to the updated packagePath
            ExportPackage(definition);
            // Create dto from definition
            var updatedDto = new CreatedPackageSchemaDto()
            {
                Name = definition.Name,
                Value = _xmlParser.ToXml(definition).ToString(),
                Id = definition.Id,
                PackageId = definition.PackageId,
                UpdateDate = DateTime.Now
            };
            _umbracoDatabase?.Update(updatedDto);

            return true;
        }

        public string ExportPackage(PackageDefinition definition)
        {
            // Ensure it's valid
            ValidatePackage(definition);

            // Create a folder for building this package
            var temporaryPath = _hostingEnvironment.MapPathContentRoot(Path.Combine(_tempFolderPath, Guid.NewGuid().ToString()));
            Directory.CreateDirectory(temporaryPath);

            try
            {
                // Init package file
                XDocument compiledPackageXml = CreateCompiledPackageXml(out XElement root);

                // Info section
                root.Add(GetPackageInfoXml(definition));

                PackageDocumentsAndTags(definition, root);
                PackageDocumentTypes(definition, root);
                PackageMediaTypes(definition, root);
                PackageTemplates(definition, root);
                PackageStylesheets(definition, root);
                PackageStaticFiles(definition.Scripts, root, "Scripts", "Script", _fileSystems.ScriptsFileSystem!);
                PackageStaticFiles(definition.PartialViews, root, "PartialViews", "View", _fileSystems.PartialViewsFileSystem!);
                PackageMacros(definition, root);
                PackageDictionaryItems(definition, root);
                PackageLanguages(definition, root);
                PackageDataTypes(definition, root);
                Dictionary<string, Stream> mediaFiles = PackageMedia(definition, root);

                string fileName;
                string tempPackagePath;
                if (mediaFiles.Count > 0)
                {
                    fileName = "package.zip";
                    tempPackagePath = Path.Combine(temporaryPath, fileName);
                    using (FileStream fileStream = File.OpenWrite(tempPackagePath))
                    using (var archive = new ZipArchive(fileStream, ZipArchiveMode.Create, true))
                    {
                        ZipArchiveEntry packageXmlEntry = archive.CreateEntry("package.xml");
                        using (Stream entryStream = packageXmlEntry.Open())
                        {
                            compiledPackageXml.Save(entryStream);
                        }

                        foreach (KeyValuePair<string, Stream> mediaFile in mediaFiles)
                        {
                            var entryPath = $"media{mediaFile.Key.EnsureStartsWith('/')}";
                            ZipArchiveEntry mediaEntry = archive.CreateEntry(entryPath);
                            using (Stream entryStream = mediaEntry.Open())
                            using (mediaFile.Value)
                            {
                                mediaFile.Value.Seek(0, SeekOrigin.Begin);
                                mediaFile.Value.CopyTo(entryStream);
                            }
                        }
                    }
                }
                else
                {
                    fileName = "package.xml";
                    tempPackagePath = Path.Combine(temporaryPath, fileName);

                    using (FileStream fileStream = File.OpenWrite(tempPackagePath))
                    {
                        compiledPackageXml.Save(fileStream);
                    }
                }

                var directoryName = _hostingEnvironment.MapPathContentRoot(Path.Combine(_createdPackagesFolderPath, definition.Name.Replace(' ', '_')));
                Directory.CreateDirectory(directoryName);

                var finalPackagePath = Path.Combine(directoryName, fileName);

                // Clean existing files
                foreach (var packagePath in new[]
                {
                    definition.PackagePath,
                    finalPackagePath
                })
                {
                    if (File.Exists(packagePath))
                    {
                        File.Delete(packagePath);
                    }
                }

                // Move to final package path
                File.Move(tempPackagePath, finalPackagePath);

                definition.PackagePath = finalPackagePath;

                return finalPackagePath;
            }
            finally
            {
                // Clean up
                Directory.Delete(temporaryPath, true);
            }
        }

        private XDocument CreateCompiledPackageXml(out XElement root)
        {
            root = new XElement("umbPackage");
            var compiledPackageXml = new XDocument(root);
            return compiledPackageXml;
        }

        private void ValidatePackage(PackageDefinition definition)
        {
            // Ensure it's valid
            var context = new ValidationContext(definition, serviceProvider: null, items: null);
            var results = new List<ValidationResult>();
            var isValid = Validator.TryValidateObject(definition, context, results);
            if (!isValid)
            {
                throw new InvalidOperationException("Validation failed, there is invalid data on the model: " +
                                                    string.Join(", ", results.Select(x => x.ErrorMessage)));
            }
        }

        private void PackageDataTypes(PackageDefinition definition, XContainer root)
        {
            var dataTypes = new XElement("DataTypes");
            foreach (var dtId in definition.DataTypes)
            {
                if (!int.TryParse(dtId, NumberStyles.Integer, CultureInfo.InvariantCulture, out var outInt))
                {
                    continue;
                }

                IDataType? dataType = _dataTypeService.GetDataType(outInt);
                if (dataType == null)
                {
                    continue;
                }

                dataTypes.Add(_serializer.Serialize(dataType));
            }

            root.Add(dataTypes);
        }

        private void PackageLanguages(PackageDefinition definition, XContainer root)
        {
            var languages = new XElement("Languages");
            foreach (var langId in definition.Languages)
            {
                if (!int.TryParse(langId, NumberStyles.Integer, CultureInfo.InvariantCulture, out var outInt))
                {
                    continue;
                }

                ILanguage? lang = _localizationService.GetLanguageById(outInt);
                if (lang == null)
                {
                    continue;
                }

                languages.Add(_serializer.Serialize(lang));
            }

            root.Add(languages);
        }

        private void PackageDictionaryItems(PackageDefinition definition, XContainer root)
        {
            var rootDictionaryItems = new XElement("DictionaryItems");
            var items = new Dictionary<Guid, (IDictionaryItem dictionaryItem, XElement serializedDictionaryValue)>();

            foreach (var dictionaryId in definition.DictionaryItems)
            {
                if (!int.TryParse(dictionaryId, NumberStyles.Integer, CultureInfo.InvariantCulture, out var outInt))
                {
                    continue;
                }

                IDictionaryItem? di = _localizationService.GetDictionaryItemById(outInt);

                if (di == null)
                {
                    continue;
                }

                items[di.Key] = (di, _serializer.Serialize(di, false));
            }

            // organize them in hierarchy ...
            var itemCount = items.Count;
            var processed = new Dictionary<Guid, XElement>();
            while (processed.Count < itemCount)
            {
                foreach (Guid key in items.Keys.ToList())
                {
                    (IDictionaryItem dictionaryItem, XElement serializedDictionaryValue) = items[key];

                    if (!dictionaryItem.ParentId.HasValue)
                    {
                        // if it has no parent, its definitely just at the root
                        AppendDictionaryElement(rootDictionaryItems, items, processed, key, serializedDictionaryValue);
                    }
                    else
                    {
                        if (processed.ContainsKey(dictionaryItem.ParentId.Value))
                        {
                            // we've processed this parent element already so we can just append this xml child to it
                            AppendDictionaryElement(processed[dictionaryItem.ParentId.Value], items, processed, key,
                                serializedDictionaryValue);
                        }
                        else if (items.ContainsKey(dictionaryItem.ParentId.Value))
                        {
                            // we know the parent exists in the dictionary but
                            // we haven't processed it yet so we'll leave it for the next loop
                            continue;
                        }
                        else
                        {
                            // in this case, the parent of this item doesn't exist in our collection, we have no
                            // choice but to add it to the root.
                            AppendDictionaryElement(rootDictionaryItems, items, processed, key,
                                serializedDictionaryValue);
                        }
                    }
                }
            }

            root.Add(rootDictionaryItems);

            static void AppendDictionaryElement(XElement rootDictionaryItems,
                Dictionary<Guid, (IDictionaryItem dictionaryItem, XElement serializedDictionaryValue)> items,
                Dictionary<Guid, XElement> processed, Guid key, XElement serializedDictionaryValue)
            {
                // track it
                processed.Add(key, serializedDictionaryValue);

                // append it
                rootDictionaryItems.Add(serializedDictionaryValue);

                // remove it so its not re-processed
                items.Remove(key);
            }
        }

        private void PackageMacros(PackageDefinition definition, XContainer root)
        {
            var packagedMacros = new List<IMacro>();
            var macros = new XElement("Macros");
            foreach (var macroId in definition.Macros)
            {
                if (!int.TryParse(macroId, NumberStyles.Integer, CultureInfo.InvariantCulture, out int outInt))
                {
                    continue;
                }

                XElement? macroXml = GetMacroXml(outInt, out IMacro? macro);
                if (macroXml is null)
                {
                    continue;
                }

                macros.Add(macroXml);
                packagedMacros.Add(macro!);
            }

            root.Add(macros);

            // Get the partial views for macros and package those (exclude views outside of the default directory, e.g. App_Plugins\*\Views)
            IEnumerable<string> views = packagedMacros
                .Where(x => x.MacroSource.StartsWith(Constants.SystemDirectories.MacroPartials))
                .Select(x =>
                    x.MacroSource.Substring(Constants.SystemDirectories.MacroPartials.Length).Replace('/', '\\'));
            PackageStaticFiles(views, root, "MacroPartialViews", "View", _fileSystems.MacroPartialsFileSystem!);
        }

        private void PackageStylesheets(PackageDefinition definition, XContainer root)
        {
            var stylesheetsXml = new XElement("Stylesheets");
            foreach (var stylesheet in definition.Stylesheets)
            {
                if (stylesheet.IsNullOrWhiteSpace())
                {
                    continue;
                }

                XElement? xml = GetStylesheetXml(stylesheet, true);
                if (xml != null)
                {
                    stylesheetsXml.Add(xml);
                }
            }

            root.Add(stylesheetsXml);
        }

        private void PackageStaticFiles(
            IEnumerable<string> filePaths,
            XContainer root,
            string containerName,
            string elementName,
            IFileSystem fileSystem)
        {
            var scriptsXml = new XElement(containerName);
            foreach (var file in filePaths)
            {
                if (file.IsNullOrWhiteSpace())
                {
                    continue;
                }

                if (!fileSystem.FileExists(file))
                {
                    throw new InvalidOperationException("No file found with path " + file);
                }

                using Stream? stream = fileSystem.OpenFile(file);
                if (stream is not null)
                {
                    using (var reader = new StreamReader(stream))
                    {
                        var fileContents = reader.ReadToEnd();
                        scriptsXml.Add(
                            new XElement(
                                elementName,
                                new XAttribute("path", file),
                                new XCData(fileContents)));
                    }
                }
            }

            root.Add(scriptsXml);
        }

        private void PackageTemplates(PackageDefinition definition, XContainer root)
        {
            var templatesXml = new XElement("Templates");
            foreach (var templateId in definition.Templates)
            {
                if (!int.TryParse(templateId, NumberStyles.Integer, CultureInfo.InvariantCulture, out var outInt))
                {
                    continue;
                }

                ITemplate? template = _fileService.GetTemplate(outInt);
                if (template == null)
                {
                    continue;
                }

                templatesXml.Add(_serializer.Serialize(template));
            }

            root.Add(templatesXml);
        }

        private void PackageDocumentTypes(PackageDefinition definition, XContainer root)
        {
            var contentTypes = new HashSet<IContentType>();
            var docTypesXml = new XElement("DocumentTypes");
            foreach (var dtId in definition.DocumentTypes)
            {
                if (!int.TryParse(dtId, NumberStyles.Integer, CultureInfo.InvariantCulture, out var outInt))
                {
                    continue;
                }

                IContentType? contentType = _contentTypeService.Get(outInt);
                if (contentType == null)
                {
                    continue;
                }

                AddDocumentType(contentType, contentTypes);
            }

            foreach (IContentType contentType in contentTypes)
            {
                docTypesXml.Add(_serializer.Serialize(contentType));
            }

            root.Add(docTypesXml);
        }

        private void PackageMediaTypes(PackageDefinition definition, XContainer root)
        {
            var mediaTypes = new HashSet<IMediaType>();
            var mediaTypesXml = new XElement("MediaTypes");
            foreach (var mediaTypeId in definition.MediaTypes)
            {
                if (!int.TryParse(mediaTypeId, NumberStyles.Integer, CultureInfo.InvariantCulture, out var outInt))
                {
                    continue;
                }

                IMediaType? mediaType = _mediaTypeService.Get(outInt);
                if (mediaType == null)
                {
                    continue;
                }

                AddMediaType(mediaType, mediaTypes);
            }

            foreach (IMediaType mediaType in mediaTypes)
            {
                mediaTypesXml.Add(_serializer.Serialize(mediaType));
            }

            root.Add(mediaTypesXml);
        }

        private void PackageDocumentsAndTags(PackageDefinition definition, XContainer root)
        {
            // Documents and tags
            if (string.IsNullOrEmpty(definition.ContentNodeId) == false && int.TryParse(definition.ContentNodeId,
                    NumberStyles.Integer, CultureInfo.InvariantCulture, out var contentNodeId))
            {
                if (contentNodeId > 0)
                {
                    // load content from umbraco.
                    IContent? content = _contentService.GetById(contentNodeId);
                    if (content != null)
                    {
                        var contentXml = definition.ContentLoadChildNodes
                            ? content.ToDeepXml(_serializer)
                            : content.ToXml(_serializer);

                        // Create the Documents/DocumentSet node

                        root.Add(
                            new XElement(
                                "Documents",
                                new XElement(
                                    "DocumentSet",
                                    new XAttribute("importMode", "root"),
                                    contentXml)));
                    }
                }
            }
        }

        private Dictionary<string, Stream> PackageMedia(PackageDefinition definition, XElement root)
        {
            var mediaStreams = new Dictionary<string, Stream>();

            // callback that occurs on each serialized media item
            void OnSerializedMedia(IMedia media, XElement xmlMedia)
            {
                // get the media file path and store that separately in the XML.
                // the media file path is different from the URL and is specifically
                // extracted using the property editor for this media file and the current media file system.
                Stream? mediaStream = _mediaFileManager.GetFile(media, out var mediaFilePath);
                if (mediaStream != null)
                {
                    xmlMedia.Add(new XAttribute("mediaFilePath", mediaFilePath!));

                    // add the stream to our outgoing stream
                    mediaStreams.Add(mediaFilePath!, mediaStream);
                }
            }

            IEnumerable<IMedia> medias = _mediaService.GetByIds(definition.MediaUdis);

            var mediaXml = new XElement(
                "MediaItems",
                medias.Select(media =>
                {
                    XElement serializedMedia = _serializer.Serialize(
                        media,
                        definition.MediaLoadChildNodes,
                        OnSerializedMedia);

                    return new XElement("MediaSet", serializedMedia);
                }));

            root.Add(mediaXml);

            return mediaStreams;
        }

        /// <summary>
        /// Gets a macros xml node
        /// </summary>
        private XElement? GetMacroXml(int macroId, out IMacro? macro)
        {
            macro = _macroService.GetById(macroId);
            if (macro == null)
            {
                return null;
            }

            XElement xml = _serializer.Serialize(macro);
            return xml;
        }

        /// <summary>
        /// Converts a umbraco stylesheet to a package xml node
        /// </summary>
        /// <param name="path">The path of the stylesheet.</param>
        /// <param name="includeProperties">if set to <c>true</c> [include properties].</param>
        private XElement? GetStylesheetXml(string path, bool includeProperties)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(path));
            }

            IStylesheet? stylesheet = _fileService.GetStylesheet(path);
            if (stylesheet == null)
            {
                return null;
            }

            return _serializer.Serialize(stylesheet, includeProperties);
        }

        private void AddDocumentType(IContentType dt, HashSet<IContentType> dtl)
        {
            if (dt.ParentId > 0)
            {
                IContentType? parent = _contentTypeService.Get(dt.ParentId);
                if (parent != null)
                {
                    AddDocumentType(parent, dtl);
                }
            }

            if (!dtl.Contains(dt))
            {
                dtl.Add(dt);
            }
        }

        private void AddMediaType(IMediaType mediaType, HashSet<IMediaType> mediaTypes)
        {
            if (mediaType.ParentId > 0)
            {
                IMediaType? parent = _mediaTypeService.Get(mediaType.ParentId);
                if (parent != null)
                {
                    AddMediaType(parent, mediaTypes);
                }
            }

            if (!mediaTypes.Contains(mediaType))
            {
                mediaTypes.Add(mediaType);
            }
        }

        private static XElement GetPackageInfoXml(PackageDefinition definition)
        {
            var info = new XElement("info");

            // Package info
            var package = new XElement("package");
            package.Add(new XElement("name", definition.Name));
            info.Add(package);
            return info;
        }
    }
}


text:
package com.telefonica.euro_iaas.sdc.pupperwrapper.services.tests;

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.ArrayList;
import java.util.NoSuchElementException;

import org.junit.Before;
import org.junit.Test;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import com.telefonica.euro_iaas.sdc.puppetwrapper.common.Action;
import com.telefonica.euro_iaas.sdc.puppetwrapper.data.Node;
import com.telefonica.euro_iaas.sdc.puppetwrapper.data.Software;

public class CatalogManagerMongoTest {

    private CatalogManagerMongoImpl4Test catalogManagerMongo;

    private MongoTemplate mongoTemplateMock;

    @Before
    public void setUp() {

        mongoTemplateMock = mock(MongoTemplate.class);

        catalogManagerMongo = new CatalogManagerMongoImpl4Test();
        catalogManagerMongo.setMongoTemplate(mongoTemplateMock);

        final Node node = new Node();
        node.setId("test");
        node.setGroupName("group");
        node.setManifestGenerated(true);

        Software soft = new Software();
        soft.setName("test");
        soft.setVersion("1.0.0");
        soft.setAction(Action.INSTALL);
        node.addSoftware(soft);

        final Node node2 = new Node();
        node2.setId("test2");
        node2.setGroupName("group2");
        node2.setManifestGenerated(true);

        final Node node3 = new Node();
        node3.setId("test3");
        node3.setGroupName("group2");
        node3.setManifestGenerated(true);

//        Query query = mock(Query.class);
        Query query = new Query(Criteria.where("id").is("test"));
        when(mongoTemplateMock.findOne(query, Node.class)).thenReturn(node);

        query = new Query(Criteria.where("id").is("test3"));
        when(mongoTemplateMock.findOne(query, Node.class)).thenThrow(new NoSuchElementException());

        when(mongoTemplateMock.findAll(Node.class)).thenReturn(new ArrayList<Node>() {
            {
                add(node);
                add(node2);
                add(node3);
            }
        }).thenReturn(new ArrayList<Node>() {
            {
                add(node);
                add(node2);
                add(node3);
            }
        }).thenReturn(new ArrayList<Node>() {
            {
                add(node);
                add(node2);
            }
        });

        Query queryFindOK = new Query(Criteria.where("groupName").is("groupNameOK"));
        when(mongoTemplateMock.find(queryFindOK, Node.class)).thenReturn(new ArrayList<Node>() {
            {
                add(node);
            }
        });

        Query queryFindErr = new Query(Criteria.where("groupName").is("groupNameErr"));
        when(mongoTemplateMock.find(queryFindErr, Node.class)).thenReturn(null);

    }

    @Test(expected = NoSuchElementException.class)
    public void getNodeTestNotFound() {
        Node node = catalogManagerMongo.getNode("test3");

    }

    @Test
    public void getNodeTest() {
        Node node = new Node();
        node.setId("test");
        node.setGroupName("group");
        catalogManagerMongo.addNode(node);
        Node node1 = catalogManagerMongo.getNode("test");
        assertTrue(node1.getId().equals("test"));
    }

    @Test
    public void testAddNode() {
        int length = catalogManagerMongo.getNodeLength();
        assertTrue(length == 3);
        Node node = new Node();
        node.setId("test");
        node.setGroupName("group");
        catalogManagerMongo.addNode(node);
        length = catalogManagerMongo.getNodeLength();
        assertTrue(length == 3);
    }

    @Test
    public void testRemoveNode() {
        int length = catalogManagerMongo.getNodeLength();
        assertTrue(length == 3);
        Node node = new Node();
        node.setId("test");
        node.setGroupName("group");
        catalogManagerMongo.addNode(node);
        length = catalogManagerMongo.getNodeLength();
        assertTrue(length == 3);

        catalogManagerMongo.removeNode(node.getId());
        length = catalogManagerMongo.getNodeLength();
        assertTrue(length == 2);
    }

    @Test
    public void generateFileStrTestOnlyNode() {
        Node node = new Node();
        node.setId("test");
        node.setGroupName("group");
        catalogManagerMongo.addNode(node);

        String str = catalogManagerMongo.generateManifestStr("test");
        assertTrue(str.length() > 0);
        assertTrue(str.contains("{"));
        assertTrue(str.contains("node"));
    }

    @Test
    public void generateFileStrTestNodeAndSoft() {

        String str = catalogManagerMongo.generateManifestStr("test");
        assertTrue(str.length() > 0);
        assertTrue(str.contains("{"));
        assertTrue(str.contains("node"));
        assertTrue(str.contains("class"));
        assertTrue(str.contains("install"));
        assertTrue(str.contains("version"));
    }

    @Test
    public void generateSiteFileTest() {

        String str = catalogManagerMongo.generateSiteStr();

        assertTrue(str.length() > 1);
        assertTrue(str.contains("import 'group/*.pp'"));
        assertTrue(str.contains("import 'group2/*.pp'"));

    }

    @Test
    public void removeNodesByGroupNameTest() {

        catalogManagerMongo.removeNodesByGroupName("group");

        assertTrue(catalogManagerMongo.getNodeLength() == 3);

    }

    @Test
    public void isLastGroupNodeTestOK() {

        assertTrue(catalogManagerMongo.isLastGroupNode("groupNameOK"));

    }

    @Test
    public void isLastGroupNodeTestFail() {

        assertFalse(catalogManagerMongo.isLastGroupNode("groupNameErr"));

    }
}

redpajama_set_name: RedPajamaGithub


text:
.class public Lcom/android/internal/telephony/cdma/RuimPhoneBookInterfaceManager;
.super Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;
.source "RuimPhoneBookInterfaceManager.java"

# direct methods
.method public constructor <init>(Lcom/android/internal/telephony/cdma/CDMAPhone;)V
    .locals 0
    .parameter "phone"

    .prologue
    .line 36
    invoke-direct {p0, p1}, Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;-><init>(Lcom/android/internal/telephony/PhoneBase;)V

    .line 38
    return-void
.end method

# virtual methods
.method public dispose()V
    .locals 0

    .prologue
    .line 42
    invoke-super {p0}, Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->dispose()V

    .line 43
    return-void
.end method

.method protected finalize()V
    .locals 3

    .prologue
    .line 48
    :try_start_0
    invoke-super {p0}, Landroid/os/Binder;->finalize()V
    :try_end_0
    .catch Ljava/lang/Throwable; {:try_start_0 .. :try_end_0} :catch_0

    .line 52
    :goto_0
    iget-object v1, p0, Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->LOG_TAG:Ljava/lang/String;

    const-string v2, "RuimPhoneBookInterfaceManager finalized"

    invoke-static {v1, v2}, Landroid/telephony/Rlog;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 53
    return-void

    .line 49
    :catch_0
    move-exception v0

    .line 50
    .local v0, throwable:Ljava/lang/Throwable;
    iget-object v1, p0, Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->LOG_TAG:Ljava/lang/String;

    const-string v2, "Error while finalizing:"

    invoke-static {v1, v2, v0}, Landroid/telephony/Rlog;->e(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I

    goto :goto_0
.end method

.method public getAdnRecordsSize(I)[I
    .locals 6
    .parameter "efid"

    .prologue
    .line 57
    new-instance v3, Ljava/lang/StringBuilder;

    invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V

    const-string v4, "getAdnRecordsSize: efid="

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3, p1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v3

    invoke-virtual {p0, v3}, Lcom/android/internal/telephony/cdma/RuimPhoneBookInterfaceManager;->logd(Ljava/lang/String;)V

    .line 58
    iget-object v4, p0, Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->mLock:Ljava/lang/Object;

    monitor-enter v4

    .line 59
    :try_start_0
    invoke-virtual {p0}, Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->checkThread()V

    .line 60
    const/4 v3, 0x3

    new-array v3, v3, [I

    iput-object v3, p0, Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->mRecordSize:[I

    .line 63
    new-instance v2, Ljava/util/concurrent/atomic/AtomicBoolean;

    const/4 v3, 0x0

    invoke-direct {v2, v3}, Ljava/util/concurrent/atomic/AtomicBoolean;-><init>(Z)V

    .line 64
    .local v2, status:Ljava/util/concurrent/atomic/AtomicBoolean;
    iget-object v3, p0, Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->mBaseHandler:Landroid/os/Handler;

    const/4 v5, 0x1

    invoke-virtual {v3, v5, v2}, Landroid/os/Handler;->obtainMessage(ILjava/lang/Object;)Landroid/os/Message;

    move-result-object v1

    .line 66
    .local v1, response:Landroid/os/Message;
    iget-object v3, p0, Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->mPhone:Lcom/android/internal/telephony/PhoneBase;

    invoke-virtual {v3}, Lcom/android/internal/telephony/PhoneBase;->getIccFileHandler()Lcom/android/internal/telephony/uicc/IccFileHandler;

    move-result-object v0

    .line 68
    .local v0, fh:Lcom/android/internal/telephony/uicc/IccFileHandler;
    if-eqz v0, :cond_0

    .line 69
    invoke-virtual {v0, p1, v1}, Lcom/android/internal/telephony/uicc/IccFileHandler;->getEFLinearRecordSize(ILandroid/os/Message;)V

    .line 70
    invoke-virtual {p0, v2}, Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->waitForResult(Ljava/util/concurrent/atomic/AtomicBoolean;)V

    .line 72
    :cond_0
    monitor-exit v4
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    .line 74
    iget-object v3, p0, Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->mRecordSize:[I

    return-object v3

    .line 72
    .end local v0           #fh:Lcom/android/internal/telephony/uicc/IccFileHandler;
    .end local v1           #response:Landroid/os/Message;
    .end local v2           #status:Ljava/util/concurrent/atomic/AtomicBoolean;
    :catchall_0
    move-exception v3

    :try_start_1
    monitor-exit v4
    :try_end_1
    .catchall {:try_start_1 .. :try_end_1} :catchall_0

    throw v3
.end method

.method protected logd(Ljava/lang/String;)V
    .locals 3
    .parameter "msg"

    .prologue
    .line 79
    iget-object v0, p0, Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->LOG_TAG:Ljava/lang/String;

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    const-string v2, "[RuimPbInterfaceManager] "

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    invoke-static {v0, v1}, Landroid/telephony/Rlog;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 80
    return-void
.end method

.method protected loge(Ljava/lang/String;)V
    .locals 3
    .parameter "msg"

    .prologue
    .line 84
    iget-object v0, p0, Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->LOG_TAG:Ljava/lang/String;

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    const-string v2, "[RuimPbInterfaceManager] "

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    invoke-static {v0, v1}, Landroid/telephony/Rlog;->e(Ljava/lang/String;Ljava/lang/String;)I

    .line 85
    return-void
.end method


text:
using System.Collections.Generic;
using Newtonsoft.Json;

namespace DtoGenerator.DescriptionTypes
{
    internal class ClassDescription
    {
        [JsonProperty("className")]
        internal string ClassName { get; set; }

        [JsonProperty("properties")]
        internal List<PropertyDescription> Properties { get; set; }
    }
}


text:
#ifndef BOOST_SPIRIT_RANGE_RUN_HPP
#define BOOST_SPIRIT_RANGE_RUN_HPP

///////////////////////////////////////////////////////////////////////////////
#include <vector>

#include <boost/spirit/home/classic/namespace.hpp>

///////////////////////////////////////////////////////////////////////////////
namespace boost { namespace spirit {

BOOST_SPIRIT_CLASSIC_NAMESPACE_BEGIN

namespace utility { namespace impl {

    ///////////////////////////////////////////////////////////////////////////
    //
    //  range class
    //
    //      Implements a closed range of values. This class is used in
    //      the implementation of the range_run class.
    //
    //      { Low level implementation detail }
    //      { Not to be confused with BOOST_SPIRIT_CLASSIC_NS::range }
    //
    ///////////////////////////////////////////////////////////////////////////
    template <typename CharT>
    struct range {

                        range(CharT first, CharT last);

        bool            is_valid() const;
        bool            includes(CharT v) const;
        bool            includes(range const& r) const;
        bool            overlaps(range const& r) const;
        void            merge(range const& r);

        CharT first;
        CharT last;
    };

    //////////////////////////////////
    template <typename CharT>
    struct range_char_compare {

        bool operator()(range<CharT> const& x, const CharT y) const
        { return x.first < y; }

        bool operator()(const CharT x, range<CharT> const& y) const
        { return x < y.first; }

        // This additional operator is required for the checked STL shipped
        // with VC8 testing the ordering of the iterators passed to the
        // std::lower_bound algo this range_char_compare<> predicate is passed
        // to.
        bool operator()(range<CharT> const& x, range<CharT> const& y) const
        { return x.first < y.first; }
    };

    //////////////////////////////////
    template <typename CharT>
    struct range_compare {

        bool operator()(range<CharT> const& x, range<CharT> const& y) const
        { return x.first < y.first; }
    };

    ///////////////////////////////////////////////////////////////////////////
    //
    //  range_run
    //
    //      An implementation of a sparse bit (boolean) set. The set uses
    //      a sorted vector of disjoint ranges. This class implements the
    //      bare minimum essentials from which the full range of set
    //      operators can be implemented. The set is constructed from
    //      ranges. Internally, adjacent or overlapping ranges are
    //      coalesced.
    //
    //      range_runs are very space-economical in situations where there
    //      are lots of ranges and a few individual disjoint values.
    //      Searching is O(log n) where n is the number of ranges.
    //
    //      { Low level implementation detail }
    //
    ///////////////////////////////////////////////////////////////////////////
    template <typename CharT>
    class range_run {

    public:

        typedef range<CharT> range_t;
        typedef std::vector<range_t> run_t;
        typedef typename run_t::iterator iterator;
        typedef typename run_t::const_iterator const_iterator;

        void            swap(range_run& rr);
        bool            test(CharT v) const;
        void            set(range_t const& r);
        void            clear(range_t const& r);
        void            clear();

        const_iterator  begin() const;
        const_iterator  end() const;

    private:

        void            merge(iterator iter, range_t const& r);

        run_t run;
    };

}}

BOOST_SPIRIT_CLASSIC_NAMESPACE_END

}} // namespace BOOST_SPIRIT_CLASSIC_NS::utility::impl

#endif

#include <boost/spirit/home/classic/utility/impl/chset/range_run.ipp>


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading;
using BohFoundation.Domain.Claims;

namespace BohFoundation.TestHelpers
{
    public static class TestHelpersIdentity
    {
            public static void PopulateIdentityWithStandardAnon()
            {
                Thread.CurrentPrincipal = new GenericPrincipal(new ClaimsIdentity(new GenericIdentity(String.Empty), new Collection<Claim>()), new string[0]);
            }

            public static void PopulateAdminIdentity(Guid usersGuid, string email)
            {
                PopulateIdentity(usersGuid, email, ClaimsNames.Admin);
            }

            public static void PopulateReferenceIdentity(Guid usersGuid, string email)
            {
                PopulateIdentity(usersGuid, email, ClaimsNames.Reference);
            }

            public static void PopulateApplicantIdentity(Guid usersGuid, string email)
            {
                PopulateIdentity(usersGuid, email, ClaimsNames.Applicant);
            }

            public static void PopulateApplicationEvaluatorIdentity(Guid usersGuid, string email)
            {
                PopulateIdentity(usersGuid, email, ClaimsNames.ApplicationEvaluator);
            }

            public static void PopulateApplicationEvaluatorPendingConfirmationIdentity(Guid usersGuid, string email)
            {
                PopulateIdentity(usersGuid, email, ClaimsNames.ApplicationEvaluatorPendingConfirmation);
            }

            public static void PopulateIdentityWithNoPermissions(Guid usersGuid, string email)
            {
                PopulateIdentity(usersGuid, email, new string[0]);
            }

            public static void PopulateIdentity(Guid userGuid, string email, string claimName)
            {
                var array = new[] {claimName};
                PopulateIdentity(userGuid, email, array);
            }

            public static void PopulateIdentity(Guid usersGuid, string email, string[] claimsArray)
            {
                var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.NameIdentifier, usersGuid.ToString()),
                    new Claim(ClaimTypes.Email, email),
                    new Claim(ClaimsNames.FirstName, TestHelpersCommonFields.FirstName),
                    new Claim(ClaimsNames.LastName, TestHelpersCommonFields.LastName),
                    new Claim(ClaimsNames.GraduatingYear, TestHelpersCommonFields.GraduatingYear.ToString())
                };

                claims.AddRange(claimsArray.Select(claimName => new Claim(claimName, true.ToString())));

                var claimsIdentity = new ClaimsIdentity(new Collection<Claim>(claims));

                ClaimsPrincipal.Current.AddIdentity(claimsIdentity);

                Thread.CurrentPrincipal = new GenericPrincipal(new ClaimsIdentity(new GenericIdentity(email), claims),
                    new string[0]);
            }
        }
    }


text:
export default function wrapTryCatch(tryCatchTarget:Function):any {
  return function tryCatcher() {
    try {
      return tryCatchTarget.apply(this, arguments);
    } catch (e) {
      return this["throw"](e);
    }
  }
};


text:
<?php

namespace BinSoul\Test\Db\Platform\MySQL;

use BinSoul\Db\Platform\MySQL\DefaultConnection;
use BinSoul\Db\Platform\MySQL\MySQLConnectionSettings;
use BinSoul\Db\Platform\MySQL\MySQLiFake;
use BinSoul\Db\Platform\MySQL\MySQLiStmtFake;
use BinSoul\Db\Platform\MySQL\AbstractResult;

include_once 'MySQLiFake.php';

class DefaultConnectionTest extends \PHPUnit_Framework_TestCase
{
    private function buildSettings()
    {
        return MySQLConnectionSettings::fromArray(
            [
                'host' => '127.0.0.1',
                'username' => 'root',
                'password' => 'password',
                'schema' => 'schema',
            ]
        );
    }
    protected function setUp()
    {
        MySQLiFake::reset();
    }

    public function test_open_succes()
    {
        $connection = new DefaultConnection($this->buildSettings());
        $this->assertTrue($connection->open());
        $this->assertFalse($connection->open());
    }

    /**
     * @expectedException \BinSoul\Db\Exception\ConnectionException
     */
    public function test_open_failure()
    {
        MySQLiFake::$allowConnect = false;

        $connection = new DefaultConnection($this->buildSettings());
        $connection->open();
    }

    public function test_close_success()
    {
        $connection = new DefaultConnection($this->buildSettings());
        $connection->open();
        $this->assertTrue($connection->close());
        $this->assertTrue(MySQLiFake::$closeCalled);

        $this->assertFalse($connection->close());
    }

    public function test_close_rolls_back_transactions()
    {
        $connection = new DefaultConnection($this->buildSettings());
        $connection->open();
        $connection->begin();
        $this->assertTrue($connection->close());
        $this->assertTrue(MySQLiFake::$rollbackCalled);
    }

    public function test_begin_starts_transaction()
    {
        MySQLiFake::$allowAutocommit = true;
        $connection = new DefaultConnection($this->buildSettings());
        $connection->open();
        $this->assertTrue($connection->begin());
        $this->assertTrue(MySQLiFake::$autocommitCalled);
        $this->assertTrue(MySQLiFake::$queryCalled);
        $this->assertContains('start transaction', MySQLiFake::$lastStatement, '', true);
    }

    public function test_begin_returns_false_if_autocommit_fails()
    {
        MySQLiFake::$allowAutocommit = false;
        $connection = new DefaultConnection($this->buildSettings());
        $connection->open();
        $this->assertFalse($connection->begin());
        $this->assertTrue(MySQLiFake::$autocommitCalled);
        $this->assertFalse(MySQLiFake::$queryCalled);
    }

    public function test_begin_uses_savepoints()
    {
        MySQLiFake::$allowAutocommit = true;
        $connection = new DefaultConnection($this->buildSettings());
        $connection->open();
        $this->assertTrue($connection->begin());
        $this->assertTrue($connection->begin());
        $this->assertContains('savepoint', MySQLiFake::$lastStatement, '', true);
    }

    public function test_commit()
    {
        $connection = new DefaultConnection($this->buildSettings());
        $connection->open();
        $connection->begin();
        $this->assertTrue($connection->commit());
        $this->assertTrue(MySQLiFake::$commitCalled);
        $this->assertTrue(MySQLiFake::$autocommitCalled);
    }

    public function test_commit_uses_savepoints()
    {
        $connection = new DefaultConnection($this->buildSettings());
        $connection->open();
        $connection->begin();
        $connection->begin();
        $this->assertTrue($connection->commit());
        $this->assertContains('savepoint', MySQLiFake::$lastStatement, '', true);
    }

    public function test_commit_returns_false_if_not_in_transaction()
    {
        $connection = new DefaultConnection($this->buildSettings());
        $connection->open();
        $this->assertFalse($connection->commit());
        $this->assertFalse(MySQLiFake::$commitCalled);
    }

    public function test_rollback()
    {
        $connection = new DefaultConnection($this->buildSettings());
        $connection->open();
        $connection->begin();
        $this->assertTrue($connection->rollback());
        $this->assertTrue(MySQLiFake::$rollbackCalled);
        $this->assertTrue(MySQLiFake::$autocommitCalled);
    }

    public function test_rollback_uses_savepoints()
    {
        $connection = new DefaultConnection($this->buildSettings());
        $connection->open();
        $connection->begin();
        $connection->begin();
        $this->assertTrue($connection->rollback());
        $this->assertContains('rollback', MySQLiFake::$lastStatement, '', true);
    }

    public function test_rollback_returns_false_if_not_in_transaction()
    {
        $connection = new DefaultConnection($this->buildSettings());
        $connection->open();
        $this->assertFalse($connection->rollback());
        $this->assertFalse(MySQLiFake::$rollbackCalled);
    }

    public function test_execute_without_parameters()
    {
        $connection = new DefaultConnection($this->buildSettings());
        $connection->open();

        $result = $connection->execute('select * from table', []);
        $this->assertTrue(MySQLiFake::$queryCalled);
        $this->assertInstanceOf(AbstractResult::class, $result);
    }

    /**
     * @expectedException \BinSoul\Db\Exception\OperationException
     */
    public function test_execute_without_parameters_throws_operation_exception()
    {
        MySQLiFake::$allowQuery = false;

        $connection = new DefaultConnection($this->buildSettings());
        $connection->open();

        $connection->execute('select * from table', []);
    }

    /**
     * @expectedException \BinSoul\Db\Exception\ConnectionException
     */
    public function test_execute_without_parameters_throws_connection_exception()
    {
        MySQLiFake::$allowQuery = false;
        MySQLiFake::$definedErrorCode = 2006;

        $connection = new DefaultConnection($this->buildSettings());
        $connection->open();

        $connection->execute('select * from table', []);
    }

    public function test_execute_with_parameters()
    {
        $connection = new DefaultConnection($this->buildSettings(), false);
        $connection->open();

        $result = $connection->execute('select * from table where id=?', [1, 1.5, 'foo', [], [1, 2], null]);
        $this->assertTrue(MySQLiFake::$prepareCalled);
        $this->assertInstanceOf(AbstractResult::class, $result);

        MySQLiFake::reset();

        $connection = new DefaultConnection($this->buildSettings(), true);
        $connection->open();

        $result = $connection->execute('select * from table where id=?', [1, 1.5, 'foo', [], [1, 2], null]);
        $this->assertTrue(MySQLiFake::$prepareCalled);
        $this->assertInstanceOf(AbstractResult::class, $result);
    }

    /**
     * @expectedException \BinSoul\Db\Exception\ConnectionException
     */
    public function test_prepare_throws_exception()
    {
        MySQLiFake::$allowPrepare = false;
        MySQLiFake::$definedErrorCode = 2006;

        $connection = new DefaultConnection($this->buildSettings());
        $connection->open();

        $connection->execute('select * from table where id=?', [1]);
    }

    /**
     * @expectedException \BinSoul\Db\Exception\ConnectionException
     */
    public function test_execute_throws_exception()
    {
        MySQLiStmtFake::$allowExecute = false;
        MySQLiStmtFake::$definedErrorCode = 2006;

        $connection = new DefaultConnection($this->buildSettings());
        $connection->open();

        $connection->execute('select * from table where id=?', [1]);
    }
}


text:
namespace acommon {

// only use this on types with a trivial constructors destructor

#ifdef __GNUC__ // use variable arrays

#define VARARRAY(type, name, num) type name[num]
#define VARARRAYM(type, name, num, max) type name[num]

#else // use malloc

  struct MallocPtr {
    void * ptr;
    MallocPtr() : ptr(0) {};
    ~MallocPtr() {if (ptr) free(ptr);}
  };

#define VARARRAY(type, name, num) \
  acommon::MallocPtr name##_data;             \
  name##_data.ptr = malloc(sizeof(type) * (num)); \
  type * name = (type *)name##_data.ptr

#define VARARRAYM(type, name, num, max) type name[max]

#endif

#if 0 // this version uses alloca

#define VARARRAY(type, name, num) \
  type * name = (type *)alloca(sizeof(type) * (num))

#define VARARRAYM(type, name, num, max) \
  type * name = (type *)alloca(sizeof(type) * (num))

#endif

}

#endif


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class Home extends T_Controller{

    function __construct() {
		parent::__construct();
        $this->load->model('forms_model');
	}

    public function index(){
        $data = array();
        $data['forms_list'] = $this->forms_model->forms_list();
        $data['items_list'] = $this->forms_model->items_list();
        $this->load->view('home', $data);
    }

    public function create_form(){
        $this->load->library('form_validation');
        $this->form_validation->set_rules('author', 'Author', 'required');
        if ($this->form_validation->run() == FALSE)
          {
           echo "";
           exit();
          }
    	$data = array();
    	$form_code = $data['form_code'] = $this->input->post('form_code');
    	$create_time = date("Y-m-d H:i:s", time());
        $author = $data['author'] = $this->input->post('author');
        $forms_data = array(
               'form_code' => $form_code,
               'create_time' => $create_time,
               'author' => $author
            );

		if ($this->forms_model->insert_form($forms_data)) {
            $this->load->view('form', $data);
        }else{
            echo "
Sorry, Execution fails!
";
        }
    }

    public function my_form() {
        $form_id = $this->input->get('form_id');
        //var_dump($form_id);
        if ( strlen($form_id)==24 )
        {
            $data = array();
            $data['my_form'] = $this->forms_model->my_form($form_id);
            $this->load->view('my_form', $data);
        }
        elseif ( $form_id=="" OR strlen($form_id)!=24 ){
            echo "
Sorry, The form_id does not meet specifications.
";
        }
        else
        {
            echo "
Sorry, There is something wrong...
";
        }
    }

    public function edit_form() {
        $form_id = $this->input->get('form_id');
        $data = array();
        $data['my_form'] = $this->forms_model->my_form($form_id);
        $this->load->view('edit_form', $data);
    }

    public function update_form() {
        $prev_url = $_SERVER['HTTP_REFERER'];
        $form_id = substr($prev_url, -24 );
        $update_code =  $this->input->post('form_code');
        $data = array();
        $data['update_code'] = $update_code;
        if ($this->forms_model->update_form($form_id,$update_code))
        {
            $this->load->view('form_update', $data);
            //echo "
Your form was update successfully!
";
        }
        else {echo "";}
    }

    public function form_items() {
        $form_id = $this->input->get('form_id');

        if ( strlen($form_id)==24 )
        {
            $data = array();
            $data['my_form'] = $this->forms_model->my_form($form_id);
            $data['form_items'] = $this->forms_model->form_items($form_id);
            $this->load->view('form_items', $data);
        }
        elseif ( $form_id=="" OR strlen($form_id)!=24 ){
            echo "
Sorry, The form_id does not meet specifications.
";
        }
        else { echo "
Sorry, There is something wrong...
"; }
    }

    public function submit_data() {
            $prev_url = $_SERVER['HTTP_REFERER'];
            $url_array=parse_url($prev_url);
            $url_str = $url_array['query'];
            $temp_str=substr($url_str, 0, 7);
            if ($temp_str=="item_id") {
                $item_id = substr($url_str, -24 );
                $item_arr= $this->forms_model->form_id($item_id);
                $form_id = $item_arr[0][0];
            } elseif ($temp_str=="form_id") {
                $form_id = substr($prev_url, -24 );
            }else {
                echo "
Sorry, There is something wrong...
";
            }

            $items = $this->input->post();
            array_pop($items); //remove button item
            //$arr_oid = array("form_id"=>$oid);
            array_unshift($items, $form_id);
            $data['items'] = $items;
            if ($this->forms_model->submit_data($items)) {
                $this->load->view('items', $data);
            }else{
                echo "
Sorry, Form Data submit fails!
";
            }
    }

    public function my_item(){
            $item_id = $this->input->get('item_id');
            $data = array();
            $iterms = $this->forms_model->my_item($item_id);
            array_shift($iterms[0]); //remove _id item
            $data['my_items'] = $iterms;
            //print_r($iterms[0]); exit();
            $form_id = $iterms[0][0];
            $data['form_id'] = $form_id;
            $data['my_form'] = $this->forms_model->my_form($form_id);
            $this->load->view('my_items', $data);
    }

    public function search_form() {
            $this->load->library("cimongo/Cimongo");
            $keyword = trim($this->input->get('keyword'));
            $select_option = $this->input->get('select_option');
            if ($select_option == "author") {
                $query=$this->cimongo->where(array('author'=>$keyword))->get("forms");
            } elseif ($select_option == "form_id") {
                $wheres = array("_id"=>new MongoId("$keyword"));
                $query=$this->cimongo->where($wheres)->get("forms");
            } else {
                $wheres=array("form_code"=>new MongoRegex("/.*".$keyword.".*/i"));
                $query=$this->cimongo->where($wheres)->get("forms");
                //$query=$this->cimongo->like('form_code', '$keyword', 'i', FALSE, TRUE)->get("forms");
            }
            $result = $query->result_array();
            //var_dump($result);
            $data = array();
            $data['result_list'] = $result;
            $this->load->view('search_form', $data);
    }

    public function search_item() {
            $this->load->library("cimongo/Cimongo");
            $keyword = trim($this->input->get('keyword'));
            $select_option = $this->input->get('select_option');
            if ($select_option == "form_id") {
                $query=$this->cimongo->where(array(0=>$keyword))->get("items");
            } elseif ($select_option == "item_id") {
                $wheres = array("_id"=>new MongoId("$keyword"));
                $query=$this->cimongo->where($wheres)->get("items");
            } else {
                $where_clause = array(
                        '$or'=>array(
                            array("textinput"=>$keyword),
                            array("passwordinput"=>$keyword),
                            array("searchinput"=>$keyword),
                            array("prependedtext"=>$keyword),
                            array("appendedtext"=>$keyword),
                            array("prependedcheckbox"=>$keyword),
                            array("appendedcheckbox"=>$keyword),
                            array("buttondropdown"=>$keyword),
                            array("radios"=>$keyword),
                            array("checkboxes"=>$keyword),
                            array("selectbasic"=>$keyword),
                            array("selectmultiple"=>$keyword),
                            array("filebutton"=>$keyword),
                            array("textarea"=>new MongoRegex("/.*".$keyword.".*/i"))
                        )
                    );
                $query = $this->cimongo->where($where_clause, TRUE)->get("items");
            }
            $result = $query->result_array();
            //var_dump($result);exit();
            $data = array();
            $data['result_list'] = $result;
            $this->load->view('search_item', $data);
    }
}


text:
namespace Envoy {
namespace Api {

Event::DispatcherPtr Impl::allocateDispatcher() {
  return Event::DispatcherPtr{new Event::DispatcherImpl()};
}

Impl::Impl(std::chrono::milliseconds file_flush_interval_msec)
    : file_flush_interval_msec_(file_flush_interval_msec) {}

Filesystem::FileSharedPtr Impl::createFile(const std::string& path, Event::Dispatcher& dispatcher,
                                           Thread::BasicLockable& lock, Stats::Store& stats_store) {
  return std::make_shared<Filesystem::FileImpl>(path, dispatcher, lock, stats_store,
                                                file_flush_interval_msec_);
}

bool Impl::fileExists(const std::string& path) { return Filesystem::fileExists(path); }

std::string Impl::fileReadToEnd(const std::string& path) { return Filesystem::fileReadToEnd(path); }

} // namespace Api
} // namespace Envoy


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class com.radaee.view.PDFView</title>
<meta name="date" content="2014-02-13">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
com.radaee.view.PDFView

Packages that use PDFView

Package
Description

com.radaee.view

Uses of PDFView in com.radaee.view

Subclasses of PDFView in com.radaee.view

Modifier and Type
Class and Description

class
PDFViewCurl

class
PDFViewDual

class
PDFViewHorz

class
PDFViewThumb

class
PDFViewVert

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
#include "config.h"

#if ENABLE(TOUCH_EVENTS)

#include "TouchEvent.h"

#include "EventDispatcher.h"
#include "EventNames.h"
#include "EventRetargeter.h"
#include "TouchList.h"
#include <wtf/CurrentTime.h>

namespace WebCore {

TouchEvent::TouchEvent()
{
}

TouchEvent::TouchEvent(TouchList* touches, TouchList* targetTouches,
        TouchList* changedTouches, const AtomicString& type,
        PassRefPtr<AbstractView> view, int screenX, int screenY, int pageX, int pageY,
        bool ctrlKey, bool altKey, bool shiftKey, bool metaKey)
    : MouseRelatedEvent(type, true, true, currentTime(), view, 0, IntPoint(screenX, screenY),
                        IntPoint(pageX, pageY),
#if ENABLE(POINTER_LOCK)
                        IntPoint(0, 0),
#endif
                        ctrlKey, altKey, shiftKey, metaKey)
    , m_touches(touches)
    , m_targetTouches(targetTouches)
    , m_changedTouches(changedTouches)
#if PLATFORM(BLACKBERRY)
    , m_touchHold(false)
    , m_doubleTap(false)
#endif
{
}

TouchEvent::~TouchEvent()
{
}

void TouchEvent::initTouchEvent(TouchList* touches, TouchList* targetTouches,
        TouchList* changedTouches, const AtomicString& type,
        PassRefPtr<AbstractView> view, int screenX, int screenY, int clientX, int clientY,
        bool ctrlKey, bool altKey, bool shiftKey, bool metaKey)
{
    if (dispatched())
        return;

    initUIEvent(type, true, true, view, 0);

    m_touches = touches;
    m_targetTouches = targetTouches;
    m_changedTouches = changedTouches;
    m_screenLocation = IntPoint(screenX, screenY);
    m_ctrlKey = ctrlKey;
    m_altKey = altKey;
    m_shiftKey = shiftKey;
    m_metaKey = metaKey;
    initCoordinates(IntPoint(clientX, clientY));
#if PLATFORM(BLACKBERRY)
    m_doubleTap = false;
    m_touchHold = false;
#endif

}

const AtomicString& TouchEvent::interfaceName() const
{
    return eventNames().interfaceForTouchEvent;
}

bool TouchEvent::isTouchEvent() const
{
    return true;
}

PassRefPtr<TouchEventDispatchMediator> TouchEventDispatchMediator::create(PassRefPtr<TouchEvent> touchEvent)
{
    return adoptRef(new TouchEventDispatchMediator(touchEvent));
}

TouchEventDispatchMediator::TouchEventDispatchMediator(PassRefPtr<TouchEvent> touchEvent)
    : EventDispatchMediator(touchEvent)
{
}

TouchEvent* TouchEventDispatchMediator::event() const
{
    return static_cast<TouchEvent*>(EventDispatchMediator::event());
}

bool TouchEventDispatchMediator::dispatchEvent(EventDispatcher* dispatcher) const
{
    EventRetargeter::adjustForTouchEvent(dispatcher->node(), *event(), dispatcher->eventPath());
    return dispatcher->dispatch();
}

} // namespace WebCore

#endif // ENABLE(TOUCH_EVENTS)


text:
var fs = require('fs')
var path = require('path')
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var CopyWebpackPlugin = require('copy-webpack-plugin')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
var SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin')
var UglifyJsPlugin = require('uglifyjs-webpack-plugin')
var loadMinified = require('./load-minified')
const {getInstalledPathSync} = require('get-installed-path')
var BuukDonePlugin = require('./plugins/buuk-done-plugin')

var env = config.build.env

var webpackConfig = merge(baseWebpackConfig, {
    module: {
        rules: utils.styleLoaders({
            sourceMap: config.build.productionSourceMap,
            extract: true
        })
    },
    devtool: config.build.productionSourceMap ? '#source-map' : false,
    output: {
        path: config.build.assetsRoot,
        filename: utils.assetsPath('js/[name].[chunkhash].js'),
        chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
    },
    plugins: [
        // http://vuejs.github.io/vue-loader/en/workflow/production.html
        new webpack.DefinePlugin({
            'process.env': env
        }),
        new UglifyJsPlugin({
            cache: true,
            parallel: true,
            uglifyOptions: {
                compress: {
                    arrows: false,
                    booleans: false,
                    collapse_vars: false,
                    computed_props: false,
                    hoist_funs: false,
                    hoist_props: false,
                    hoist_vars: false,
                    if_return: false,
                    join_vars: false,
                    keep_infinity: true,
                    loops: false,
                    negate_iife: false,
                    properties: false,
                    reduce_funcs: false,
                    reduce_vars: false,
                    sequences: false,
                    side_effects: false,
                    switches: false,
                    top_retain: false,
                    toplevel: false,
                    typeofs: false,
                    unused: false,

                    // Switch off all types of compression except those needed to convince
                    // react-devtools that we're using a production build
                    conditionals: true,
                    dead_code: true,
                    evaluate: true,
                    comparisons: true,
                    inline: true
                },
                mangle: true
            }
        }),
        // extract css into its own file
        new ExtractTextPlugin({
            filename: utils.assetsPath('css/[name].[contenthash].css')
        }),
        // Compress extracted CSS. We are using this plugin so that possible
        // duplicated CSS from different components can be deduped.
        new OptimizeCSSPlugin({
            cssProcessorOptions: {
                safe: true
            }
        }),
        // generate dist index.html with correct asset hash for caching.
        // you can customize output by editing /index.html
        // see https://github.com/ampedandwired/html-webpack-plugin
        new HtmlWebpackPlugin({
            title: require(`${process.cwd()}/buuk-config.js`).name,
            filename: config.build.index,
            template: `${getInstalledPathSync('buuk')}/index.html`,
            inject: true,
            minify: {
                removeComments: true,
                collapseWhitespace: true,
                removeAttributeQuotes: true
                // more options:
                // https://github.com/kangax/html-minifier#options-quick-reference
            },
            // necessary to consistently work with multiple chunks via CommonsChunkPlugin
            chunksSortMode: 'dependency',
            serviceWorkerLoader: `<script>${loadMinified(path.join(__dirname,
                './service-worker-prod.js'))}</script>`
        }),
        // split vendor js into its own file
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor',
            minChunks: function (module, count) {
                // any required modules inside node_modules are extracted to vendor
                return (
                    module.resource &&
                    /\.js$/.test(module.resource) &&
                    module.resource.indexOf(
                        path.join(__dirname, '../node_modules')
                    ) === 0
                )
            }
        }),
        // extract webpack runtime and module manifest to its own file in order to
        // prevent vendor hash from being updated whenever app bundle is updated
        new webpack.optimize.CommonsChunkPlugin({
            name: 'manifest',
            chunks: ['vendor']
        }),
        // copy custom static assets
        new CopyWebpackPlugin([
            {
                from: path.resolve(__dirname, '../static'),
                to: config.build.assetsSubDirectory,
                ignore: ['.*']
            }
        ]),
        // service worker caching
        new SWPrecacheWebpackPlugin({
            cacheId: 'buuk',
            filename: 'service-worker.js',
            staticFileGlobs: ['dist/**/*.{js,html,css}'],
            minify: true,
            stripPrefix: 'dist/'
        }),
        // Buuk output plugin.
        new BuukDonePlugin()
    ],
})

if (config.build.productionGzip) {
    var CompressionWebpackPlugin = require('compression-webpack-plugin')

    webpackConfig.plugins.push(
        new CompressionWebpackPlugin({
            asset: '[path].gz[query]',
            algorithm: 'gzip',
            test: new RegExp(
                '\\.(' +
                config.build.productionGzipExtensions.join('|') +
                ')$'
            ),
            threshold: 10240,
            minRatio: 0.8
        })
    )
}

if (config.build.bundleAnalyzerReport) {
    var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
    webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}

module.exports = webpackConfig