text:
package tw.com.fstop.app.spring.validator;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import tw.com.fstop.app.model.User;

public class UserFormValidator implements Validator
{

    @Override
    public boolean supports(Class<?> clazz)
    {
        return User.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors)
    {
        User user = (User) target;

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userName", "userForm_userName_empty_is_not_allowed");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "userForm_email_empty_is_not_allowed");

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "credentialValue", "userForm_credentialValue_empty_is_not_allowed");

        //extra field for confirm password
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "confirmCredentialValue","userForm_confirmCredentialValue_empty_is_not_allowed");
        if (!user.getCredentialValue().equals(user.getConfirmCredentialValue()))
        {
            errors.rejectValue("confirmCredentialValue", "userform_confirmCredentialValue_credential_is_not_the_same");
        }

        //match password policy ?

    }

}


text:
Conticious.CategoryIndexController = Ember.Controller.extend({
    needs: ['category', 'categories'],
    showNewFieldArea: false,
    showNewSubcategoryArea: false,

    showNewField: function() {
        return this.get('showNewFieldArea') || this.get('showNewSubcategoryArea');
    }.property('showNewFieldArea', 'showNewSubcategoryArea'),

    actions: {
        openNewField: function() {
            this.set('showNewFieldArea', true);
        },

        cancelNewField: function() {
            this.set('showNewFieldArea', false);
            this.set('newFieldName', null);
            this.set('newFieldType', null);
            this.set('newFieldRequired', false);
        },

        openNewSubcategory: function() {
            this.set('showNewSubcategoryArea', true);
        },

        cancelNewSubcategory: function() {
            this.set('showNewSubcategoryArea', false);
            this.set('newSubcategoryName', null);
        },

        saveCategory: function(category) {
            this.doSaveCategory(category);
        },

        saveCategoryField: function(categoryField) {
            categoryField.save();
        },

        revertCategoryField: function(categoryField) {
            categoryField.rollback();
        },

        deleteCategoryField: function(categoryField) {
            categoryField.deleteRecord();
            categoryField.save();
        }
    },

    doSaveCategory: function(category) {
        category.save();
        var defaultFields = category.get('defaultFields');
        if (defaultFields) {
            defaultFields.forEach(function(field) {
                if (field.get('isDirty') || field.get('isNew')) {
                    field.save();
                }
            });
        }

        var subcategories = category.get('subategories');
        if (subcategories) {
            subcategories.forEach(function(subcategory) {
                if (subcategory.get('isDirty') || subcategory.get('isNew')) {
                    subcategory.save();
                }
            });
        }
    },

    newFieldIsAssociation: function() {
        return this.get('newFieldType') && (this.get('newFieldType') === "toOne" || this.get('newFieldType') === "toMany");
    }.property('newFieldType'),

    init: function() {
        this._super();

        var fieldTypes = [];
        fieldTypes.pushObject('textarea');
        fieldTypes.pushObject('textfield');
        fieldTypes.pushObject('boolean');
        fieldTypes.pushObject('array');
        fieldTypes.pushObject('toOne');
        fieldTypes.pushObject('toMany');

        this.set('fieldTypes', fieldTypes);
    }
});

redpajama_set_name: RedPajamaGithub


text:
package utils

import (
	"time"
)

// ISO8601 ...
const ISO8601 = "2006-01-02T15:04:05.000Z"

// StringtoTime ...
func StringtoTime(s string) (time.Time, error) {
	return time.ParseInLocation(ISO8601, s, time.UTC)
}

// TimetoString ...
func TimetoString(t time.Time) string {
	return t.UTC().Format(ISO8601)
}

// UnixmillitoTime ...
func UnixmillitoTime(m int64) time.Time {
	return time.Unix(m/1000, m%1000*1e6).UTC()
}

// TimetoUnixmilli ...
func TimetoUnixmilli(t time.Time) int64 {
	return t.UnixNano() / 1e6
}

// StringtoUnixmilli ...
func StringtoUnixmilli(s string) (int64, error) {
	var m int64
	t, err := StringtoTime(s)
	if err != nil {
		return m, err
	}
	m = TimetoUnixmilli(t)
	return m, err
}

// UnixmillitoString ...
func UnixmillitoString(m int64) string {
	return TimetoString(UnixmillitoTime(m))
}


text:
#ifndef _IHARDWARE_MNMESH_H_
#define _IHARDWARE_MNMESH_H_

#define IHARDWARE_MNMESH_INTERFACE_ID Interface_ID(0x65b154eb, 0x87d2b74)

class MNMesh;

class IHardwareMNMesh : public BaseInterface
{
public:
	virtual Interface_ID	GetID() { return IHARDWARE_MNMESH_INTERFACE_ID; }

	// Interface Lifetime
	virtual LifetimeType	LifetimeControl() { return noRelease; }
};

#endif


text:
 select dbms_metadata.get_ddl('REF_CONSTRAINT',c.constraint_name,c.owner) as ddl, c.owner, c.constraint_name, 'constraint' as object_type from dual d
   ,all_constraints c
   where constraint_type not in ('P', 'C', 'U', 'O', 'F')
   and c.owner not in ('SYS', 'SYSTEM', 'WMSYS', 'SYSMAN','MDSYS','ORDSYS','XDB', 'WKSYS','OLAPSYS', 'DBSNMP', 'DMSYS','CTXSYS','WK_TEST', 'ORDPLUGINS', 'OUTLN', 'EXFSYS')


text:
package org.wso2.carbon.governance.registry.eventing.handlers;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.governance.api.exception.GovernanceException;
import org.wso2.carbon.governance.api.util.GovernanceConstants;
import org.wso2.carbon.governance.lcm.tasks.events.LifecycleNotificationEvent;
import org.wso2.carbon.governance.lcm.tasks.LCNotificationScheduler;
import org.wso2.carbon.governance.registry.eventing.handlers.utils.events.*;
import org.wso2.carbon.governance.registry.eventing.internal.EventDataHolder;
import org.wso2.carbon.registry.common.eventing.RegistryEvent;
import org.wso2.carbon.registry.core.Collection;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.registry.core.ResourceImpl;
import org.wso2.carbon.registry.core.config.Mount;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.jdbc.handlers.Handler;
import org.wso2.carbon.registry.core.jdbc.handlers.RequestContext;
import org.wso2.carbon.registry.core.session.CurrentSession;
import org.wso2.carbon.registry.core.utils.RegistryUtils;

import java.util.*;

public class GovernanceEventingHandler extends Handler {
    private static final Log log = LogFactory.getLog(GovernanceEventingHandler.class);

    /**
     * Constant used to validate vote click.
     */
    private final String vote_click = "voteClick";

    /**
     * Constant used to validate item click.
     */
    private final String item_click = "itemClick";

    public void init(String defaultNotificationEndpoint) {
        EventDataHolder.getInstance().setDefaultNotificationServiceURL(defaultNotificationEndpoint);
    }

    public GovernanceEventingHandler() {
        try {
            EventDataHolder.getInstance().getRegistryNotificationService().registerEventType("checklist.item.checked", CheckListItemCheckedEvent.EVENT_NAME, CheckListItemCheckedEvent.EVENT_NAME);
            /*Utils.getRegistryNotificationService().registerEventTypeExclusion("checklist.item.checked", "/");
            Utils.getRegistryNotificationService().registerEventTypeExclusion("checklist.item.checked", "/system");
            Utils.getRegistryNotificationService().registerEventTypeExclusion("checklist.item.checked", "/system/.*");*/
            EventDataHolder.getInstance().getRegistryNotificationService().registerEventType("checklist.item.unchecked", CheckListItemUncheckedEvent.EVENT_NAME, CheckListItemUncheckedEvent.EVENT_NAME);
            /*Utils.getRegistryNotificationService().registerEventTypeExclusion("checklist.item.unchecked", "/");
            Utils.getRegistryNotificationService().registerEventTypeExclusion("checklist.item.unchecked", "/system");
            Utils.getRegistryNotificationService().registerEventTypeExclusion("checklist.item.unchecked", "/system/.*");*/
            EventDataHolder.getInstance().getRegistryNotificationService().registerEventType("lifecycle.state.changed", LifeCycleStateChangedEvent.EVENT_NAME, LifeCycleStateChangedEvent.EVENT_NAME);
            /*Utils.getRegistryNotificationService().registerEventTypeExclusion("lifecycle.state.changed", "/");
            Utils.getRegistryNotificationService().registerEventTypeExclusion("lifecycle.state.changed", "/system");
            Utils.getRegistryNotificationService().registerEventTypeExclusion("lifecycle.state.changed", "/system/.*");*/
            EventDataHolder.getInstance().getRegistryNotificationService().registerEventType("lifecycle.deleted", LifeCycleDeletedEvent.EVENT_NAME, LifeCycleDeletedEvent.EVENT_NAME);
            /*Utils.getRegistryNotificationService().registerEventTypeExclusion("lifecycle.deleted", "/");
            Utils.getRegistryNotificationService().registerEventTypeExclusion("lifecycle.deleted", "/system");
            Utils.getRegistryNotificationService().registerEventTypeExclusion("lifecycle.deleted", "/system/.*");*/
            EventDataHolder.getInstance().getRegistryNotificationService().registerEventType("lifecycle.created", LifeCycleCreatedEvent.EVENT_NAME, LifeCycleCreatedEvent.EVENT_NAME);
            /*Utils.getRegistryNotificationService().registerEventTypeExclusion("lifecycle.created", "/");
            Utils.getRegistryNotificationService().registerEventTypeExclusion("lifecycle.created", "/system");
            Utils.getRegistryNotificationService().registerEventTypeExclusion("lifecycle.created", "/system/.*");*/
            EventDataHolder.getInstance().getRegistryNotificationService().registerEventType("lifecycle.approved", LifeCycleApprovedEvent.EVENT_NAME, LifeCycleApprovedEvent.EVENT_NAME);
            EventDataHolder.getInstance().getRegistryNotificationService().registerEventType("lifecycle.approval.need", LifeCycleApprovalNeededEvent.EVENT_NAME, LifeCycleApprovalNeededEvent.EVENT_NAME);
            EventDataHolder.getInstance().getRegistryNotificationService().registerEventType("lifecycle.approval.withdrawn", LifeCycleApprovalWithdrawnEvent.EVENT_NAME, LifeCycleApprovalWithdrawnEvent.EVENT_NAME);
            EventDataHolder.getInstance().getRegistryNotificationService().registerEventType("lifecycle.checkpoint.notification", LifecycleNotificationEvent.EVENT_NAME, LifecycleNotificationEvent.EVENT_NAME);

            EventDataHolder.getInstance().getRegistryNotificationService().registerEventType("publisher.checklist.checked", PublisherCheckListItemCheckedEvent.EVENT_NAME, null);
            EventDataHolder.getInstance().getRegistryNotificationService().registerEventType("publisher.checklist.item.unchecked", PublisherCheckListItemUncheckedEvent.EVENT_NAME, null);
            EventDataHolder.getInstance().getRegistryNotificationService().registerEventType("publisher.lifecycle.state.changed", PublisherLifeCycleStateChangedEvent.EVENT_NAME, null);
            EventDataHolder.getInstance().getRegistryNotificationService().registerEventType("publisher.update", PublisherResourceUpdatedEvent.EVENT_NAME,null);
            EventDataHolder.getInstance().getRegistryNotificationService().registerEventType("store.lifecycle.state.changed", StoreLifeCycleStateChangedEvent.EVENT_NAME, null);
            EventDataHolder.getInstance().getRegistryNotificationService().registerEventType("store.update", StoreResourceUpdatedEvent.EVENT_NAME, null);

        } catch (Exception e) {
            handleException("Unable to register Event Types", e);
        }
    }

