text:
using System;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using Csla;
using System.ComponentModel;
using System.Threading.Tasks;
using ProjectTracker.Dal;

namespace ProjectTracker.Library
{
  [Serializable()]
  public class ProjectEdit : CslaBaseTypes.BusinessBase<ProjectEdit>
  {
    public static readonly PropertyInfo<byte[]> TimeStampProperty =
      RegisterProperty<byte[]>(nameof(TimeStamp));
    [Browsable(false)]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public byte[] TimeStamp
    {
      get { return GetProperty(TimeStampProperty); }
      set { SetProperty(TimeStampProperty, value); }
    }

    public static readonly PropertyInfo<int> IdProperty =
      RegisterProperty<int>(nameof(Id));
    [Display(Name = "Project id")]
    public int Id
    {
      get { return GetProperty(IdProperty); }
      private set { LoadProperty(IdProperty, value); }
    }

    public static readonly PropertyInfo<string> NameProperty =
      RegisterProperty<string>(nameof(Name));
    [Display(Name = "Project name")]
    [Required]
    [StringLength(50)]
    public string Name
    {
      get { return GetProperty(NameProperty); }
      set { SetProperty(NameProperty, value); }
    }

    public static readonly PropertyInfo<DateTime?> StartedProperty =
      RegisterProperty<DateTime?>(nameof(Started));
    public DateTime? Started
    {
      get { return GetProperty(StartedProperty); }
      set { SetProperty(StartedProperty, value); }
    }

    public static readonly PropertyInfo<DateTime?> EndedProperty =
      RegisterProperty<DateTime?>(nameof(Ended));
    public DateTime? Ended
    {
      get { return GetProperty(EndedProperty); }
      set { SetProperty(EndedProperty, value); }
    }

    public static readonly PropertyInfo<string> DescriptionProperty =
      RegisterProperty<string>(nameof(Description));
    public string Description
    {
      get { return GetProperty(DescriptionProperty); }
      set { SetProperty(DescriptionProperty, value); }
    }

    public static readonly PropertyInfo<ProjectResources> ResourcesProperty =
      RegisterProperty<ProjectResources>(nameof(Resources));
    public ProjectResources Resources
    {
      get { return GetProperty(ResourcesProperty); }
      private set { LoadProperty(ResourcesProperty, value); }
    }

    public override string ToString()
    {
      return Id.ToString();
    }

    protected override void AddBusinessRules()
    {
      base.AddBusinessRules();
      //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(NameProperty));
      BusinessRules.AddRule(
        new StartDateGTEndDate {
          PrimaryProperty = StartedProperty,
          AffectedProperties = { EndedProperty } });
      BusinessRules.AddRule(
        new StartDateGTEndDate {
          PrimaryProperty = EndedProperty,
          AffectedProperties = { StartedProperty } });

      BusinessRules.AddRule(
        new Csla.Rules.CommonRules.IsInRole(
          Csla.Rules.AuthorizationActions.WriteProperty,
          NameProperty,
          "ProjectManager"));
      BusinessRules.AddRule(new Csla.Rules.CommonRules.IsInRole(
        Csla.Rules.AuthorizationActions.WriteProperty, StartedProperty, Security.Roles.ProjectManager));
      BusinessRules.AddRule(new Csla.Rules.CommonRules.IsInRole(
        Csla.Rules.AuthorizationActions.WriteProperty, EndedProperty, Security.Roles.ProjectManager));
      BusinessRules.AddRule(new Csla.Rules.CommonRules.IsInRole(
        Csla.Rules.AuthorizationActions.WriteProperty, DescriptionProperty, Security.Roles.ProjectManager));
      BusinessRules.AddRule(new NoDuplicateResource { PrimaryProperty = ResourcesProperty });
    }

    [EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
    [ObjectAuthorizationRules]
    public static void AddObjectAuthorizationRules()
    {
      Csla.Rules.BusinessRules.AddRule(
        typeof(ProjectEdit),
        new Csla.Rules.CommonRules.IsInRole(
          Csla.Rules.AuthorizationActions.CreateObject,
          "ProjectManager"));
      Csla.Rules.BusinessRules.AddRule(typeof(ProjectEdit),
        new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.EditObject, Security.Roles.ProjectManager));
      Csla.Rules.BusinessRules.AddRule(typeof(ProjectEdit),
        new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.DeleteObject, Security.Roles.ProjectManager, Security.Roles.Administrator));
    }

    protected override void OnChildChanged(Csla.Core.ChildChangedEventArgs e)
    {
      if (e.ChildObject is ProjectResources)
      {
        BusinessRules.CheckRules(ResourcesProperty);
        OnPropertyChanged(ResourcesProperty);
      }
      base.OnChildChanged(e);
    }

    private class NoDuplicateResource : Csla.Rules.BusinessRule
    {
      protected override void Execute(Csla.Rules.IRuleContext context)
      {
        var target = (ProjectEdit)context.Target;
        foreach (var item in target.Resources)
        {
          var count = target.Resources.Count(r => r.ResourceId == item.ResourceId);
          if (count > 1)
          {
            context.AddErrorResult("Duplicate resources not allowed");
            return;
          }
        }
      }
    }

    private class StartDateGTEndDate : Csla.Rules.BusinessRule
    {
      protected override void Execute(Csla.Rules.IRuleContext context)
      {
        var target = (ProjectEdit)context.Target;

        var started = target.ReadProperty(StartedProperty);
        var ended = target.ReadProperty(EndedProperty);
        if (started.HasValue && ended.HasValue && started > ended || !started.HasValue && ended.HasValue)
          context.AddErrorResult("Start date can't be after end date");
      }
    }

    public async static Task<ProjectEdit> NewProjectAsync()
    {
      return await DataPortal.CreateAsync<ProjectEdit>();
    }

    public async static Task<ProjectEdit> GetProjectAsync(int id)
    {
      return await DataPortal.FetchAsync<ProjectEdit>(id);
    }

    public static ProjectEdit NewProject()
    {
      return DataPortal.Create<ProjectEdit>();
    }

    public static ProjectEdit GetProject(int id)
    {
      return DataPortal.Fetch<ProjectEdit>(id);
    }

    public static async Task DeleteProjectAsync(int id)
    {
      await DataPortal.DeleteAsync<ProjectEdit>(id);
    }

    public static async Task<bool> ExistsAsync(int id)
    {
      var cmd = await DataPortal.CreateAsync<ProjectExistsCommand>(id);
      cmd = await DataPortal.ExecuteAsync(cmd);
      return cmd.ProjectExists;
    }

    [Create]
    [RunLocal]
    private void Create()
    {
      LoadProperty(ResourcesProperty, DataPortal.CreateChild<ProjectResources>());
      BusinessRules.CheckRules();
    }

    [Fetch]
    private void Fetch(int id, [Inject] IProjectDal dal)
    {
      var data = dal.Fetch(id);
      using (BypassPropertyChecks)
      {
        Id = data.Id;
        Name = data.Name;
        Description = data.Description;
        Started = data.Started;
        Ended = data.Ended;
        TimeStamp = data.LastChanged;
        Resources = DataPortal.FetchChild<ProjectResources>(id);
      }
    }

    [Insert]
    private void Insert([Inject] IProjectDal dal)
    {
      using (BypassPropertyChecks)
      {
        var item = new ProjectTracker.Dal.ProjectDto
        {
          Name = this.Name,
          Description = this.Description,
          Started = this.Started,
          Ended = this.Ended
        };
        dal.Insert(item);
        Id = item.Id;
        TimeStamp = item.LastChanged;
      }
      FieldManager.UpdateChildren(this);
    }

    [Update]
    private void Update([Inject] IProjectDal dal)
    {
      using (BypassPropertyChecks)
      {
        var item = new ProjectTracker.Dal.ProjectDto
        {
          Id = this.Id,
          Name = this.Name,
          Description = this.Description,
          Started = this.Started,
          Ended = this.Ended,
          LastChanged = this.TimeStamp
        };
        dal.Update(item);
        TimeStamp = item.LastChanged;
      }
      FieldManager.UpdateChildren(this.Id);
    }

    [DeleteSelf]
    private void DeleteSelf([Inject] IProjectDal dal)
    {
      using (BypassPropertyChecks)
      {
        Resources.Clear();
        FieldManager.UpdateChildren(this);
        Delete(this.Id, dal);
      }
    }

    [Delete]
    private void Delete(int id, [Inject] IProjectDal dal)
    {
      dal.Delete(id);
    }
  }
}


text:
package org.wso2.carbon.registry.extensions.handlers.utils;

import com.ibm.wsdl.extensions.schema.SchemaImportImpl;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ws.commons.schema.XmlSchema;
import org.apache.ws.commons.schema.XmlSchemaCollection;
import org.apache.ws.commons.schema.XmlSchemaExternal;
import org.apache.ws.commons.schema.XmlSchemaObjectCollection;
import org.wso2.carbon.CarbonException;
import org.wso2.carbon.registry.core.*;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.jdbc.handlers.RequestContext;
import org.wso2.carbon.registry.core.utils.RegistryUtils;
import org.wso2.carbon.registry.extensions.utils.CommonConstants;
import org.wso2.carbon.registry.extensions.utils.CommonUtil;
import org.wso2.carbon.registry.extensions.utils.WSDLUtil;
import org.wso2.carbon.registry.extensions.utils.WSDLValidationInfo;
import org.wso2.carbon.utils.CarbonUtils;
import org.xml.sax.InputSource;

import javax.wsdl.Types;
import javax.wsdl.extensions.schema.Schema;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;

public class SchemaProcessor {
    private Registry registry;
    private Registry systemRegistry;
    private List<String> processedSchemas;
    private List<String> visitedSchemas;
    private Map<String, SchemaInfo> schemas;
    private List<Association> associations;
    private String baseURI = null;
    private WSDLValidationInfo validationInfo;
    private static final String SCHEMA_VALIDATION_MESSAGE = "Schema Validation Message ";
    private static final String SCHEMA_STATUS = "Schema Validation";
    private boolean useOriginalSchema;

    private String resourceName = "";

    private static final Log log = LogFactory.getLog(SchemaProcessor.class);

    private int i;

    private String absoluteFilePath = null;//to hold the absolute path of schema from the sourceuri

    public SchemaProcessor(RequestContext requestContext, WSDLValidationInfo validationInfo) {
        this.registry = requestContext.getRegistry();
        try {
            this.systemRegistry = CommonUtil.getUnchrootedSystemRegistry(requestContext);
        } catch (RegistryException ignore) {
            this.systemRegistry = null;
        }
        i = 0;
        schemas = new LinkedHashMap<String, SchemaInfo> ();
        processedSchemas = new ArrayList<String>();
        visitedSchemas = new ArrayList<String>();
        associations = new ArrayList<Association>();
        this.validationInfo = validationInfo;
    }

    public SchemaProcessor(RequestContext requestContext, WSDLValidationInfo validationInfo, boolean useOriginalSchema) {
        this(requestContext,validationInfo);
        this.useOriginalSchema = useOriginalSchema;
    }

