text:
package org.wso2.carbon.device.mgt.core.operation.mgt;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.InvalidDeviceException;
import org.wso2.carbon.device.mgt.common.MonitoringOperation;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.TransactionManagementException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.common.operation.mgt.ActivityStatus;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager;
import org.wso2.carbon.device.mgt.common.push.notification.NotificationContext;
import org.wso2.carbon.device.mgt.common.push.notification.NotificationStrategy;
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationExecutionFailedException;
import org.wso2.carbon.device.mgt.core.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.dao.DeviceDAO;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.EnrollmentDAO;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationDAO;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationMappingDAO;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.util.OperationDAOUtil;
import org.wso2.carbon.device.mgt.core.operation.mgt.util.DeviceIDHolder;
import org.wso2.carbon.device.mgt.core.operation.mgt.util.OperationCreateTimeComparator;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.task.DeviceTaskManager;
import org.wso2.carbon.device.mgt.core.task.impl.DeviceTaskManagerImpl;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * This class implements all the functionality exposed as part of the OperationManager. Any transaction initiated
 * upon persisting information related to operation state, etc has to be managed, demarcated and terminated via the
 * methods available in OperationManagementDAOFactory.
 */
public class OperationManagerImpl implements OperationManager {

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

    private OperationDAO commandOperationDAO;
    private OperationDAO configOperationDAO;
    private OperationDAO profileOperationDAO;
    private OperationDAO policyOperationDAO;
    private OperationMappingDAO operationMappingDAO;
    private OperationDAO operationDAO;
    private DeviceDAO deviceDAO;
    private EnrollmentDAO enrollmentDAO;
    private NotificationStrategy notificationStrategy;
    private String deviceType;

    public OperationManagerImpl() {
        commandOperationDAO = OperationManagementDAOFactory.getCommandOperationDAO();
        configOperationDAO = OperationManagementDAOFactory.getConfigOperationDAO();
        profileOperationDAO = OperationManagementDAOFactory.getProfileOperationDAO();
        policyOperationDAO = OperationManagementDAOFactory.getPolicyOperationDAO();
        operationMappingDAO = OperationManagementDAOFactory.getOperationMappingDAO();
        operationDAO = OperationManagementDAOFactory.getOperationDAO();
        deviceDAO = DeviceManagementDAOFactory.getDeviceDAO();
        enrollmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO();
    }

    public OperationManagerImpl(String deviceType) {
        this();
        this.deviceType = deviceType;
    }

    public NotificationStrategy getNotificationStrategy() {
        return notificationStrategy;
    }

    public void setNotificationStrategy(NotificationStrategy notificationStrategy) {
        this.notificationStrategy = notificationStrategy;
    }

    public OperationManagerImpl(String deviceType, NotificationStrategy notificationStrategy) {
        this(deviceType);
        this.notificationStrategy = notificationStrategy;
    }