    public void put(RequestContext requestContext) throws RegistryException {

        String path = requestContext.getResourcePath().getPath();
        String relativePath = RegistryUtils.getRelativePath(requestContext.getRegistryContext(),
                path);
        Resource oldResource = requestContext.getOldResource();
        Resource newResource = requestContext.getResource();

        boolean isNotCollection = !(requestContext.getResource() instanceof Collection);

        if (oldResource == null || newResource == null ||
            oldResource.getProperties() == null || newResource.getProperties() == null) {
            return;
        }
        Properties props = oldResource.getProperties();
        Properties newProps = newResource.getProperties();
        String lcName = newResource.getProperty("registry.LC.name");
        String oldLcName = oldResource.getProperty("registry.LC.name");
        List oldLifecycleList = (List) props.get("registry.Aspects");
        List newLifecycleList = (List) newProps.get("registry.Aspects");
        boolean isNotificationSent = false;
        if (lcName == null && oldLcName != null) {
            StringBuilder messageBuilder = new StringBuilder("[").append(oldLcName)
                    .append("] The LifeCycle was deleted for resource at ").append(relativePath).append(".");
            RegistryEvent<String> event = new LifeCycleDeletedEvent<String>(messageBuilder.toString());
            ((LifeCycleDeletedEvent)event).setResourcePath(relativePath);
            event.setParameter("LifecycleName", oldLcName);
            event.setTenantId(CurrentSession.getCallerTenantId());
            try {
                notify(event, requestContext.getRegistry(), relativePath);
                isNotificationSent = true;
            } catch (Exception e) {
                handleException("Unable to send notification for Put Operation", e);
            }
            return;
        } else if (lcName != null && oldLcName != null && !lcName.equals(oldLcName)
                && oldLifecycleList.size() < newLifecycleList.size()) {
            // Add lifecycle checkpoint notification scheduler data when lifecycle state is attached.
            List stateList = (List) newProps.get("registry.lifecycle." + lcName + ".state");
            if (stateList != null) {
                String lifecycleState = (String) stateList.get(0);
                addLCNotificationScheduler(newResource, lcName, lifecycleState, false);
            }
        } else if (lcName != null && oldLcName == null) {
            // Adding scheduler entry when a service is created. This handles the scheduler entries for attaching
            // default lifecycle schedulers at the service creation time.
            List statesList = (List) newProps.get("registry.lifecycle." + lcName + ".state");
            if (statesList != null) {
                // Getting 0 index because its the initial state of a lifecycle
                String lifecycleState = (String) statesList.get(0);
                addLCNotificationScheduler(newResource, lcName, lifecycleState, false);
            }
            StringBuilder messageBuilder = new StringBuilder("[").append(lcName)
                    .append("] The LifeCycle was created for resource at ").append(relativePath).append(".");
            RegistryEvent<String> event = new LifeCycleCreatedEvent<String>(messageBuilder.toString());
            ((LifeCycleCreatedEvent)event).setResourcePath(relativePath);
            event.setParameter("LifecycleName", lcName);
            event.setTenantId(CurrentSession.getCallerTenantId());
            try {
                notify(event, requestContext.getRegistry(), relativePath);
                isNotificationSent = true;
            } catch (Exception e) {
                handleException("Unable to send notification for Put Operation", e);
            }
            // Below notification send when lifecycle assigned assert and at least one approval doesn't required
            // Preconditioned checklistitem check.
            if(sendInitialNotification(requestContext, relativePath)){
            	RegistryEvent<String> approvalEvent = new LifeCycleApprovalNeededEvent<String>(
                        "[" + lcName + "] The LifeCycle was created and some transitions are awating for approval, resource locate at "+ relativePath +".");
           				((LifeCycleApprovalNeededEvent)approvalEvent).setResourcePath(relativePath);
           		approvalEvent.setParameter("LifecycleName", lcName);
           		approvalEvent.setTenantId(CurrentSession.getCallerTenantId());
           		try {
           			notify(approvalEvent, requestContext.getRegistry(), relativePath);
                    isNotificationSent = true;
                } catch (Exception e) {
                	handleException("Unable to send notification for Put Operation", e);
                }
           		return;
            }
            return;
        }

        for (Map.Entry<Object, Object> e : props.entrySet()) {
            String propKey = (String) e.getKey();
            if (propKey.matches("registry\\p{Punct}.*\\p{Punct}checklist\\p{Punct}.*")) {
                List<String> propValues = (List<String>) e.getValue();
                List<String> newPropValues = (List<String>) newProps.get(propKey);
                if ((propValues == null) || (newPropValues == null))
                    continue;
                if ((propValues.size() > 2) && (newPropValues.size() > 2)) {
                    String oldName = null;
                    String oldValue = null;
                    String oldLifeCycleState = null;
                    String newName = null;
                    String newValue = null;
                    String newLifeCycleState = null;
                    for (String param : propValues) {
                        if (param.startsWith("status:")) {
                            oldLifeCycleState = param.substring(7);
                        } else if (param.startsWith("name:")) {
                            oldName = param.substring(5);
                        } else if (param.startsWith("value:")) {
                            oldValue = param.substring(6);
                        }
                    }
                    for (String param : newPropValues) {
                        if (param.startsWith("status:")) {
                            newLifeCycleState = param.substring(7);
                        } else if (param.startsWith("name:")) {
                            newName = param.substring(5);
                        } else if (param.startsWith("value:")) {
                            newValue = param.substring(6);
                        }
                    }
                    if(oldName!=null && oldValue!=null) {
                        if (oldName.equalsIgnoreCase(newName) &&
                                oldLifeCycleState.equalsIgnoreCase(newLifeCycleState) &&
                                !oldValue.equalsIgnoreCase(newValue)) {
                            RegistryEvent<String> event = null;
                            if (oldValue.equals(Boolean.toString(Boolean.TRUE)) ||
                                    oldValue.equals(Boolean.toString(Boolean.FALSE))) {
                                if (oldValue.equals(Boolean.toString(Boolean.TRUE))) {
                                    event = new CheckListItemUncheckedEvent<String>(
                                            "[" + lcName + "] The CheckList item '" + oldName + "' of LifeCycle State '" +
                                                    oldLifeCycleState + "' was Unchecked for resource at "+relativePath +".");
                                    ((CheckListItemUncheckedEvent)event).setResourcePath(relativePath);
                                } else {
                                    event = new CheckListItemCheckedEvent<String>(
                                            "[" + lcName + "] The CheckList item '" + oldName + "' of LifeCycle State '" +
                                                    oldLifeCycleState + "' was Checked for resource at "+relativePath +".");
                                    ((CheckListItemCheckedEvent)event).setResourcePath(relativePath);
                                }
                            } else {
                                // In here we are un-aware of the changes that happened.
                                event = new CheckListItemCheckedEvent<String>(
                                        "[" + lcName + "] The State of the CheckList item '" + oldName + "' of LifeCycle State '" +
                                                oldLifeCycleState + "' was changed for resource at "+relativePath +".");
                                ((CheckListItemCheckedEvent)event).setResourcePath(relativePath);
                            }
                            event.setParameter("LifecycleName", lcName);
                            event.setParameter("LifecycleState", oldLifeCycleState);
                            event.setParameter("CheckItem", oldName);
                            event.setTenantId(CurrentSession.getCallerTenantId());
                            try {
                                notify(event, requestContext.getRegistry(), relativePath);
                            } catch (Exception ex) {
                                handleException("Unable to send notification for Put Operation", ex);
                            }
                            createPublisherLCNotification(event, requestContext, relativePath);
                            isNotificationSent = true;
                        }
                    }
                }
            }
        }
        if (oldResource != null && sendNotifications(requestContext,relativePath) && isNotCollection && !isNotificationSent) {
            RegistryEvent<String> pubEvent = new PublisherResourceUpdatedEvent<String>("The resource at path " + relativePath + " was updated.");
            ((PublisherResourceUpdatedEvent)pubEvent).setResourcePath(relativePath);
            pubEvent.setParameter("RegistryOperation", "put");
            pubEvent.setTenantId(CurrentSession.getCallerTenantId());
            try {
                notify(pubEvent, requestContext.getRegistry(), relativePath);
            } catch (Exception e) {
                handleException("Unable to send notification for Update Operation", e);
            }

            RegistryEvent<String> storeEvent = new StoreResourceUpdatedEvent<String>("The resource at path " + relativePath + " was updated.");
            ((StoreResourceUpdatedEvent)storeEvent).setResourcePath(relativePath);
            storeEvent.setParameter("RegistryOperation", "put");
            storeEvent.setTenantId(CurrentSession.getCallerTenantId());

            try {
                notify(storeEvent, requestContext.getRegistry(), relativePath);
            } catch (Exception e) {
                handleException("Unable to send notification for Update Operation", e);
            }

        }
        invokeApprovalNotification(requestContext, relativePath);
    }