    /* Save the schema, schema imports, associations in the registry. Intended to used by the XSD Media-type handler
       only.
     */
    public String putSchemaToRegistry( RequestContext requestContext,
                                       String resourcePath,
                                       String commonLocation,
                                       boolean processIncludes,boolean disableSymlinkCreation) throws RegistryException {

        boolean isDefaultEnvironment = true;
        String currentSchemaLocation = null;
        String currentEnvironment = null;
        String masterVersion = null;

        List<String> dependeinciesList = new ArrayList<String>();

        resourceName = resourcePath.substring(resourcePath.lastIndexOf(RegistryConstants.PATH_SEPARATOR) + 1);
        XmlSchemaCollection xmlSchemaCollection = new XmlSchemaCollection();
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream((byte[])requestContext.getResource().getContent());
        InputSource inputSource = new InputSource(byteArrayInputStream);
        String url = "http://this.schema.needs/a/valid/source/url/to/proceed.xsd";

        String version = requestContext.getResource().getProperty("version");
        if(version == null){
            version = CommonConstants.SCHEMA_VERSION_DEFAULT_VALUE;
        }

        if(requestContext.getSourceURL() != null) {
            url = requestContext.getSourceURL();
        }
        XmlSchema xmlSchema;
        try {
            xmlSchemaCollection.setBaseUri(url);
            xmlSchema = xmlSchemaCollection.read(inputSource, null);
            xmlSchema.setSourceURI(url);
            evaluateSchemasRecursively(xmlSchema, null, false, true);
        }catch (URISyntaxException e) {
            String msg = "Syntax error in the uri";
            log.error(msg, e);
            throw new RegistryException(msg, e);//to preserver the exception handling execution path of the rest of the
            //application.
        }catch (RuntimeException re) {
            String msg = "Could not read the XML Schema Definition file. ";
            if (re.getCause() instanceof org.apache.ws.commons.schema.XmlSchemaException) {
                msg += re.getCause().getMessage();
                log.error(msg, re);
                throw new RegistryException(msg);
            }

            throw new RegistryException(msg, re);
        }

        String path = null; // should depend on the central location / relative location flag
        if (!resourcePath.equals(RegistryConstants.PATH_SEPARATOR + resourceName)
                & !resourcePath.contains(commonLocation) & (registry.resourceExists(resourcePath))) {

            if (currentSchemaLocation == null) {
                currentEnvironment = resourcePath.substring(0, resourcePath.indexOf(CommonUtil.
                        derivePathFragmentFromNamespace(xmlSchema.getTargetNamespace()).replace("//", "/")));
                currentSchemaLocation = currentEnvironment.substring(RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH.length() + 1);
            }
            if (masterVersion == null) {
                String namespaceSegment = CommonUtil.
                        derivePathFragmentFromNamespace(xmlSchema.getTargetNamespace()).replace("//", "/");
                String suffix = resourcePath.substring(resourcePath.indexOf(namespaceSegment)
                        + namespaceSegment.length());
                masterVersion = suffix.substring(0, suffix.indexOf(RegistryConstants.PATH_SEPARATOR));
            }
            isDefaultEnvironment = false;

            Association[] associations = registry.getAssociations(resourcePath, CommonConstants.DEPENDS);
            for (Association association : associations) {
                if (association.getSourcePath().equals(resourcePath)) {
                    dependeinciesList.add(association.getDestinationPath());
                }
            }
            dependeinciesList.add(resourcePath);

            //            updateSchemaPaths(currentEnvironment,masterVersion,dependeinciesList);

            //            updateSchemaInternalsAndAssociations();
            String symlinkLocation = RegistryUtils.getAbsolutePath(requestContext.getRegistryContext(),
                    requestContext.getResource().getProperty(RegistryConstants.SYMLINK_PROPERTY_NAME));

            Resource metaResource = requestContext.getResource();
            path = saveSchemasToRegistry(requestContext, currentEnvironment, symlinkLocation,
                                         metaResource, masterVersion, dependeinciesList,disableSymlinkCreation);
            persistAssociations(path);

        } else {
            updateSchemaPaths(commonLocation, version);

            updateSchemaInternalsAndAssociations();
            String symlinkLocation = RegistryUtils.getAbsolutePath(requestContext.getRegistryContext(),
                    requestContext.getResource().getProperty(RegistryConstants.SYMLINK_PROPERTY_NAME));

            Resource metaResource = requestContext.getResource();
            path = saveSchemaToRegistry(requestContext, resourcePath, symlinkLocation, metaResource,disableSymlinkCreation);
            persistAssociations(path);
        }
        return path;
    }

    /* Save the schema, schema imports, associations in the registry. Intended to used by the XSD Media-type handler
       only.
     */
    public String importSchemaToRegistry(RequestContext requestContext,
                                       String resourcePath,
                                       String commonLocation,
                                       boolean processIncludes,boolean disableSymlinkCreation) throws RegistryException {
        resourceName = resourcePath.substring(resourcePath.lastIndexOf(RegistryConstants.PATH_SEPARATOR) + 1);
        String url = requestContext.getSourceURL();
        String version = requestContext.getResource().getProperty("version");
        if(version == null){
            version = CommonConstants.SCHEMA_VERSION_DEFAULT_VALUE;
        }
        XmlSchemaCollection xmlSchemaCollection = new XmlSchemaCollection();
        xmlSchemaCollection.setBaseUri(url);
        baseURI = url;
        InputSource inputSource = new InputSource(url);

        try {
            // Here we assue schema is correct. Schema validation is beyond our scope, so we don't
            // bother with a ValidationEventHandler.
            XmlSchema xmlSchema = xmlSchemaCollection.read(inputSource, null);
            evaluateSchemasRecursively(xmlSchema, null, false, true);
        }catch (URISyntaxException e) {
            String msg = "Syntax error in the uri";
            log.error(msg, e);
            throw new RegistryException(msg, e);//to preserver the exception handling execution path of the rest of the
            //application.
        }
        catch (RuntimeException re) {
            String msg = "Could not read the XML Schema Definition file. ";
            if (re.getCause() instanceof org.apache.ws.commons.schema.XmlSchemaException) {
                msg += re.getCause().getMessage();
                log.error(msg, re);
                throw new RegistryException(msg);
            }
            throw new RegistryException(msg, re);
        }
        updateSchemaPaths(commonLocation,version);

        updateSchemaInternalsAndAssociations();

        String symlinkLocation = requestContext.getResource().getProperty(RegistryConstants.SYMLINK_PROPERTY_NAME);

        Resource metaResource = requestContext.getResource();
        String path = saveSchemaToRegistry(requestContext, resourcePath, symlinkLocation, metaResource,disableSymlinkCreation); // should depend on the central location / relative location flag
        persistAssociations(path);
        return path;
    }

    public void evaluateSchemas(
            Types types,
            String wsdlDocumentBaseURI,
            boolean evaluateImports,
            ArrayList<String> dependencies) throws RegistryException {
        baseURI = wsdlDocumentBaseURI;
        /* evaluating schemas found under wsdl:types tag in a wsdl */
        if (types != null) {
            List extensibleElements = types.getExtensibilityElements();
            Schema schema;
            Object extensionObject;
            XmlSchema xmlSchema;
            XmlSchemaCollection xmlSchemaCollection;
            wsdlDocumentBaseURI = wsdlDocumentBaseURI.substring(0, wsdlDocumentBaseURI.lastIndexOf("/") + 1);
            for (Object extensibleElement : extensibleElements) {
                extensionObject = extensibleElement;
                if (extensionObject instanceof Schema) {
                    schema = (Schema)extensionObject;
                    if (schema.getImports().size() > 0) {
                        SchemaImportImpl schemaImport =
                                (SchemaImportImpl) ((Vector) schema.getImports().values()
                                        .toArray()[0]).firstElement();
                        if (schemaImport.getReferencedSchema() != null) {
                            // already added imported xsd
                            CommonUtil.addImportedArtifact(
                                    new File(schemaImport.getReferencedSchema().getDocumentBaseURI()).toString());
                        }
                    }
                    xmlSchemaCollection = new XmlSchemaCollection();
                    /* setting base URI in the collection to load relative schemas */
                    xmlSchemaCollection.setBaseUri(wsdlDocumentBaseURI);
                    xmlSchema = xmlSchemaCollection.read(schema.getElement());
                    try {
                        evaluateSchemasRecursively(xmlSchema, dependencies, true, false);
                    } catch (URISyntaxException e) {
                        String msg = "Syntax error in the uri";
                        log.error(msg, e);
                        throw new RegistryException(msg, e);//to preserver the exception handling execution path of the rest of the
                        //application.
                    }
                }
            }
        }
    }

    private void evaluateSchemasRecursively(
            XmlSchema xmlSchema,
            ArrayList<String> dependencies,
            boolean isWSDLInlineSchema, boolean isMasterSchema) throws RegistryException, URISyntaxException {
        // first process the imports and includes
        XmlSchemaObjectCollection includes = xmlSchema.getIncludes();
        SchemaInfo schemaInfo = new SchemaInfo();
        schemaInfo.setMasterSchema(isMasterSchema);
        if (xmlSchema.getSourceURI() != null) {
        	// set this as an visited schema to stop infinite traversal
            visitedSchemas.add(xmlSchema.getSourceURI());
            //Get the uri form of the sourceUri string.
            URI uri = new URI(xmlSchema.getSourceURI());
            //Extract the absolute path of master schema which has 'file' uri.
            if (isMasterSchema && uri.getScheme().equals("file")) {
                String sourceUri = xmlSchema.getSourceURI();
                absoluteFilePath = StringUtils.removeStart(sourceUri, "file:///");//gives the file path
                // without "file:///" prefix.
            }
        }

        if (includes != null) {
            Object externalComponent;
            XmlSchemaExternal xmlSchemaExternal;
            XmlSchema innerSchema;
            for (Iterator iter = includes.getIterator(); iter.hasNext();) {
                externalComponent = iter.next();
                if (externalComponent instanceof XmlSchemaExternal) {
                    xmlSchemaExternal = (XmlSchemaExternal)externalComponent;
                    innerSchema = xmlSchemaExternal.getSchema();
                    if (innerSchema != null) {
                        String sourceURI = innerSchema.getSourceURI();
                        if (isWSDLInlineSchema) {
                            dependencies.add(sourceURI);
                        }
                        else {
                            schemaInfo.getSchemaDependencies().add(sourceURI);
                        }

                        if (!visitedSchemas.contains(sourceURI)) {
                            String dependencyAbsoluteFilePath = StringUtils.removeStart(sourceURI, "file:/");//gives
                            // the file path without "file:/" prefix.
                            if (!dependencyAbsoluteFilePath.equals(absoluteFilePath)) {//evaluate schema recursively if the
                                //absolute filepaths are different.
                                evaluateSchemasRecursively(
                                        innerSchema,
                                        null,   /* passing null is safe since we are passing isWSDLSchema = false */
                                        false, false); /* ignore inline schema and proceed with included ones */
                            }
                        }
                    }
                }
            }
        }

        if (!isWSDLInlineSchema) {
            // after processing includes and imports save the xml schema
            String sourceURI = xmlSchema.getSourceURI();
            String fileNameToSave;
            if (isMasterSchema) {
                fileNameToSave = extractResourceFromURL(resourceName, ".xsd");
            } else {
                fileNameToSave = extractResourceFromURL(sourceURI.substring(sourceURI.lastIndexOf(RegistryConstants.PATH_SEPARATOR) + 1), ".xsd");
            }

            fileNameToSave = fileNameToSave.replace("?xsd=", ".");
            String originalName = fileNameToSave;
            while (processedSchemas.contains(fileNameToSave)) {
                fileNameToSave = fileNameToSave.substring(0, fileNameToSave.indexOf(".")) + ++i + ".xsd";
            }

            // If this was the master schema, and we already have a schema by that name, simply swap
            // proposed names. But in the process, validate whether the schema that already exists
            // on the list is not a master schema, and thereby avoid any recursion.
            if (schemaInfo.isMasterSchema() && !originalName.equals(fileNameToSave)) {
                for (SchemaInfo schema : schemas.values()) {
                    if (schema.getProposedResourceName().equals(originalName)) {
                        if (!schema.isMasterSchema()) {
                            schema.setProposedResourceName(fileNameToSave);
                            fileNameToSave = originalName;
                        }
                        break;
                    }
                }
            }
            // add this entry to the processed schema map
            processedSchemas.add(fileNameToSave);
            //schemaInfo.setProposedRegistryURL(fileNameToSave);
            schemaInfo.setProposedResourceName(fileNameToSave);
            schemaInfo.setSchema((xmlSchema));
            schemaInfo.setOriginalURL(sourceURI);
            schemas.put(getAbsoluteSchemaURL(sourceURI), schemaInfo);
        }
    }