    @Override
    public Activity addOperation(Operation operation,
                                 List<DeviceIdentifier> deviceIds)
            throws OperationManagementException, InvalidDeviceException {
        if (log.isDebugEnabled()) {
            log.debug("operation:[" + operation.toString() + "]");
            for (DeviceIdentifier deviceIdentifier : deviceIds) {
                log.debug("device identifier id:[" + deviceIdentifier.getId() + "] type:[" +
                          deviceIdentifier.getType() + "]");
            }
        }
        try {
            DeviceIDHolder deviceValidationResult = DeviceManagerUtil.validateDeviceIdentifiers(deviceIds);
            List<DeviceIdentifier> validDeviceIds = deviceValidationResult.getValidDeviceIDList();
            if (validDeviceIds.size() > 0) {
                DeviceIDHolder deviceAuthorizationResult = this.authorizeDevices(operation, validDeviceIds);
                List<DeviceIdentifier> authorizedDeviceList = deviceAuthorizationResult.getValidDeviceIDList();
                if (authorizedDeviceList.size() <= 0) {
                    log.warn("User : " + getUser() + " is not authorized to perform operations on given device-list.");
                    Activity activity = new Activity();
                    //Send the operation statuses only for admin triggered operations
                    String deviceType = validDeviceIds.get(0).getType();
                    activity.setActivityStatus(this.getActivityStatus(deviceValidationResult, deviceAuthorizationResult,
                                                                      deviceType));
                    return activity;
                }

                OperationManagementDAOFactory.beginTransaction();
                org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation operationDto =
                        OperationDAOUtil.convertOperation(operation);
                int operationId = this.lookupOperationDAO(operation).addOperation(operationDto);
                boolean isScheduledOperation = this.isTaskScheduledOperation(operation, deviceIds);
                boolean isNotRepeated = false;
                boolean isScheduled = false;

                // check whether device list is greater than batch size notification strategy has enable to send push
                // notification using scheduler task
                if (DeviceConfigurationManager.getInstance().getDeviceManagementConfig().
                        getPushNotificationConfiguration().getSchedulerBatchSize() <= authorizedDeviceList.size() &&
                        notificationStrategy != null) {
                    isScheduled = notificationStrategy.getConfig().isScheduled();
                }

                boolean hasExistingTaskOperation;
                int enrolmentId;
                if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Control.NO_REPEAT == operationDto.
                                                                                getControl()) {
                    isNotRepeated = true;
                }

                //TODO have to create a sql to load device details from deviceDAO using single query.
                String operationCode = operationDto.getCode();
                for (DeviceIdentifier deviceId : authorizedDeviceList) {
                    Device device = getDevice(deviceId);
                    enrolmentId = device.getEnrolmentInfo().getId();
                    //Do not repeat the task operations
                    if (isScheduledOperation) {
                        hasExistingTaskOperation = operationDAO.updateTaskOperation(enrolmentId, operationCode);
                        if (!hasExistingTaskOperation) {
                            operationMappingDAO.addOperationMapping(operationId, enrolmentId, isScheduled);
                        }
                    } else if (isNotRepeated) {
                        operationDAO.updateEnrollmentOperationsStatus(enrolmentId, operationCode,
                                                                      org.wso2.carbon.device.mgt.core.dto.operation.mgt.
                                                                              Operation.Status.PENDING,
                                                                      org.wso2.carbon.device.mgt.core.dto.operation.mgt.
                                                                              Operation.Status.REPEATED);
                        operationMappingDAO.addOperationMapping(operationId, enrolmentId, isScheduled);
                    } else {
                        operationMappingDAO.addOperationMapping(operationId, enrolmentId, isScheduled);
                    }
                    /*
                    If notification strategy has not enable to send push notification using scheduler task
                    we will send notification immediately
                    */
                    if (notificationStrategy != null && !isScheduled) {
                        try {
                            if (log.isDebugEnabled()) {
                                log.debug("Sending push notification to " + deviceId + " from add operation method.");
                            }
                            notificationStrategy.execute(new NotificationContext(deviceId, operation));
                            operationMappingDAO.updateOperationMapping(operationId, enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.PushNotificationStatus.COMPLETED);
                        } catch (PushNotificationExecutionFailedException e) {
                            log.error("Error occurred while sending push notifications to " +
                                      deviceId.getType() + " device carrying id '" +
                                      deviceId + "'", e);
                            // Reschedule if push notification failed.
                            operationMappingDAO.updateOperationMapping(operationId, enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.PushNotificationStatus.SCHEDULED);
                        }
                    }
                }

                OperationManagementDAOFactory.commitTransaction();
                Activity activity = new Activity();
                activity.setActivityId(DeviceManagementConstants.OperationAttributes.ACTIVITY + operationId);
                activity.setCode(operationCode);
                activity.setCreatedTimeStamp(new Date().toString());
                activity.setType(Activity.Type.valueOf(operationDto.getType().toString()));
                //For now set the operation statuses only for admin triggered operations
                if (!isScheduledOperation) {
                    //Get the device-type from 1st valid DeviceIdentifier. We know the 1st element is definitely there.
                    String deviceType = validDeviceIds.get(0).getType();
                    activity.setActivityStatus(this.getActivityStatus(deviceValidationResult, deviceAuthorizationResult,
                                                                      deviceType));
                }
                return activity;
            } else {
                throw new InvalidDeviceException("Invalid device Identifiers found.");
            }
        } catch (OperationManagementDAOException e) {
            OperationManagementDAOFactory.rollbackTransaction();
            throw new OperationManagementException("Error occurred while adding operation", e);
        } catch (TransactionManagementException e) {
            throw new OperationManagementException("Error occurred while initiating the transaction", e);
        } finally {
            OperationManagementDAOFactory.closeConnection();
        }
    }

    private List<ActivityStatus> getActivityStatus(DeviceIDHolder deviceIdValidationResult, DeviceIDHolder deviceAuthResult,
                                                   String deviceType) {
        List<ActivityStatus> activityStatuses = new ArrayList<>();
        ActivityStatus activityStatus;
        //Add the invalid DeviceIds
        for (String id : deviceIdValidationResult.getErrorDeviceIdList()) {
            activityStatus = new ActivityStatus();
            activityStatus.setDeviceIdentifier(new DeviceIdentifier(id,deviceType));
            activityStatus.setStatus(ActivityStatus.Status.INVALID);
            activityStatuses.add(activityStatus);
        }

        //Add the unauthorized DeviceIds
        for (String id : deviceAuthResult.getErrorDeviceIdList()) {
            activityStatus = new ActivityStatus();
            activityStatus.setDeviceIdentifier(new DeviceIdentifier(id, deviceType));
            activityStatus.setStatus(ActivityStatus.Status.UNAUTHORIZED);
            activityStatuses.add(activityStatus);
        }

        //Add the authorized DeviceIds
        for (DeviceIdentifier id : deviceAuthResult.getValidDeviceIDList()) {
            activityStatus = new ActivityStatus();
            activityStatus.setDeviceIdentifier(id);
            activityStatus.setStatus(ActivityStatus.Status.PENDING);
            activityStatuses.add(activityStatus);
        }
        return activityStatuses;
    }

    private DeviceIDHolder authorizeDevices(
            Operation operation, List<DeviceIdentifier> deviceIds) throws OperationManagementException {
        List<DeviceIdentifier> authorizedDeviceList;
        List<String> unAuthorizedDeviceList = new ArrayList<>();
        DeviceIDHolder deviceIDHolder = new DeviceIDHolder();
        try {
            if (operation != null && isAuthenticationSkippedOperation(operation)) {
                authorizedDeviceList = deviceIds;
            } else {
                boolean isAuthorized;
                authorizedDeviceList = new ArrayList<>();
                for (DeviceIdentifier devId : deviceIds) {
                    isAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService().
                            isUserAuthorized(devId);
                    if (isAuthorized) {
                        authorizedDeviceList.add(devId);
                    } else {
                        unAuthorizedDeviceList.add(devId.getId());
                    }
                }
            }
        } catch (DeviceAccessAuthorizationException e) {
            throw new OperationManagementException("Error occurred while authorizing access to the devices for user :" +
                                                   this.getUser(), e);
        }
        deviceIDHolder.setValidDeviceIDList(authorizedDeviceList);
        deviceIDHolder.setErrorDeviceIdList(unAuthorizedDeviceList);
        return deviceIDHolder;
    }

    private Device getDevice(DeviceIdentifier deviceId) throws OperationManagementException {
        try {
            return DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceId, false);
        } catch (DeviceManagementException e) {
            throw new OperationManagementException(
                    "Error occurred while retrieving device info.", e);
        }
    }

    @Override
    public List<? extends Operation> getOperations(DeviceIdentifier deviceId) throws OperationManagementException {
        List<Operation> operations = null;

        if (!isActionAuthorized(deviceId)) {
            throw new OperationManagementException("User '" + getUser() + "' is not authorized to access the '" +
                                                   deviceId.getType() + "' device, which carries the identifier '" +
                                                   deviceId.getId() + "'");
        }

        EnrolmentInfo enrolmentInfo = this.getActiveEnrolmentInfo(deviceId);
        if (enrolmentInfo == null) {
            return null;
        }

        try {
            OperationManagementDAOFactory.openConnection();
            List<? extends org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation> operationList =
                    operationDAO.getOperationsForDevice(enrolmentInfo.getId());

            operations = new ArrayList<>();
            for (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation : operationList) {
                Operation operation = OperationDAOUtil.convertOperation(dtoOperation);
                operations.add(operation);
            }
        } catch (OperationManagementDAOException e) {
            throw new OperationManagementException("Error occurred while retrieving the list of " +
                                                   "operations assigned for '" + deviceId.getType() +
                                                   "' device '" + deviceId.getId() + "'", e);
        } catch (SQLException e) {
            throw new OperationManagementException(
                    "Error occurred while opening a connection to the data source", e);
        } finally {
            OperationManagementDAOFactory.closeConnection();
        }
        return operations;
    }

    @Override
    public PaginationResult getOperations(DeviceIdentifier deviceId, PaginationRequest request)
            throws OperationManagementException {
        PaginationResult paginationResult = null;
        List<Operation> operations = new ArrayList<>();
        String owner = request.getOwner();
        if (!isActionAuthorized(deviceId)) {
            throw new OperationManagementException("User '" + getUser() + "' is not authorized to access the '" +
                                                   deviceId.getType() + "' device, which carries the identifier '" +
                                                   deviceId.getId() + "' of owner '" + owner + "'" );
        }

        EnrolmentInfo enrolmentInfo = this.getEnrolmentInfo(deviceId, owner);
        if (enrolmentInfo == null) {
            throw new OperationManagementException("Device not found for given device " +
                                                   "Identifier:" + deviceId.getId() + " and given type" +
                                                   deviceId.getType());
        }
        int enrolmentId = enrolmentInfo.getId();
        try {
            OperationManagementDAOFactory.openConnection();
            List<? extends org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation> operationList =
                    operationDAO.getOperationsForDevice(enrolmentId, request);
            for (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation : operationList) {
                Operation operation = OperationDAOUtil.convertOperation(dtoOperation);
                operations.add(operation);
            }
            paginationResult = new PaginationResult();
            int count = operationDAO.getOperationCountForDevice(enrolmentId);
            paginationResult.setData(operations);
            paginationResult.setRecordsTotal(count);
            paginationResult.setRecordsFiltered(count);
        } catch (OperationManagementDAOException e) {
            throw new OperationManagementException("Error occurred while retrieving the list of " +
                                                   "operations assigned for '" + deviceId.getType() +
                                                   "' device '" + deviceId.getId() + "'", e);
        } catch (SQLException e) {
            throw new OperationManagementException(
                    "Error occurred while opening a connection to the data source", e);
        } finally {
            OperationManagementDAOFactory.closeConnection();
        }

        return paginationResult;
    }

    @Override
    public List<? extends Operation> getPendingOperations(DeviceIdentifier deviceId) throws
                                                                                OperationManagementException {
        if (log.isDebugEnabled()) {
            log.debug("Device identifier id:[" + deviceId.getId() + "] type:[" + deviceId.getType() + "]");
        }
        List<Operation> operations = new ArrayList<>();
        List<org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation> dtoOperationList = new ArrayList<>();

        if (!isActionAuthorized(deviceId)) {
            throw new OperationManagementException("User '" + getUser() + "' is not authorized to access the '" +
                                                   deviceId.getType() + "' device, which carries the identifier '" +
                                                   deviceId.getId() + "'");
        }

        //
        EnrolmentInfo enrolmentInfo = this.getActiveEnrolmentInfo(deviceId);
        if (enrolmentInfo == null) {
            throw new OperationManagementException("Device not found for the given device Identifier:" +
                                                   deviceId.getId() + " and given type:" +
                                                   deviceId.getType());
        }
        int enrolmentId = enrolmentInfo.getId();
        //Changing the enrollment status & attempt count if the device is marked as inactive or unreachable
        switch (enrolmentInfo.getStatus()) {
            case INACTIVE:
            case UNREACHABLE:
                this.setEnrolmentStatus(enrolmentId, EnrolmentInfo.Status.ACTIVE);
                break;
        }

        try {
            OperationManagementDAOFactory.openConnection();
            dtoOperationList.addAll(commandOperationDAO.getOperationsByDeviceAndStatus(
                    enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING));
            dtoOperationList.addAll(configOperationDAO.getOperationsByDeviceAndStatus(
                    enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING));
            dtoOperationList.addAll(profileOperationDAO.getOperationsByDeviceAndStatus(
                    enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING));
            dtoOperationList.addAll(policyOperationDAO.getOperationsByDeviceAndStatus(
                    enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING));
            Operation operation;
            for (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation : dtoOperationList) {
                operation = OperationDAOUtil.convertOperation(dtoOperation);
                operations.add(operation);
            }
            Collections.sort(operations, new OperationCreateTimeComparator());
        } catch (OperationManagementDAOException e) {
            throw new OperationManagementException("Error occurred while retrieving the list of " +
                                                   "pending operations assigned for '" + deviceId.getType() +
                                                   "' device '" + deviceId.getId() + "'", e);
        } catch (SQLException e) {
            throw new OperationManagementException(
                    "Error occurred while opening a connection to the data source", e);
        } finally {
            OperationManagementDAOFactory.closeConnection();
        }
        return operations;
    }

    @Override
    public Operation getNextPendingOperation(DeviceIdentifier deviceId) throws OperationManagementException {
        if (log.isDebugEnabled()) {
            log.debug("device identifier id:[" + deviceId.getId() + "] type:[" + deviceId.getType() + "]");
        }
        Operation operation = null;

        if (!isActionAuthorized(deviceId)) {
            throw new OperationManagementException("User '" + getUser() + "' is not authorized to access the '" +
                                                   deviceId.getType() + "' device, which carries the identifier '" +
                                                   deviceId.getId() + "'");
        }

        EnrolmentInfo enrolmentInfo = this.getActiveEnrolmentInfo(deviceId);
        if (enrolmentInfo == null) {
            throw new OperationManagementException("Device not found for given device " +
                                                   "Identifier:" + deviceId.getId() + " and given type" +
                                                   deviceId.getType());
        }
        int enrolmentId = enrolmentInfo.getId();
        //Changing the enrollment status & attempt count if the device is marked as inactive or unreachable
        switch (enrolmentInfo.getStatus()) {
            case INACTIVE:
            case UNREACHABLE:
                this.setEnrolmentStatus(enrolmentId, EnrolmentInfo.Status.ACTIVE);
                break;
        }

        try {
            OperationManagementDAOFactory.openConnection();
            org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = operationDAO.getNextOperation(
                                                                                enrolmentInfo.getId());
            if (dtoOperation != null) {
                if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND.equals(dtoOperation.getType()
                )) {
                    org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation;
                    commandOperation =
                            (org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO.
                                                                                getOperation(dtoOperation.getId());
                    dtoOperation.setEnabled(commandOperation.isEnabled());
                } else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG.equals(dtoOperation.
                                                                                getType())) {
                    dtoOperation = configOperationDAO.getOperation(dtoOperation.getId());
                } else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.PROFILE.equals(dtoOperation.
                                                                                getType())) {
                    dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId());
                } else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.POLICY.equals(dtoOperation.
                                                                                getType())) {
                    dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId());
                }
                operation = OperationDAOUtil.convertOperation(dtoOperation);
            }
        } catch (OperationManagementDAOException e) {
            throw new OperationManagementException("Error occurred while retrieving next pending operation", e);
        } catch (SQLException e) {
            throw new OperationManagementException(
                    "Error occurred while opening a connection to the data source", e);
        } finally {
            OperationManagementDAOFactory.closeConnection();
        }
        return operation;
    }

    @Override
    public void updateOperation(DeviceIdentifier deviceId, Operation operation) throws OperationManagementException {
        int operationId = operation.getId();
        if (log.isDebugEnabled()) {
            log.debug("operation Id:" + operationId + " status:" + operation.getStatus());
        }

        if (!isActionAuthorized(deviceId)) {
            throw new OperationManagementException("User '" + getUser() + "' is not authorized to access the '" +
                                                   deviceId.getType() + "' device, which carries the identifier '" +
                                                   deviceId.getId() + "'");
        }

        EnrolmentInfo enrolmentInfo = this.getActiveEnrolmentInfo(deviceId);
        if (enrolmentInfo == null) {
            throw new OperationManagementException(
                    "Device not found for device id:" + deviceId.getId() + " " + "type:" +
                    deviceId.getType());
        }

        try {
            int enrolmentId = enrolmentInfo.getId();
            OperationManagementDAOFactory.beginTransaction();
            boolean isUpdated = false;
            if (operation.getStatus() != null) {
                isUpdated = operationDAO.updateOperationStatus(enrolmentId, operationId,
                                                               org.wso2.carbon.device.mgt.core.dto.operation.mgt.
                                                                       Operation.Status.valueOf(operation.getStatus().
                                                                       toString()));
            }
            if (isUpdated && operation.getOperationResponse() != null) {
                operationDAO.addOperationResponse(enrolmentId, operationId, operation.getOperationResponse());
            }
            OperationManagementDAOFactory.commitTransaction();
        } catch (OperationManagementDAOException e) {
            OperationManagementDAOFactory.rollbackTransaction();
            throw new OperationManagementException(
                    "Error occurred while updating the operation: " + operationId + " status:" +
                    operation.getStatus(), e);
        } catch (TransactionManagementException e) {
            throw new OperationManagementException("Error occurred while initiating a transaction", e);
        } finally {
            OperationManagementDAOFactory.closeConnection();
        }
    }

    @Override
    public void deleteOperation(int operationId) throws OperationManagementException {
        try {
            OperationManagementDAOFactory.beginTransaction();
            org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation operation =
                    operationDAO.getOperation(operationId);
            if (operation == null) {
                throw new OperationManagementException("Operation not found for operation id : " + operationId);
            }
            lookupOperationDAO(operation).deleteOperation(operationId);
            OperationManagementDAOFactory.commitTransaction();
        } catch (OperationManagementDAOException e) {
            OperationManagementDAOFactory.rollbackTransaction();
            throw new OperationManagementException("Error occurred while deleting the operation: " + operationId, e);
        } catch (TransactionManagementException e) {
            throw new OperationManagementException("Error occurred while initiating a transaction", e);
        } finally {
            OperationManagementDAOFactory.closeConnection();
        }
    }

    @Override
    public Operation getOperationByDeviceAndOperationId(DeviceIdentifier deviceId, int operationId)
            throws OperationManagementException {
        Operation operation = null;
        if (log.isDebugEnabled()) {
            log.debug("Operation Id: " + operationId + " Device Type: " + deviceId.getType() + " Device Identifier: " +
                      deviceId.getId());
        }

        if (!isActionAuthorized(deviceId)) {
            throw new OperationManagementException("User '" + getUser() + "' is not authorized to access the '" +
                                                   deviceId.getType() + "' device, which carries the identifier '" +
                                                   deviceId.getId() + "'");
        }

        EnrolmentInfo enrolmentInfo = this.getActiveEnrolmentInfo(deviceId);
        if (enrolmentInfo == null) {
            throw new OperationManagementException("Device not found for given device identifier: " +
                                                   deviceId.getId() + " type: " + deviceId.getType());
        }

        try {
            OperationManagementDAOFactory.openConnection();
            org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = operationDAO.
                                                                     getOperationByDeviceAndId(enrolmentInfo.getId(),
                                                                                operationId);
            if (dtoOperation.getType().
                    equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND)) {
                org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation;
                commandOperation =
                        (org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO.
                                                                      getOperation(dtoOperation.getId());
                dtoOperation.setEnabled(commandOperation.isEnabled());
            } else if (dtoOperation.getType().
                    equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG)) {
                dtoOperation = configOperationDAO.getOperation(dtoOperation.getId());
            } else if (dtoOperation.getType().equals(
                    org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.PROFILE)) {
                dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId());
            } else if (dtoOperation.getType().equals(
                    org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.POLICY)) {
                dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId());
            }

            if (dtoOperation == null) {
                throw new OperationManagementException("Operation not found for operation Id:" + operationId +
                                                       " device id:" + deviceId.getId());
            }
            operation = OperationDAOUtil.convertOperation(dtoOperation);
        } catch (OperationManagementDAOException e) {
            throw new OperationManagementException("Error occurred while retrieving the list of " +
                                                   "operations assigned for '" + deviceId.getType() +
                                                   "' device '" + deviceId.getId() + "'", e);
        } catch (SQLException e) {
            throw new OperationManagementException("Error occurred while opening connection to the data source",
                                                   e);
        } finally {
            OperationManagementDAOFactory.closeConnection();
        }

        return operation;
    }

    @Override
    public List<? extends Operation> getOperationsByDeviceAndStatus(
            DeviceIdentifier deviceId, Operation.Status status) throws OperationManagementException {
        List<Operation> operations = new ArrayList<>();
        List<org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation> dtoOperationList = new ArrayList<>();

        if (!isActionAuthorized(deviceId)) {
            throw new OperationManagementException("User '" + getUser() + "' is not authorized to access the '" +
                                                   deviceId.getType() + "' device, which carries the identifier '" +
                                                   deviceId.getId() + "'");
        }

        EnrolmentInfo enrolmentInfo = this.getActiveEnrolmentInfo(deviceId);
        if (enrolmentInfo == null) {
            throw new OperationManagementException(
                    "Device not found for device id:" + deviceId.getId() + " " + "type:" +
                    deviceId.getType());
        }

        try {
            int enrolmentId = enrolmentInfo.getId();
            OperationManagementDAOFactory.openConnection();
            org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status dtoOpStatus =
                    org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.valueOf(status.toString());
            dtoOperationList.addAll(commandOperationDAO.getOperationsByDeviceAndStatus(enrolmentId, dtoOpStatus));
            dtoOperationList.addAll(configOperationDAO.getOperationsByDeviceAndStatus(enrolmentId,
                                                       org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.
                                                               Status.PENDING));
            dtoOperationList.addAll(profileOperationDAO.getOperationsByDeviceAndStatus(enrolmentId,
                                                       org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.
                                                               Status.PENDING));
            dtoOperationList.addAll(policyOperationDAO.getOperationsByDeviceAndStatus(enrolmentId,
                                                       org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.
                                                               Status.PENDING));

            Operation operation;

            for (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation : dtoOperationList) {
                operation = OperationDAOUtil.convertOperation(dtoOperation);
                operations.add(operation);
            }

        } catch (OperationManagementDAOException e) {
            throw new OperationManagementException("Error occurred while retrieving the list of " +
                                                   "operations assigned for '" + deviceId.getType() +
                                                   "' device '" +
                                                   deviceId.getId() + "' and status:" + status.toString(), e);
        } catch (SQLException e) {
            throw new OperationManagementException(
                    "Error occurred while opening a connection to the data source", e);
        } finally {
            OperationManagementDAOFactory.closeConnection();
        }
        return operations;
    }

    @Override
    public Operation getOperation(int operationId) throws OperationManagementException {
        Operation operation;
        try {
            OperationManagementDAOFactory.openConnection();
            org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = operationDAO.getOperation(
                                                                                operationId);
            if (dtoOperation == null) {
                throw new OperationManagementException("Operation not found for given Id:" + operationId);
            }

            if (dtoOperation.getType()
                            .equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND)) {
                org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation;
                commandOperation =
                        (org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO.
                                                                                getOperation(dtoOperation.getId());
                dtoOperation.setEnabled(commandOperation.isEnabled());
            } else if (dtoOperation.getType().
                    equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG)) {
                dtoOperation = configOperationDAO.getOperation(dtoOperation.getId());
            } else if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.
                                                             PROFILE)) {
                dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId());
            } else if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.
                                                             POLICY)) {
                dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId());
            }
            operation = OperationDAOUtil.convertOperation(dtoOperation);
        } catch (OperationManagementDAOException e) {
            throw new OperationManagementException("Error occurred while retrieving the operation with operation Id '" +
                                                   operationId, e);
        } catch (SQLException e) {
            throw new OperationManagementException("Error occurred while opening a connection to the data source", e);
        } finally {
            OperationManagementDAOFactory.closeConnection();
        }
        return operation;
    }

    //    @Override
    //    public Operation getOperationByActivityId(String activity) throws OperationManagementException {
    //        // This parses the operation id from activity id (ex : ACTIVITY_23) and converts to the integer.
    //        Operation operation;
    //        int enrollmentOpMappingId = Integer.parseInt(
    //                activity.replace(DeviceManagementConstants.OperationAttributes.ACTIVITY, ""));
    //        if (enrollmentOpMappingId == 0) {
    //            throw new IllegalArgumentException("Operation ID cannot be null or zero (0).");
    //        }
    //        try {
    //            OperationManagementDAOFactory.openConnection();
    //            org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation =
    //                    operationDAO.getOperationFromEnrollment(enrollmentOpMappingId);
    //
    //            if (dtoOperation == null) {
    //                throw new OperationManagementException("Operation not found for given activity Id:" + activity);
    //            }
    //            org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status status = dtoOperation.getStatus();
    //            if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND)) {
    //                org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation;
    //                commandOperation =
    //                        (org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO.
    //                                getOperation(dtoOperation.getId());
    //                dtoOperation.setEnabled(commandOperation.isEnabled());
    //            } else if (dtoOperation.getType().
    //                    equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG)) {
    //                dtoOperation = configOperationDAO.getOperation(dtoOperation.getId());
    //            } else if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.
    //                    PROFILE)) {
    //                dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId());
    //            } else if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.
    //                    POLICY)) {
    //                dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId());
    //            }
    //            operation = OperationDAOUtil.convertOperation(dtoOperation);
    //            int enrolmentId = operationDAO.getEnrolmentIdFromMappingId(enrollmentOpMappingId);
    //            if (enrolmentId != 0) {
    //                operation.setResponses(operationDAO.getOperationResponses(enrolmentId, operation.getId()));
    //            }
    //
    //            operation.setStatus(Operation.Status.valueOf(status.toString()));
    //            operation.setActivityId(activity);
    //
    //        } catch (SQLException e) {
    //            throw new OperationManagementException("Error occurred while opening a connection to the data source", e);
    //        } catch (OperationManagementDAOException e) {
    //            throw new OperationManagementException("Error occurred while retrieving the operation with activity Id '" +
    //                    activity, e);
    //        } finally {
    //            OperationManagementDAOFactory.closeConnection();
    //        }
    //
    //        //   return this.getOperation(operationId);
    //        return operation;
    //    }

    @Override
    public Activity getOperationByActivityId(String activity) throws OperationManagementException {
        // This parses the operation id from activity id (ex : ACTIVITY_23) and converts to the integer.
        int operationId = Integer.parseInt(
                activity.replace(DeviceManagementConstants.OperationAttributes.ACTIVITY, ""));
        if (operationId == 0) {
            throw new IllegalArgumentException("Operation ID cannot be null or zero (0).");
        }
        try {
            OperationManagementDAOFactory.openConnection();
            return operationDAO.getActivity(operationId);
        } catch (SQLException e) {
            throw new OperationManagementException("Error occurred while opening a connection to the data source.", e);
        } catch (OperationManagementDAOException e) {
            throw new OperationManagementException("Error occurred while retrieving the operation with activity Id '" +
                                                   activity, e);
        } finally {
            OperationManagementDAOFactory.closeConnection();
        }
    }

    @Override
    public List<Operation> getOperationUpdatedAfter(long timestamp) throws OperationManagementException {
        return null;
    }

    @Override
    public List<Activity> getActivitiesUpdatedAfter(long timestamp) throws OperationManagementException {
        try {
            OperationManagementDAOFactory.openConnection();
            return operationDAO.getActivitiesUpdatedAfter(timestamp);
        } catch (SQLException e) {
            throw new OperationManagementException("Error occurred while opening a connection to the data source.", e);
        } catch (OperationManagementDAOException e) {
            throw new OperationManagementException("Error occurred while getting the activity list changed after a " +
                                                   "given time.", e);
        } finally {
            OperationManagementDAOFactory.closeConnection();
        }
    }

    @Override
    public List<Activity> getActivitiesUpdatedAfter(long timestamp, int limit,
                                                    int offset) throws OperationManagementException {
        try {
            OperationManagementDAOFactory.openConnection();
            return operationDAO.getActivitiesUpdatedAfter(timestamp, limit, offset);
        } catch (SQLException e) {
            throw new OperationManagementException("Error occurred while opening a connection to the data source.", e);
        } catch (OperationManagementDAOException e) {
            throw new OperationManagementException("Error occurred while getting the activity list changed after a " +
                                                   "given time.", e);
        } finally {
            OperationManagementDAOFactory.closeConnection();
        }
    }

    @Override
    public int getActivityCountUpdatedAfter(long timestamp) throws OperationManagementException {
        try {
            OperationManagementDAOFactory.openConnection();
            return operationDAO.getActivityCountUpdatedAfter(timestamp);
        } catch (SQLException e) {
            throw new OperationManagementException("Error occurred while opening a connection to the data source.", e);
        } catch (OperationManagementDAOException e) {
            throw new OperationManagementException("Error occurred while getting the activity count changed after a " +
                                                   "given time.", e);
        } finally {
            OperationManagementDAOFactory.closeConnection();
        }
    }

    private OperationDAO lookupOperationDAO(Operation operation) {

        if (operation instanceof CommandOperation) {
            return commandOperationDAO;
        } else if (operation instanceof ProfileOperation) {
            return profileOperationDAO;
        } else if (operation instanceof ConfigOperation) {
            return configOperationDAO;
        } else if (operation instanceof PolicyOperation) {
            return policyOperationDAO;
        } else {
            return operationDAO;
        }
    }

    private OperationDAO lookupOperationDAO(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation operation) {

        if (operation instanceof org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) {
            return commandOperationDAO;
        } else if (operation instanceof org.wso2.carbon.device.mgt.core.dto.operation.mgt.ProfileOperation) {
            return profileOperationDAO;
        } else if (operation instanceof org.wso2.carbon.device.mgt.core.dto.operation.mgt.ConfigOperation) {
            return configOperationDAO;
        } else {
            return operationDAO;
        }
    }

    private String getUser() {
        return CarbonContext.getThreadLocalCarbonContext().getUsername();
    }

    private boolean isAuthenticationSkippedOperation(Operation operation) {

        //This is to check weather operations are coming from the task related to retrieving device information.
        DeviceTaskManager taskManager = new DeviceTaskManagerImpl(deviceType);
        if (taskManager.isTaskOperation(operation.getCode())) {
            return true;
        }

        boolean status;
        switch (operation.getCode()) {
            case DeviceManagementConstants.AuthorizationSkippedOperationCodes.POLICY_OPERATION_CODE:
                status = true;
                break;
            case DeviceManagementConstants.AuthorizationSkippedOperationCodes.MONITOR_OPERATION_CODE:
                status = true;
                break;
            case DeviceManagementConstants.AuthorizationSkippedOperationCodes.POLICY_REVOKE_OPERATION_CODE:
                status = true;
                break;
            default:
                status = false;
        }

        return status;
    }

    private boolean isActionAuthorized(DeviceIdentifier deviceId) {
        boolean isUserAuthorized;
        try {
            isUserAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService().
                    isUserAuthorized(deviceId, DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS);
        } catch (DeviceAccessAuthorizationException e) {
            log.error("Error occurred while trying to authorize current user upon the invoked operation", e);
            return false;
        }
        return isUserAuthorized;
    }

    private int getEnrolmentByStatus(DeviceIdentifier deviceId,
                                     EnrolmentInfo.Status status) throws OperationManagementException {
        int enrolmentId;
        try {
            DeviceManagementDAOFactory.openConnection();
            int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
            enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, status, tenantId);
        } catch (DeviceManagementDAOException e) {
            throw new OperationManagementException("Error occurred while retrieving metadata of '" +
                                                   deviceId.getType() + "' device carrying the identifier '" +
                                                   deviceId.getId() + "'", e);
        } catch (SQLException e) {
            throw new OperationManagementException(
                    "Error occurred while opening a connection to the data source", e);
        } finally {
            DeviceManagementDAOFactory.closeConnection();
        }
        return enrolmentId;
    }

    private EnrolmentInfo getEnrolmentInfo(DeviceIdentifier deviceId, String owner) throws OperationManagementException {
        EnrolmentInfo enrolmentInfo = null;
        try {
            int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
            String user = this.getUser();
            DeviceManagementDAOFactory.openConnection();
            if (this.isSameUser(user, owner)) {
                enrolmentInfo = deviceDAO.getEnrolment(deviceId, owner, tenantId);
            } else {
                boolean isAdminUser = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService().
                        isDeviceAdminUser();
                if (isAdminUser) {
                    enrolmentInfo = deviceDAO.getEnrolment(deviceId, owner, tenantId);
                }
                //TODO : Add a check for group admin if this fails
            }
        } catch (DeviceManagementDAOException e) {
            throw new OperationManagementException("Error occurred while retrieving enrollment data of '" +
                                                   deviceId.getType() + "' device carrying the identifier '" +
                                                   deviceId.getId() + "' of owner '" + owner + "'", e);
        } catch (SQLException e) {
            throw new OperationManagementException(
                    "Error occurred while opening a connection to the data source", e);
        } catch (DeviceAccessAuthorizationException e) {
            throw new OperationManagementException("Error occurred while checking the device access permissions for '" +
                                                   deviceId.getType() + "' device carrying the identifier '" +
                                                   deviceId.getId() + "' of owner '" + owner + "'", e);
        } finally {
            DeviceManagementDAOFactory.closeConnection();
        }
        return enrolmentInfo;
    }

    private EnrolmentInfo getActiveEnrolmentInfo(DeviceIdentifier deviceId) throws OperationManagementException {
        EnrolmentInfo enrolmentInfo;
        try {
            DeviceManagementDAOFactory.openConnection();
            int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
            enrolmentInfo = deviceDAO.getActiveEnrolment(deviceId, tenantId);
        } catch (DeviceManagementDAOException e) {
            throw new OperationManagementException("Error occurred while retrieving enrollment data of '" +
                                                   deviceId.getType() + "' device carrying the identifier '" +
                                                   deviceId.getId() + "'", e);
        } catch (SQLException e) {
            throw new OperationManagementException(
                    "Error occurred while opening a connection to the data source", e);
        } finally {
            DeviceManagementDAOFactory.closeConnection();
        }
        return enrolmentInfo;
    }

    private boolean setEnrolmentStatus(int enrolmentId, EnrolmentInfo.Status status) throws OperationManagementException {
        boolean updateStatus;
        try {
            DeviceManagementDAOFactory.beginTransaction();
            int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
            String user = this.getUser();
            updateStatus = enrollmentDAO.setStatus(enrolmentId, user, status, tenantId);
            DeviceManagementDAOFactory.commitTransaction();
        } catch (DeviceManagementDAOException e) {
            DeviceManagementDAOFactory.rollbackTransaction();
            throw new OperationManagementException("Error occurred while updating enrollment status of device of " +
                                                   "enrolment-id '" + enrolmentId + "'", e);
        } catch (TransactionManagementException e) {
            throw new OperationManagementException("Error occurred while initiating a transaction", e);
        } finally {
            DeviceManagementDAOFactory.closeConnection();
        }
        return updateStatus;
    }

    private boolean isTaskScheduledOperation(Operation operation, List<DeviceIdentifier> deviceIds) {
        DeviceManagementProviderService deviceManagementProviderService = DeviceManagementDataHolder.getInstance().
                getDeviceManagementProvider();

        List<MonitoringOperation> monitoringOperations = deviceManagementProviderService.getMonitoringOperationList(deviceType);//Get task list from each device type

        for(MonitoringOperation op : monitoringOperations){
            if (operation.getCode().equals(op.getTaskName())) {
                return true;
            }
        }

//        for(String dti : taskOperation){
//            if (dti.equals(deviceType)) {
//                monitoringOperations = deviceTypeSpecificTasks.get(dti);
//
//            }
//        }
//
//        for(DeviceIdentifier deviceIdentifier : deviceIds){
//            String deviceType = deviceIdentifier.getType();
//
//
//
//        }

//        TaskConfiguration taskConfiguration = DeviceConfigurationManager.getInstance().getDeviceManagementConfig().
//                getTaskConfiguration();
//        for (TaskConfiguration.Operation op : taskConfiguration.getOperations()) {
//            if (operation.getCode().equals(op.getOperationName())) {
//                return true;
//            }
//        }
        return false;
    }

    private boolean isSameUser(String user, String owner) {
        return user.equalsIgnoreCase(owner);
    }
}