   @SuppressWarnings("unchecked")
    public void invokeAspect(RequestContext requestContext) throws RegistryException {
        Map<String, String> parameters = new HashMap<String, String>();
        Resource resource = requestContext.getOldResource();
        String oldPath = resource.getPath();

        Properties props = resource.getProperties();
        //String lcName = resource.getProperty("registry.LC.name");
        boolean isEnvironmentChange=false;
        List<String> properties = new ArrayList<String>();
        Map<String, String> changeStates = new HashMap<String, String>();
        Map<String, String> oldStates = new HashMap<String, String>();

        for (Object key : props.keySet()) {
            String propKey = (String)key;
            if (propKey.matches("registry\\p{Punct}lifecycle\\p{Punct}.*\\p{Punct}state")) {
                properties.add(propKey);
            }
        }
        if (properties.size() == 0) {
            return;
        }
        String relativeOldPath = RegistryUtils.getRelativePath(requestContext.getRegistryContext(),oldPath);
        for (String  property :  properties){
            String oldState = resource.getProperty(property);
            oldStates.put(property,oldState);
        }
        //String oldState = resource.getProperty(stateKey);
        if ((requestContext.getAspect() == null) || (requestContext.getAction() == null)) {
            return;
        }
        if (!requestContext.isProcessingComplete()) {
            Object parameterNames = requestContext.getProperty("parameterNames");
            if (parameterNames != null) {
                for (String key : (Set<String>)parameterNames) {
                    parameters.put(key, (String)requestContext.getProperty(key));
                }
                requestContext.getAspect().invoke(requestContext, requestContext.getAction(),
                        parameters);
            } else {
                requestContext.getAspect().invoke(requestContext, requestContext.getAction());
            }
            requestContext.setProcessingComplete(true);
        }
        String path = requestContext.getResourcePath().getPath();
        String relativePath = RegistryUtils.getRelativePath(requestContext.getRegistryContext(),
                path);
        if (!requestContext.getRegistry().resourceExists(path)) {
            return;
        }
        resource = requestContext.getRegistry().get(path);

        if (resource == null) {
            return;
        }

        if(resource.getProperty(GovernanceConstants.REGISTRY_IS_ENVIRONMENT_CHANGE)!=null &&
                !resource.getProperty(GovernanceConstants.REGISTRY_IS_ENVIRONMENT_CHANGE).isEmpty()){
            isEnvironmentChange = Boolean.parseBoolean(resource.getProperty(GovernanceConstants.REGISTRY_IS_ENVIRONMENT_CHANGE));
            resource.removeProperty(GovernanceConstants.REGISTRY_IS_ENVIRONMENT_CHANGE);
            requestContext.setResource(resource);
            requestContext.getRegistry().put(path,resource);
        }

       for (String  property :  properties){
           String newState = resource.getProperty(property);
           changeStates.put(property,newState);
       }
        //String newState = resource.getProperty(stateKey);
       // Add lifecycle checkpoint notification scheduler data when lifecycle state changes.
       String action = requestContext.getAction();
       // Filtering lifecycle actions.
       if ((!vote_click.equals(action) && !item_click.equals(action))) {
           for (String  property :  properties){
               String lcName = getLCName(property);
               addLCNotificationScheduler(resource, lcName, changeStates.get(property), true);
           }
       }
       String oldState = null;
       String newState = null;
       for (String  property :  properties){
           if(changeStates.get(property) != null && oldStates.get(property) != null && !changeStates.get(property).equals(oldStates.get(property))){
               String lcName = getLCName(property);
               oldState = oldStates.get(property);
               newState = changeStates.get(property);
               String extendedMessage = "";
               boolean isUpdateOnly = false;
               if (!oldPath.equals(path)) {
                   if (resource instanceof Collection) {
                       extendedMessage = ". The collection has moved from: '" + relativeOldPath + "' to: '" +
                                         relativePath + "'.";
                   } else {
                       extendedMessage = ". The resource has moved from: '" + relativeOldPath + "' to: '" +
                                         relativePath + "'.";
                   }
               } else {
                   extendedMessage = " for resource at " + path + ".";
                   isUpdateOnly = true;
               }
               RegistryEvent<String> event = new LifeCycleStateChangedEvent<String>("[" + lcName + "] The LifeCycle State Changed from '" +
                                                                                oldState + "' to '" + newState+"'" + extendedMessage);
               event.setParameter("LifecycleName", lcName);
               event.setParameter("OldLifecycleState", oldState);
               event.setParameter("NewLifecycleState", newState);
               if(isEnvironmentChange){
                   ((LifeCycleStateChangedEvent)event).setResourcePath(relativeOldPath);
               }else{
                   ((LifeCycleStateChangedEvent)event).setResourcePath(relativePath);
               }
               event.setTenantId(CurrentSession.getCallerTenantId());
               try {
                   notify(event, requestContext.getRegistry(), relativePath);
               } catch (Exception e) {
                   handleException("Unable to send notification for Aspect Invoke Operation", e);
               }
               if (isUpdateOnly) {
                   //Send Store Notification
                   sendPublisherLCNotification(lcName,oldState,newState,isEnvironmentChange,relativeOldPath,relativePath,requestContext, extendedMessage);
                   //end of the store notification

                   //Send publisher Notification
                   sendStoreLCNotification(lcName,oldState,newState,isEnvironmentChange,relativeOldPath,relativePath,requestContext, extendedMessage);
                   //end of the publisher notification
               }

               // When LC move one stage to another, Approval notification may send to user
               if(sendInitialNotification(requestContext, relativePath)){
                   RegistryEvent<String> approveEvent = new LifeCycleApprovalNeededEvent<String>(
                           "[" + lcName + "] The LifeCycle State '" + newState +
                           "' required approval for state transitions, for resource locate at "+relativePath +".");
                   approveEvent.setParameter("LifecycleName", lcName);
                   approveEvent.setParameter("OldLifecycleState", oldState);
                   approveEvent.setParameter("NewLifecycleState", newState);
                   if(isEnvironmentChange){
                       ((LifeCycleApprovalNeededEvent)approveEvent).setResourcePath(relativeOldPath);
                   }else{
                       ((LifeCycleApprovalNeededEvent)approveEvent).setResourcePath(relativePath);
                   }
                   approveEvent.setTenantId(CurrentSession.getCallerTenantId());
                   try {
                       notify(approveEvent, requestContext.getRegistry(), relativePath);
                   } catch (Exception e) {
                       handleException("Unable to send notification for Put Operation", e);
                   }
               }
           } else {
               continue;
           }
       }

    }

    protected void notify(RegistryEvent event, Registry registry, String path) throws Exception {
        try {
            if (EventDataHolder.getInstance().getRegistryNotificationService() == null) {
                log.debug("Eventing service is unavailable.");
                return;
            }
            if (registry == null || registry.getEventingServiceURL(path) == null) {
                EventDataHolder.getInstance().getRegistryNotificationService().notify(event);
                return;
            } else if (EventDataHolder.getInstance().getDefaultNotificationServiceURL() == null) {
                log.error("Governance Eventing Handler is not properly initialized");
            } else if (registry.getEventingServiceURL(path).equals(
                    EventDataHolder.getInstance().getDefaultNotificationServiceURL())) {
                EventDataHolder.getInstance().getRegistryNotificationService().notify(event);
                return;
            } else {
                EventDataHolder.getInstance().getRegistryNotificationService()
                               .notify(event, registry.getEventingServiceURL(path));
                return;
            }
        } catch (RegistryException e) {
            log.error("Unable to send notification", e);
        }
        log.error("Unable to send notification");
    }

    private void handleException(String message, Exception e) {
        log.error(message, e);
    }
    /**
     * Send notification when Approval voting happened /approval notification removed
     * 		Or when approval is enabled(after user click on checklist)
     * @param requestContext
     * @param relativePath
     */
    private void invokeApprovalNotification(RequestContext requestContext, String relativePath ){
    	Resource oldResource = requestContext.getOldResource();
        Resource newResource = requestContext.getResource();

        Properties props = oldResource.getProperties();
        Properties newProps = newResource.getProperties();

    	String lcName = newResource.getProperty("registry.LC.name");

    	for (Map.Entry<Object, Object> e : props.entrySet()) {
            String propKey = (String) e.getKey();
            if(propKey.matches("registry\\p{Punct}.*\\p{Punct}votes\\p{Punct}.*")){
            	 List<String> propValues = (List<String>) e.getValue();
                 List<String> newPropValues = (List<String>) newProps.get(propKey);
                 if ((propValues == null) || (newPropValues == null))
                     continue;
                 if ((propValues.size() > 2) && (newPropValues.size() > 2)) {
	                 String oldName = null;
	                 String oldValue = null;
	                 int oldVote = 0;
	                 String oldLifeCycleState = null;
	                 String newName = null;
	                 String newValue = null;
	                 int newVote = 0;
	                 String newLifeCycleState = null;
	                 for (String param : propValues) {
	                     if (param.startsWith("status:")) {
	                         oldLifeCycleState = param.substring(7);
	                     } else if (param.startsWith("name:")) {
	                         oldName = param.substring(5);
	                     } else if (param.startsWith("current:")) {
	                         oldValue = param.substring(8);
	                         oldVote = Integer.parseInt(oldValue);
	                     }
	                 }
	                 for (String param : newPropValues) {
	                     if (param.startsWith("status:")) {
	                         newLifeCycleState = param.substring(7);
	                     } else if (param.startsWith("name:")) {
	                         newName = param.substring(5);
	                     } else if (param.startsWith("current:")) {
	                         newValue = param.substring(8);
	                         newVote = Integer.parseInt(newValue);
	                     }
	                 }
                     if(oldName!=null && oldValue!=null){
                         if (oldName.equalsIgnoreCase(newName) &&
                                 oldLifeCycleState.equalsIgnoreCase(newLifeCycleState) &&
                                 !oldValue.equalsIgnoreCase(newValue)) {
                             RegistryEvent<String> event = null;
                             if(newVote > oldVote){
                                 event = new LifeCycleApprovedEvent<String>(
                                         "[" + lcName + "] LifeCycle State '" + oldLifeCycleState + "', transitions event '" + oldName + "'" +
                                                 " was approved for resource at "+relativePath +".");
                                 ((LifeCycleApprovedEvent)event).setResourcePath(relativePath);
                             }else{
                                 event = new LifeCycleApprovalWithdrawnEvent<String>(
                                         "[" + lcName + "] LifeCycle State '" + oldLifeCycleState + "' transitions event '" + oldName + "'" +
                                                 " approvel was removed for resource at "+relativePath +".");
                                 ((LifeCycleApprovalWithdrawnEvent)event).setResourcePath(relativePath);
                             }
                             event.setParameter("LifecycleName", lcName);
                             event.setParameter("LifecycleState", oldLifeCycleState);
                             event.setParameter("CheckItem", oldName);
                             event.setTenantId(CurrentSession.getCallerTenantId());
                             try {
                                 notify(event, requestContext.getRegistry(), relativePath);
                             } catch (Exception ex) {
                                 handleException("Unable to send notification for Put Operation", ex);
                             }
                         }
                     }
                 }
            }
    	}
    }

    /**
     *
     * @param requestContext
     * @param relativePath
     * @return boolean True value return when at least one approval doesn't dependent on check list.
     */
    private boolean sendInitialNotification(RequestContext requestContext, String relativePath) {
        Resource newResource = requestContext.getResource();
        Properties newProps = newResource.getProperties();
    	boolean sendNotification =  false;
    	for (Map.Entry<Object, Object> e : newProps.entrySet()) {
            String propKey = (String) e.getKey();
            if (propKey.matches("registry\\p{Punct}.*\\p{Punct}votes\\p{Punct}.*")) {
                List<String> newPropValues = (List<String>) newProps.get(propKey);
                if (newPropValues == null)
                    continue;
                if (newPropValues.size() > 2) {
                    String newName = null;
                    for (String param : newPropValues) {
                        if (param.startsWith("name:")) {
                            newName = param.substring(5);
                        }
                    }
                    if(newName !=  null && !newName.isEmpty()){
                    	sendNotification = true;
                    	return sendNotification;
                    }
                }
            }
    	}
    	return sendNotification;
	}

    /**
     * This method is used to add schedulers to lifecycle checkpoints. These schedulers will be triggered by a
     * schedule task. Checkpoints are added with to the lifecycle state and lifecycle name.
     *
     * @param resource          resource which the scheduler needs to be added.
     * @param lifecycleName     lifecycle name of the scheduler
     * @param lifecycleState    lifecycle state of the scheduler.
     * @param isInvokeAspect    does this add scheduler method is called when invoking a lifecycle.
     */
    private void addLCNotificationScheduler(Resource resource, String lifecycleName, String lifecycleState, boolean
            isInvokeAspect) {
        LCNotificationScheduler lifecycleNotificationScheduler =
                new LCNotificationScheduler();
        try {
            lifecycleNotificationScheduler
                    .addScheduler((ResourceImpl) resource, lifecycleName, lifecycleState, isInvokeAspect);
        } catch (GovernanceException e) {
            log.error("Lifecycle '" + lifecycleName + "'checkpoint addition failed for state " + lifecycleState, e);
        }
    }

