org.mybatis.guice.transactional.Transactional Java Examples

The following examples show how to use org.mybatis.guice.transactional.Transactional. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractGuacamoleTunnelService.java    From guacamole-client with Apache License 2.0 6 votes vote down vote up
@Override
@Transactional
public GuacamoleTunnel getGuacamoleTunnel(RemoteAuthenticatedUser user,
        SharedConnectionDefinition definition,
        GuacamoleClientInformation info, Map<String, String> tokens)
        throws GuacamoleException {

    // Create a connection record which describes the shared connection
    ActiveConnectionRecord connectionRecord = activeConnectionRecordProvider.get();
    connectionRecord.init(user, definition.getActiveConnection(),
            definition.getSharingProfile());

    // Connect to shared connection described by the created record
    GuacamoleTunnel tunnel = assignGuacamoleTunnel(connectionRecord, info, tokens, false);

    // Register tunnel, such that it is closed when the
    // SharedConnectionDefinition is invalidated
    definition.registerTunnel(tunnel);
    return tunnel;

}
 
Example #2
Source File: DeviceDAO.java    From hmdm-server with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Updates the device data in persistent data store. The reference to related customer account and last update
 * time of the device are not affected by this method.</p>
 *
 * @param device a device to be updated.
 * @throws SecurityException if current user is not authorized to update this device.
 */
@Transactional
public void updateDevice(Device device) {
    updateById(device.getId(), this.mapper::getDeviceById, dbDevice -> {
        device.setCustomerId(dbDevice.getCustomerId());

        final Integer currentUserId = SecurityContext.get().getCurrentUser().get().getId();
        this.mapper.updateDevice(device);
        this.mapper.removeDeviceGroupsByDeviceId(currentUserId, device.getCustomerId(), device.getId());
        if (device.getGroups() != null && !device.getGroups().isEmpty()) {
            this.mapper.insertDeviceGroups(
                    device.getId(), device.getGroups().stream().map(LookupItem::getId).collect(Collectors.toList())
            );
        }
    }, SecurityException::onDeviceAccessViolation);
}
 
Example #3
Source File: EntityService.java    From guacamole-client with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the set of all group identifiers of which the given entity is a
 * member, taking into account the given collection of known group
 * memberships which are not necessarily defined within the database.
 * 
 * Note that group visibility with respect to the queried entity is NOT
 * taken into account. If the entity is a member of a group, the identifier
 * of that group will be included in the returned set even if the current
 * user lacks "READ" permission for that group.
 *
 * @param entity
 *     The entity whose effective groups should be returned.
 *
 * @param effectiveGroups
 *     The identifiers of any known effective groups that should be taken
 *     into account, such as those defined externally to the database.
 *
 * @return
 *     The set of identifiers of all groups that the given entity is a
 *     member of, including those where membership is inherited through
 *     membership in other groups.
 */
@Transactional
public Set<String> retrieveEffectiveGroups(ModeledPermissions<? extends EntityModel> entity,
        Collection<String> effectiveGroups) {

    // Retrieve the effective user groups of the given entity, recursively if possible
    boolean recursive = environment.isRecursiveQuerySupported(sqlSession);
    Set<String> identifiers = entityMapper.selectEffectiveGroupIdentifiers(entity.getModel(), effectiveGroups, recursive);

    // If the set of user groups retrieved was not produced recursively,
    // manually repeat the query to expand the set until all effective
    // groups have been found
    if (!recursive && !identifiers.isEmpty()) {
        Set<String> previousIdentifiers;
        do {
            previousIdentifiers = identifiers;
            identifiers = entityMapper.selectEffectiveGroupIdentifiers(entity.getModel(), previousIdentifiers, false);
        } while (identifiers.size() > previousIdentifiers.size());
    }

    return identifiers;

}
 