    public String getSchemaRegistryPath(String parentRegistryPath, String sourceURL) throws RegistryException {
        SchemaInfo schemaInfo = schemas.get(getAbsoluteSchemaURL(sourceURL));
        if (schemaInfo != null) {
            //return WSDLUtil.getLocationPrefix(parentRegistryPath) + schemaInfo.getProposedRegistryURL();
            return WSDLUtil.computeRelativePathWithVersion(parentRegistryPath, schemaInfo.getProposedRegistryURL(), systemRegistry);
        }
        return null;
    }

    public String getSchemaAssociationPath(String sourceURL) {
        SchemaInfo schemaInfo = schemas.get(sourceURL);
        if (schemaInfo != null) {
            String proposedRegistryURL = schemaInfo.getProposedRegistryURL();
            return proposedRegistryURL.replaceAll("\\.\\./", "");
        }
        return null;
    }

    /**
     * For each schema found in schemas, change corresponding schemaInfo's ProposedRegistryURL based on
     * commonSchemaLocation and mangled targetNamespace
     * @param commonSchemaLocation the location to store schemas
     * @throws RegistryException if the operation failed.
     */
    private void updateSchemaPaths(String commonSchemaLocation, String version) throws RegistryException {
        /* i.e. ROOT/commonSchemaLocation */
        if (!systemRegistry.resourceExists(commonSchemaLocation)) {
            systemRegistry.put(commonSchemaLocation, systemRegistry.newCollection());
        }
        for (SchemaInfo schemaInfo: schemas.values()) {
            XmlSchema schema = schemaInfo.getSchema();
            String targetNamespace = schema.getTargetNamespace();
            if ((targetNamespace == null) || ("".equals(targetNamespace))) {
                targetNamespace = "unqualified";
            }
            String schemaLocation = (commonSchemaLocation +
                    CommonUtil.derivePathFragmentFromNamespace(targetNamespace)).replace("//", "/");
            schemaLocation += version +"/"+ schemaInfo.getProposedResourceName();
            schemaInfo.setProposedRegistryURL(schemaLocation);
        }
    }
    private void updateSchemaPaths(String commonSchemaLocation,String version,List dependencies) throws RegistryException {
        /* i.e. ROOT/commonSchemaLocation */
        if (!systemRegistry.resourceExists(commonSchemaLocation)) {
            systemRegistry.put(commonSchemaLocation, systemRegistry.newCollection());
        }
        outerLoop:
        for (SchemaInfo schemaInfo: schemas.values()) {
            XmlSchema schema = schemaInfo.getSchema();
            String targetNamespace = schema.getTargetNamespace();
            if ((targetNamespace == null) || ("".equals(targetNamespace))) {
                targetNamespace = "unqualified";
            }

            String schemaLocation = (commonSchemaLocation +
                    CommonUtil.derivePathFragmentFromNamespace(targetNamespace)).replace("//", "/");
            String regex =  schemaLocation + "[\\d].[\\d].[\\d]" + RegistryConstants.PATH_SEPARATOR
                    + schemaInfo.getProposedResourceName();

            for (Object dependency : dependencies) {
                String path = dependency.toString();
                if(path.matches(regex)){
                    schemaLocation = path;
                    schemaInfo.setProposedRegistryURL(schemaLocation);
                    continue outerLoop;
                }
            }
            schemaLocation = schemaLocation + version + RegistryConstants.PATH_SEPARATOR
                    + schemaInfo.getProposedResourceName();
            schemaInfo.setProposedRegistryURL(schemaLocation);

        }
    }

    /**
     * Update the schema's internal import location according to the new registry URLs.
     * Furthermore, fill the associations arraylist according to the detectored associations.
     */
    private void updateSchemaInternalsAndAssociations() throws RegistryException {
        for (SchemaInfo schemaInfo: schemas.values()) {
            XmlSchema schema = schemaInfo.getSchema();
            XmlSchemaObjectCollection includes = schema.getIncludes();
            if (includes != null) {
                for (Iterator iter = includes.getIterator(); iter.hasNext();) {
                    Object externalComponent = iter.next();
                    if (externalComponent instanceof XmlSchemaExternal) {
                        XmlSchemaExternal xmlSchemaExternal = (XmlSchemaExternal)externalComponent;
                        XmlSchema schema1 = xmlSchemaExternal.getSchema();
                        if (schema1 != null) {
                            String sourceURI = getAbsoluteSchemaURL(schema1.getSourceURI());
                            if (schemas.containsKey(sourceURI)) {
                                SchemaInfo info = schemas.get(sourceURI);
                                String relativeSchemaPath = WSDLUtil.computeRelativePathWithVersion(schemaInfo.getProposedRegistryURL(), info.getProposedRegistryURL(), registry);
                                xmlSchemaExternal.setSchemaLocation(relativeSchemaPath);
                            }
                        }
                    }
                }
            }

            // creating associations
            for(String associatedTo : schemaInfo.getSchemaDependencies()) {
                SchemaInfo schemaInfoAssociated = schemas.get(associatedTo);
                if (schemaInfoAssociated != null) {
                    associations.add(new Association(schemaInfo.getProposedRegistryURL(),
                            schemaInfoAssociated.getProposedRegistryURL(),
                            CommonConstants.DEPENDS));
                    associations.add(new Association(schemaInfoAssociated.getProposedRegistryURL(),
                            schemaInfo.getProposedRegistryURL(),
                            CommonConstants.USED_BY));
                }
            }
        }
    }

    public String saveSchemasToRegistry(RequestContext requestContext, String commonSchemaLocation,
                                        String symlinkLocation, Resource metaResource,boolean disableSymlinkCreation)
            throws RegistryException {
        updateSchemaPaths(commonSchemaLocation,requestContext.getResource().getProperty("version"));
        updateSchemaInternalsAndAssociations();
        String path = saveSchemaToRegistry(requestContext, null, symlinkLocation, metaResource,disableSymlinkCreation);
        persistAssociations(path);
        return path;
    }
    public String saveSchemasToRegistry(RequestContext requestContext, String commonSchemaLocation,
                                        String symlinkLocation, Resource metaResource,String version,List dependencies,boolean disableSymlinkCreation)
            throws RegistryException {
        updateSchemaPaths(commonSchemaLocation,version,dependencies);
        updateSchemaInternalsAndAssociations();
        String path = saveSchemaToRegistry(requestContext, null, symlinkLocation, metaResource,disableSymlinkCreation);
        persistAssociations(path);
        return path;
    }