    private String getLCName(String property){
        String[] peps = property.split("\\p{Punct}");
        if (peps != null && peps.length == 4){
              return peps[2];
        }
        return null;
    }

    private void sendStoreLCNotification(String lcName, String oldState, String newState,boolean isEnvironmentChange, String relativeOldPath, String relativePath,RequestContext requestContext, String extendedMessage){
        //Send Store Notification

        RegistryEvent<String> storeLCChanges = new StoreLifeCycleStateChangedEvent<String>("[" + lcName + "] The LifeCycle State Changed from '" +
                                                                                oldState + "' to '" + newState+"'"+ extendedMessage);
        storeLCChanges.setParameter("LifecycleName", lcName);
        storeLCChanges.setParameter("OldLifecycleState", oldState);
        storeLCChanges.setParameter("NewLifecycleState", newState);
        if(isEnvironmentChange){
            ((StoreLifeCycleStateChangedEvent)storeLCChanges).setResourcePath(relativeOldPath);
        }else{
            ((StoreLifeCycleStateChangedEvent)storeLCChanges).setResourcePath(relativePath);
        }
        storeLCChanges.setTenantId(CurrentSession.getCallerTenantId());
        try {
            notify(storeLCChanges, requestContext.getRegistry(), relativePath);
        } catch (Exception e) {
            handleException("Unable to send notification for Aspect Invoke Operation", e);
        }
        //end of the store notification
    }

    private void sendPublisherLCNotification(String lcName, String oldState, String newState,boolean isEnvironmentChange, String relativeOldPath, String relativePath,RequestContext requestContext, String extendedMessage){
        //Send Store Notification
        RegistryEvent<String> publisherLCChanges = new PublisherLifeCycleStateChangedEvent<String>("[" + lcName + "] The LifeCycle State Changed from '" +
                                                                                oldState + "' to '" + newState+"'"+ extendedMessage);
        publisherLCChanges.setParameter("LifecycleName", lcName);
        publisherLCChanges.setParameter("OldLifecycleState", oldState);
        publisherLCChanges.setParameter("NewLifecycleState", newState);
        if(isEnvironmentChange){
            ((PublisherLifeCycleStateChangedEvent)publisherLCChanges).setResourcePath(relativeOldPath);
        }else{
            ((PublisherLifeCycleStateChangedEvent)publisherLCChanges).setResourcePath(relativePath);
        }
        publisherLCChanges.setTenantId(CurrentSession.getCallerTenantId());
        try {
            notify(publisherLCChanges, requestContext.getRegistry(), relativePath);
        } catch (Exception e) {
            handleException("Unable to send notification for Aspect Invoke Operation", e);
        }
        //end of the store notification
    }

    private void createPublisherLCNotification(RegistryEvent event, RequestContext requestContext, String relativePath) {
        if (event instanceof CheckListItemUncheckedEvent) {
            RegistryEvent checkListEvent = new PublisherCheckListItemUncheckedEvent<String>(event.getMessage().toString());
            ((PublisherCheckListItemUncheckedEvent)checkListEvent).setResourcePath(relativePath);
            checkListEvent.setParameter("LifecycleState", ((Map<String, String>)event.getParameters()).get("LifecycleState"));
            checkListEvent.setParameter("CheckItem", ((Map<String, String>)event.getParameters()).get("CheckItem"));
            checkListEvent.setParameter("LifecycleName", ((Map<String, String>)event.getParameters()).get("LifecycleName"));
            checkListEvent.setTenantId(CurrentSession.getCallerTenantId());
            try {
                notify(checkListEvent, requestContext.getRegistry(), relativePath);
            } catch (Exception e) {
                handleException("Unable to send notification for Aspect Invoke Operation", e);
            }

        } else if (event instanceof CheckListItemCheckedEvent) {
            RegistryEvent checkListEvent = new PublisherCheckListItemCheckedEvent<String>(event.getMessage().toString());
            ((PublisherCheckListItemCheckedEvent)checkListEvent).setResourcePath(relativePath);
            checkListEvent.setParameter("LifecycleState", ((Map<String, String>)event.getParameters()).get("LifecycleState"));
            checkListEvent.setParameter("CheckItem", ((Map<String, String>)event.getParameters()).get("CheckItem"));
            checkListEvent.setTenantId(CurrentSession.getCallerTenantId());
            checkListEvent.setParameter("LifecycleName", ((Map<String, String>)event.getParameters()).get("LifecycleName"));
            try {
                notify(checkListEvent, requestContext.getRegistry(), relativePath);
            } catch (Exception e) {
                handleException("Unable to send notification for Aspect Invoke Operation", e);
            }
        }

    }

    /**
     * Method to get the actual depth of the request
     */
    private int getRequestDepth(RequestContext requestContext){
        int requestDepth = -1;
        if (requestContext.getRegistry().getRegistryContext() != null &&
            requestContext.getRegistry().getRegistryContext().getDataAccessManager() != null &&
            requestContext.getRegistry().getRegistryContext().getDataAccessManager().getDatabaseTransaction() != null) {
            requestDepth =
                    requestContext.getRegistry().getRegistryContext().getDataAccessManager().getDatabaseTransaction()
                                  .getNestedDepth();
        }
        return requestDepth;
    }

    private boolean sendNotifications(RequestContext requestContext, String relativePath) {

        boolean isMountPath = false;
        List<Mount> mounts = requestContext.getRegistry().getRegistryContext().getMounts();
        for (Mount mount : mounts) {
            String mountPath = mount.getPath();
            if (relativePath.startsWith(mountPath)) {
                isMountPath = true;
            }
        }
        if (isMountPath) {
            if (getRequestDepth(requestContext) != 1) {
                return false;
            } else {
                return true;
            }
        } else {
            int requestDepth = getRequestDepth(requestContext);
            if (!(requestDepth == 1 || requestDepth == 3)) {
                return false;
            } else {
                return true;
            }
        }

    }
}


text:
package com.codeaspect.puffer.converters;

import com.codeaspect.puffer.annotations.PacketMessage;
import com.codeaspect.puffer.annotations.TemporalFormat;
import com.codeaspect.puffer.packet.Packet;
import com.codeaspect.puffer.testutils.TestUtils;
import junit.framework.Assert;
import org.junit.Ignore;
import org.junit.Test;

import java.lang.reflect.Field;
import java.util.Date;

public class AnnotationBasedDateConverterTest {

	@Ignore
	public static class TestPacket implements Packet {
		@PacketMessage(position=1, length=7)
		@TemporalFormat("dd-MM-yyyy")
		public Date date;
	};

	private Converter<Date> converter = new AnnotationBasedDateConverter();

	private static final Date TEST_DATE = TestUtils.createDate(18,8,2014);
	private static final String TEST_STRING = "18-08-2014";

	@Test
	public void testHydrate() throws NoSuchFieldException, SecurityException{
		Field field = TestPacket.class.getDeclaredField("date");
		Date date = converter.hydrate(field, TEST_STRING);
		Assert.assertEquals(TEST_DATE, date);
	}

	@Test
	public void testStringify() throws NoSuchFieldException, SecurityException{
		Field field = TestPacket.class.getDeclaredField("date");
		String date = converter.stringify(field, TEST_DATE);
		Assert.assertEquals(TEST_STRING, date);
	}

}


text:
I am a PDPackage and i represent a package (RPackageSet) and all his dependencies (PDPackageDependency).

Instance variables :

	- dependencies : a collection of PDPackageDependency (actually the nodes of a graph dependency, from a source PDPackage to a target PDPackage)
	- included : says if the PDPackage is included or not in the set of packages at the beginning.
	- rpackage : the instance of asRPackageSet
	- inStack : useful for tarjan algorithm and cycle algorithm. It avoid stack access
	- tarjanIndex and tarjanLowLink : integer for the tarjan algorithm.
	- bfsParent : see cycle algorithm
	- seen : says if all dependencies have been added to the Package


text:
<?php

namespace Auto\MainBundle\Controller;

use Auto\MainBundle\Entity\Comment;
use Auto\MainBundle\Entity\ZayavkaAuto;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Validator\Constraints\DateTime;

class MyAjaxController extends Controller
{
    /* ПОЛУЧЕНИЯ МОДЕЛЕЙ АВТОМОБИЛЯ ДЛЯ ПОЛЯ */
    public function getModelsAction(){
        header('Content-Type: application/json');

        $request = $this->container->get('request');
        $data = $request->request->get('mark_id');

        $model = $this->getDoctrine()
            ->getRepository('AutoMainBundle:Model');

        $query = $model->createQueryBuilder('m')
            ->where("m.mark_id=$data")
            ->getQuery();

        $models = $query->getResult();

        $model = array();

        for($i = 0; $i < count($models); $i++){
            $model[$i]['id'] = $models[$i]->getId();
            $model[$i]['model'] = $models[$i]->getModel();
        }

        $response = array("code" => 100, "success" => true, "models" => $model);

        return new Response(json_encode($response));
    }

    /* ПОЛУЧЕНИЯ ГОДОВ ВЫПУСКА АВТОМОБИЛЯ ДЛЯ ПОЛЯ */
    public function getCarYearAction(){
        header('Content-Type: application/json');

        $request = $this->container->get('request');
        $data = $request->request->get('model_id');

        $year = $this->getDoctrine()
            ->getRepository('AutoMainBundle:CarYear');

        $query = $year->createQueryBuilder('y')
            ->where("y.model_id=$data")
            ->getQuery();

        $years = $query->getResult();

        $year = array();

        for($i = 0; $i < count($years); $i++){
            $year[$i]['id'] = $years[$i]->getId();
            $year[$i]['year'] = $years[$i]->getYear();
        }

        $response = array("code" => 100, "success" => true, "year" => $year);

        return new Response(json_encode($response));
    }

    /* ПОЛУЧЕНИЯ ГОРОДОВ ДЛЯ ПОЛЯ */
    public function getCityAction(){
        header('Content-Type: application/json');

        $request = $this->container->get('request');
        $data = $request->request->get('region_id');

        $city = $this->getDoctrine()
            ->getRepository('AutoMainBundle:City');

        $query = $city->createQueryBuilder('c')
            ->where("c.region_id=$data")
            ->getQuery();

        $cities = $query->getResult();

        $city = array();

        for($i = 0; $i < count($cities); $i++){
            $city[$i]['id'] = $cities[$i]->getId();
            $city[$i]['name'] = $cities[$i]->getName();
        }

        $response = array("code" => 100, "success" => true, "city" => $city);

        return new Response(json_encode($response));
    }

