Search in sources :

Example 96 with BadRequestException

use of javax.ws.rs.BadRequestException in project openremote by openremote.

the class AssetResourceImpl method createUserAssetLinks.

@Override
public void createUserAssetLinks(RequestParams requestParams, List<UserAssetLink> userAssetLinks) {
    // Restricted users cannot create or delete links
    if (isRestrictedUser()) {
        throw new WebApplicationException(FORBIDDEN);
    }
    // Check all links are for the same user and realm
    String realm = userAssetLinks.get(0).getId().getRealm();
    String userId = userAssetLinks.get(0).getId().getUserId();
    String[] assetIds = new String[userAssetLinks.size()];
    IntStream.range(0, userAssetLinks.size()).forEach(i -> {
        UserAssetLink userAssetLink = userAssetLinks.get(i);
        assetIds[i] = userAssetLink.getId().getAssetId();
        if (!userAssetLink.getId().getRealm().equals(realm) || !userAssetLink.getId().getUserId().equals(userId)) {
            throw new BadRequestException("All user asset links must be for the same user");
        }
    });
    if (!isSuperUser() && !realm.equals(getAuthenticatedRealm())) {
        throw new WebApplicationException(FORBIDDEN);
    }
    if (!identityService.getIdentityProvider().isUserInTenant(userId, realm)) {
        throw new WebApplicationException(FORBIDDEN);
    }
    List<Asset<?>> assets = assetStorageService.findAll(new AssetQuery().select(new AssetQuery.Select().excludeAttributes()).tenant(new TenantPredicate(realm)).ids(assetIds));
    if (assets.size() != userAssetLinks.size()) {
        throw new BadRequestException("One or more asset IDs are invalid");
    }
    try {
        assetStorageService.storeUserAssetLinks(userAssetLinks);
    } catch (Exception e) {
        throw new WebApplicationException(BAD_REQUEST);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) AssetQuery(org.openremote.model.query.AssetQuery) BadRequestException(javax.ws.rs.BadRequestException) Asset(org.openremote.model.asset.Asset) TenantPredicate(org.openremote.model.query.filter.TenantPredicate) UserAssetLink(org.openremote.model.asset.UserAssetLink) BadRequestException(javax.ws.rs.BadRequestException) OptimisticLockException(javax.persistence.OptimisticLockException) ConstraintViolationException(javax.validation.ConstraintViolationException) WebApplicationException(javax.ws.rs.WebApplicationException)

Example 97 with BadRequestException

use of javax.ws.rs.BadRequestException in project openremote by openremote.

the class AssetResourceImpl method queryAssets.

@Override
public Asset<?>[] queryAssets(RequestParams requestParams, AssetQuery query) {
    try {
        query = assetStorageService.prepareAssetQuery(query, getAuthContext(), getRequestRealm());
        List<Asset<?>> result = assetStorageService.findAll(query);
        // Compress response (the request attribute enables the interceptor)
        request.setAttribute(HttpHeaders.CONTENT_ENCODING, "gzip");
        return result.toArray(new Asset[0]);
    } catch (IllegalStateException ex) {
        throw new BadRequestException(ex);
    }
}
Also used : Asset(org.openremote.model.asset.Asset) BadRequestException(javax.ws.rs.BadRequestException)

Example 98 with BadRequestException

use of javax.ws.rs.BadRequestException in project openremote by openremote.

the class ConsoleResourceImpl method register.

@Override
public ConsoleRegistration register(RequestParams requestParams, ConsoleRegistration consoleRegistration) {
    if (getRequestTenant() == null) {
        throw new BadRequestException("Invalid realm");
    }
    ConsoleAsset consoleAsset = null;
    // If console registration has an id and asset exists then ensure asset type is console
    if (!TextUtil.isNullOrEmpty(consoleRegistration.getId())) {
        Asset<?> existingAsset = assetStorageService.find(consoleRegistration.getId(), true);
        if (existingAsset != null && !(existingAsset instanceof ConsoleAsset)) {
            throw new BadRequestException("Console registration ID is not for a Console asset: " + consoleRegistration.getId());
        }
        consoleAsset = (ConsoleAsset) existingAsset;
    }
    if (consoleAsset == null) {
        consoleAsset = initConsoleAsset(consoleRegistration, true, true);
        consoleAsset.setRealm(getRequestRealm());
        consoleAsset.setParentId(getConsoleParentAssetId(getRequestRealm()));
        consoleAsset.setId(consoleRegistration.getId());
    }
    consoleAsset.setConsoleName(consoleRegistration.getName()).setConsoleVersion(consoleRegistration.getVersion()).setConsoleProviders(new ConsoleProviders(consoleRegistration.getProviders())).setConsolePlatform(consoleRegistration.getPlatform());
    consoleAsset = assetStorageService.merge(consoleAsset);
    consoleRegistration.setId(consoleAsset.getId());
    // If authenticated link the console to this user
    if (isAuthenticated()) {
        assetStorageService.storeUserAssetLinks(Collections.singletonList(new UserAssetLink(getAuthenticatedRealm(), getUserId(), consoleAsset.getId())));
    }
    return consoleRegistration;
}
Also used : ConsoleAsset(org.openremote.model.asset.impl.ConsoleAsset) ConsoleProviders(org.openremote.model.console.ConsoleProviders) BadRequestException(javax.ws.rs.BadRequestException) UserAssetLink(org.openremote.model.asset.UserAssetLink)

Example 99 with BadRequestException

use of javax.ws.rs.BadRequestException in project kylo by Teradata.

the class DataSetController method updateDataSet.

@PUT
@ApiOperation("Updates an existing data set")
@ApiResponses({ @ApiResponse(code = 200, message = "Data set updated", response = DataSet.class), @ApiResponse(code = 400, message = "Invalid data source", response = RestResponseStatus.class), @ApiResponse(code = 500, message = "Internal server error", response = RestResponseStatus.class) })
@Path("{id}")
@Consumes(MediaType.APPLICATION_JSON)
public Response updateDataSet(@Nonnull final DataSet source) {
    log.entry(source);
    final boolean encryptCredentials = true;
    final DataSet dataSet;
    try {
        dataSet = dataSetService.updateDataSet(source, encryptCredentials);
    } catch (final CatalogException e) {
        throw new BadRequestException(getMessage(e));
    }
    return Response.ok(log.exit(dataSet)).build();
}
Also used : DataSet(com.thinkbiganalytics.kylo.catalog.rest.model.DataSet) CatalogException(com.thinkbiganalytics.kylo.catalog.CatalogException) BadRequestException(javax.ws.rs.BadRequestException) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) ApiOperation(io.swagger.annotations.ApiOperation) PUT(javax.ws.rs.PUT) ApiResponses(io.swagger.annotations.ApiResponses)