Example #4
Source File: ModeledDirectoryObjectService.java    From guacamole-client with Apache License 2.0 6 votes vote down vote up
@Override
@Transactional
public void updateObject(ModeledAuthenticatedUser user, InternalType object)
    throws GuacamoleException {

    ModelType model = object.getModel();
    beforeUpdate(user, object, model);
    
    // Update object
    getObjectMapper().update(model);

    // Replace any existing arbitrary attributes
    getObjectMapper().deleteAttributes(model);
    if (model.hasArbitraryAttributes())
        getObjectMapper().insertAttributes(model);

}
 
Example #5
Source File: ModeledDirectoryObjectService.java    From guacamole-client with Apache License 2.0 6 votes vote down vote up
@Override
@Transactional
public InternalType createObject(ModeledAuthenticatedUser user, ExternalType object)
    throws GuacamoleException {

    ModelType model = getModelInstance(user, object);
    beforeCreate(user, object, model);
    
    // Create object
    getObjectMapper().insert(model);

    // Set identifier on original object
    object.setIdentifier(model.getIdentifier());

    // Add implicit permissions
    Collection<ObjectPermissionModel> implicitPermissions = getImplicitPermissions(user, model);
    if (!implicitPermissions.isEmpty())
        getPermissionMapper().insert(implicitPermissions);

    // Add any arbitrary attributes
    if (model.hasArbitraryAttributes())
        getObjectMapper().insertAttributes(model);

    return getObjectInstance(user, model);

}
 
Example #6
Source File: ApplicationDAO.java    From hmdm-server with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Removes the application referenced by the specified ID. The associated application versions are removed as
 * well.</p>
 *
 * @param id an ID of an application to delete.
 * @throws SecurityException if current user is not granted a permission to delete the specified application.
 */
@Transactional
public void removeApplicationById(Integer id) {
    Application dbApplication = this.mapper.findById(id);
    if (dbApplication != null && dbApplication.isCommonApplication()) {
        if (!SecurityContext.get().isSuperAdmin()) {
            throw SecurityException.onAdminDataAccessViolation("delete common application");
        }
    }

    boolean used = this.mapper.isApplicationUsedInConfigurations(id);
    if (used) {
        throw new ApplicationReferenceExistsException(id, "configurations");
    }

    updateById(
            id,
            this::findById,
            (record) -> this.mapper.removeApplicationById(record.getId()),
            SecurityException::onApplicationAccessViolation
    );
}
 
Example #7
Source File: ServicesStackController.java    From apollo with Apache License 2.0 6 votes vote down vote up
@LoggedIn
@Transactional
@PUT("/services-stack")
public void updateServicesStack(int id, String name, boolean isEnabled, String servicesCsv, Req req) {
    List<Integer> servicesIds = StringParser.splitCsvToIntegerList(servicesCsv);
    if (servicesIds.size() <= 0) {
        assignJsonResponseToReq(req, HttpStatus.BAD_REQUEST, "The ServicesStack you asked to update has an empty services list");
        return;
    }
    servicesIds.forEach(serviceId -> {
        if (serviceDao.getService(id).getIsPartOfGroup()) {
            assignJsonResponseToReq(req, HttpStatus.BAD_REQUEST, "Can't add to stack service that is part of a group");
            return;
        }
    });
    ServicesStack servicesStack = new ServicesStack(id, name, isEnabled);
    stackDao.updateStack(servicesStack);
    servicesStackDao.clearServicesStack(id);
    servicesStackDao.addServicesToStack(servicesIds, id);
    assignJsonResponseToReq(req, HttpStatus.OK, getServicesStack(id));
}
 