    public function newZayavkaAction(){
        header('Content-Type: application/json');

        $em = $this->getDoctrine()->getManager();

        $session = $this->get('session');

        $request = $this->container->get('request');

        $region = $request->request->get('region');
        $mark = $request->request->get('mark');
        $model = $request->request->get('model');
        $year_from = $request->request->get('year_from');
        $year_to = $request->request->get('year_to');
        $run_from = $request->request->get('run_from');
        $run_to = $request->request->get('run_to');
        $price_from = $request->request->get('price_from');
        $price_to = $request->request->get('price_to');
        $body = $request->request->get('body');
        $color = $request->request->get('color');
        $new = $request->request->get('new_old');
        $description = $request->request->get('description');

        $zayavka = new ZayavkaAuto();
        $error = '';

        $zayavka->setNew($new);
        if(isset($region) && !empty($region)){
            $zayavka->setRegion($region);
        }
        if(isset($mark) && !empty($mark) && $mark != 'Выберите марку'){
            $zayavka->setMark($mark);
        }else{
            $error .= 'Не выбрана марка автомобиля';
            $response = array("code" => 200, "success" => false, 'error' => $error);
            return new Response(json_encode($response));
        }

        if(isset($model) && !empty($model) && $model != 'Выберите модель'){
            $zayavka->setModel($model);
        }
        if(isset($year_from) && !empty($year_from) && $year_from != 'Укажите год выпуска'){
            $zayavka->setYearFrom($year_from);
        }
        if(isset($year_to) && !empty($year_to) && $year_to != 'Укажите год выпуска'){
            $zayavka->setYearTo($year_to);
        }
        if(isset($run_from) && !empty($run_from)){
            $zayavka->setRunFrom(abs((int)$run_from));
        }else{
            $zayavka->setRunFrom(0);
        }
        if(isset($run_to) && !empty($run_to)){
            $zayavka->setRunTo(abs((int)$run_to));
        }else{
            $zayavka->setRunTo(1000000);
        }
        if(isset($price_from) && !empty($price_from)){
            $zayavka->setPriceFrom(abs((int)$price_from));
        }
        if(isset($price_to) && !empty($price_to)){
            $zayavka->setPriceTo(abs((int)$price_to));
        }
        if(isset($body) && !empty($body)){
            $zayavka->setBody($body);
        }
        if(isset($color) && !empty($color)){
            $zayavka->setColor($color);
        }
        if(isset($description) && !empty($description)){
            $zayavka->setDescription($description);
        }

        $zayavka->setUserId($session->get('user_id'));
        $zayavka->setDateAdd(new \DateTime('now'));
        $zayavka->setDateUpdate(new \DateTime('now'));

        $em->persist($zayavka);
        $em->flush();

        $response = array("code" => 100, "success" => true,
            'new' => $zayavka->getNew(),
            'region' => $zayavka->getRegion(),
            'mark' => $zayavka->getMark(),
            'model' => $zayavka->getModel(),
            'year_from' => $zayavka->getYearFrom(),
            'year_to' => $zayavka->getYearTo(),
            'body' => $zayavka->getBody(),
            'price_from' => $zayavka->getPriceFrom(),
            'price_to' => $zayavka->getPriceTo(),
            'run_from' => $zayavka->getRunFrom(),
            'run_to' => $zayavka->getRunTo(),
            'color' => $zayavka->getColor(),
            'description' => $zayavka->getDescription(),
            'user_id' => $session->get('user_id'));

        return new Response(json_encode($response));
    }

    public function addCommentAction(){
        header('Content-Type: application/json');

        $em = $this->getDoctrine()->getManager();
        $session = $this->get('session');

        // GETTING USER NAME AND EMAIL FROM SESSION IF ONE IS AUTH
        $user_id = $session->get('user_id');
        $user_name = $session->get('user_name');
        $user_email = $session->get('user_email');

        $request = $this->container->get('request');

        $name = trim($request->request->get('name'));
        if(isset($user_name) && !empty($user_name)){
            $name = $user_name;
        }
        $email = trim($request->request->get('email'));
        if(isset($user_email) && !empty($user_email)){
            $email = $user_email;
        }
        $text = trim($request->request->get('text'));
        $auto_id = $request->request->get('auto_id');
        $parent_id = $request->request->get('parent_id');

        $comment = new Comment();
        $error = '';

        if(isset($user_id) && !empty($user_id)){
            $comment->setIdUser($user_id);
        }
        if(isset($name) && !empty($name) && !is_null($name) ){
            $comment->setName($name);
        }else{
            $error .= '
Необходимо ввести имя!
';
        }
        if(isset($email) && !empty($email) && !is_null($email) ){
            $comment->setEmail($email);
        }else{
            $error .= '
Необходимо ввести email!
';
        }
        if(isset($text) && !empty($text) && !is_null($text) ){
            $comment->setText($text);
        }else{
            $error .= '
Поле комментария не должно быть пустым!
';
        }

        if($error == ''){
            $comment->setDateAdd(new \DateTime('now'));
            $comment->setIdAuto($auto_id);
            $comment->setParentId($parent_id);
            $comment->setPublic(1);

            $em->persist($comment);
            $em->flush();

            $date = date_format($comment->getDateAdd(), 'd.m.Y, H:i');

            $response = array("code" => 100, "success" => true,
                'comment_id' => $comment->getId(),
                'name' => htmlspecialchars($name),
                'email' => htmlspecialchars($email),
                'text' => htmlspecialchars($text),
                'date' => $date,
            );
        }else{

            $response = array("code" => 200, "success" => false,
                'name' => htmlspecialchars($name),
                'email' => htmlspecialchars($email),
                'text' => htmlspecialchars($text),
                'error' => $error,
            );
        }

        return new Response(json_encode($response));
    }

    public function deleteCommentAction() {
        header('Content-Type: application/json');

        $em = $this->getDoctrine()->getManager();
        $request = $this->container->get('request');

        $id = abs((int)$request->request->get('id'));

        $comment = $em->getRepository('AutoMainBundle:Comment')->findOneById($id);

        if(!$comment){
            $response = array('code' => 200, 'success' => false);
        }else{
            $em->remove($comment);
            $em->flush();

            $response = array('code' => 200, 'success' => true);
        }

        return new Response(json_encode($response));
    }

}


text:
"""
URLconf for registration using django-registration's simple one-step
workflow.

"""

from django.conf.urls import include, url
from django.views.generic.base import TemplateView

from . import views

urlpatterns = [
    url(r'^register/$',
        views.RegistrationView.as_view(),
        name='registration_register'),
    url(r'^register/closed/$',
        TemplateView.as_view(
            template_name='registration/registration_closed.html'
        ),
        name='registration_disallowed'),
    url(r'', include('registration.auth_urls')),
]


text:
<?php namespace League\Fractal\Test;

use League\Fractal\Manager;
use League\Fractal\Pagination\Cursor;
use League\Fractal\Resource\Collection;
use League\Fractal\Resource\Item;
use League\Fractal\Scope;
use League\Fractal\Serializer\ArraySerializer;
use League\Fractal\Test\Stub\Transformer\DefaultIncludeBookTransformer;
use Mockery;

class ScopeTest extends \PHPUnit_Framework_TestCase
{
    protected $simpleItem = array('foo' => 'bar');
    protected $simpleCollection = array(array('foo' => 'bar'));

    public function testEmbedChildScope()
    {
        $manager = new Manager();

        $resource = new Item(array('foo' => 'bar'), function () {
        });

        $scope = new Scope($manager, $resource, 'book');
        $this->assertEquals($scope->getScopeIdentifier(), 'book');
        $childScope = $scope->embedChildScope('author', $resource);

        $this->assertInstanceOf('League\Fractal\Scope', $childScope);
    }

    public function testGetManager()
    {
        $resource = new Item(array('foo' => 'bar'), function () {
        });

        $scope = new Scope(new Manager(), $resource, 'book');

        $this->assertInstanceOf('League\Fractal\Manager', $scope->getManager());
    }

    /**
     * @covers League\Fractal\Scope::toArray
     */
    public function testToArray()
    {
        $manager = new Manager();

        $resource = new Item(array('foo' => 'bar'), function ($data) {
            return $data;
        });

        $scope = new Scope($manager, $resource);

        $this->assertEquals(array('data' => array('foo' => 'bar')), $scope->toArray());
    }

    public function testGetCurrentScope()
    {
        $manager = new Manager();

        $resource = new Item(array('name' => 'Larry Ullman'), function () {
        });

        $scope = new Scope($manager, $resource, 'book');
        $this->assertEquals('book', $scope->getScopeIdentifier());

        $childScope = $scope->embedChildScope('author', $resource);
        $this->assertEquals('author', $childScope->getScopeIdentifier());

        $grandChildScope = $childScope->embedChildScope('profile', $resource);
        $this->assertEquals('profile', $grandChildScope->getScopeIdentifier());
    }

    public function testGetIdentifier()
    {
        $manager = new Manager();

        $resource = new Item(array('name' => 'Larry Ullman'), function () {
        });

        $scope = new Scope($manager, $resource, 'book');
        $this->assertEquals('book', $scope->getIdentifier());

        $childScope = $scope->embedChildScope('author', $resource);
        $this->assertEquals('book.author', $childScope->getIdentifier());

        $grandChildScope = $childScope->embedChildScope('profile', $resource);
        $this->assertEquals('book.author.profile', $grandChildScope->getIdentifier());
    }

    public function testGetParentScopes()
    {
        $manager = new Manager();

        $resource = new Item(array('name' => 'Larry Ullman'), function () {
        });

        $scope = new Scope($manager, $resource, 'book');

        $childScope = $scope->embedChildScope('author', $resource);
        $this->assertEquals(array('book'), $childScope->getParentScopes());

        $grandChildScope = $childScope->embedChildScope('profile', $resource);
        $this->assertEquals(array('book', 'author'), $grandChildScope->getParentScopes());
    }

    public function testIsRequested()
    {
        $manager = new Manager();
        $manager->parseIncludes(array('foo', 'bar', 'baz.bart'));

        $scope = new Scope($manager, Mockery::mock('League\Fractal\Resource\ResourceAbstract'));

        $this->assertTrue($scope->isRequested('foo'));
        $this->assertTrue($scope->isRequested('bar'));
        $this->assertTrue($scope->isRequested('baz'));
        $this->assertTrue($scope->isRequested('baz.bart'));
        $this->assertFalse($scope->isRequested('nope'));

        $childScope = $scope->embedChildScope('baz', Mockery::mock('League\Fractal\Resource\ResourceAbstract'));
        $this->assertTrue($childScope->isRequested('bart'));
        $this->assertFalse($childScope->isRequested('foo'));
        $this->assertFalse($childScope->isRequested('bar'));
        $this->assertFalse($childScope->isRequested('baz'));
    }

    /**
     * @expectedException InvalidArgumentException
     */
    public function testScopeRequiresConcreteImplementation()
    {
        $manager = new Manager();
        $manager->parseIncludes('book');

        $resource = Mockery::mock('League\Fractal\Resource\ResourceAbstract', array(
            array('bar' => 'baz'),
            function() {}
        ))->makePartial();

        $scope = new Scope($manager, $resource);
        $scope->toArray();
    }

    public function testToArrayWithIncludes()
    {
        $manager = new Manager();
        $manager->parseIncludes('book');

        $transformer = Mockery::mock('League\Fractal\TransformerAbstract')->makePartial();
        $transformer->shouldReceive('getAvailableIncludes')->twice()->andReturn(array('book'));
        $transformer->shouldReceive('transform')->once()->andReturnUsing(function (array $data) {
            return $data;
        });
        $transformer->shouldReceive('processIncludedResources')->once()->andReturn(array('book' => array('yin' => 'yang')));

        $resource = new Item(array('bar' => 'baz'), $transformer);

        $scope = new Scope($manager, $resource);

        $this->assertEquals(array('data' => array('bar' => 'baz', 'book' => array('yin' => 'yang'))), $scope->toArray());
    }