text:
template

colors

#dc6a4f

#2a373f

#FAFAFA

#F5F5E4

#a59a7e

#e4e4dc

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Pax\Entity;

use Doctrine\ORM\EntityRepository;
use Pax\Entity\PaxFuncionarios;

/**
 * PaxFuncionariosRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class PaxFuncionariosRepository extends EntityRepository
{
    public function findByLogin(PaxFuncionarios $funcionarios, $login, $senha)
    {
        /**
         * @var $funcionarioLogin \Pax\Entity\PaxFuncionarios
         */
        $funcionarioLogin = $this->createQueryBuilder('f')
            ->where('f.login = :a1')
            ->setParameter('a1', $login)
            ->getQuery()
            ->getOneOrNullResult();
        //var_dump($funcionarios);die;

        if(!empty($funcionarioLogin)):
            $funcionarios->setSalt($funcionarioLogin->getSalt());
            if($funcionarios->encryptSenha($senha) == $funcionarioLogin->getSenha()):
                $funcionario = $funcionarioLogin->toArray();
                unset($funcionario['senha']);
                unset($funcionario['salt']);
                //var_dump($funcionario);die("Re-PaxFuncionariosRepository - L33");
                return $funcionario ;
            endif;

        endif;

        return false;
    }
}


text:
require 'spec_helper'