    @SuppressWarnings("unchecked")
    private String saveSchemaToRegistry(RequestContext requestContext, String resourcePath,
                                        String symlinkLocation, Resource metaResource,boolean disableSymlinkCreation)
            throws RegistryException {
        String path = resourcePath;
        for (SchemaInfo schemaInfo: schemas.values()) {
            XmlSchema schema = schemaInfo.getSchema();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            schema.write(byteArrayOutputStream);
            byte[] xsdContent = byteArrayOutputStream.toByteArray();

            String schemaPath = schemaInfo.getProposedRegistryURL();
            Resource xsdResource;
            if (metaResource != null && registry.resourceExists(schemaPath)) {
                xsdResource = registry.get(schemaPath);
            } else {
                xsdResource = new ResourceImpl();
                if (metaResource != null) {
                    Properties properties = metaResource.getProperties();
                    if (properties != null) {
                        List<String> linkProperties = Arrays.asList(
                                RegistryConstants.REGISTRY_LINK,
                                RegistryConstants.REGISTRY_USER,
                                RegistryConstants.REGISTRY_MOUNT,
                                RegistryConstants.REGISTRY_AUTHOR,
                                RegistryConstants.REGISTRY_MOUNT_POINT,
                                RegistryConstants.REGISTRY_TARGET_POINT,
                                RegistryConstants.REGISTRY_ACTUAL_PATH,
                                RegistryConstants.REGISTRY_REAL_PATH);
                        for (Map.Entry<Object, Object> e : properties.entrySet()) {
                            String key = (String) e.getKey();
                            if (!linkProperties.contains(key)) {
                                xsdResource.setProperty(key, (List<String>) e.getValue());
                            }
                        }
                    }
                }
            }
            xsdResource.setMediaType("application/x-xsd+xml");

            if (this.useOriginalSchema) {
                try {
                    xsdResource.setContent(CarbonUtils.getBytesFromFile(new File(new URI(schemaInfo.getOriginalURL()))));
                } catch (CarbonException e) {
                    String errMsg = "Trying to store original schema in registry failed while " +
                                    "generating the content from original schema.";
                    log.error(errMsg, e);
                    throw new RegistryException(errMsg, e);
                } catch (URISyntaxException e) {
                    String errMsg = "Trying to store original schema in registry failed due to error " +
                                    "occurred in file url:" + schemaInfo.getOriginalURL();
                    log.error(errMsg, e);
                    throw new RegistryException(errMsg, e);
                }
            } else {
                xsdResource.setContent(xsdContent);
            }

            if(metaResource != null){
                xsdResource.setDescription(metaResource.getDescription());
            }
            String targetNamespace = schema.getTargetNamespace();
            xsdResource.setProperty("targetNamespace", targetNamespace);

            if (schemaInfo.isMasterSchema() && validationInfo != null) {

                ArrayList<String> messages = validationInfo.getValidationMessages();
                if (messages.size() > 0) {
                    xsdResource.setProperty(SCHEMA_STATUS, WSDLUtils.INVALID);
                } else {
                    xsdResource.setProperty(SCHEMA_STATUS, WSDLUtils.VALID);
                }
                int i = 1;
                for (String message : messages) {
                    if (message == null) {
                        continue;
                    }
                    if (message.length() > 1000) {
                        message = message.substring(0, 997) + "...";
                    }
                    xsdResource.setProperty(SCHEMA_VALIDATION_MESSAGE + i, message);
                    i++;
                }
            }
            if(schemaInfo.isMasterSchema()){
//                persisting the UUID for master schema
                xsdResource.setUUID(metaResource.getUUID());

//                if there is a change in the path, we delete the old resource
                if(path != null && !schemaPath.equals(path) && registry.resourceExists(path)){
                    Resource oldResource = registry.get(path);
                    if(oldResource.getProperty("registry.resource.symlink.path") != null){
                        registry.delete(oldResource.getProperty("registry.resource.symlink.path"));
                    }
                    registry.delete(path);
                }
            }

            boolean newSchemaUpload = !registry.resourceExists(schemaPath);
            saveToRepositorySafely(requestContext, schemaInfo.getOriginalURL(), schemaPath,
                    xsdResource);
            if (symlinkLocation == null && resourcePath != null &&
                    !(resourcePath.equals("/") || resourcePath.equals(schemaPath)
                            || resourcePath.equals(""))) {
                symlinkLocation = RegistryUtils.getParentPath(resourcePath);
            }

            if (schemaInfo.isMasterSchema() && symlinkLocation != null) {
                if (registry.resourceExists(symlinkLocation)) {
                    Resource resource = registry.get(symlinkLocation);
                    if (resource != null) {
                        String isLink = resource.getProperty("registry.link");
                        String mountPoint = resource.getProperty("registry.mountpoint");
                        String targetPoint = resource.getProperty("registry.targetpoint");
                        String actualPath = resource.getProperty("registry.actualpath");
                        if (isLink != null && mountPoint != null && targetPoint != null) {
    //                        symlinkLocation = symlinkLocation.replace(mountPoint, targetPoint);
                            symlinkLocation = actualPath + RegistryConstants.PATH_SEPARATOR;
                        }
                    }
                }
                // 1. New resource: resourcePath = /foo, schemaPath = /ns/name.xsd, symlinkPath = /foo, resourceExist = false, resourceIsSymLink = false, createSymlink = true. DoWork = true
                // 2. New resource, existing symlink: resourcePath = /foo, xsdPath = /ns/name.xsd, symlinkPath = /foo, resourceExist = false, resourceIsSymLink = true, createSymlink = false
                // 3. Edit from symlink: resourcePath = /foo, schemaPath = /ns/name.xsd, symlinkPath = /foo, resourceExist = true, resourceIsSymLink = true,  createSymlink = false,
                // 4. Edit from resource: resourcePath = /ns/name.xsd, schemaPath = /ns/name.xsd, symlinkPath = /ns/name.xsd, resourceExist = true, resourceIsSymLink = false, createSymlink = false,
                // 5. Edit from resource, change ns: resourcePath = /ns/name.xsd, schemaPath = /ns2/name.xsd, symlinkPath = /ns/name.xsd, resourceExist = true, resourceIsSymLink = false, createSymlink = false, deleteResource = true. DoWork = true
                // 6. Edit from symlink, change ns: resourcePath = /ns/name.xsd, schemaPath = /ns2/name.xsd, symlinkPath = /ns/name.xsd, resourceExist = true, resourceIsSymLink = true, createSymlink = delete and add, deleteResource = true. DoWork = true
                if (!symlinkLocation.endsWith(RegistryConstants.PATH_SEPARATOR)) {
                    symlinkLocation = symlinkLocation + RegistryConstants.PATH_SEPARATOR;
                }
                /*
                String symLinkTargetNs = "";
                if(!symlinkLocation.startsWith("/_system/governance")) {
                    if (targetNamespace.startsWith("http://")) {
                        symLinkTargetNs = targetNamespace.replaceAll("http://", "").replaceAll("\\.", "_") + "_";
                    } else if (targetNamespace.startsWith("https://")) {
                        symLinkTargetNs = targetNamespace.replaceAll("https://", "").replaceAll("\\.", "_") + "_";
                    }
                }
                String symlinkPath = symlinkLocation + symLinkTargetNs +resourceName;
                                */
                String symlinkPath = symlinkLocation + extractResourceFromURL(resourceName,".xsd");
                int j = 0;
            if(!disableSymlinkCreation) {
                while (true) {
                    if (!registry.resourceExists(symlinkPath)) {
                        if (CommonUtil.isSymbolicLinkMapExisting()) {
                            CommonUtil.addToSymbolicLinkMap(symlinkPath, schemaPath);
                        } else {
                            systemRegistry.createLink(symlinkPath, schemaPath);
                        }
                        break;
                    } else if (newSchemaUpload) {
                        if (registry.get(symlinkPath).getProperty(RegistryConstants.REGISTRY_LINK) != null) {
                            //only symlinks can be exist in the root
                            String actualPath = registry.get(symlinkPath).getProperty(RegistryConstants.REGISTRY_ACTUAL_PATH);
                            if (schemaPath.equals(actualPath)) {
                                break;
                            }
                        }
                    } else {
                        break;
                    }
                    j++;
                    symlinkPath = RegistryConstants.ROOT_PATH + extractResourceFromURL(resourceName,"-"+j+".xsd");
                }
            }
            }

            if (schemaInfo.isMasterSchema()) {
                path = schemaPath;
            }
        }
        return path;
    }

    /**
     * Save associations to the registry if they do not exist.
     * Execution time could be improved if registry provides a better way to check existing associations.
     *
     * @throws RegistryException
     */
    private void persistAssociations(String schemaPath) throws RegistryException {
        // until registry provides a functionality to check existing associations, this method will consume a LOT of time
        for (Association association: associations) {
            boolean isAssociationExist = false;
            Association[] existingAssociations = registry.getAllAssociations(association.getSourcePath());
            if (existingAssociations != null) {
                for (Association currentAssociation: existingAssociations) {
                    if (currentAssociation.getDestinationPath().equals(association.getDestinationPath()) &&
                            currentAssociation.getAssociationType().equals(association.getAssociationType())) {
                        isAssociationExist = true;
                        break;
                    }
                }
            }
            if (!isAssociationExist) {
                registry.addAssociation(association.getSourcePath(),
                        association.getDestinationPath(),
                        association.getAssociationType());
            }
        }
        // this code was added to fix CARBON-11188
        if( schemaPath!= null && associations.isEmpty()) {
            Association[] dependencies = registry.getAssociations(schemaPath, CommonConstants.DEPENDS);
            for(Association dependency : dependencies) {
                if(dependency.getSourcePath().equals(schemaPath)) {
                    registry.removeAssociation(dependency.getSourcePath(), dependency.getDestinationPath(), CommonConstants.DEPENDS);
                    registry.removeAssociation(dependency.getDestinationPath(), dependency.getSourcePath(), CommonConstants.USED_BY);
                }
            }
        }
    }

    /**
     * Saves the resource iff the resource is not already existing in the repository
     * @param path: resource path
     * @param resource: resource object
     * @throws RegistryException
     */
    private void saveToRepositorySafely(RequestContext context, String url, String path,
                                        Resource resource) throws RegistryException {

        String schemaId = resource.getUUID();

        if (schemaId == null) {
            // generate a service id
            schemaId = UUID.randomUUID().toString();
            resource.setUUID(schemaId);
        }
//        if (systemRegistry != null) {
//            CommonUtil.addGovernanceArtifactEntryWithAbsoluteValues(systemRegistry, schemaId, path);
//        }

        if (!registry.resourceExists(path)) {
            addSchemaToRegistry(context, path, url, resource, registry);
        } else {
            log.debug("A Resource already exists at given location. Overwriting resource content.");
            addSchemaToRegistry(context, path, url, resource, registry);
        }

//        if (!(resource instanceof Collection) &&
//           ((ResourceImpl) resource).isVersionableChange()) {
//            registry.createVersion(path);
//        }
        String relativeArtifactPath = RegistryUtils.getRelativePath(registry.getRegistryContext(), path);
        // adn then get the relative path to the GOVERNANCE_BASE_PATH
        relativeArtifactPath = RegistryUtils.getRelativePathToOriginal(relativeArtifactPath,
                RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH);
        ((ResourceImpl)resource).setPath(relativeArtifactPath);
    }

    /**
     * Method that gets called instructing a schema to be added the registry.
     *
     * @param context  the request context for this request.
     * @param path     the path to add the resource to.
     * @param url      the path from which the resource was imported from.
     * @param resource the resource to be added.
     * @param registry the registry instance to use.
     *
     * @throws RegistryException if the operation failed.
     */
    protected void addSchemaToRegistry(RequestContext context, String path, String url,
                                       Resource resource, Registry registry) throws RegistryException {
        registry.put(path, resource);
    }

    private String extractResourceFromURL(String wsdlURL, String suffix) {
        String resourceName = wsdlURL;
        if (wsdlURL.indexOf("?") > 0) {
            resourceName = wsdlURL.substring(0, wsdlURL.indexOf("?")) + suffix;
        } else if (wsdlURL.indexOf(".") > 0) {
            resourceName = wsdlURL.substring(0, wsdlURL.lastIndexOf(".")) + suffix;
        } else if (!wsdlURL.endsWith(suffix)) {
            resourceName = wsdlURL + suffix;
        }
        return resourceName;
    }

    private String getAbsoluteSchemaURL(String schemaLocation) throws RegistryException {
         if (schemaLocation != null && baseURI != null) {
             try {
                 URI uri = new URI(baseURI);
                 URI absoluteURI = uri.resolve(schemaLocation);
                 return absoluteURI.toString();
             } catch (URISyntaxException e) {
                 throw new RegistryException(e.getMessage(), e);
             }
         }
        return schemaLocation;
    }

}

redpajama_set_name: RedPajamaGithub


text:
#include <media/MediaProcessor.h>
#include <media/utils/RtpUtils.h>
#include <boost/asio.hpp>

#ifndef TEST_H_
#define TEST_H_
namespace erizo {
class Test: public RawDataReceiver {
public:
	Test();
	virtual ~Test();
	void receiveRawData(unsigned char*data, int len);

	void rec();
	void send(char *buff, int buffSize);
private:

	boost::asio::ip::udp::socket* socket_;
	boost::asio::ip::udp::resolver* resolver_;

	boost::asio::ip::udp::resolver::query* query_;
	boost::asio::io_service* ioservice_;
	InputProcessor* ip;
	erizo::RtpParser pars;

};

}
#endif /* TEST_H_ */