Example #8
Source File: ConfigurationDAO.java    From hmdm-server with Apache License 2.0 6 votes vote down vote up
@Transactional
public Configuration getConfigurationByIdFull(Integer id) {
    final Configuration configuration = getSingleRecord(() -> this.mapper.getConfigurationById(id), SecurityException::onConfigurationAccessViolation);
    if (configuration != null) {
        final List<ApplicationSetting> appSettings = this.applicationSettingDAO.getApplicationSettingsByConfigurationId(id);
        configuration.setApplicationSettings(appSettings);

        final List<ConfigurationApplicationParameters> applicationParameters = this.mapper.getApplicationParameters(id);
        configuration.setApplicationUsageParameters(applicationParameters);

        final List<ConfigurationFile> files = this.configurationFileDAO.getConfigurationFiles(id);
        configuration.setFiles(files);

    }

    return configuration;
}
 
Example #9
Source File: ServicesStackController.java    From apollo with Apache License 2.0 6 votes vote down vote up
@LoggedIn
@Transactional
@POST("/services-stack")
public void addServicesStack(String name, boolean isEnabled, String servicesCsv, Req req) {
    List<Integer> servicesIds = StringParser.splitCsvToIntegerList(servicesCsv);
    ServicesStack servicesStack = new ServicesStack(name, isEnabled);
    stackDao.addStack(servicesStack);
    if (servicesIds.size() > 0) {
        servicesIds.forEach(id -> {
            if (serviceDao.getService(id).getIsPartOfGroup()) {
                assignJsonResponseToReq(req, HttpStatus.BAD_REQUEST, "Can't add to stack service that is part of a group");
                return;
            }
        });
        servicesStackDao.addServicesToStack(servicesIds, servicesStack.getId());
    }
    assignJsonResponseToReq(req, HttpStatus.CREATED, getServicesStack(servicesStack.getId()));
}
 
Example #10
Source File: PushService.java    From hmdm-server with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Sends the messages on configuration update for the devices related to specified configuration.</p>
 *
 * @param configurationId an ID of updated configuration.
 */
@Transactional
public void notifyDevicesOnUpdate(Integer configurationId) {
    final Configuration configuration = this.configurationDAO.getConfigurationById(configurationId);
    if (configuration != null) {
        final List<Device> devices
                = this.deviceDAO.getDeviceIdsByConfigurationId(configurationId);
        devices.forEach(device -> {
            PushMessage message = new PushMessage();
            message.setDeviceId(device.getId());
            message.setMessageType(PushMessage.TYPE_CONFIG_UPDATED);

            this.send(message);
        });
    }
}
 
Example #11
Source File: PostgresDeviceLogPluginSettingsDAO.java    From hmdm-server with Apache License 2.0 5 votes vote down vote up
@Transactional
public void deletePluginSettingRule(int id) {
    final PostgresDeviceLogPluginSettings settings = getSingleRecord(
            () -> this.mapper.getPluginSettingsByRuleIdForAuthorization(id),
            (s) -> SecurityException.onCustomerDataAccessViolation(id, "pluginDeviceLogRule")
    );

    if (settings != null) {
        this.mapper.deletePluginSettingRule(id);
    }
}
 
Example #12
Source File: EnvironmentsStackController.java    From apollo with Apache License 2.0 5 votes vote down vote up
@LoggedIn
@Transactional
@PUT("/environments-stack")
public void updateEnvironmentsStack(int id, String name, boolean isEnabled, String environmentsCsv, Req req) {
    List<Integer> environmentsIds = StringParser.splitCsvToIntegerList(environmentsCsv);
    if (environmentsIds.size() <= 0) {
        assignJsonResponseToReq(req, HttpStatus.BAD_REQUEST, "The EnvironmentsStack you asked to update has an empty environments list");
        return;
    }
    EnvironmentsStack environmentsStack = new EnvironmentsStack(id, name, isEnabled);
    stackDao.updateStack(environmentsStack);
    environmentsStackDao.clearEnvironmentsStack(id);
    environmentsStackDao.addEnvironmentsToStack(environmentsIds, id);
    assignJsonResponseToReq(req, HttpStatus.OK, getEnvironmentsStack(id));
}
 