Example 100 with BadRequestException

use of javax.ws.rs.BadRequestException in project kylo by Teradata.

the class DataSourceController method testDataSource.

@POST
@ApiOperation("Tests datasource")
@ApiResponses({ @ApiResponse(code = 204, message = "Data source test successful", response = DataSource.class), @ApiResponse(code = 400, message = "Invalid datasource", response = RestResponseStatus.class), @ApiResponse(code = 500, message = "Internal server error", response = RestResponseStatus.class) })
@Consumes(MediaType.APPLICATION_JSON)
@Path("/test")
public Response testDataSource(@Nonnull final DataSource dataSource) {
    log.entry(dataSource);
    String pluginId = dataSource.getConnector().getPluginId();
    Optional<ConnectorPlugin> plugin = this.pluginManager.getPlugin(pluginId);
    if (!plugin.isPresent()) {
        throw new BadRequestException(getMessage("catalog.datasource.testDataSource.connectorPluginNotFound", pluginId));
    }
    List<ConnectorTab> tabs = plugin.get().getDescriptor().getTabs();
    if (tabs == null) {
        throw new BadRequestException(getMessage("catalog.datasource.testDataSource.testNotAvailableForPlugin", pluginId));
    }
    ConnectorTab connectorTab = tabs.get(0);
    String sref = connectorTab.getSref();
    DataSource decrypted = modelTransform.decryptOptions(dataSource);
    if (".browse".equals(sref)) {
        doListFiles(DataSourceUtil.getPaths(decrypted).orElseThrow(IllegalStateException::new).get(0), decrypted);
    } else if (".connection".equals(sref)) {
        doListTables(null, null, decrypted);
    } else {
        throw new BadRequestException(getMessage("catalog.datasource.testDataSource.testNotAvailableForTab", sref));
    }
    log.exit();
    return Response.noContent().build();
}
Also used : ConnectorPlugin(com.thinkbiganalytics.kylo.catalog.spi.ConnectorPlugin) BadRequestException(javax.ws.rs.BadRequestException) ConnectorTab(com.thinkbiganalytics.kylo.catalog.rest.model.ConnectorTab) DataSource(com.thinkbiganalytics.kylo.catalog.rest.model.DataSource) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Aggregations

BadRequestException (javax.ws.rs.BadRequestException)238 Path (javax.ws.rs.Path)92 ApiOperation (io.swagger.annotations.ApiOperation)80 POST (javax.ws.rs.POST)65 Consumes (javax.ws.rs.Consumes)61 Produces (javax.ws.rs.Produces)55 AuditEvent (org.graylog2.audit.jersey.AuditEvent)52 NotFoundException (javax.ws.rs.NotFoundException)42 Timed (com.codahale.metrics.annotation.Timed)40 PUT (javax.ws.rs.PUT)40 ApiResponses (io.swagger.annotations.ApiResponses)38 Test (org.junit.Test)34 GET (javax.ws.rs.GET)32 IOException (java.io.IOException)30 Response (javax.ws.rs.core.Response)27 RequiresPermissions (org.apache.shiro.authz.annotation.RequiresPermissions)27 InternalServerErrorException (javax.ws.rs.InternalServerErrorException)26 NoAuditEvent (org.graylog2.audit.jersey.NoAuditEvent)26 URI (java.net.URI)24 HashMap (java.util.HashMap)22