text:
package com.microsoft.azure.management.monitor.v2018_04_16;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;

/**
 * Specify action need to be taken when rule type is Alert.
 */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "odata.type")
@JsonTypeName("Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.Microsoft.AppInsights.Nexus.DataContracts.Resources.ScheduledQueryRules.AlertingAction")
public class AlertingAction extends Action {
    /**
     * Severity of the alert. Possible values include: '0', '1', '2', '3', '4'.
     */
    @JsonProperty(value = "severity", required = true)
    private AlertSeverity severity;

    /**
     * Azure action group reference.
     */
    @JsonProperty(value = "aznsAction")
    private AzNsActionGroup aznsAction;

    /**
     * time (in minutes) for which Alerts should be throttled or suppressed.
     */
    @JsonProperty(value = "throttlingInMin")
    private Integer throttlingInMin;

    /**
     * The trigger condition that results in the alert rule being.
     */
    @JsonProperty(value = "trigger", required = true)
    private TriggerCondition trigger;

    /**
     * Get severity of the alert. Possible values include: '0', '1', '2', '3', '4'.
     *
     * @return the severity value
     */
    public AlertSeverity severity() {
        return this.severity;
    }

    /**
     * Set severity of the alert. Possible values include: '0', '1', '2', '3', '4'.
     *
     * @param severity the severity value to set
     * @return the AlertingAction object itself.
     */
    public AlertingAction withSeverity(AlertSeverity severity) {
        this.severity = severity;
        return this;
    }

    /**
     * Get azure action group reference.
     *
     * @return the aznsAction value
     */
    public AzNsActionGroup aznsAction() {
        return this.aznsAction;
    }

    /**
     * Set azure action group reference.
     *
     * @param aznsAction the aznsAction value to set
     * @return the AlertingAction object itself.
     */
    public AlertingAction withAznsAction(AzNsActionGroup aznsAction) {
        this.aznsAction = aznsAction;
        return this;
    }

    /**
     * Get time (in minutes) for which Alerts should be throttled or suppressed.
     *
     * @return the throttlingInMin value
     */
    public Integer throttlingInMin() {
        return this.throttlingInMin;
    }

    /**
     * Set time (in minutes) for which Alerts should be throttled or suppressed.
     *
     * @param throttlingInMin the throttlingInMin value to set
     * @return the AlertingAction object itself.
     */
    public AlertingAction withThrottlingInMin(Integer throttlingInMin) {
        this.throttlingInMin = throttlingInMin;
        return this;
    }

    /**
     * Get the trigger condition that results in the alert rule being.
     *
     * @return the trigger value
     */
    public TriggerCondition trigger() {
        return this.trigger;
    }

    /**
     * Set the trigger condition that results in the alert rule being.
     *
     * @param trigger the trigger value to set
     * @return the AlertingAction object itself.
     */
    public AlertingAction withTrigger(TriggerCondition trigger) {
        this.trigger = trigger;
        return this;
    }

}


text:
require "test_helper"

class UpdateSqlTest < Minitest::Test
  attr_reader :haystack, :relation, :bindings

  context "#to_sql" do
    context "in the general case" do
      setup do
        @relation = Book.all
        @bindings = [
          Binding(Hayfork::SEARCH_RESULT_TYPE, "Book"),
          Binding(Hayfork::SEARCH_RESULT_ID, Book.arel_table[:id]),
          Binding(Hayfork::TEXT, Book.arel_table[:title]),
          Binding(Hayfork::SEARCH_VECTOR, Book.arel_table[:title]),
          Binding("another_field", Book.arel_table[:isbn]),
        ]
      end

      should "check if relevant values have changed before replacing entries in the Haystack" do
        stub(update).delete.stub!.to_sql.returns("<!-- DELETE -->")
        stub(update).insert.stub!.to_sql.returns("<!-- INSERT -->")
        assert_equal <<~SQL.squish, update.to_sql.squish.strip
          IF OLD.title IS DISTINCT FROM NEW.title OR OLD.isbn IS DISTINCT FROM NEW.isbn THEN
            <!-- DELETE -->
            <!-- INSERT -->
          END IF;
        SQL
      end

      context "when the model uses attr_readonly" do
        setup do
          Book.attr_readonly :isbn
          fail "isbn should be readonly now" unless Book.readonly_attributes.member?("isbn")
        end

        teardown do
          Book.readonly_attributes.delete "isbn"
          fail "isbn should not be readonly now" if Book.readonly_attributes.member?("isbn")
        end

        should "not check values that are readonly" do
          stub(update).delete.stub!.to_sql.returns("<!-- DELETE -->")
          stub(update).insert.stub!.to_sql.returns("<!-- INSERT -->")
          assert_equal <<~SQL.squish, update.to_sql.squish.strip
            IF OLD.title IS DISTINCT FROM NEW.title THEN
              <!-- DELETE -->
              <!-- INSERT -->
            END IF;
          SQL
        end
      end
    end
  end

  context "#values_to_check_on_update" do
    setup do
      @relation = Book.all
      @bindings = [ Binding(Hayfork::SEARCH_VECTOR, Book.arel_table[:title]) ]
    end

    should "always include search_vector_value" do
      assert_equal Set["title"], update.values_to_check_on_update
    end

    should "include merged attributes" do
      bindings.push Binding("another_field", Book.arel_table[:isbn])
      assert_equal Set["title", "isbn"], update.values_to_check_on_update
    end

    should "ignored attributes whose values are constants" do
      bindings.push Binding("another_field", "CONSTANT")
      assert_equal Set["title"], update.values_to_check_on_update
    end

    context "when @relation has JOINs" do
      setup do
        @relation = Book.joins(:author)
        @bindings.push Binding("another_field", Author.arel_table[:name])
      end

      context "on a mutable attribute" do
        should "include the foreign key of a belongs_to association" do
          assert_equal Set["title", "author_id"], update.values_to_check_on_update
        end
      end

      context "on a readonly attribute" do
        setup do
          Book.attr_readonly :author_id
          fail "author_id should be readonly now" unless Book.readonly_attributes.member?("author_id")
        end

        teardown do
          Book.readonly_attributes.delete "author_id"
          fail "author_id should not be readonly now" if Book.readonly_attributes.member?("author_id")
        end

        should "exclude the immutable foreign key" do
          assert_equal Set["title"], update.values_to_check_on_update
        end
      end

      # TODO: do nothing for joins where the foreign_key is on the other table
      # TODO: should handle `belongs_to :through`

    end

    context "when @relation has a WHERE clause" do
      should "include the keys of a vanilla `where`" do
        @relation = Book.where(isbn: "7")
        assert_equal Set["title", "isbn"], update.values_to_check_on_update
      end

      should "include the keys of a `where.not`" do
        @relation = Book.where.not(isbn: "7")
        assert_equal Set["title", "isbn"], update.values_to_check_on_update
      end

      should "include the keys of a `where` that uses Arel" do
        @relation = Book.where(Book.arel_table[:isbn].gteq("7"))
        assert_equal Set["title", "isbn"], update.values_to_check_on_update
      end

      # TODO: should alert of limits — predicates it can't parse, etc

    end
  end

private
  attr_reader :relation, :bindings

  def statement
    @statement ||= Hayfork::Statement.new(Haystack, Book.all, :title)
  end

  def Binding(column_name, raw_value)
    column = Haystack.columns_hash.fetch(column_name)
    Hayfork::Binding.new(statement, column, raw_value)
  end

  def update
    @update ||= Hayfork::UpdateSql.new(Haystack, relation, bindings)
  end

end


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
O-Index (OWASP Java HTML Sanitizer)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index

code.google.com home

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C D E F G H I J L M O P R S T U V W

O

onElements(String...) -
Method in class org.owasp.html.HtmlPolicyBuilder.AttributeBuilder

Allows the named attributes on the given elements but filters the
 attributes' values based on previous calls to matching(...).

openDocument() -
Method in interface org.owasp.html.HtmlStreamEventReceiver

openDocument() -
Method in class org.owasp.html.HtmlStreamRenderer

openDocument() -
Method in class org.owasp.html.TagBalancingHtmlStreamEventReceiver

openTag(String, List<String>) -
Method in interface org.owasp.html.HtmlSanitizer.Policy

Called when an HTML tag like <foo bar=baz> is seen in the input.

openTag(String, List<String>) -
Method in interface org.owasp.html.HtmlStreamEventReceiver

openTag(String, List<String>) -
Method in class org.owasp.html.HtmlStreamRenderer

openTag(String, List<String>) -
Method in class org.owasp.html.TagBalancingHtmlStreamEventReceiver

org.owasp.html - package org.owasp.html
An efficient HtmlSanitizer
 configurable via a flexible
 HtmlPolicyBuilder.
org.owasp.html.examples - package org.owasp.html.examples

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index

code.google.com home

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C D E F G H I J L M O P R S T U V W


text:
<?php

namespace Drupal\Tests\Core\PathProcessor;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Config\ImmutableConfig;
use Drupal\Core\PathProcessor\PathProcessorFront;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Test front page path processing.
 *
 * @group PathProcessor
 * @coversDefaultClass \Drupal\Core\PathProcessor\PathProcessorFront
 */
class PathProcessorFrontTest extends UnitTestCase {

  /**
   * Test basic inbound processing functionality.
   *
   * @covers ::processInbound
   * @dataProvider providerProcessInbound
   */
  public function testProcessInbound($path, $expected) {
    $config_factory = $this->prophesize(ConfigFactoryInterface::class);
    $config = $this->prophesize(ImmutableConfig::class);
    $config_factory->get('system.site')
      ->willReturn($config->reveal());
    $config->get('page.front')
      ->willReturn('/node');
    $processor = new PathProcessorFront($config_factory->reveal());
    $this->assertEquals($expected, $processor->processInbound($path, new Request()));
  }

  /**
   * Inbound paths and expected results.
   */
  public function providerProcessInbound() {
    return [
      ['/', '/node'],
      ['/user', '/user'],
    ];
  }

  /**
   * Test inbound failure with broken config.
   *
   * @covers ::processInbound
   */
  public function testProcessInboundBadConfig() {
    $config_factory = $this->prophesize(ConfigFactoryInterface::class);
    $config = $this->prophesize(ImmutableConfig::class);
    $config_factory->get('system.site')
      ->willReturn($config->reveal());
    $config->get('page.front')
      ->willReturn('');
    $processor = new PathProcessorFront($config_factory->reveal());
    $this->setExpectedException(NotFoundHttpException::class);
    $processor->processInbound('/', new Request());
  }

  /**
   * Test basic outbound processing functionality.
   *
   * @covers ::processOutbound
   * @dataProvider providerProcessOutbound
   */
  public function testProcessOutbound($path, $expected) {
    $config_factory = $this->prophesize(ConfigFactoryInterface::class);
    $processor = new PathProcessorFront($config_factory->reveal());
    $this->assertEquals($expected, $processor->processOutbound($path));
  }