Example #13
Source File: PostgresDeviceLogPluginSettingsDAO.java    From hmdm-server with Apache License 2.0 5 votes vote down vote up
@Override
@Transactional
public void savePluginSettingsRule(@NotNull DeviceLogRule rule) {
    PostgresDeviceLogPluginSettings postgresSettings = (PostgresDeviceLogPluginSettings) getPluginSettings();
    if (postgresSettings != null) {
        PostgresDeviceLogRule postgresRule = (PostgresDeviceLogRule) rule;

        postgresRule.setSettingId(postgresSettings.getId());

        if (postgresRule.getId() == null) {
            this.mapper.insertPluginSettingsRule(postgresRule);
        } else {
            this.mapper.updatePluginSettingsRule(postgresRule);
        }


        this.mapper.deletePluginSettingsRuleDevices(postgresRule.getId());
        if (postgresRule.getDevices() != null && !postgresRule.getDevices().isEmpty()) {
            final List<Integer> deviceIds = postgresRule.getDevices()
                    .stream()
                    .map(LookupItem::getId)
                    .collect(Collectors.toList());
            this.mapper.insertPluginSettingsRuleDevices(postgresRule.getId(), deviceIds);
        }

    } else {
        throw new IllegalStateException("Device Log Plugin settings record is required to be created prior " +
                "to saving the rule: " + rule);
    }
}
 
Example #14
Source File: PostgresDeviceLogDAO.java    From hmdm-server with Apache License 2.0 5 votes vote down vote up
/**
 * <p>Finds the log records matching the specified filter.</p>
 *
 * @param filter a filter used to narrowing down the search results.
 * @return a list of log records matching the specified filter.
 */
@Override
@Transactional
public List<DeviceLogRecord> findAll(DeviceLogFilter filter) {
    prepareFilter(filter);

    final List<PostgresDeviceLogRecord> result = this.getListWithCurrentUser(currentUser -> {
        filter.setCustomerId(currentUser.getCustomerId());
        filter.setUserId(currentUser.getId());
        return this.deviceLogMapper.findAllLogRecordsByCustomerId(filter);
    });

    return new ArrayList<>(result);
}
 
Example #15
Source File: AuditDAO.java    From hmdm-server with Apache License 2.0 5 votes vote down vote up
/**
 * <p>Finds the audit log records matching the specified filter.</p>
 *
 * @param filter a filter used to narrowing down the search results.
 * @return a list of audit log records matching the specified filter.
 */
@Transactional
public List<AuditLogRecord> findAll(AuditLogFilter filter) {
    prepareFilter(filter);

    final List<AuditLogRecord> result = this.getListWithCurrentUser(currentUser -> {
        filter.setCustomerId(currentUser.getCustomerId());
        filter.setUserId(currentUser.getId());
        return this.mapper.findAllLogRecordsByCustomerId(filter);
    });

    return new ArrayList<>(result);
}
 
Example #16
Source File: PluginDAO.java    From hmdm-server with Apache License 2.0 5 votes vote down vote up
/**
 * <p>Disables the specified plugins for customer account assoicated with the current user.</p>
 *
 * @param pluginIds a list of plugin IDs.
 */
@Transactional
public void saveDisabledPlugins(Integer[] pluginIds) {
    SecurityContext.get().getCurrentUser()
            .map(user -> {
                this.pluginMapper.cleanUpDisabledPlugins(user.getCustomerId());
                if (pluginIds.length > 0) {
                    this.pluginMapper.insertDisabledPlugin(pluginIds, user.getCustomerId());
                }
                return 1;
            })
            .orElseThrow(SecurityException::onAnonymousAccess);
}
 
Example #17
Source File: NotificationDAO.java    From hmdm-server with Apache License 2.0 5 votes vote down vote up
/**
 * <p>Sends the specified notification message. This implementation puts it to queue to be retrieved by device later.</p>
 *
 * @param message a message to send.
 * @return an ID of a message.
 */
@Transactional
public int send(PushMessage message) {
    this.notificationMapper.insertPushMessage(message);
    this.notificationMapper.insertPendingPush(message.getId());
    return message.getId();
}
 