    public function testToArrayWithSideloadedIncludes()
    {
        $serializer = Mockery::mock('League\Fractal\Serializer\ArraySerializer')->makePartial();
        $serializer->shouldReceive('sideloadIncludes')->andReturn(true);
        $serializer->shouldReceive('item')->andReturnUsing(function ($key, $data) {
            return array('data' => $data);
        });
        $serializer->shouldReceive('includedData')->andReturnUsing(function ($key, $data) {
            return array('sideloaded' => array_pop($data));
        });

        $manager = new Manager();
        $manager->parseIncludes('book');
        $manager->setSerializer($serializer);

        $transformer = Mockery::mock('League\Fractal\TransformerAbstract')->makePartial();
        $transformer->shouldReceive('getAvailableIncludes')->twice()->andReturn(array('book'));
        $transformer->shouldReceive('transform')->once()->andReturnUsing(function (array $data) {
            return $data;
        });
        $transformer->shouldReceive('processIncludedResources')->once()->andReturn(array('book' => array('yin' => 'yang')));

        $resource = new Item(array('bar' => 'baz'), $transformer);

        $scope = new Scope($manager, $resource);

        $expected = array(
            'data' => array('bar' => 'baz'),
            'sideloaded' => array('book' => array('yin' => 'yang')),
        );

        $this->assertEquals($expected, $scope->toArray());
    }

    public function testPushParentScope()
    {
        $manager = new Manager();

        $resource = new Item(array('name' => 'Larry Ullman'), function () {
        });

        $scope = new Scope($manager, $resource);

        $this->assertEquals(1, $scope->pushParentScope('book'));
        $this->assertEquals(2, $scope->pushParentScope('author'));
        $this->assertEquals(3, $scope->pushParentScope('profile'));

        $this->assertEquals(array('book', 'author', 'profile'), $scope->getParentScopes());
    }

    public function testRunAppropriateTransformerWithItem()
    {
        $manager = new Manager();

        $transformer = Mockery::mock('League\Fractal\TransformerAbstract');
        $transformer->shouldReceive('transform')->once()->andReturn($this->simpleItem);
        $transformer->shouldReceive('getAvailableIncludes')->once()->andReturn(array());
        $transformer->shouldReceive('getDefaultIncludes')->once()->andReturn(array());

        $resource = new Item($this->simpleItem, $transformer);
        $scope = $manager->createData($resource);
        $this->assertEquals(array('data' => $this->simpleItem), $scope->toArray());
    }

    public function testRunAppropriateTransformerWithCollection()
    {
        $manager = new Manager();

        $transformer = Mockery::mock('League\Fractal\TransformerAbstract');
        $transformer->shouldReceive('transform')->once()->andReturn(array('foo' => 'bar'));
        $transformer->shouldReceive('getAvailableIncludes')->once()->andReturn(array());
        $transformer->shouldReceive('getDefaultIncludes')->once()->andReturn(array());

        $resource = new Collection(array(array('foo' => 'bar')), $transformer);
        $scope = $manager->createData($resource);

        $this->assertEquals(array('data' => array(array('foo' => 'bar'))), $scope->toArray());
    }

    /**
     * @covers League\Fractal\Scope::executeResourceTransformers
     * @expectedException InvalidArgumentException
     * @expectedExceptionMessage Argument $resource should be an instance of League\Fractal\Resource\Item or League\Fractal\Resource\Collection
     */
    public function testCreateDataWithClassFuckKnows()
    {
        $manager = new Manager();

        $transformer = Mockery::mock('League\Fractal\TransformerAbstract')->makePartial();

        $resource = Mockery::mock('League\Fractal\Resource\ResourceAbstract', array($this->simpleItem, $transformer))->makePartial();
        $scope = $manager->createData($resource);
        $scope->toArray();
    }

    public function testPaginatorOutput()
    {
        $manager = new Manager();

        $collection = new Collection(array(array('foo' => 'bar', 'baz' => 'ban')), function (array $data) {
            return $data;
        });

        $paginator = Mockery::mock('League\Fractal\Pagination\IlluminatePaginatorAdapter')->makePartial();

        $total = 100;
        $perPage = $count = 5;
        $currentPage = 2;
        $lastPage = 20;

        $paginator->shouldReceive('getTotal')->once()->andReturn($total);
        $paginator->shouldReceive('getCount')->once()->andReturn($count);
        $paginator->shouldReceive('getPerPage')->once()->andReturn($perPage);
        $paginator->shouldReceive('getCurrentPage')->once()->andReturn($currentPage);
        $paginator->shouldReceive('getLastPage')->once()->andReturn($lastPage);
        $paginator->shouldReceive('getUrl')->times(2)->andReturnUsing(function ($page) {
            return 'http://example.com/foo?page='.$page;
        });

        $collection->setPaginator($paginator);

        $rootScope = $manager->createData($collection);

        $expectedOutput = array(
            'meta' => array(
                'pagination' => array(
                    'total' => $total,
                    'count' => $count,
                    'per_page' => $perPage,
                    'current_page' => $currentPage,
                    'total_pages' => $lastPage,
                    'links' => array(
                        'previous' => 'http://example.com/foo?page=1',
                        'next' => 'http://example.com/foo?page=3',
                    ),
                ),
            ),
            'data' => array(
                array(
                    'foo' => 'bar',
                    'baz' => 'ban',
                ),
            )
        );

        $this->assertEquals($expectedOutput, $rootScope->toArray());
    }

    public function testCursorOutput()
    {
        $manager = new Manager();

        $inputData = array(
            array(
                'foo' => 'bar',
                'baz' => 'ban',
            )
        );

        $collection = new Collection($inputData, function (array $data) {
            return $data;
        });

        $cursor = new Cursor(0, 'ban', 'ban', 2);

        $collection->setCursor($cursor);

        $rootScope = $manager->createData($collection);

        $expectedOutput = array(
            'meta' => array(
                'cursor' => array(
                    'current' => 0,
                    'prev' => 'ban',
                    'next' => 'ban',
                    'count' => 2,
                ),
            ),
            'data' => $inputData,
        );

        $this->assertEquals($expectedOutput, $rootScope->toArray());
    }

    public function testDefaultIncludeSuccess()
    {
        $manager = new Manager();
        $manager->setSerializer(new ArraySerializer());

        // Send this stub junk, it has a specific format anyhow
        $resource = new Item(array(), new DefaultIncludeBookTransformer());

        // Try without metadata
        $scope = new Scope($manager, $resource);

        $expected = array(
            'a' => 'b',
            'author' => array(
                'c' => 'd',
            ),
        );

        $this->assertEquals($expected, $scope->toArray());
    }

    public function tearDown()
    {
        Mockery::close();
    }
}


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

/**
 *
 * @author fancyydk
 */
public class EdgarIndex {
    public static final int FIRST_QUARTER = 1;
    public static final int LAST_QUARTER = 4;

    private int startYear;
    private int startQuarter;
    private int endYear;
    private int endQuarter;

    public EdgarIndex() {
    }
    public EdgarIndex(int startYear, int startQuarter, int endYear, int endQuarter) {
        this.startYear = startYear;
        this.startQuarter = startQuarter;
        this.endYear = endYear;
        this.endQuarter = endQuarter;
    }

    public void setStartYear(int startYear) {
        this.startYear = startYear;
    }
    public void setStartYear(String startYear) {
        setStartYear(Integer.parseInt(startYear));
    }
    public int getStartYear() {
        return startYear;
    }

    public void setStartQuarter(int startQuarter) {
        this.startQuarter = startQuarter;
    }
    public void setStartQuarter(String startQuarter) {
        setStartQuarter(Integer.parseInt(startQuarter));
    }
    public int getStartQuarter() {
        return startQuarter;
    }

    public void setEndYear(int endYear) {
        this.endYear = endYear;
    }
    public void setEndYear(String endYear) {
        setEndYear(Integer.parseInt(endYear));
    }
    public int getEndYear() {
        return endYear;
    }

    public void setEndQuarter(int endQuarter) {
        this.endQuarter = endQuarter;
    }
    public void setEndQuarter(String endQuarter) {
        setEndQuarter(Integer.parseInt(endQuarter));
    }
    public int getEndQuarter() {
        return endQuarter;
    }

    public void setAll(int startYear, int startQuarter, int endYear, int endQuarter) {
        setStartYear(startYear);
        setStartQuarter(startQuarter);
        setEndYear(endYear);
        setEndQuarter(endQuarter);
    }
    public void setAll(String startYear, String startQuarter, String endYear, String endQuarter) {
        setAll(Integer.parseInt(startYear), Integer.parseInt(startQuarter), Integer.parseInt(endYear), Integer.parseInt(endQuarter));
    }

    public boolean isValidIndex() {
        if (startYear < 0 || startYear > endYear) {
            return false;
        }
        if (endYear < 0 || endYear < startYear) {
            return false;
        }
        if (startQuarter < 1 || startQuarter > 4) {
            return false;
        }
        if (endQuarter < 1 || endQuarter > 4) {
            return false;
        }

        return true;
    }