  /**
   * Outbound paths and expected results.
   */
  public function providerProcessOutbound() {
    return [
      ['/<front>', '/'],
      ['<front>', '<front>'],
      ['/user', '/user'],
    ];
  }

}


text:
<?php

namespace KRSolutions\Bundle\KRCMSBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;
use KRSolutions\Bundle\KRCMSBundle\Entity\Menu;
use KRSolutions\Bundle\KRCMSBundle\Entity\Page;
use KRSolutions\Bundle\KRCMSBundle\Entity\PageInterface;
use KRSolutions\Bundle\KRCMSBundle\Entity\PageTypeInterface;

/**
 * PageRepository
 */
class PageRepository extends EntityRepository
{

    /**
     * Get a page by it's permalink
     *
     * @param string $permalink Page permalink
     *
     * @return Page|null
     */
    public function getActivePageFromPermalink($permalink)
    {
        $qb = $this->createQueryBuilder('pages');
        $qb->addSelect('parent');
        $qb->addSelect('pageTypes');
        $qb->addSelect('parentPageTypes');
        $qb->addSelect('files');

        $qb->leftJoin('pages.parent', 'parent');
        $qb->leftJoin('parent.pageType', 'parentPageTypes');
        $qb->leftJoin('pages.pageType', 'pageTypes');
        $qb->leftJoin('pages.files', 'files');

        if (null !== $permalink) {
            $qb->andWhere('pages.permalink = :permalink');
            $qb->setParameter('permalink', $permalink);
        } else {
            $qb->andWhere('pages.permalink IS NULL');
        }

        // Check if the page is active
        $qb->andWhere('pages.publishAt < CURRENT_TIMESTAMP() OR pages.publishAt IS NULL');
        $qb->andWhere('pages.publishTill > CURRENT_TIMESTAMP() OR pages.publishTill IS NULL');

        $qb->orderBy('pages.orderId', 'asc');

        return $qb->getQuery()->getOneOrNullResult();
    }

    /**
     * Get pages by menu
     *
     * @param Menu $menu Menu entity
     *
     * @return array
     */
    public function getActivePagesFromMenu(Menu $menu)
    {
        $qb = $this->createQueryBuilder('pages');

        if (null !== $menu) {
            $qb->andWhere('pages.menu = :menu');
            $qb->setParameter('menu', $menu);
        } else {
            $qb->andWhere('pages.menu IS NULL');
        }

        // Check if the page is active
        $qb->andWhere('pages.publishAt < CURRENT_TIMESTAMP() OR pages.publishAt IS NULL');
        $qb->andWhere('pages.publishTill > CURRENT_TIMESTAMP() OR pages.publishTill IS NULL');

        $qb->orderBy('pages.orderId', 'asc');

        return $qb->getQuery()->getResult();
    }

    /**
     * Get pages by menu name
     *
     * @param string $menuName Menu name
     *
     * @return array
     */
    public function getActivePagesFromMenuName($menuName = null)
    {
        $qb = $this->createQueryBuilder('pages');

        if (null !== $menuName) {
            $qb->innerJoin('pages.menu', 'menus', Join::WITH, 'menus.name = :menuName');
            $qb->setParameter('menuName', $menuName);
        } else {
            $qb->andWhere('pages.menu IS NULL');
        }

        // Check if the page is active
        $qb->andWhere('pages.publishAt < CURRENT_TIMESTAMP() OR pages.publishAt IS NULL');
        $qb->andWhere('pages.publishTill > CURRENT_TIMESTAMP() OR pages.publishTill IS NULL');

        $qb->orderBy('pages.orderId', 'asc');

        return $qb->getQuery()->getResult();
    }

    /**
     * Get pages (query builder)
     *
     * @return array
     */
    public function getActivePagesQB()
    {
        $qb = $this->createQueryBuilder('pages');

        // Check if the page is active
        $qb->andWhere('pages.publishAt < CURRENT_TIMESTAMP() OR pages.publishAt IS NULL');
        $qb->andWhere('pages.publishTill > CURRENT_TIMESTAMP() OR pages.publishTill IS NULL');

        $qb->orderBy('pages.orderId', 'asc');

        return $qb;
    }

    /**
     * Get active pages
     *
     * @return array
     */
    public function getActivePages()
    {
        return $this->getActivePagesQB()->getQuery()->getResult();
    }

    /**
     * Get active pages from parent page
     *
     * @param Page $page
     *
     * @return array
     */
    public function getActivePagesFromPage(Page $page)
    {
        $qb = $this->createQueryBuilder('pages');

        if (null !== $page) {
            $qb->andWhere('pages.parent = :page');
            $qb->setParameter('page', $page);
        } else {
            $qb->andWhere('pages.parent IS NULL');
        }

        // Check if the page is active
        $qb->andWhere('pages.publishAt < CURRENT_TIMESTAMP() OR pages.publishAt IS NULL');
        $qb->andWhere('pages.publishTill > CURRENT_TIMESTAMP() OR pages.publishTill IS NULL');

        $qb->orderBy('pages.orderId', 'asc');

        return $qb->getQuery()->getResult();
    }

    /**
     * Get active children from parent page
     *
     * @param Page $page
     *
     * @return \Doctrine\DBAL\Query\QueryBuilder
     */
    public function getActiveChildrenQB(Page $page)
    {
        $qb = $this->createQueryBuilder('pages');

        $qb->andWhere('pages.parent = :page');
        $qb->setParameter('page', $page);

        // Check if the page is active
        $qb->andWhere('pages.publishAt < CURRENT_TIMESTAMP() OR pages.publishAt IS NULL');
        $qb->andWhere('pages.publishTill > CURRENT_TIMESTAMP() OR pages.publishTill IS NULL');

        $qb->orderBy('pages.'.$page->getPageType()->getChildrenOrderBy(), $page->getPageType()->getChildrenOrderDirection());

        return $qb;
    }

    /**
     * Search active pages
     *
     * @param string $search_term
     *
     * @return \Doctrine\DBAL\Query\QueryBuilder
     */
    public function searchActivePagesQB($search_term = '')
    {
        $qb = $this->createQueryBuilder('pages');

        $qb->where('pages.title LIKE :search_term');
        $qb->orWhere('pages.content LIKE :search_term');
        $qb->setParameter('search_term', '%'.$search_term.'%');

        // Check if the page is active
        $qb->andWhere('pages.publishAt < CURRENT_TIMESTAMP() OR pages.publishAt IS NULL');
        $qb->andWhere('pages.publishTill > CURRENT_TIMESTAMP() OR pages.publishTill IS NULL');

        return $qb;
    }

    /**
     * Get active pages with a menu title from parent page
     *
     * @param Page $page
     *
     * @return array
     */
    public function getActivePagesWithMenuTitleFromPage(Page $page)
    {
        $qb = $this->createQueryBuilder('pages');

        $qb->innerJoin('pages.pageType', 'pageType', Join::WITH, 'pageType.isMenuItem = true');

        if (null !== $page) {
            $qb->andWhere('pages.parent = :page');
            $qb->setParameter('page', $page);
        } else {
            $qb->andWhere('pages.parent IS NULL');
        }

        $qb->andWhere('pages.menuTitle IS NOT NULL');

        // Check if the page is active
        $qb->andWhere('pages.publishAt < CURRENT_TIMESTAMP() OR pages.publishAt IS NULL');
        $qb->andWhere('pages.publishTill > CURRENT_TIMESTAMP() OR pages.publishTill IS NULL');

        $qb->orderBy('pages.orderId', 'asc');

        return $qb->getQuery()->getResult();
    }

    /**
     * Get page by id
     *
     * @param integer $pageId
     *
     * @return null|Page
     */
    public function getPageById($pageId)
    {
        $qb = $this->createQueryBuilder('pages');

        $qb->where('pages.id = :pageId');
        $qb->setParameter('pageId', intval($pageId));

        return $qb->getQuery()->getOneOrNullResult();
    }

    /**
     * Get page by permalink
     *
     * @param string $permalink
     *
     * @return null|Page
     */
    public function getPageByPermalink($permalink)
    {
        $qb = $this->createQueryBuilder('pages');

        $qb->where('pages.permalink = :permalink');
        $qb->setParameter('permalink', $permalink);

        return $qb->getQuery()->getOneOrNullResult();
    }

    /**
     * Get all pages
     *
     * @return array
     */
    public function getAllPages()
    {
        $qb = $this->createQueryBuilder('pages');

        $qb->orderBy('pages.orderId', 'asc');

        return $qb->getQuery()->getResult();
    }

    /**
     * Get all parent pages
     *
     * @return array
     */
    public function getAllParentPages()
    {
        $qb = $this->createQueryBuilder('pages');

        $qb->where('pages.parent IS NULL');
        $qb->orderBy('pages.orderId', 'asc');

        return $qb->getQuery()->getResult();
    }

    /**
     * Get all loose pages
     *
     * @return array
     */
    public function getAllLoosePages()
    {
        $qb = $this->createQueryBuilder('pages');

        $qb->where('pages.parent IS NULL');
        $qb->andWhere('pages.menu IS NULL');

        $qb->orderBy('pages.orderId', 'asc');

        return $qb->getQuery()->getResult();
    }

    /**
     * Get all child pages
     *
     * @param Page $parentPage
     *
     * @return array
     */
    public function getAllChildPages(Page $parentPage)
    {
        $qb = $this->createQueryBuilder('pages');

        $qb->where('pages.parent = :parentPage');
        $qb->setParameter('parentPage', $parentPage);

        $qb->orderBy('pages.orderId', 'asc');

        return $qb->getQuery()->getResult();
    }

    /**
     * getAllChildablePagesQB
     *
     * @return QueryBuilder
     */
    public function getAllChildablePagesQB()
    {
        $qb = $this->createQueryBuilder('pages');

        $qb->innerJoin('pages.pageType', 'pageType', Join::WITH, 'pageType.hasChildren = true');

        return $qb;
    }

    /**
     * getAllChildablePages
     *
     * @return array
     */
    public function getAllChildablePages()
    {
        $qb = $this->getAllChildablePagesQB();

        return $qb->getQuery()->getResult();
    }

    /**
     * Get all childable pages except for the given page
     *
     * @param PageInterface $exceptThisPage
     *
     * @return QueryBuilder
     */
    public function getAllChildablePagesExceptThisPageQB(PageInterface $exceptThisPage = null)
    {
        $qb = $this->getAllChildablePagesQB();

        if (null !== $exceptThisPage && null !== $exceptThisPage->getId()) {
            $qb->where('pages <> :exceptThisPage');
            $qb->setParameter('exceptThisPage', $exceptThisPage);
        }

        $qb->innerJoin('pages.pageType', 'parentPageType');
        $qb->innerJoin('parentPageType.pageTypeChildren', 'pageTypeChildren', Join::WITH, 'pageTypeChildren = :pageTypeChild');
        $qb->setParameter('pageTypeChild', $exceptThisPage->getPageType());

        return $qb;
    }