Example #18
Source File: NotificationDAO.java    From hmdm-server with Apache License 2.0 5 votes vote down vote up
/**
 * <p>Gets the list of messages to be delivered to specified device. The returned messages are immediately marked as
 * delivered.</p>
 *
 * @param deviceId a device number identifying the device.
 * @return a list of messages to be delivered to device.
 */
@Transactional
public List<PushMessage> getPendingMessagesForDelivery(String deviceId) {
    final List<PushMessage> messages = this.notificationMapper.getPendingMessagesForDelivery(deviceId);
    if (!messages.isEmpty()) {
        final List<Integer> messageIds = messages.stream().map(PushMessage::getId).collect(Collectors.toList());
        this.notificationMapper.markMessagesAsDelivered(messageIds);
    }
    return messages;
}
 
Example #19
Source File: ApplicationDAO.java    From hmdm-server with Apache License 2.0 5 votes vote down vote up
/**
 * <p>Creates new application record in DB.</p>
 *
 * @param application an application record to be created.
 */
@Transactional
public int insertWebApplication(Application application) {
    log.debug("Entering #insertWebApplication: application = {}", application);

    final Optional<Integer> currentCustomerId = SecurityContext.get().getCurrentCustomerId();
    if (currentCustomerId.isPresent()) {
        String pkg;
        Long count;
        do {
            pkg = DigestUtils.sha1Hex(application.getUrl() + System.currentTimeMillis());
            count = this.mapper.countByPackageId(currentCustomerId.get(), pkg);
        } while (count > 0);

        application.setPkg(pkg);
        application.setVersion("0");

        insertRecord(application, this.mapper::insertApplication);

        final ApplicationVersion applicationVersion = new ApplicationVersion(application);

        this.mapper.insertApplicationVersion(applicationVersion);
        this.mapper.recalculateLatestVersion(application.getId());

        return application.getId();
    } else {
        throw SecurityException.onAnonymousAccess();
    }
}
 
Example #20
Source File: ConfigurationDAO.java    From hmdm-server with Apache License 2.0 5 votes vote down vote up
@Transactional
public void removeConfigurationById(Integer id) {
    long count = this.mapper.countDevices(id);
    if (count > 0) {
        throw new ConfigurationReferenceExistsException(id, "devices");
    }

    updateById(
            id,
            this.mapper::getConfigurationById,
            configuration -> this.mapper.removeConfigurationById(configuration.getId()),
            SecurityException::onConfigurationAccessViolation
    );
}
 
Example #21
Source File: MessagingDAO.java    From hmdm-server with Apache License 2.0 5 votes vote down vote up
/**
 * <p>Finds the message records matching the specified filter.</p>
 *
 * @param filter a filter used to narrowing down the search results.
 * @return a list of message records matching the specified filter.
 */
@Transactional
public List<Message> findAll(MessageFilter filter) {
    prepareFilter(filter);

    final List<Message> result = this.getListWithCurrentUser(currentUser -> {
        filter.setCustomerId(currentUser.getCustomerId());
        return this.messageMapper.findAllMessages(filter);
    });

    return new ArrayList<>(result);
}
 
Example #22
Source File: EnvironmentsStackController.java    From apollo with Apache License 2.0 5 votes vote down vote up
@LoggedIn
@Transactional
@GET("/environments-stack/{stackId}")
public EnvironmentsStack getEnvironmentsStack(int stackId) {
    EnvironmentsStack environmentsStack = stackDao.getEnvironmentsStack(stackId);
    environmentsStack.setEnvironments(environmentsStackDao.getEnvironments(stackId));
    return environmentsStack;
}
 