    public String toString() {
        return startYear + "," + startQuarter + " - " + endYear + "," + endQuarter;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _04.DeserializeString
{
    class DeserializeString
    {
        static void Main()
        {
            SortedDictionary<int, char> wordChars = new SortedDictionary<int, char>();
            string input = Console.ReadLine();
            while (input != "end")
            {
                string[] tokens = input.Split(':');
                char @char = tokens[0].First();
                int[] indexes = tokens[1].Split('/').Select(n => int.Parse(n)).ToArray();
                foreach (var i in indexes)
                {
                    wordChars.Add(i, @char);
                }
                input = Console.ReadLine();
            }
            Console.WriteLine(wordChars.Values.ToArray());
        }
    }
}


text:
<?php

namespace Geocoder\Provider;

use Geocoder\HttpAdapter\HttpAdapterInterface;
use Geocoder\Exception\UnsupportedException;
use Geocoder\Exception\NoResultException;

/**
 * @author Antoine Corcy <contact@sbin.dk>
 */
class YandexProvider extends AbstractProvider implements LocaleAwareProviderInterface
{
    /**
     * @var string
     */
    const GEOCODE_ENDPOINT_URL = 'http://geocode-maps.yandex.ru/1.x/?format=json&geocode=%s';

    /**
     * @var string
     */
    const REVERSE_ENDPOINT_URL = 'http://geocode-maps.yandex.ru/1.x/?format=json&geocode=%F,%F';

    /**
     * @var string
     */
    private $toponym = null;

    /**
     * @param HttpAdapterInterface $adapter An HTTP adapter.
     * @param string               $locale  A locale (optional).
     * @param string               $toponym Toponym biasing only for reverse geocoding (optional).
     */
    public function __construct(HttpAdapterInterface $adapter, $locale = null, $toponym = null)
    {
        parent::__construct($adapter, $locale);

        $this->toponym = $toponym;
    }

    /**
     * {@inheritDoc}
     */
    public function getGeocodedData($address)
    {
        // This API doesn't handle IPs
        if (filter_var($address, FILTER_VALIDATE_IP)) {
            throw new UnsupportedException('The YandexProvider does not support IP addresses.');
        }

        $query = sprintf(self::GEOCODE_ENDPOINT_URL, urlencode($address));

        return $this->executeQuery($query);
    }

    /**
     * {@inheritDoc}
     */
    public function getReversedData(array $coordinates)
    {
        $query = sprintf(self::REVERSE_ENDPOINT_URL, $coordinates[1], $coordinates[0]);

        if (null !== $this->toponym) {
            $query = sprintf('%s&kind=%s', $query, $this->toponym);
        }

        return $this->executeQuery($query);
    }

    /**
     * {@inheritDoc}
     */
    public function getName()
    {
        return 'yandex';
    }

    /**
     * @param string $query
     *
     * @return array
     */
    protected function executeQuery($query)
    {
        if (null !== $this->getLocale()) {
            $query = sprintf('%s&lang=%s', $query, str_replace('_', '-', $this->getLocale()));
        }

        $query = sprintf('%s&results=%d', $query, $this->getMaxResults());

        $content = $this->getAdapter()->getContent($query);
        $json    = (array) json_decode($content, true);

        if (empty($json) || '0' === $json['response']['GeoObjectCollection']['metaDataProperty']['GeocoderResponseMetaData']['found']) {
            throw new NoResultException(sprintf('Could not execute query %s', $query));
        }

        $data = $json['response']['GeoObjectCollection']['featureMember'];

        $results = array();

        foreach ($data as $item) {
            $item           = $item['GeoObject'];
            $country        = $item['metaDataProperty']['GeocoderMetaData']['AddressDetails']['Country'];
            $addressDetails = isset($country['AdministrativeArea']) ? $country['AdministrativeArea'] : $country;
            $locality       = isset($addressDetails['Locality']['Thoroughfare']) ? $addressDetails['Locality']['Thoroughfare'] : null;
            $coordinates    = explode(' ', $item['Point']['pos']);
            $bounds         = null;
            $lowerCorner    = explode(' ', $item['boundedBy']['Envelope']['lowerCorner']);
            $upperCorner    = explode(' ', $item['boundedBy']['Envelope']['upperCorner']);
            $bounds         = array(
                'south' => isset($lowerCorner[1]) ? $lowerCorner[1] : null,
                'west'  => isset($lowerCorner[0]) ? $lowerCorner[0] : null,
                'north' => isset($upperCorner[1]) ? $upperCorner[1] : null,
                'east'  => isset($upperCorner[0]) ? $upperCorner[0] : null
            );

            $results[] = array_merge($this->getDefaults(), array(
                'latitude'      => isset($coordinates[1]) ? $coordinates[1] : null,
                'longitude'     => isset($coordinates[0]) ? $coordinates[0] : null,
                'bounds'        => $bounds,
                'streetNumber'  => isset($locality['Premise']['PremiseNumber']) ? $locality['Premise']['PremiseNumber'] : null,
                'streetName'    => isset($locality['ThoroughfareName']) ? $locality['ThoroughfareName'] : null,
                'cityDistrict'  => isset($addressDetails['AdministrativeAreaName']) ? $addressDetails['AdministrativeAreaName'] : null,
                'country'       => isset($country['CountryName']) ? $country['CountryName'] : null,
                'countryCode'   => isset($country['CountryNameCode']) ? $country['CountryNameCode'] : null,
            ));
        }

        return $results;
    }
}


text:
<?php

?>
<?php include '../../common/view/header.admin.html.php';?>
<?php
$path = explode(',', $node->path);
js::set('path', json_encode($path));
?>

     <?php echo $book->title;?>

      <?php echo html::a($this->inlink('create'), ' ' . $lang->book->createBook, "class='btn btn-primary'");?>

<?php echo $catalog;?>

<?php include '../../common/view/footer.html.php';?>


text:
import Todos from 'components/todos.vue';
import About from 'components/about.vue';

const routes = [
	{
		path: '/todo/:status?',
		name: 'todos',
		component: Todos,
		props: true,
		alias: ['/']
	},{
		path: '/about',
		name: 'about',
		component: About
	}
];

export default routes;


text:
class ServicesController < ApplicationController
  before_action :set_service, only: [:edit, :update]
  after_action :verify_authorized

  def index
    @services = Service.includes(:service_category)
    authorize @services
  end

  def edit
    authorize @service
  end

  def update
    authorize @service
    if @service.update(service_params)
      redirect_to service_categories_url
    else
      render :index
    end
  end

  private

  def set_service
    @service = Service.find(secure_id)
  end

  def secure_id
    params[:id].to_i
  end

  def service_params
    params.require(:service).permit(:id, :name)
  end
end


text:
/**
 *
  Package: MAG - VistA Imaging
  WARNING: Per VHA Directive 2004-038, this routine should not be modified.
  Date Created: Nov, 2009
  Site Name:  Washington OI Field Office, Silver Spring, MD
  Developer:  vhaiswlouthj
  Description: DICOM Study cache manager. Maintains the cache of study instances
  			   and expires old studies after 15 minutes.

        ;; +--------------------------------------------------------------------+
        ;; Property of the US Government.
        ;; No permission to copy or redistribute this software is given.
        ;; Use of unreleased versions of this software requires the user
        ;;  to execute a written test agreement with the VistA Imaging
        ;;  Development Office of the Department of Veterans Affairs,
        ;;  telephone (301) 734-0100.
        ;;
        ;; The Food and Drug Administration classifies this software as
        ;; a Class II medical device.  As such, it may not be changed
        ;; in any way.  Modifications to this software may result in an
        ;; adulterated medical device under 21CFR820, the use of which
        ;; is considered to be a violation of US Federal Statutes.
        ;; +--------------------------------------------------------------------+

 */
package gov.va.med.imaging.vistaimagingdatasource.dicom.storage;

import gov.va.med.imaging.artifactsource.ResolvedArtifactSource;
import gov.va.med.imaging.core.interfaces.exceptions.ConnectionException;
import gov.va.med.imaging.core.interfaces.exceptions.MethodException;
import gov.va.med.imaging.core.interfaces.exceptions.ParentREFDeletedMethodException;
import gov.va.med.imaging.datasource.AbstractVersionableDataSource;
import gov.va.med.imaging.datasource.DicomStorageDataSourceSpi;
import gov.va.med.imaging.datasource.exceptions.InvalidCredentialsException;
import gov.va.med.imaging.exchange.business.ResolvedSite;
import gov.va.med.imaging.exchange.business.Site;
import gov.va.med.imaging.exchange.business.dicom.DGWEmailInfo;
import gov.va.med.imaging.exchange.business.dicom.DicomCorrectInfo;
import gov.va.med.imaging.exchange.business.dicom.DicomUid;
import gov.va.med.imaging.exchange.business.dicom.InstanceFile;
import gov.va.med.imaging.exchange.business.dicom.InstrumentConfig;
import gov.va.med.imaging.exchange.business.dicom.ModalityConfig;
import gov.va.med.imaging.exchange.business.dicom.PatientRef;
import gov.va.med.imaging.exchange.business.dicom.PatientStudyInfo;
import gov.va.med.imaging.exchange.business.dicom.PatientStudyLookupResults;
import gov.va.med.imaging.exchange.business.dicom.ProcedureRef;
import gov.va.med.imaging.exchange.business.dicom.SOPInstance;
import gov.va.med.imaging.exchange.business.dicom.Series;
import gov.va.med.imaging.exchange.business.dicom.Study;
import gov.va.med.imaging.exchange.business.dicom.UIDActionConfig;
import gov.va.med.imaging.exchange.business.dicom.UIDCheckInfo;
import gov.va.med.imaging.exchange.business.dicom.UIDCheckResult;
import gov.va.med.imaging.exchange.business.dicom.rdsr.Dose;
import gov.va.med.imaging.exchange.enums.ImagingSecurityContextType;
import gov.va.med.imaging.protocol.vista.VistaImagingDicomTranslator;
import gov.va.med.imaging.transactioncontext.TransactionContextFactory;
import gov.va.med.imaging.url.vista.StringUtils;
import gov.va.med.imaging.url.vista.VistaQuery;
import gov.va.med.imaging.url.vista.exceptions.InvalidVistaCredentialsException;
import gov.va.med.imaging.url.vista.exceptions.VistaMethodException;
import gov.va.med.imaging.vistadatasource.session.VistaSession;
import gov.va.med.imaging.vistaimagingdatasource.VistaImagingDicomQueryFactory;
import gov.va.med.imaging.vistaimagingdatasource.common.VistaSessionFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

/**
 * An implementation of a DicomStorageDataSourceSpi that talks to VistA.
 *
 * NOTE: 1.) public methods that do Vista access (particularly anything defined
 * in the DicomDataSourceSpi interface) must acquire a VistaSession instance
 * using getVistaSession(). 2.) private methods which are only called from
 * public methods that do Vista access must include a VistaSession parameter,
 * they should not acquire their own VistaSession 3.) Where a method is both
 * public and called from within this class, there should be a public version
 * following rule 1, calling a private version following rule 2.
 *
 * @author vhaiswlouthj
 *
 */
public class VistaImagingDicomStorageDataSourceService
extends AbstractVersionableDataSource
implements DicomStorageDataSourceSpi, VistaSessionFactory
{
	// The required version of VistA Imaging needed to execute the RPC calls for
	// this operation

	// TODO CHANGE TO 3.0P34
	public final static String MAG_REQUIRED_VERSION = "3.0P83";
	public final static int DEFAULT_PATIENT_SENSITIVITY_LEVEL = 2;
	public final static String SUPPORTED_PROTOCOL = "vistaimaging";

	/*
	 * =====================================================================
	 * Instance fields and methods
	 * =====================================================================
	 */
	private Logger logger = Logger.getLogger(this.getClass());

	/**
	 * @param resolvedArtifactSource
	 * @param protocol
	 */
	public VistaImagingDicomStorageDataSourceService(ResolvedArtifactSource resolvedArtifactSource, String protocol)
	{
		super(resolvedArtifactSource, protocol);
	}

	// to support local data source
	public VistaImagingDicomStorageDataSourceService(ResolvedArtifactSource resolvedArtifactSource)
	{
		super(resolvedArtifactSource, SUPPORTED_PROTOCOL);
	}

	/**
	 * The artifact source must be checked in the constructor to assure that it is an instance
	 * of ResolvedSite.
	 *
	 * @return
	 */
	protected ResolvedSite getResolvedSite()
	{
		return (ResolvedSite)getResolvedArtifactSource();
	}

	protected Site getSite()
	{
		return getResolvedSite().getSite();
	}

	/* (non-Javadoc)
	 * @see gov.va.med.imaging.vistaimagingdatasource.dicom.storage.SessionFactory#getVistaSession()
	 */
	public VistaSession getVistaSession() throws IOException, ConnectionException, MethodException
	{
		TransactionContextFactory.get().setImagingSecurityContextType(ImagingSecurityContextType.DICOM_QR_CONTEXT.name());
		return VistaSession.getOrCreate(getMetadataUrl(), getSite());
	}

	public List<InstrumentConfig> getDgwInstrumentList(String hostName) throws MethodException, ConnectionException
	{
		logger.info("Executing getDgwInstrumentList in the VistA implementation of the DicomStorageDataSourceSpi");
		VistaSession session = null;
		List<InstrumentConfig> instruments = new ArrayList<InstrumentConfig>();

		try
		{
			session = getVistaSession();

			VistaQuery vm = VistaImagingDicomQueryFactory.createGetDgwInstrumentListQuery(hostName);
			String returnValue = getVistaSession().call(vm);
			logger.info(vm.getRpcName()+" RPC: "+StringUtils.displayEncodedChars(returnValue));
			instruments = VistaImagingDicomTranslator.translateInstrumentList(returnValue);
		}
		catch (IOException e)
        {
			throw new ConnectionException(e);
        }
    	catch (VistaMethodException e)
        {
    		throw new MethodException(e.getMessage());
        }
    	catch (InvalidVistaCredentialsException e)
        {
    		throw new InvalidCredentialsException(e.getMessage());
        }
		finally
		{
			try{session.close();}
			catch(Throwable t){}
		}

		return instruments;

	}

	public List<ModalityConfig> getDgwModalityList(String hostName) throws MethodException, ConnectionException
	{
		logger.info("Executing getDgwModalityList in the VistA implementation of the DicomStorageDataSourceSpi");
		VistaSession session = null;
		List<ModalityConfig> modalities = new ArrayList<ModalityConfig>();

		try
		{
			session = getVistaSession();

			VistaQuery vm = VistaImagingDicomQueryFactory.createGetDgwModalityListQuery(hostName);
			String returnValue = session.call(vm);
			logger.info(vm.getRpcName()+" RPC: "+StringUtils.displayEncodedChars(returnValue));
			modalities = VistaImagingDicomTranslator.translateModalityList(returnValue);
		}
		catch (IOException e)
        {
			throw new ConnectionException(e);
        }
    	catch (VistaMethodException e)
        {
    		throw new MethodException(e.getMessage());
        }
    	catch (InvalidVistaCredentialsException e)
        {
    		throw new InvalidCredentialsException(e.getMessage());
        }
		finally
		{
			try{session.close();}
			catch(Throwable t){}
		}

		return modalities;

	}

	public DGWEmailInfo getDgwEmailInfo(String hostName) throws MethodException, ConnectionException
	{
		logger.info("Executing getDgwEmailInfo in the VistA implementation of the DicomStorageDataSourceSpi");
		VistaSession session = null;
		DGWEmailInfo dgwEMI=null;

		try
		{
			session = getVistaSession();

			VistaQuery vm = VistaImagingDicomQueryFactory.createGetDGWEmailInfo(hostName);
			String returnValue = session.call(vm);
			logger.info(vm.getRpcName()+" RPC: "+StringUtils.displayEncodedChars(returnValue));
			dgwEMI = VistaImagingDicomTranslator.translateDGWEmailInfo(returnValue);
		}
		catch (IOException e)
        {
			throw new ConnectionException(e);
        }
    	catch (VistaMethodException e)
        {
    		throw new MethodException(e.getMessage());
        }
    	catch (InvalidVistaCredentialsException e)
        {
    		throw new InvalidCredentialsException(e.getMessage());
        }
		finally
		{
			try{session.close();}
			catch(Throwable t){}
		}

		return dgwEMI;

	}

	public List<UIDActionConfig> getDgwUIDActionTable(String type, String subType, String action) throws MethodException, ConnectionException
	{

		logger.info("Executing getDgwUIDActionTable in the VistA implementation of the DicomStorageDataSourceSpi");
		VistaSession session = null;
		List<UIDActionConfig> uidActions = new ArrayList<UIDActionConfig>();

		try
		{
			session = getVistaSession();

			VistaQuery vm = VistaImagingDicomQueryFactory.createGetDgwUIDActionTableQuery(type, subType, action);
			String returnValue = session.call(vm);
			logger.info(vm.getRpcName()+" RPC: "+StringUtils.displayEncodedChars(returnValue));
			uidActions = VistaImagingDicomTranslator.translateUIDActions(returnValue);
		}
		catch (IOException e)
        {
			throw new ConnectionException(e);
        }
    	catch (VistaMethodException e)
        {
    		throw new MethodException(e.getMessage());
        }
    	catch (InvalidVistaCredentialsException e)
        {
    		throw new InvalidCredentialsException(e.getMessage());
        }
		finally
		{
			try{session.close();}
			catch(Throwable t){}
		}

		return uidActions;

	}

	public PatientStudyLookupResults getPatientStudyLookupResults(PatientStudyInfo patientStudyInfo) throws MethodException, ConnectionException
	{
		PatientStudyLookupResultsDAO dao = new PatientStudyLookupResultsDAO(this);
		return dao.getEntityByCriteria(patientStudyInfo);
	}

	@Override
	public UIDCheckResult getStudyUIDCheckResult(UIDCheckInfo uidCheckInfo) throws MethodException, ConnectionException
	{
		StudyUIDCheckResultDAO retriever = new StudyUIDCheckResultDAO(this);
		return retriever.getEntityByCriteria(uidCheckInfo);
	}

	@Override
	public UIDCheckResult getSeriesUIDCheckResult(UIDCheckInfo uidCheckInfo) throws MethodException, ConnectionException
	{
		SeriesUIDCheckResultDAO retriever = new SeriesUIDCheckResultDAO(this);
		return retriever.getEntityByCriteria(uidCheckInfo);
	}

	@Override
	public UIDCheckResult getSOPInstanceUIDCheckResult(UIDCheckInfo uidCheckInfo) throws MethodException, ConnectionException
	{
		SOPInstanceUIDCheckResultDAO retriever = new SOPInstanceUIDCheckResultDAO(this);
		return retriever.getEntityByCriteria(uidCheckInfo);
	}

	@Override
	public PatientRef getOrCreatePatientRef(PatientRef patientRef) throws MethodException, ConnectionException
	{
		PatientRefDAO dao = new PatientRefDAO(this);
		PatientRef persistentRef = dao.getEntityByExample(patientRef);

		if (persistentRef == null)
		{
			persistentRef = dao.create(patientRef);
		}
		return persistentRef;
	}

	@Override
	public ProcedureRef getOrCreateProcedureRef(PatientRef patientRef, ProcedureRef procedureRef) throws MethodException, ConnectionException
	{
		ProcedureRefDAO dao = new ProcedureRefDAO(this);
		// Set foreign key to patientRef
		logger.debug(this.getClass().getName()+":Set Patient REF IEN.");
		procedureRef.setPatientRefIEN(patientRef.getIEN());
		logger.debug(this.getClass().getName()+": Get Procedure REF if exist.");
		ProcedureRef persistentRef = dao.getEntityByExample(procedureRef);

		if (persistentRef == null)
		{
			// store the procedureRef
			logger.debug(this.getClass().getName()+": Create Procedure REF.");
			persistentRef = dao.create(procedureRef);
		}
		return persistentRef;
	}

	@Override
	public Study getOrCreateStudy(PatientRef patientRef, ProcedureRef procedureRef, Study study)
						throws MethodException, ConnectionException
	{
		StudyDAO dao = new StudyDAO(this);
		// Set foreign key to patientRef and procedure Ref
		study.setPatientRefIEN(patientRef.getIEN());
		study.setProcedureRefIEN(procedureRef.getIEN());
		Study persistentRef = dao.getEntityByExample(study);

		if (persistentRef == null)
		{
			// store the study
			persistentRef = dao.create(study);
		}
		return persistentRef;
	}

	@Override
	public Series getOrCreateSeries(Study study, Series series, Integer iodValidationStatus)
						throws MethodException, ConnectionException, ParentREFDeletedMethodException
	{
		SeriesDAO dao = new SeriesDAO(this);
		// Set foreign key to study,
		series.setStudyIEN(study.getIEN());
		Series persistentRef = dao.getEntityByExample(series);
		if(persistentRef != null){
			if(!persistentRef.getStudyIEN().equals(series.getStudyIEN())){
				persistentRef = null;
			}
		}
		if (persistentRef == null)
		{
			// Persist the series
			persistentRef = dao.create(series);
		} else {
			if (Integer.decode(persistentRef.getIODViolationDetected())<iodValidationStatus.intValue()) { // register worse status only 0 -> 3
				persistentRef.setIODViolationDetected(iodValidationStatus.toString());
				dao.update(persistentRef);
			}
		}
		return persistentRef;
	}

	@Override
	public SOPInstance createSOPInstance(Series series, SOPInstance sopInstance)
						throws MethodException, ConnectionException, ParentREFDeletedMethodException
	{
		// Set foreign key to study, then persist the series
		sopInstance.setSeriesIEN(series.getIEN());
		SOPInstanceDAO dao = new SOPInstanceDAO(this);
		sopInstance = dao.create(sopInstance);
		return sopInstance;
	}

	@Override
	public InstanceFile createInstanceFile(SOPInstance sopInstance, InstanceFile instanceFile) throws MethodException, ConnectionException
	{
		// Set foreign key to study, then persist the series
		instanceFile.setSOPInstanceIEN(sopInstance.getIEN());
		InstanceFileDAO dao = new InstanceFileDAO(this);
		instanceFile = dao.create(instanceFile);
		return instanceFile;
	}

	@Override
	public Series getTIUPointer(Series series) throws MethodException, ConnectionException
	{
		TIUPointerDAO dao = new TIUPointerDAO(this);
		return dao.getEntityByExample(series);
	}

	public Integer getDicomCorrectCount(DicomCorrectInfo dicomCorrectInfo) throws MethodException, ConnectionException
	{
		DicomCorrectInfoDAO dao = new DicomCorrectInfoDAO(this);
		return dao.getDicomCorrectCount(dicomCorrectInfo);
	}

	/*
	 * (non-Javadoc)
	 * @see gov.va.med.imaging.datasource.DicomStorageDataSourceSpi#deleteStudyAndSeriesCache()
	 */
	public Boolean deleteStudyAndSeriesCache() throws MethodException{

		StudyDAO studydao = new StudyDAO(this);
		studydao.purgeStudyCache();

		SeriesDAO seriesdao = new SeriesDAO(this);
		seriesdao.purgeSeriesCache();

		return true;
	}

	@Override
	public boolean isVersionCompatible()
	{
		// TODO - Remove comments when able...
		return true;
	}

	@Override
	public Dose createRadiationDose(PatientRef patient, ProcedureRef procedure, Study study, Series series, Dose dose)
			throws MethodException,ConnectionException
	{
		RadiationDosageDAO dao = new RadiationDosageDAO(this);
		return dao.createDoseRecord(patient, procedure, study, series, dose);
	}

	@Override
	public List<Dose> getRadiationDoseDetails(String patientDfn, String accessionNumber) throws MethodException, ConnectionException
	{
		RadiationDosageDAO dao = new RadiationDosageDAO(this);
		return dao.getRadiationDoseDetails(patientDfn, accessionNumber);
	}

	/* (non-Javadoc)
	 * @see gov.va.med.imaging.datasource.DicomStorageDataSourceSpi#getDicomUid(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public DicomUid getDicomUid(String accessionNumber, String siteId, String instrument, String type)
	throws MethodException, ConnectionException
	{
		DicomUidDAO dao = new DicomUidDAO(this);
		return dao.createNewDicomUid(accessionNumber, siteId, instrument, type);
	}

}