    /**
     * Get first pages by pageTypeId
     *
     * @param string $pageTypeId Id of the PageType
     * @param int    $nrOfPages  Number of pages to fetch
     *
     * @return array
     */
    public function getFirstPagesByPageTypeId($pageTypeId, $nrOfPages)
    {
        $qb = $this->createQueryBuilder('pages');

        $qb->innerJoin('pages.pageType', 'pageType', Join::WITH, 'pageType.id = :pageTypeId');
        $qb->setParameter('pageTypeId', $pageTypeId);

        $qb->orderBy('pages.orderId', 'asc');
        $qb->setMaxResults($nrOfPages);

        return $qb->getQuery()->getResult();
    }

    /**
     * Get the next page permalink in the menu
     *
     * @param Page $activePage
     *
     * @return string|null
     */
    public function getNextPermalinkInMenu(Page $activePage)
    {
        $qb = $this->createQueryBuilder('pages');
        $qb->select('pages.permalink');

        $qb->where('pages.menu = :menu');
        $qb->setParameter('menu', $activePage->getMenu());

        $qb->andWhere('pages.orderId > :orderId');
        $qb->setParameter('orderId', $activePage->getOrderId());

        $qb->orderBy('pages.orderId', 'asc');
        $qb->setMaxResults(1);

        $result = $qb->getQuery()->getOneOrNullResult();

        if (null === $result) {
            return null;
        }

        return $result['permalink'];
    }

    /**
     * Get the previous page permalink in the menu
     *
     * @param Page $activePage
     *
     * @return string|null
     */
    public function getPreviousPermalinkInMenu(Page $activePage)
    {
        $qb = $this->createQueryBuilder('pages');
        $qb->select('pages.permalink');

        $qb->where('pages.menu = :menu');
        $qb->setParameter('menu', $activePage->getMenu());

        $qb->andWhere('pages.orderId < :orderId');
        $qb->setParameter('orderId', $activePage->getOrderId());

        $qb->orderBy('pages.orderId', 'desc');
        $qb->setMaxResults(1);

        $result = $qb->getQuery()->getOneOrNullResult();

        if (null === $result) {
            return null;
        }

        return $result['permalink'];
    }

    /**
     * Get last page from a parent page with the parent permalink
     *
     * @param string $permalink
     *
     * @return Page
     */
    public function getLastPageFromParentByPermalink($permalink)
    {
        $qb = $this->createQueryBuilder('pages');

        $qb->innerJoin('pages.parent', 'parent', Join::WITH, 'parent.permalink = :permalink');
        $qb->setParameter('permalink', $permalink);

        $qb->orderBy('pages.orderId', 'desc');
        $qb->setMaxResults(1);

        return $qb->getQuery()->getOneOrNullResult();
    }

    /**
     * Get last page from a parent page with the parent permalink
     *
     * @param string $permalink
     *
     * @return Page
     */
    public function getNewestPageFromParentByPermalink($permalink)
    {
        $qb = $this->createQueryBuilder('pages');

        $qb->innerJoin('pages.parent', 'parent', Join::WITH, 'parent.permalink = :permalink');
        $qb->setParameter('permalink', $permalink);

        $qb->orderBy('pages.createdAt', 'desc');
        $qb->setMaxResults(1);

        return $qb->getQuery()->getOneOrNullResult();
    }

    /**
     * Get last number of pages from a parent page with the parent permalink
     *
     * @param string $permalink
     * @param int    $number
     *
     * @return Page
     */
    public function getLastPagesFromParentByPermalink($permalink, $number)
    {
        $qb = $this->createQueryBuilder('pages');

        $qb->innerJoin('pages.parent', 'parent', Join::WITH, 'parent.permalink = :permalink');
        $qb->setParameter('permalink', $permalink);

        $qb->orderBy('pages.orderId', 'desc');
        $qb->setMaxResults($number);

        return $qb->getQuery()->getResult();
    }

    /**
     * Get newest number of pages from a parent page with the parent permalink
     *
     * @param string $permalink
     * @param int    $number
     *
     * @return Page
     */
    public function getNewestPagesFromParentByPermalink($permalink, $number)
    {
        $qb = $this->createQueryBuilder('pages');

        $qb->innerJoin('pages.parent', 'parent', Join::WITH, 'parent.permalink = :permalink');
        $qb->setParameter('permalink', $permalink);

        $qb->orderBy('pages.createdAt', 'desc');
        $qb->setMaxResults($number);

        return $qb->getQuery()->getResult();
    }

    /**
     * Get the next page permalink from the parent page
     *
     * @param Page $page
     *
     * @return string|null
     */
    public function getNextPermalinkFromParentPage(Page $page)
    {
        $parentPage = $page->getParent();

        if (!($parentPage instanceof Page)) {
            return null;
        }

        $qb = $this->createQueryBuilder('pages');
        $qb->select('pages.permalink');

        $qb->where('pages.parent = :parentPage');
        $qb->setParameter('parentPage', $parentPage);

        if (null !== $parentPage->getPageType()->getChildrenOrderDirection()) {
            $order = trim(strtolower($parentPage->getPageType()->getChildrenOrderDirection()));

            if ('asc' !== $order && 'desc' !== $order) {
                $order = 'asc';
            }
        } else {
            $order = 'asc';
        }

        switch ($parentPage->getPageType()->getChildrenOrderBy()) {
            case 'createdAt':
                $qb->andWhere('pages.createdAt < :createdAt');
                $qb->setParameter('createdAt', $page->getCreatedAt());

                $qb->orderBy('pages.createdAt', $order);

                break;
            case 'orderId':
            default:
                $qb->andWhere('pages.orderId > :orderId');
                $qb->setParameter('orderId', $page->getOrderId());

                $qb->orderBy('pages.orderId', $order);

                break;
        }

        $qb->setMaxResults(1);

        $result = $qb->getQuery()->getOneOrNullResult();

        if (null === $result) {
            return null;
        }

        return $result['permalink'];
    }

    /**
     * Get the next page permalink from the parent page
     *
     * @param Page $page
     *
     * @return string|null
     */
    public function getPreviousPermalinkFromParentPage(Page $page)
    {
        $parentPage = $page->getParent();

        if (!($parentPage instanceof Page)) {
            return null;
        }

        $qb = $this->createQueryBuilder('pages');
        $qb->select('pages.permalink');

        $qb->where('pages.parent = :parentPage');
        $qb->setParameter('parentPage', $parentPage);

        if (null !== $parentPage->getPageType()->getChildrenOrderDirection()) {
            $order = trim(strtolower($parentPage->getPageType()->getChildrenOrderDirection()));

            if ('asc' !== $order && 'desc' !== $order) {
                $order = 'asc';
            } elseif ($order === 'asc') {
                $order = 'desc';
            } elseif ($order === 'desc') {
                $order = 'asc';
            }
        } else {
            $order = 'asc';
        }

        switch ($parentPage->getPageType()->getChildrenOrderBy()) {
            case 'createdAt':
                $qb->andWhere('pages.createdAt > :createdAt');
                $qb->setParameter('createdAt', $page->getCreatedAt());

                $qb->orderBy('pages.createdAt', $order);

                break;
            case 'orderId':
            default:
                $qb->andWhere('pages.orderId < :orderId');
                $qb->setParameter('orderId', $page->getOrderId());

                $qb->orderBy('pages.orderId', $order);

                break;
        }

        $qb->setMaxResults(1);

        $result = $qb->getQuery()->getOneOrNullResult();

        if (null === $result) {
            return null;
        }

        return $result['permalink'];
    }

    /**
     * Get page count
     *
     * @return int
     */
    public function getPageCount()
    {
        $qb = $this->createQueryBuilder('pages');

        $qb->select('count(pages.id)');

        return intval($qb->getQuery()->getSingleScalarResult());
    }

    /**
     * Get page count by page type
     *
     * @param PageTypeInterface $pageType
     *
     * @return int
     */
    public function getPageCountByPageType(PageTypeInterface $pageType)
    {
        $qb = $this->createQueryBuilder('pages');

        $qb->select('count(pages.id)');

        $qb->where('pages.pageType = :page_type');
        $qb->setParameter('page_type', $pageType);

        return intval($qb->getQuery()->getSingleScalarResult());
    }
}


text:
layout: default
---

{{ page.title | escape }}

      <time datetime="{{ page.date | date_to_xmlschema }}" itemprop="datePublished">
        {% assign date_format = site.minima.date_format | default: "%b %-d, %Y" %} {{ page.date | date: date_format }}
      </time>
      {% if page.author %} • {{ page.author }}
      {% endif %}

    {% if jekyll.environment == 'production' and site.google_adsense %}
    {% include google-adsense-top.html %}
    {% endif %}

    {{ content }}

    {% if jekyll.environment == 'production' and site.google_adsense %}
    {% include google-adsense-bottom.html %}
    {% endif %}

  {{ site.text_current_post }}

    {% for post-from-list in site.posts limit:30 %}
    {% if post-from-list.categories == page.categories  %}

      {% assign date_format = site.minima.date_format | default: "%b %-d, %Y" %}
      {{ post-from-list.date | date: date_format }} -
      {{ post-from-list.title | escape }}

    {% endif %}
    {% endfor %}

  {% if site.disqus.shortname %} {% include disqus_comments.html %} {% endif %}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    $data['action'] = base_url('/manage/page_category');
    $data['form_title'] = '添加';
    $data['method'] = 'post';
    $this->load->view('manage/page_categories/_form', $data);


text:
package org.runmyprocess.sec;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Base64;
import java.util.Properties;
import java.util.logging.Level;
import org.runmyprocess.json.JSONArray;
import org.runmyprocess.json.JSONObject;

import static javax.xml.bind.DatatypeConverter.parseBase64Binary;

public class JDBC implements ProtocolInterface {

    final SECLogManager LOG = new SECLogManager(JDBC.class.getName());
    private Response response = new Response();

    public JDBC() {
        // TODO Auto-generated constructor stub
    }

    /**
     *
     * @param error error message
     * @return jsonObject error
     */
    private JSONObject DBAgentError(String error){
        LOG.log(error, Level.SEVERE);
        response.setStatus(400);//sets the return status to internal server error
        JSONObject errorObject = new JSONObject();
        errorObject.put("error", error);
        return errorObject;
    }

    /**
     *  Transforms a result set to a jsonObject
     * @param rs result set to transform
     * @return  jsonObject of the result set
     */
    private static final JSONObject resultSet2JSONObject(ResultSet rs) {
        JSONObject element = null;
        JSONArray joa = new JSONArray();
        JSONObject jo = new JSONObject();
        int totalLength = 0;
        ResultSetMetaData rsmd = null;
        String columnName = null;
        String columnValue = null;
        try {
            rsmd = rs.getMetaData();
            while (rs.next()) {
                element = new JSONObject();
                for (int i = 0; i < rsmd.getColumnCount(); i++) {
                    columnName = rsmd.getColumnName(i+1);
                    columnValue = rs.getString(columnName);
                    element.accumulate(columnName, columnValue);
                }
                joa.add(element);
                totalLength ++;
            }
            jo.accumulate("result", "success");
            jo.accumulate("rows", totalLength);
            jo.accumulate("data", joa);
        } catch (SQLException e) {
            jo.accumulate("result", "failure");
            jo.accumulate("error", e.getMessage());
        }
        return jo;
    }