Example #23
Source File: EnvironmentsStackController.java    From apollo with Apache License 2.0 5 votes vote down vote up
@LoggedIn
@Transactional
@POST("/environments-stack")
public void addEnvironmentsStack(String name, boolean isEnabled, String environmentsCsv, Req req) {
    List<Integer> environmentsIds = StringParser.splitCsvToIntegerList(environmentsCsv);
    EnvironmentsStack environmentsStack = new EnvironmentsStack(name, isEnabled);
    stackDao.addStack(environmentsStack);
    if (environmentsIds.size() > 0) {
        environmentsStackDao.addEnvironmentsToStack(environmentsIds, environmentsStack.getId());
    }
    assignJsonResponseToReq(req, HttpStatus.CREATED, getEnvironmentsStack(environmentsStack.getId()));
}
 
Example #24
Source File: UserDAO.java    From hmdm-server with Apache License 2.0 5 votes vote down vote up
@Transactional
public void updatePasswordBySuperAdmin(User user ) {
    if (SecurityContext.get().isSuperAdmin()) {
        this.mapper.updatePassword(user);
    } else {
        throw new IllegalArgumentException("Super-admin is allowed only");
    }
}
 
Example #25
Source File: EnvironmentsStackController.java    From apollo with Apache License 2.0 5 votes vote down vote up
@LoggedIn
@Transactional
@DELETE("/environments-stack/{id}")
public void deleteEnvironmentsStack(int id) {
    environmentsStackDao.clearEnvironmentsStack(id);
    stackDao.deleteStack(id);
}
 
Example #26
Source File: ServicesStackController.java    From apollo with Apache License 2.0 5 votes vote down vote up
@LoggedIn
@Transactional
@GET("/services-stack/{stackId}")
public ServicesStack getServicesStack(int stackId) {
    ServicesStack servicesStack = stackDao.getServicesStack(stackId);
    servicesStack.setServices(servicesStackDao.getServices(stackId));
    return servicesStack;
}
 
Example #27
Source File: ServicesStackController.java    From apollo with Apache License 2.0 5 votes vote down vote up
@LoggedIn
@Transactional
@POST("/services-stack/service")
public void addServiceToStack(int serviceId, int stackId, Req req) {
    if (serviceDao.getService(serviceId).getIsPartOfGroup()) {
        assignJsonResponseToReq(req, HttpStatus.BAD_REQUEST, "Can't add to stack service that is part of a group");
        return;
    }
    servicesStackDao.addServiceToStack(serviceId, stackId);
    assignJsonResponseToReq(req, HttpStatus.CREATED, getServicesStack(stackId));
}
 
Example #28
Source File: ServicesStackController.java    From apollo with Apache License 2.0 5 votes vote down vote up
@LoggedIn
@Transactional
@DELETE("/services-stack/{id}")
public void deleteServicesStack(int id) {
    servicesStackDao.clearServicesStack(id);
    stackDao.deleteStack(id);
}
 
Example #29
Source File: AbstractGuacamoleTunnelService.java    From guacamole-client with Apache License 2.0 5 votes vote down vote up
@Override
@Transactional
public GuacamoleTunnel getGuacamoleTunnel(final ModeledAuthenticatedUser user,
        final ModeledConnection connection, GuacamoleClientInformation info,
        Map<String, String> tokens) throws GuacamoleException {

    // Acquire access to single connection, ignoring the failover-only flag
    acquire(user, Collections.singletonList(connection), true);

    // Connect only if the connection was successfully acquired
    ActiveConnectionRecord connectionRecord = activeConnectionRecordProvider.get();
    connectionRecord.init(user, connection);
    return assignGuacamoleTunnel(connectionRecord, info, tokens, false);

}
 
Example #30
Source File: SharingProfileDirectory.java    From guacamole-client with Apache License 2.0 5 votes vote down vote up
@Override
@Transactional
public Collection<SharingProfile> getAll(Collection<String> identifiers) throws GuacamoleException {
    return Collections.<SharingProfile>unmodifiableCollection(
        sharingProfileService.retrieveObjects(getCurrentUser(), identifiers)
    );
}