describe 'citation', type: :feature, js: true, vcr: true do
  it 'no citation information' do
    visit '/works/10.0311/fk2/e11643a99d903d0ccfc2d523b344d9ff'

    expect(page).to have_css("#summary-citations", text: "No citations were reported. No usage information was reported.")
  end

  it 'show summary information list view' do
    visit '/works?query=dufek+AND+intrusion'

    expect(page).not_to have_css("#citations-tab")
    # expect(page).to have_css("#summary-citations", text: "4 citations")
    # expect(page).to have_css("#summary-views", text: "No usage information was reported.")
  end

  it 'show summary information' do
    visit '/works/10.91819/71718'

    expect(page).to have_css("#citations-tab")
    # expect(page).to have_css("#summary-citations", text: "4 citations")
    # expect(page).to have_css("#summary-views", text: "No usage information was reported.")
  end

  it 'show citation chart' do
    visit '/works/10.1007/978-1-4757-9930-9_8'
    expect(page).not_to have_css("#citations-tab")
    # expect(page).to have_css("#citations-tab", text: "4 Citations")
    # expect(page).to have_css("small", text: "4 citations reported since publication in 2011.")
    # expect(page).to have_css("svg", count: 1)
  end
end


text:
/*jshint node: true*/

'use strict';

var Stream = require('stream'),
    util = require('util');