    /**
     * establishes a connection to the database
     * @param userName
     * @param password
     * @param sqlSource
     * @param sqlDriver
     * @param driverPath
     * @return   the connection object
     * @throws Exception
     */
    private Connection getConnection(String userName, String password, String sqlSource, String sqlDriver,
                                     String driverPath) throws Exception {

        LOG.log("Connecting to "+sqlSource,Level.INFO);
        Connection conn = null;
        Properties connectionProps = new Properties();
        connectionProps.put("user", userName);
        connectionProps.put("password", password);
        URL[] urls = new URL[1];
        File f = new File(driverPath);
        urls[0] = f.toURL();
        URLClassLoader ucl = URLClassLoader.newInstance(urls);
        Driver driver = (Driver)Class.forName(sqlDriver, true, ucl).newInstance();
        DriverManager.registerDriver(new DriverShim(driver));
        conn = DriverManager.getConnection(sqlSource, userName, password);

        LOG.log("Connected to database", Level.INFO);
        return conn;
    }

    /**
     * Executes the sql statement
     * @param con the connection
     * @param sqlStatement the statement
     * @return  a jsonObject with the result of the call
     * @throws SQLException
     */
    private static JSONObject ExecuteStatement(Connection con, String sqlStatement)throws SQLException {

    // Get a statement from the connection
    Statement stmt = con.createStatement() ;
    JSONObject retObj = new JSONObject();
    // Execute the SQL
    if( stmt.execute(sqlStatement) == false )
    {
        // Get the update count
        String rep = "Query OK, "+ stmt.getUpdateCount() + " rows affected" ;
        retObj.put("Message",rep);
    }
    else
    {
        // Get the result set and the metadata
        ResultSet         rs = stmt.getResultSet() ;
        retObj = resultSet2JSONObject(rs);

    }
    stmt.close() ;
    con.close() ;

    return retObj;

    }

    /**
     * Calls to establish the connection and execute the statement
     * @param driverPath
     * @param sqlDriver
     * @param sqlSource
     * @param sqlUsername
     * @param sqlPassword
     * @param sqlStatement
     * @return  the result (jsonObject) of the execution
     * @throws Exception
     */
    private JSONObject Execute(String driverPath, String sqlDriver, String sqlSource, String sqlUsername,
                               String sqlPassword,String sqlStatement) throws Exception{

        Connection con = getConnection(sqlUsername, sqlPassword,sqlSource,sqlDriver,driverPath);
        return ExecuteStatement(con, sqlStatement);
    }

    /**
     * Recieves the information, reads the configuration information and calls the appropriate functions to set the
     * response value
     * @param jsonObject
     * @param configPath
     */
    @Override
    public void accept(JSONObject jsonObject,String configPath) {

        try {

            LOG.log("Searching for config file...", Level.INFO);
            Config conf = new Config("configFiles"+File.separator+ "JDBC.config",true);//sets the config info
            LOG.log( "Config file found  ", Level.INFO);

            String sqlUsername = jsonObject.getString("sqlUsername");
            String sqlPassword = jsonObject.getString("sqlPassword");
            String sqlStatement = jsonObject.getString("sqlStatement");
            String DBType = jsonObject.getString("DBType");
            //decode base 64 if necesary
            if (jsonObject.containsKey("base64Input") && jsonObject.getString("base64Input").equals("true")){
                sqlUsername = new String(Base64.getDecoder().decode(sqlUsername));
                sqlPassword = new String(Base64.getDecoder().decode(sqlPassword));
                sqlStatement = new String(Base64.getDecoder().decode(sqlStatement));
                DBType = new String(Base64.getDecoder().decode(DBType));
            }

            JSONObject prop = JSONObject.fromString(conf.getProperty(DBType));

            JSONObject DBData = Execute(prop.getString("sqlDriverPath"), prop.getString("sqlDriver"),
                    prop.getString("sqlSource"), sqlUsername, sqlPassword,
                    sqlStatement) ;

            response.setStatus(200);//sets the return status to 200
            JSONObject resp = new JSONObject();
            if (jsonObject.containsKey("base64Output") && jsonObject.getString("base64Output").equals("true")){

                resp.put("DBData", new String (Base64.getEncoder().encode(DBData.toString().getBytes())));//sends the info inside an object
            }else{
                resp.put("DBData", DBData);//sends the info inside an object
            }
            response.setData(resp);

        } catch (Exception e) {
            e.printStackTrace();
            response.setData(this.DBAgentError(e.getMessage()));
            SECErrorManager errorManager = new SECErrorManager();
            errorManager.logError(e.getMessage(), Level.SEVERE);

        }
    }

    @Override
    public Response getResponse() {
        return response;
    }

}


text:
package com.github.bednar.base.event;

import javax.annotation.Nonnull;

import com.mycila.event.Subscriber;

/**
 * @author Jakub Bednář (19/08/2013 1:08 PM)
 */
public abstract class AbstractSubscriber<T extends AbstractEvent> implements Subscriber<T>
{
    /**
     * @return type of event processed by subsrciber
     */
    @Nonnull
    public abstract Class<T> eventType();
}


text:
package com.markgrand.cryptoShuffle.keyManagement;

import java.util.Map;
import java.util.UUID;

/**
 * An adapter class to allow an object that implements the {@link Map} interface.
 */
public class UsedKeyMapMapAdapter implements UsedKeyMap {
    private final Map<UUID, byte[]> map;

    public UsedKeyMapMapAdapter(Map<UUID, byte[]> map) {
        this.map = map;
    }

    @Override
    public void put(UUID uuid, byte[] key) {
        map.put(uuid, key);
    }

    @Override
    public void putAll(Map<UUID, byte[]> idKeyPairs) {
        map.putAll(idKeyPairs);
    }

    @Override
    public byte[] get(UUID uuid) {
        return map.get(uuid);
    }

    @Override
    public int size() {
        return map.size();
    }
}


text:
package org.sakaiproject.portal.render.portlet;

import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

import org.sakaiproject.portal.api.PortalService;
import org.sakaiproject.portal.render.api.ToolRenderException;
import org.sakaiproject.site.api.ToolConfiguration;
import org.sakaiproject.tool.api.Placement;

/**
 * A cache of all portlets windows.
 *
 * @since Sakai 2.2.4
 * @version $Rev: 307878 $
 */
public class PortletRegistry
{

	/**
	 * Map of all portlet windows within the portal.
	 */
	private Map<String, SakaiPortletWindow> portletWindows;

	public PortletRegistry()
	{
		this.portletWindows = new ConcurrentHashMap<String, SakaiPortletWindow>();
	}

	/**
	 * Retrieve the portlet window for the specified placement.
	 *
	 * @param placement
	 * @return
	 * @throws ToolRenderException
	 */
	public SakaiPortletWindow getOrCreatePortletWindow(Placement placement)
			throws ToolRenderException
	{
		if (!portletWindows.containsKey(placement.getId()))
		{
			createPortletWindow(placement);
		}
		return getPortletWindow(placement.getId());
	}

	/**
	 * Retrieve the PortletWindow for the given id.
	 *
	 * @param placementId
	 * @return
	 */
	public SakaiPortletWindow getPortletWindow(String placementId)
	{
		return portletWindows.get(placementId);
	}

	private void createPortletWindow(Placement placement) throws ToolRenderException
	{
		SakaiPortletConfig pc = new SakaiPortletConfig(placement);
		if (!pc.isPortletConfig())
		{
			return;
		}
		String windowId = placement.getId();
		SakaiPortletWindow window = new SakaiPortletWindow(windowId, pc.contextPath,
				pc.portletName);
		portletWindows.put(windowId, window);
	}

	public boolean isPortletApplication(Placement placement)
	{
		SakaiPortletConfig pc = new SakaiPortletConfig(placement);
		return pc.isPortletConfig();
	}

	public class SakaiPortletConfig
	{
		private String portletName = null;

		private String contextPath = null;

		private boolean portlet = false;

		public SakaiPortletConfig(Placement placement)
		{
			if (placement == null)
			{
				return;
			}

			Properties toolProperties = placement.getPlacementConfig();
			if (toolProperties != null)
			{
				contextPath = toolProperties
						.getProperty(PortalService.TOOL_PORTLET_CONTEXT_PATH);
				portletName = toolProperties.getProperty(PortalService.TOOL_PORTLET_NAME);
			}
			Properties configProperties = placement.getConfig();
			if (configProperties != null)
			{
				if (isEmpty(contextPath))
				{
					contextPath = configProperties
							.getProperty(PortalService.TOOL_PORTLET_CONTEXT_PATH);
				}
				if (isEmpty(portletName))
				{
					portletName = configProperties
							.getProperty(PortalService.TOOL_PORTLET_NAME);
				}
			}
			portlet = !(isEmpty(contextPath) || isEmpty(portletName));

		}

		public boolean isPortletConfig()
		{
			return portlet;
		}

	}

	private static boolean isEmpty(String string)
	{
		return string == null || string.trim().length() == 0;

	}

	public void reset(ToolConfiguration configuration)
	{
		portletWindows.remove(configuration.getId());
	}
}


text:
package org.gnu.gnucash;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

public class GnuCashXml extends CashBase {

	private Book book;

	public GnuCashXml(final InputStream io) throws ParserConfigurationException, SAXException, IOException {
		loadDocument(io);
	}

	public void readFile() throws Exception {

		this.book = new Book(evaluateXPath("//gnc:book"));
		final ReadData data = new ReadData();
		book.read(data);
	}

	public int getBookCount() {
		return 1;
	}

}


text:
<?php

namespace Acme\CartBundle\Form\Type;

use Leaphly\Cart\Form\Type\LimitedCartFormType as BaseCartFormType;
use Symfony\Component\Form\FormBuilderInterface;
/**
 *
 * @author Giulio De Donato <liuggio@gmail.com>
 * @package Leaphly\Cart\Form\Type
 */
class LimitedCartFormType extends BaseCartFormType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array                $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);
        $builder
            ->add('customer')
        ;
    }
}


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

<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8"
><TITLE
>Qtc.Gui.QStyleOptionButton</TITLE
><LINK HREF="haddock.css" REL="stylesheet" TYPE="text/css"
>

Qtc.Gui.QStyleOptionButton

class QqStyleOptionButton x1

class QqStyleOptionButton_nf x1

class Qfeatures x1 xr

class Qicon x1 xr

class QiconSize x1

class QqiconSize x1

class QsetFeatures x1

class QsetIcon x1

class QsetIconSize x1

class QqsetIconSize x1

class QsetText x1

class Qtext x1 xr

qStyleOptionButton_delete