var BufferStreamReader = function (buf, opt) {
    Stream.Readable.call(this, opt);
    this._buf = buf;
};

util.inherits(BufferStreamReader, Stream.Readable);

BufferStreamReader.prototype._read = function () {
    this.push(this._buf);
    this.push(null);
};

module.exports = BufferStreamReader;


text:
Required dependencies:

- Windows
    Visual Studio 2013 or Express
    Python (v2.7.3 recommended, v3.x.x not supported)

- Mac
    Xcode Command Line Tools.

- Linux
    Python (v2.7.3 recommended, v3.x.x not supported)
    make
    A C/C++ compiler like GCC
    libxtst-dev and libpng++-dev (sudo apt-get install libxtst-dev libpng++-dev).

```js
npm install robotjs
```


text:
package parser.expr.assignexpr;

public class LEFT_SHIFT {
    static int i = 2;
    static int j = 1;
    public static int main() {
        return j <<= i;
    }
}


text:
package ppp.menu;

import ppp.GameState;
import ppp.PPP;
import ppp.game.PongGame;

public class MainMenu extends AbstractMenu {
	private static final long serialVersionUID = 1L;

	public MainMenu() {
		super();

		Task newGameTask = new Task() {
			public void doTask() {
				PPP ppp = PPP.getInstance();

				if (ppp.getGame() == null) {
					Task resumeTask = new Task() {
						public void doTask() {
							PPP ppp = PPP.getInstance();
							ppp.setState(GameState.GAME);
						}
					};
					addMenuItem(1, new MenuItem("Resume Game", resumeTask));
				}

				PongGame game = new PongGame();
				ppp.setGame(game);
				ppp.setState(GameState.GAME);
			}
		};
		addMenuItem(new MenuItem("New Game", newGameTask));

		Task settingsTask = new Task() {
			public void doTask() {
				PPP ppp = PPP.getInstance();
				SettingsMenu settings = new SettingsMenu(ppp.getCurrentMenu());
				ppp.setCurrentMenu(settings);
				settings.repaint();
			}
		};
		addMenuItem(new MenuItem("Settings", settingsTask));

		Task exitTask = new Task() {
			public void doTask() {
				System.exit(0);
			}
		};
		addMenuItem(new MenuItem("Exit", exitTask));

		repaint();
	}
}


text:
package com.icytown.course.experimentthree.storage2.data.model;

import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import android.arch.persistence.room.TypeConverters;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.icytown.course.experimentthree.storage2.data.common.BitmapConverter;

@Entity
@TypeConverters(value = {BitmapConverter.class})
public class User {

    @PrimaryKey
    @NonNull
    public String name;

    @NonNull
    public String password;

    @Nullable
    public Bitmap avatar;

    public User(@NonNull String name, @NonNull String password, Bitmap avatar) {
        this.name = name;
        this.password = password;
        this.avatar = avatar;
    }

    public boolean auth(@NonNull String password) {
        return this.password.equals(password);
    }
}


text:
\documentclass[a4paper]{article}
\usepackage[utf8]{inputenc}

\usepackage{graphicx}  % import graphics
\usepackage{listings}  % support source code listing
\usepackage{amsmath}  % math stuff
\usepackage{amssymb} %
\usepackage{a4wide} % wide pages
\usepackage{fancyhdr} % nice headers
\usepackage{tikz}
\usetikzlibrary{arrows}
\usetikzlibrary{petri}

\lstset{basicstyle=\footnotesize,language=Python,numbers=left, numberstyle=\tiny, stepnumber=5,firstnumber=0, numbersep=5pt} % set up listings
\pagestyle{fancy}             % header

\usepackage[none]{hyphenat}
\sloppy

% change enums style: first level (a), (b), (c)
\renewcommand{\labelenumi}{\arabic{enumi}.}
\renewcommand{\labelenumii}{\alph{enumii})}

%term/semester
\newcommand{\term}{
	Summer 2012 -- Saarland University
}

%lecture name
\newcommand{\lecture}{
	Algorithm Engineering
}

%assignment iteration
\newcommand{\assignment}{
	Team FortyTwo Final Report
}

%set up names, matricle number, and email
\newcommand{\authors}{
  Florian Benz, Steven Schäfer, Bernhard Schommer
}

% use to start a new exercise
\newcommand{\exercise}[1]
{
  \stepcounter{subsection}
  \subsection*{Exercise \thesubsection: #1}

}

\begin{document}
\title{
  \vspace{-3cm}
  \large
  \lecture \\
  \small \term \\
  \huge \assignment
}
\author{\small \authors}

\setlength \headheight{25pt}
\fancyhead[R]{\begin{tabular}{r}\lecture \\ \assignment \end{tabular}}
\fancyhead[L]{\authors}

\maketitle

\section{Overview}

\subsection{Pre-processing}

First, we pre-process the OSM data to extract a single street graph consisting of intersections in the original graph.
For each travel mode, we extract whether a vertex or an edge is accessible.
Our graph format consists of a compressed sparse row representation of the graph.
Each vertex and edge can be uniquely identified by its offset.
We use this to store additional attributes like distance, steps and positions in separate files.

The second step of the pre-processing partitions the large graph into small clusters with
nearly the same amount of vertices.
We employ Metis~\cite{met12} for the graph partitioning with the objective of minimizing
the number of edges between clusters.
After this step, we have several clusters (e.g. 1000) and one overlay graph that consits
of all boundary vertices and the cut edges.
The result for Europe is shown in Figure~\ref{fig}.

\begin{figure}
\includegraphics[scale=0.1]{terminal}
\caption{The street graph of Europe partitioned into balanced clusters}
\label{fig}
\end{figure}

Up to now, the pre-processing is independent of the used metrics.
This has the advantage that only the metric-specific pre-processing is needed
for changes or additional metrics.
For each cluster, metric, and transport mode, we pre-compute a matrix of the shortest
paths of all boundary vertices to all other boundary vertices of the cluster.

The whole idea of metric-independent partitioning and the metric matrices is based
on the approach presented by Delling et al~\cite{del11}.
This is the approach used for Microsoft Bing.
However, the idea is not new.
The earlier benchmarks by Schütz~\cite{sch04} show that a good partitioning leads
to better performance. Especially in contrast to a simple grid.

One advantage of the partition-based approach is that in contrast to many other
approaches arbitrary metrics  are supported and take advantage of fast queries.
Another advantage of the separated pre-processing steps is that updates can
be made so fast that real-time traffic updates are possible.

\subsection{Queries}

During the startup of the server, all files are mapped into the server's address space.
As a result our startup overhead is negligible and we do not have to load data from disk afterwards.

When a query arrives, we find for each waypoint the nearest node in the OSM data.
This might not correspond to a vertex in our street graph;
in this case the node lies on an edge and we compute all reachable endpoints of this edge.
At this point, we run Dijkstra's algorithm in both clusters and
a bidirectional version of Dijkstra's algorithm on the overlay graph.
Finally, the resulting JSON object is created and returned.

The street graph is significantly smaller than the original OSM graph.
Furthermore, it is sparse; the average out-degree is around 2.4.
To improve the efficiency of Dijkstra's algorithm on street graphs, we use a 4-heap
that is optimized for the memory characteristics on the server.

To find the nearest neighbor, we use precomputed k-d trees.
This results in very fast queries during runtime.
The construction algorithm is reminiscent of quicksort.
On disk the k-d tree is stored as a permutation of encoded vertex indices, edge offset, and step offsets.
A k-d tree is created for each cluster and for the overlay graph.
To find the matching cluster for a waypoint, we use precomputed bounding boxes.

We use Go as our implementation language.
Go is a modern, concurrent and statically compiled programming language.
As the standard library comes with an HTTP server and JSON marshaling,
the initial implementation went very smoothly.
In addition, it is a joy to parallelize computations.

\section{Encountered Problems}

The OSM data turned out to be astonishingly clean, compared to the output of a monkey with a typewriter.
By default the data is sorted by creation date, which is nice if you want to build a history viewer.
For our purposes, this ordering is useless if you want to apply any kind of graph algorithm
directly to the OSM files.

Due to the Go garbage collector, the addressable memory on a 64 bit machine is limited to 16 GB.
Our parser needs more memory to process the whole of Germany for pedestrian routing.
This is solved by allocating large data structures in the non-GC heap
and in addition we reduced our memory footprint.

\section{Additional Features}

Our server can perform concurrent non-blocking logging with accurate timing information.
In addition, the server can output profiling data for a request;
this has already been useful in troubleshooting performance problems.

Additionally, we have created a small JavaScript based frontend that
gives us an easy way to test and visualize the results of our implementation
(see http://urania.mpi-inf.mpg.de:23401/awesome).
As a reference route, the result of Google Directions is shown side-by-side.
Google Places autocompelte is included for convenience.

\begin{thebibliography}{9}

\bibitem{del11}
	D. Delling, A. V. Goldberg, T. Pajor, R. F. Werneck, \emph{Customizable route planning}. SEA'11.

\bibitem{met12}
    \emph{Metis}, http://glaros.dtc.umn.edu/gkhome/metis/metis/overview.

\bibitem{sch04}
	B. Schütz, \emph{Partition-Based Speed-Up of Dijkstra's Algorithm}. 2004, http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.115.3514.

\end{thebibliography}

\end{document}


text:
#ifndef HX_CFFI_NEKO_LOADER_H
#define HX_CFFI_NEKO_LOADER_H

//-------- NEKO Interface -----------------------------------------------------
namespace
{

#include <hx/NekoFunc.h>

void *sNekoDllHandle = 0;

void *LoadNekoFunc(const char *inName)
{
   #ifdef HX_WINRT
   return 0;
   #else
   static bool tried = false;
   if (tried && !sNekoDllHandle)
       return 0;
   tried = true;

   if (!sNekoDllHandle)
   {
      #ifdef HX_WINDOWS
      sNekoDllHandle = GetModuleHandleA("neko.dll");
      #else
      sNekoDllHandle = dlopen("libneko." NEKO_EXT, RTLD_NOW);
      // The debian package creates libneko.so.0 without libneko.so...
      // The fedora/openSUSE rpm packages create libneko.so.1...
      if (!sNekoDllHandle)
         sNekoDllHandle = dlopen("libneko." NEKO_EXT ".0", RTLD_NOW);
      if (!sNekoDllHandle)
         sNekoDllHandle = dlopen("libneko." NEKO_EXT ".1", RTLD_NOW);
      if (!sNekoDllHandle)
         sNekoDllHandle = dlopen("libneko." NEKO_EXT ".2", RTLD_NOW);
      #endif

      if (!sNekoDllHandle)
      {
         fprintf(stderr,"Could not link to neko.\n");
         return 0;
      }
   }

   #ifdef HX_WINDOWS
   void *result = (void *)GetProcAddress((HMODULE)sNekoDllHandle,inName);
   #else
   void *result = dlsym(sNekoDllHandle,inName);
   #endif

   //printf(" %s = %p\n", inName, result );
   return result;
   #endif // !HX_WINRT
}

static int __a_id = 0;
static int __s_id = 0;
static int b_id = 0;
static int length_id = 0;
static int push_id = 0;

neko_value *gNeko2HaxeString = 0;
neko_value *gNekoNewArray = 0;
neko_value gNekoNull = 0;
neko_value gNekoTrue = 0;
neko_value gNekoFalse = 0;

namespace
{
void CheckInitDynamicNekoLoader()
{
   if (!gNekoNull)
   {
      printf("Haxe code is missing a call to cpp.Prime.nekoInit().\n");
   }
}
}

/*

*/

void *DynamicNekoLoader(const char *inName);

typedef neko_value (*alloc_object_func)(neko_value);
typedef neko_value (*alloc_string_func)(const char *);
typedef neko_value (*alloc_abstract_func)(neko_vkind,void *);
typedef neko_value (*val_call1_func)(neko_value,neko_value);
typedef neko_value (*val_field_func)(neko_value,int);
typedef neko_value *(*alloc_root_func)(int);
typedef char *(*alloc_private_func)(int);
typedef neko_value (*copy_string_func)(const char *,int);
typedef int (*val_id_func)(const char *);
typedef neko_buffer (*alloc_buffer_func)(const char *);
typedef neko_value (*val_buffer_func)(neko_buffer);
typedef void (*buffer_append_sub_func)(neko_buffer,const char *,int);
typedef void (*fail_func)(neko_value,const char *,int);
typedef neko_value (*alloc_array_func)(unsigned int);
typedef void (*val_gc_func)(neko_value,void *);
typedef void (*val_ocall1_func)(neko_value,int,neko_value);
typedef neko_value (*alloc_empty_string_func)(int);

static alloc_object_func dyn_alloc_object = 0;
static alloc_string_func dyn_alloc_string = 0;
static alloc_abstract_func dyn_alloc_abstract = 0;
static val_call1_func dyn_val_call1 = 0;
static val_field_func dyn_val_field = 0;
static alloc_root_func dyn_alloc_root = 0;
static alloc_private_func dyn_alloc_private = 0;
static alloc_private_func dyn_alloc = 0;
static copy_string_func dyn_copy_string = 0;
static val_id_func dyn_val_id = 0;
static alloc_buffer_func dyn_alloc_buffer = 0;
static val_buffer_func dyn_val_buffer = 0;
static fail_func dyn_fail = 0;
static buffer_append_sub_func dyn_buffer_append_sub = 0;
static alloc_array_func dyn_alloc_array = 0;
static val_gc_func dyn_val_gc = 0;
static val_ocall1_func dyn_val_ocall1 = 0;
static alloc_empty_string_func dyn_alloc_empty_string = 0;

neko_value api_alloc_string(const char *inString)
{
   CheckInitDynamicNekoLoader();
   neko_value neko_string = dyn_alloc_string(inString);
   if (gNeko2HaxeString)
      return dyn_val_call1(*gNeko2HaxeString,neko_string);
   return neko_string;
}

neko_value api_alloc_raw_string(int inLength)
{
   CheckInitDynamicNekoLoader();
   return dyn_alloc_empty_string(inLength);
}

#define NOT_IMPLEMNETED(func) dyn_fail(api_alloc_string("NOT Implemented:" func),__FILE__,__LINE__)

void * api_empty() { return 0; }

bool api_val_bool(neko_value  arg1) { return arg1==gNekoTrue; }
int api_val_int(neko_value  arg1) { return neko_val_int(arg1); }
double api_val_float(neko_value  arg1) { return *(double *)( ((char *)arg1) + 4 ); }
double api_val_number(neko_value  arg1) { return neko_val_is_int(arg1) ? neko_val_int(arg1) : api_val_float(arg1); }

neko_value api_alloc_bool(bool arg1) { CheckInitDynamicNekoLoader(); return arg1 ? gNekoTrue : gNekoFalse; }
neko_value api_alloc_int(int arg1) { return neko_alloc_int(arg1); }
neko_value api_alloc_empty_object()
{
   return dyn_alloc_object(gNekoNull);
}

neko_value api_buffer_to_string(neko_buffer arg1)
{
   neko_value neko_string = dyn_val_buffer(arg1);
   if (gNeko2HaxeString)
      return dyn_val_call1(*gNeko2HaxeString,neko_string);
   return neko_string;
}

const char * api_val_string(neko_value  arg1)
{
	if (neko_val_is_string(arg1))
	   return neko_val_string(arg1);

	if (neko_val_is_object(arg1))
   {
	   neko_value s = dyn_val_field(arg1,__s_id);
      if (neko_val_is_string(s))
	      return neko_val_string(s);
   }

   return 0;
}

double  api_val_field_numeric(neko_value  arg1,int arg2)
{
	neko_value field = dyn_val_field(arg1, arg2);
	if (neko_val_is_number(field))
		return api_val_number(field);
	if (field==gNekoTrue)
      return 1;
	return 0;
}

neko_buffer api_alloc_buffer_len(int inLen)
{
	char *s=dyn_alloc_private(inLen+1);
	memset(s,' ',inLen);
	s[inLen] = 0;
	neko_buffer b = dyn_alloc_buffer(s);
	return b;
}

int api_val_strlen(neko_value  arg1)
{
	if (neko_val_is_string(arg1))
	   return neko_val_strlen(arg1);

	if (neko_val_is_object(arg1))
   {
      neko_value l =  dyn_val_field(arg1,length_id);
      if (neko_val_is_int(l))
         return api_val_int(l);
   }
	return 0;
}
void api_buffer_set_size(neko_buffer inBuffer,int inLen) { NOT_IMPLEMNETED("api_buffer_set_size"); }

void api_buffer_append_char(neko_buffer inBuffer,int inChar)
{
	char buf[2] = { (char)inChar, '\0' };
	dyn_buffer_append_sub(inBuffer,buf,1);
}

// Byte arrays - not used on neko
neko_buffer api_val_to_buffer(neko_value  arg1) { return 0; }
bool api_val_is_buffer(neko_value  arg1) { return false; }
int api_buffer_size(neko_buffer inBuffer) { return 0; }
char * api_buffer_data(neko_buffer inBuffer) { return 0; }

char * api_val_dup_string(neko_value inVal)
{
	int len = api_val_strlen(inVal);
	const char *ptr = api_val_string(inVal);
	char *result = dyn_alloc_private(len+1);
	memcpy(result,ptr,len);
	result[len] = '\0';
	return result;
}

neko_value api_alloc_string_len(const char *inStr,int inLen)
{
	if (gNeko2HaxeString)
		return dyn_val_call1(*gNeko2HaxeString,dyn_copy_string(inStr,inLen));
   return dyn_copy_string(inStr,inLen);
}

neko_value api_alloc_wstring_len(const wchar_t *inStr,int inLen)
{
  int len = 0;
  const wchar_t *chars = inStr;
  for(int i=0;i<inLen;i++)
   {
      int c = chars[i];
      if( c <= 0x7F ) len++;
      else if( c <= 0x7FF ) len+=2;
      else if( c <= 0xFFFF ) len+=3;
      else len+= 4;
   }

   char *result = dyn_alloc_private(len);//+1?
   unsigned char *data =  (unsigned char *) &result[0];
   for(int i=0;i<inLen;i++)
   {
      int c = chars[i];
      if( c <= 0x7F )
         *data++ = c;
      else if( c <= 0x7FF )
      {
         *data++ = 0xC0 | (c >> 6);
         *data++ = 0x80 | (c & 63);
      }
      else if( c <= 0xFFFF )
      {
         *data++ = 0xE0 | (c >> 12);
         *data++ = 0x80 | ((c >> 6) & 63);
         *data++ = 0x80 | (c & 63);
      }
      else
      {
         *data++ = 0xF0 | (c >> 18);
         *data++ = 0x80 | ((c >> 12) & 63);
         *data++ = 0x80 | ((c >> 6) & 63);
         *data++ = 0x80 | (c & 63);
      }
   }
   //result[len] = 0;

   return api_alloc_string_len(result,len);
}

const wchar_t *api_val_wstring(neko_value  arg1)
{
	int len = api_val_strlen(arg1);

   unsigned char *b = (unsigned char *)api_val_string(arg1);
   wchar_t *result = (wchar_t *)dyn_alloc_private((len+1)*sizeof(wchar_t));
   int l = 0;

   for(int i=0;i<len;)
   {
       int c = b[i++];
       if (c==0) break;
       else if( c < 0x80 )
       {
           result[l++] = c;
       }
       else if( c < 0xE0 )
           result[l++] = ( ((c & 0x3F) << 6) | (b[i++] & 0x7F) );
       else if( c < 0xF0 )
       {
           int c2 = b[i++];
           result[l++] = ( ((c & 0x1F) << 12) | ((c2 & 0x7F) << 6) | ( b[i++] & 0x7F) );
       }
       else
       {
           int c2 = b[i++];
           int c3 = b[i++];
           result[l++] = ( ((c & 0x0F) << 18) | ((c2 & 0x7F) << 12) | ((c3 << 6) & 0x7F) | (b[i++] & 0x7F) );
       }
   }
   result[l] = '\0';

   return result;
}

wchar_t * api_val_dup_wstring(neko_value inVal)
{
	return (wchar_t *)api_val_wstring(inVal);
}

int api_val_type(neko_value  arg1)
{
	int t=neko_val_type(arg1);

	if (t==VAL_OBJECT)
	{
		neko_value __a = dyn_val_field(arg1,__a_id);
		if (neko_val_is_array(__a))
			return valtArray;
		neko_value __s = dyn_val_field(arg1,__s_id);
		if (neko_val_is_string(__s))
			return valtString;
	}
	if (t<7)
		return (hxValueType)t;
	if (t==VAL_ABSTRACT)
		return valtAbstractBase;

	if (t==VAL_PRIMITIVE || t==VAL_JITFUN)
		return valtFunction;
	if (t==VAL_32_BITS || t==VAL_INT)
		return valtInt;
	return valtNull;
}

neko_value *api_alloc_root()
{
   return dyn_alloc_root(1);
}

void * api_val_to_kind(neko_value  arg1,neko_vkind arg2)
{
	neko_vkind k = (neko_vkind)neko_val_kind(arg1);
	if (k!=arg2)
		return 0;
	return neko_val_data(arg1);
}

int api_alloc_kind()
{
	static int id = 1;
	int result = id;
	id += 4;
	return result;
}
neko_value api_alloc_null()
{
   CheckInitDynamicNekoLoader();
   return gNekoNull;
}

neko_value api_create_abstract(neko_vkind inKind,int inSize,void *inFinalizer)
{
   void *data = dyn_alloc(inSize);
   neko_value val = dyn_alloc_abstract(inKind, data);
   dyn_val_gc(val, inFinalizer);
   return val;
}

void api_free_abstract(neko_value inAbstract)
{
   if (neko_val_is_abstract(inAbstract))
   {
      dyn_val_gc(inAbstract,0);
      neko_val_kind(inAbstract) = 0;
   }
}

neko_value api_buffer_val(neko_buffer arg1)
{
   return api_alloc_null();
}

void api_hx_error()
{
   dyn_fail(dyn_alloc_string("An unknown error has occurred."),"",1);
}

void * api_val_data(neko_value  arg1) { return neko_val_data(arg1); }

// Array access - generic
int api_val_array_size(neko_value  arg1)
{
	if (neko_val_is_array(arg1))
	   return neko_val_array_size(arg1);
	neko_value l = dyn_val_field(arg1,length_id);
	return neko_val_int(l);
}

neko_value  api_val_array_i(neko_value  arg1,int arg2)
{
	if (neko_val_is_array(arg1))
	   return neko_val_array_ptr(arg1)[arg2];
	return neko_val_array_ptr(dyn_val_field(arg1,__a_id))[arg2];
}

void api_val_array_set_i(neko_value  arg1,int arg2,neko_value inVal)
{
	if (!neko_val_is_array(arg1))
		arg1 = dyn_val_field(arg1,__a_id);
	neko_val_array_ptr(arg1)[arg2] = inVal;
}

void api_val_array_set_size(neko_value  arg1,int inLen)
{
	NOT_IMPLEMNETED("api_val_array_set_size");
}

void api_val_array_push(neko_value  inArray,neko_value inValue)
{
   dyn_val_ocall1(inArray,push_id,inValue);
}

neko_value  api_alloc_array(int arg1)
{
   if (!gNekoNewArray)
	   return dyn_alloc_array(arg1);
	return dyn_val_call1(*gNekoNewArray,neko_alloc_int(arg1));
}

neko_value * api_val_array_value(neko_value  arg1)
{
	if (neko_val_is_array(arg1))
	   return neko_val_array_ptr(arg1);
	return neko_val_array_ptr(dyn_val_field(arg1,__a_id));
}

neko_value  api_val_call0_traceexcept(neko_value  arg1)
{
	NOT_IMPLEMNETED("api_val_call0_traceexcept");
	return gNekoNull;
}

int  api_val_fun_nargs(neko_value arg1)
{
   if (!arg1 || !neko_val_is_function(arg1) )
      return faNotFunction;
   return neko_val_fun_nargs(arg1);
}

void api_val_gc(neko_value obj, void *finalizer)
{
   // Let neko deal with ints or abstracts ...
   if (neko_val_is_int(obj) || neko_val_is_abstract(obj))
   {
      dyn_val_gc(obj,finalizer);
   }
   else
   {
      // Hack type to abstract for the duration
      neko_val_type old_tag = neko_val_tag(obj);
      neko_val_tag(obj) = VAL_ABSTRACT;
      dyn_val_gc(obj,finalizer);
      neko_val_tag(obj) = old_tag;
   }
}

void api_gc_change_managed_memory(int,const char *)
{
   // Nothing to do here
}

#define IMPLEMENT_HERE(x) if (!strcmp(inName,#x)) return (void *)api_##x;
#define IGNORE_API(x) if (!strcmp(inName,#x)) return (void *)api_empty;

void *DynamicNekoLoader(const char *inName)
{
   IMPLEMENT_HERE(alloc_kind)
   IMPLEMENT_HERE(alloc_null)
   IMPLEMENT_HERE(val_to_kind)
   if (!strcmp(inName,"hx_fail"))
      return LoadNekoFunc("_neko_failure");
   IMPLEMENT_HERE(val_type)
   IMPLEMENT_HERE(val_bool)
   IMPLEMENT_HERE(val_int)
   IMPLEMENT_HERE(val_float)
   IMPLEMENT_HERE(val_number)
   IMPLEMENT_HERE(val_field_numeric)
   IMPLEMENT_HERE(alloc_bool)
   IMPLEMENT_HERE(alloc_int)
   IMPLEMENT_HERE(alloc_empty_object)
   IMPLEMENT_HERE(alloc_root)
   IMPLEMENT_HERE(val_gc)

   IMPLEMENT_HERE(create_abstract)
   IMPLEMENT_HERE(free_abstract)

   IGNORE_API(gc_enter_blocking)
   IGNORE_API(gc_exit_blocking)
   IGNORE_API(gc_safe_point)
   IGNORE_API(gc_add_root)
   IGNORE_API(gc_remove_root)
   IGNORE_API(gc_set_top_of_stack)
   IGNORE_API(gc_change_managed_memory)
   IGNORE_API(create_root)
   IGNORE_API(query_root)
   IGNORE_API(destroy_root)
   IGNORE_API(hx_register_prim)
   IGNORE_API(val_array_int)
   IGNORE_API(val_array_double)
   IGNORE_API(val_array_float)
   IGNORE_API(val_array_bool)

   if (!strcmp(inName,"hx_alloc"))
      return LoadNekoFunc("neko_alloc");

   IMPLEMENT_HERE(buffer_to_string)
   IMPLEMENT_HERE(buffer_val)

   if (!strcmp(inName,"val_iter_field_vals"))
      return LoadNekoFunc("neko_val_iter_fields");

   IMPLEMENT_HERE(val_strlen)
   IMPLEMENT_HERE(val_wstring)
   IMPLEMENT_HERE(val_string)
   IMPLEMENT_HERE(alloc_string)
   IMPLEMENT_HERE(alloc_raw_string)
   IMPLEMENT_HERE(val_dup_wstring)
   IMPLEMENT_HERE(val_dup_string)
   IMPLEMENT_HERE(alloc_string_len)
   IMPLEMENT_HERE(alloc_wstring_len)

   IMPLEMENT_HERE(val_is_buffer)
   IMPLEMENT_HERE(val_to_buffer)
   IMPLEMENT_HERE(alloc_buffer_len)
   IMPLEMENT_HERE(buffer_size)
   IMPLEMENT_HERE(buffer_set_size)
   IMPLEMENT_HERE(buffer_append_char)
   IMPLEMENT_HERE(buffer_data)

   IMPLEMENT_HERE(hx_error)
   IMPLEMENT_HERE(val_array_i)
   IMPLEMENT_HERE(val_array_size)
   IMPLEMENT_HERE(val_data)
   IMPLEMENT_HERE(val_array_set_i)
   IMPLEMENT_HERE(val_array_set_size)
   IMPLEMENT_HERE(val_array_push)
   IMPLEMENT_HERE(alloc_array)
   IMPLEMENT_HERE(val_array_value)

   IMPLEMENT_HERE(val_fun_nargs)

   IMPLEMENT_HERE(val_call0_traceexcept)

   char buffer[100];
   strcpy(buffer,"neko_");
   strcat(buffer,inName);
   void *result = LoadNekoFunc(buffer);
   if (result)
      return result;

	return 0;
}

ResolveProc InitDynamicNekoLoader()
{
   static bool init = false;
   if (!init)
   {
      dyn_alloc_private = (alloc_private_func)LoadNekoFunc("neko_alloc_private");
      dyn_alloc = (alloc_private_func)LoadNekoFunc("neko_alloc");
      dyn_alloc_object = (alloc_object_func)LoadNekoFunc("neko_alloc_object");
      dyn_alloc_string = (alloc_string_func)LoadNekoFunc("neko_alloc_string");
      dyn_alloc_abstract = (alloc_abstract_func)LoadNekoFunc("neko_alloc_abstract");
      dyn_val_call1 = (val_call1_func)LoadNekoFunc("neko_val_call1");
      dyn_val_field = (val_field_func)LoadNekoFunc("neko_val_field");
      dyn_alloc_root = (alloc_root_func)LoadNekoFunc("neko_alloc_root");
      dyn_copy_string = (copy_string_func)LoadNekoFunc("neko_copy_string");
      dyn_val_id = (val_id_func)LoadNekoFunc("neko_val_id");
      dyn_alloc_buffer = (alloc_buffer_func)LoadNekoFunc("neko_alloc_buffer");
      dyn_val_buffer = (val_buffer_func)LoadNekoFunc("neko_buffer_to_string");
      dyn_fail = (fail_func)LoadNekoFunc("_neko_failure");
      dyn_buffer_append_sub = (buffer_append_sub_func)LoadNekoFunc("neko_buffer_append_sub");
      dyn_alloc_array = (alloc_array_func)LoadNekoFunc("neko_alloc_array");
      dyn_val_gc = (val_gc_func)LoadNekoFunc("neko_val_gc");
      dyn_val_ocall1 = (val_ocall1_func)LoadNekoFunc("neko_val_ocall1");
      dyn_alloc_empty_string = (alloc_empty_string_func)LoadNekoFunc("neko_alloc_empty_string");
      init = true;
   }

   if (!dyn_val_id)
     return 0;

   __a_id = dyn_val_id("__a");
   __s_id = dyn_val_id("__s");
   b_id = dyn_val_id("b");
   length_id = dyn_val_id("length");
   push_id = dyn_val_id("push");

   return DynamicNekoLoader;
}

neko_value neko_init(neko_value inNewString,neko_value inNewArray,neko_value inNull, neko_value inTrue, neko_value inFalse)
{
   InitDynamicNekoLoader();

   gNekoNull = inNull;
   gNekoTrue = inTrue;
   gNekoFalse = inFalse;

   gNeko2HaxeString = dyn_alloc_root(1);
   *gNeko2HaxeString = inNewString;
   gNekoNewArray = dyn_alloc_root(1);
   *gNekoNewArray = inNewArray;

   return gNekoNull;
}

} // end anon namespace

#endif


text:
package com.amazonaws.services.mediastore.model;

import javax.annotation.Generated;

/**
 * <p>
 * The service is temporarily unavailable.
 * </p>
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class InternalServerErrorException extends com.amazonaws.services.mediastore.model.AWSMediaStoreException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new InternalServerErrorException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public InternalServerErrorException(String message) {
        super(message);
    }

}


text:
#ifndef FFMPEG_CMDUTILS_H
#define FFMPEG_CMDUTILS_H

#include <inttypes.h>

/**
 * Parses a string and returns its corresponding value as a double.
 * Exits from the application if the string cannot be correctly
 * parsed or the corresponding value is invalid.
 *
 * @param context the context of the value to be set (e.g. the
 * corresponding commandline option name)
 * @param numstr the string to be parsed
 * @param type the type (OPT_INT64 or OPT_FLOAT) as which the
 * string should be parsed
 * @param min the minimum valid accepted value
 * @param max the maximum valid accepted value
 */
double parse_number_or_die(const char *context, const char *numstr, int type, double min, double max);

typedef struct {
    const char *name;
    int flags;
#define HAS_ARG    0x0001
#define OPT_BOOL   0x0002
#define OPT_EXPERT 0x0004
#define OPT_STRING 0x0008
#define OPT_VIDEO  0x0010
#define OPT_AUDIO  0x0020
#define OPT_GRAB   0x0040
#define OPT_INT    0x0080
#define OPT_FLOAT  0x0100
#define OPT_SUBTITLE 0x0200
#define OPT_FUNC2  0x0400
#define OPT_INT64  0x0800
     union {
        void (*func_arg)(const char *); //FIXME passing error code as int return would be nicer then exit() in the func
        int *int_arg;
        char **str_arg;
        float *float_arg;
        int (*func2_arg)(const char *, const char *);
        int64_t *int64_arg;
    } u;
    const char *help;
    const char *argname;
} OptionDef;

void show_help_options(const OptionDef *options, const char *msg, int mask, int value);

/**
 * Parses the command line arguments.
 * @param options Array with the definitions required to interpret every
 * option of the form: -<option_name> [<argument>]
 * @param parse_arg_function Name of the function called to process every
 * argument without a leading option name flag. NULL if such arguments do
 * not have to be processed.
 */
void parse_options(int argc, char **argv, const OptionDef *options,
                   void (* parse_arg_function)(const char*));

void print_error(const char *filename, int err);

/**
 * Prints the program banner to stderr. The banner contents depend on the
 * current version of the repository and of the libav* libraries used by
 * the program.
 * @param program_name name of the program
 * @param program_birth_year year of birth of the program
 */
void show_banner(const char *program_name, int program_birth_year);

/**
 * Prints the version of the program to stdout. The version message
 * depends on the current versions of the repository and of the libav*
 * libraries.
 * @param program_name name of the program
 */
void show_version(const char *program_name);

/**
 * Prints the license of the program to stdout. The license depends on
 * the license of the libraries compiled into the program.
 */
void show_license(void);

#endif /* FFMPEG_CMDUTILS_H */