Search in sources :

Example 26 with PathParam

use of javax.ws.rs.PathParam in project streamline by hortonworks.

the class NamespaceCatalogResource method unmapAllServicesToClusterInNamespace.

@DELETE
@Path("/namespaces/{id}/mapping")
@Timed
public Response unmapAllServicesToClusterInNamespace(@PathParam("id") Long namespaceId, @Context SecurityContext securityContext) {
    SecurityUtil.checkRoleOrPermissions(authorizer, securityContext, Roles.ROLE_ENVIRONMENT_SUPER_ADMIN, Namespace.NAMESPACE, namespaceId, WRITE);
    Namespace namespace = environmentService.getNamespace(namespaceId);
    if (namespace == null) {
        throw EntityNotFoundException.byId(namespaceId.toString());
    }
    String streamingEngine = namespace.getStreamingEngine();
    Collection<NamespaceServiceClusterMap> mappings = environmentService.listServiceClusterMapping(namespaceId);
    boolean containsStreamingEngine = mappings.stream().anyMatch(m -> m.getServiceName().equals(streamingEngine));
    if (containsStreamingEngine) {
        assertNoTopologyReferringNamespaceIsRunning(namespaceId, WSUtils.getUserFromSecurityContext(securityContext));
    }
    List<NamespaceServiceClusterMap> removed = mappings.stream().map((x) -> environmentService.removeServiceClusterMapping(x.getNamespaceId(), x.getServiceName(), x.getClusterId())).collect(toList());
    return WSUtils.respondEntities(removed, OK);
}
Also used : Topology(com.hortonworks.streamline.streams.catalog.Topology) Roles(com.hortonworks.streamline.streams.security.Roles) Produces(javax.ws.rs.Produces) BadRequestException(com.hortonworks.streamline.common.exception.service.exception.request.BadRequestException) QueryParam(com.hortonworks.registries.common.QueryParam) LoggerFactory(org.slf4j.LoggerFactory) Path(javax.ws.rs.Path) SecurityContext(javax.ws.rs.core.SecurityContext) StringUtils(org.apache.commons.lang3.StringUtils) BooleanUtils(org.apache.commons.lang.BooleanUtils) MediaType(javax.ws.rs.core.MediaType) WSUtils(com.hortonworks.streamline.common.util.WSUtils) READ(com.hortonworks.streamline.streams.security.Permission.READ) StreamlineAuthorizer(com.hortonworks.streamline.streams.security.StreamlineAuthorizer) EnumSet(java.util.EnumSet) DELETE(javax.ws.rs.DELETE) SecurityUtil(com.hortonworks.streamline.streams.security.SecurityUtil) Namespace(com.hortonworks.streamline.streams.cluster.catalog.Namespace) Context(javax.ws.rs.core.Context) Permission(com.hortonworks.streamline.streams.security.Permission) DELETE(com.hortonworks.streamline.streams.security.Permission.DELETE) OK(javax.ws.rs.core.Response.Status.OK) AlreadyExistsException(com.hortonworks.registries.storage.exception.AlreadyExistsException) Collection(java.util.Collection) Objects(java.util.Objects) Timed(com.codahale.metrics.annotation.Timed) List(java.util.List) Response(javax.ws.rs.core.Response) ProcessingException(javax.ws.rs.ProcessingException) Optional(java.util.Optional) UriInfo(javax.ws.rs.core.UriInfo) CREATED(javax.ws.rs.core.Response.Status.CREATED) NamespaceServiceClusterMap(com.hortonworks.streamline.streams.cluster.catalog.NamespaceServiceClusterMap) PathParam(javax.ws.rs.PathParam) EntityNotFoundException(com.hortonworks.streamline.common.exception.service.exception.request.EntityNotFoundException) GET(javax.ws.rs.GET) ArrayList(java.util.ArrayList) EnvironmentService(com.hortonworks.streamline.streams.cluster.service.EnvironmentService) TopologyNotAliveException(com.hortonworks.streamline.streams.exception.TopologyNotAliveException) WRITE(com.hortonworks.streamline.streams.security.Permission.WRITE) Logger(org.slf4j.Logger) POST(javax.ws.rs.POST) TopologyActionsService(com.hortonworks.streamline.streams.actions.topology.service.TopologyActionsService) IOException(java.io.IOException) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Collectors.toList(java.util.stream.Collectors.toList) StreamCatalogService(com.hortonworks.streamline.streams.catalog.service.StreamCatalogService) PUT(javax.ws.rs.PUT) Collections(java.util.Collections) NamespaceServiceClusterMap(com.hortonworks.streamline.streams.cluster.catalog.NamespaceServiceClusterMap) Namespace(com.hortonworks.streamline.streams.cluster.catalog.Namespace) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) DELETE(com.hortonworks.streamline.streams.security.Permission.DELETE) Timed(com.codahale.metrics.annotation.Timed)

Example 27 with PathParam

use of javax.ws.rs.PathParam in project streamline by hortonworks.

the class ServiceCatalogResource method registerService.

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/clusters/{clusterId}/services/register/{serviceName}")
@Timed
public Response registerService(@PathParam("clusterId") Long clusterId, @PathParam("serviceName") String serviceName, FormDataMultiPart form) {
    ServiceBundle serviceBundle = environmentService.getServiceBundleByName(serviceName);
    if (serviceBundle == null) {
        throw BadRequestException.message("Not supported service: " + serviceName);
    }
    ManualServiceRegistrar registrar;
    try {
        Class<?> clazz = Class.forName(serviceBundle.getRegisterClass());
        registrar = (ManualServiceRegistrar) clazz.newInstance();
    } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
        throw new RuntimeException(e);
    }
    Cluster cluster = environmentService.getCluster(clusterId);
    if (cluster == null) {
        throw EntityNotFoundException.byId("Cluster " + clusterId);
    }
    Service service = environmentService.getServiceByName(clusterId, serviceName);
    if (service != null) {
        throw EntityAlreadyExistsException.byName("Service " + serviceName + " is already exist in Cluster " + clusterId);
    }
    registrar.init(environmentService);
    ComponentUISpecification specification = serviceBundle.getServiceUISpecification();
    List<String> fileFieldNames = specification.getFields().stream().filter(uiField -> uiField.getType().equals(ComponentUISpecification.UIFieldType.FILE)).map(uiField -> uiField.getFieldName()).collect(toList());
    Map<String, List<FormDataBodyPart>> fields = form.getFields();
    List<FormDataBodyPart> cfgFormList = fields.getOrDefault("config", Collections.emptyList());
    Config config;
    if (!cfgFormList.isEmpty()) {
        String jsonConfig = cfgFormList.get(0).getEntityAs(String.class);
        try {
            config = objectMapper.readValue(jsonConfig, Config.class);
        } catch (IOException e) {
            throw BadRequestException.message("config is missing");
        }
    } else {
        config = new Config();
    }
    List<ManualServiceRegistrar.ConfigFileInfo> configFileInfos = fields.entrySet().stream().filter(entry -> fileFieldNames.contains(entry.getKey())).flatMap(entry -> {
        String key = entry.getKey();
        List<FormDataBodyPart> values = entry.getValue();
        return values.stream().map(val -> new ManualServiceRegistrar.ConfigFileInfo(key, val.getEntityAs(InputStream.class)));
    }).collect(toList());
    try {
        Service registeredService = registrar.register(cluster, config, configFileInfos);
        return WSUtils.respondEntity(buildManualServiceRegisterResult(registeredService), CREATED);
    } catch (IllegalArgumentException e) {
        throw BadRequestException.message(e.getMessage());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : Produces(javax.ws.rs.Produces) BadRequestException(com.hortonworks.streamline.common.exception.service.exception.request.BadRequestException) QueryParam(com.hortonworks.registries.common.QueryParam) LoggerFactory(org.slf4j.LoggerFactory) Path(javax.ws.rs.Path) SecurityContext(javax.ws.rs.core.SecurityContext) ComponentUISpecification(com.hortonworks.streamline.common.ComponentUISpecification) MediaType(javax.ws.rs.core.MediaType) Consumes(javax.ws.rs.Consumes) Map(java.util.Map) WSUtils(com.hortonworks.streamline.common.util.WSUtils) FormDataBodyPart(org.glassfish.jersey.media.multipart.FormDataBodyPart) READ(com.hortonworks.streamline.streams.security.Permission.READ) StreamlineAuthorizer(com.hortonworks.streamline.streams.security.StreamlineAuthorizer) DELETE(javax.ws.rs.DELETE) Config(com.hortonworks.streamline.common.Config) SecurityUtil(com.hortonworks.streamline.streams.security.SecurityUtil) Context(javax.ws.rs.core.Context) ServiceWithComponents(com.hortonworks.streamline.streams.cluster.model.ServiceWithComponents) OK(javax.ws.rs.core.Response.Status.OK) Collection(java.util.Collection) Timed(com.codahale.metrics.annotation.Timed) List(java.util.List) Service(com.hortonworks.streamline.streams.cluster.catalog.Service) Response(javax.ws.rs.core.Response) UriInfo(javax.ws.rs.core.UriInfo) Cluster(com.hortonworks.streamline.streams.cluster.catalog.Cluster) CREATED(javax.ws.rs.core.Response.Status.CREATED) PathParam(javax.ws.rs.PathParam) EntityNotFoundException(com.hortonworks.streamline.common.exception.service.exception.request.EntityNotFoundException) GET(javax.ws.rs.GET) ServiceBundle(com.hortonworks.streamline.streams.cluster.catalog.ServiceBundle) FormDataMultiPart(org.glassfish.jersey.media.multipart.FormDataMultiPart) ArrayList(java.util.ArrayList) EnvironmentService(com.hortonworks.streamline.streams.cluster.service.EnvironmentService) ServiceConfiguration(com.hortonworks.streamline.streams.cluster.catalog.ServiceConfiguration) WRITE(com.hortonworks.streamline.streams.security.Permission.WRITE) Logger(org.slf4j.Logger) POST(javax.ws.rs.POST) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) EntityAlreadyExistsException(com.hortonworks.streamline.common.exception.service.exception.request.EntityAlreadyExistsException) Component(com.hortonworks.streamline.streams.cluster.catalog.Component) ManualServiceRegistrar(com.hortonworks.streamline.streams.cluster.register.ManualServiceRegistrar) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Collectors.toList(java.util.stream.Collectors.toList) PUT(javax.ws.rs.PUT) Collections(java.util.Collections) InputStream(java.io.InputStream) Config(com.hortonworks.streamline.common.Config) InputStream(java.io.InputStream) Cluster(com.hortonworks.streamline.streams.cluster.catalog.Cluster) Service(com.hortonworks.streamline.streams.cluster.catalog.Service) EnvironmentService(com.hortonworks.streamline.streams.cluster.service.EnvironmentService) IOException(java.io.IOException) ManualServiceRegistrar(com.hortonworks.streamline.streams.cluster.register.ManualServiceRegistrar) ServiceBundle(com.hortonworks.streamline.streams.cluster.catalog.ServiceBundle) FormDataBodyPart(org.glassfish.jersey.media.multipart.FormDataBodyPart) List(java.util.List) ArrayList(java.util.ArrayList) Collectors.toList(java.util.stream.Collectors.toList) ComponentUISpecification(com.hortonworks.streamline.common.ComponentUISpecification) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Timed(com.codahale.metrics.annotation.Timed)

Example 28 with PathParam

use of javax.ws.rs.PathParam in project presto by prestodb.

the class TaskResource method getResults.

@GET
@Path("{taskId}/results/{bufferId}/{token}")
@Produces(PRESTO_PAGES)
public void getResults(@PathParam("taskId") TaskId taskId, @PathParam("bufferId") OutputBufferId bufferId, @PathParam("token") final long token, @HeaderParam(PRESTO_MAX_SIZE) DataSize maxSize, @Suspended AsyncResponse asyncResponse) {
    requireNonNull(taskId, "taskId is null");
    requireNonNull(bufferId, "bufferId is null");
    long start = System.nanoTime();
    ListenableFuture<BufferResult> bufferResultFuture = taskManager.getTaskResults(taskId, bufferId, token, maxSize);
    Duration waitTime = randomizeWaitTime(DEFAULT_MAX_WAIT_TIME);
    bufferResultFuture = addTimeout(bufferResultFuture, () -> BufferResult.emptyResults(taskManager.getTaskInstanceId(taskId), token, false), waitTime, timeoutExecutor);
    ListenableFuture<Response> responseFuture = Futures.transform(bufferResultFuture, result -> {
        List<SerializedPage> serializedPages = result.getSerializedPages();
        GenericEntity<?> entity = null;
        Status status;
        if (serializedPages.isEmpty()) {
            status = Status.NO_CONTENT;
        } else {
            entity = new GenericEntity<>(serializedPages, new TypeToken<List<Page>>() {
            }.getType());
            status = Status.OK;
        }
        return Response.status(status).entity(entity).header(PRESTO_TASK_INSTANCE_ID, result.getTaskInstanceId()).header(PRESTO_PAGE_TOKEN, result.getToken()).header(PRESTO_PAGE_NEXT_TOKEN, result.getNextToken()).header(PRESTO_BUFFER_COMPLETE, result.isBufferComplete()).build();
    }, directExecutor());
    // For hard timeout, add an additional time to max wait for thread scheduling contention and GC
    Duration timeout = new Duration(waitTime.toMillis() + ADDITIONAL_WAIT_TIME.toMillis(), MILLISECONDS);
    bindAsyncResponse(asyncResponse, responseFuture, responseExecutor).withTimeout(timeout, Response.status(Status.NO_CONTENT).header(PRESTO_TASK_INSTANCE_ID, taskManager.getTaskInstanceId(taskId)).header(PRESTO_PAGE_TOKEN, token).header(PRESTO_PAGE_NEXT_TOKEN, token).header(PRESTO_BUFFER_COMPLETE, false).build());
    responseFuture.addListener(() -> readFromOutputBufferTime.add(Duration.nanosSince(start)), directExecutor());
    asyncResponse.register((CompletionCallback) throwable -> resultsRequestTime.add(Duration.nanosSince(start)));
}
Also used : TaskStatus(com.facebook.presto.execution.TaskStatus) Status(javax.ws.rs.core.Response.Status) JsonCodec(com.facebook.airlift.json.JsonCodec) Page(com.facebook.presto.common.Page) RolesAllowed(javax.annotation.security.RolesAllowed) Produces(javax.ws.rs.Produces) Iterables.transform(com.google.common.collect.Iterables.transform) TaskStatus(com.facebook.presto.execution.TaskStatus) SerializedPage(com.facebook.presto.spi.page.SerializedPage) Path(javax.ws.rs.Path) TaskState(com.facebook.presto.execution.TaskState) OutputBufferId(com.facebook.presto.execution.buffer.OutputBuffers.OutputBufferId) APPLICATION_THRIFT_COMPACT(com.facebook.airlift.http.client.thrift.ThriftRequestUtils.APPLICATION_THRIFT_COMPACT) Duration(io.airlift.units.Duration) DEFAULT_MAX_WAIT_TIME(com.facebook.presto.util.TaskUtils.DEFAULT_MAX_WAIT_TIME) PlanFragment(com.facebook.presto.sql.planner.PlanFragment) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) DefaultValue(javax.ws.rs.DefaultValue) HeaderParam(javax.ws.rs.HeaderParam) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) BufferResult(com.facebook.presto.execution.buffer.BufferResult) DELETE(javax.ws.rs.DELETE) PRESTO_PAGE_TOKEN(com.facebook.presto.client.PrestoHeaders.PRESTO_PAGE_TOKEN) Context(javax.ws.rs.core.Context) MetadataUpdates(com.facebook.presto.metadata.MetadataUpdates) AsyncResponse(javax.ws.rs.container.AsyncResponse) APPLICATION_JACKSON_SMILE(com.facebook.presto.PrestoMediaTypes.APPLICATION_JACKSON_SMILE) GenericEntity(javax.ws.rs.core.GenericEntity) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Suspended(javax.ws.rs.container.Suspended) Codec(com.facebook.airlift.json.Codec) MoreExecutors.directExecutor(com.google.common.util.concurrent.MoreExecutors.directExecutor) DataSize(io.airlift.units.DataSize) List(java.util.List) Response(javax.ws.rs.core.Response) CompletionCallback(javax.ws.rs.container.CompletionCallback) PRESTO_BUFFER_COMPLETE(com.facebook.presto.client.PrestoHeaders.PRESTO_BUFFER_COMPLETE) UriInfo(javax.ws.rs.core.UriInfo) APPLICATION_THRIFT_BINARY(com.facebook.airlift.http.client.thrift.ThriftRequestUtils.APPLICATION_THRIFT_BINARY) PRESTO_CURRENT_STATE(com.facebook.presto.client.PrestoHeaders.PRESTO_CURRENT_STATE) TaskUtils.randomizeWaitTime(com.facebook.presto.util.TaskUtils.randomizeWaitTime) Nested(org.weakref.jmx.Nested) PathParam(javax.ws.rs.PathParam) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) GET(javax.ws.rs.GET) TypeToken(com.google.common.reflect.TypeToken) Inject(javax.inject.Inject) PRESTO_TASK_INSTANCE_ID(com.facebook.presto.client.PrestoHeaders.PRESTO_TASK_INSTANCE_ID) TimeStat(com.facebook.airlift.stats.TimeStat) BoundedExecutor(com.facebook.airlift.concurrent.BoundedExecutor) MoreFutures.addTimeout(com.facebook.airlift.concurrent.MoreFutures.addTimeout) ImmutableList(com.google.common.collect.ImmutableList) Managed(org.weakref.jmx.Managed) PRESTO_MAX_SIZE(com.facebook.presto.client.PrestoHeaders.PRESTO_MAX_SIZE) SmileCodec(com.facebook.airlift.json.smile.SmileCodec) TaskManager(com.facebook.presto.execution.TaskManager) Objects.requireNonNull(java.util.Objects.requireNonNull) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) INTERNAL(com.facebook.presto.server.security.RoleType.INTERNAL) APPLICATION_THRIFT_FB_COMPACT(com.facebook.airlift.http.client.thrift.ThriftRequestUtils.APPLICATION_THRIFT_FB_COMPACT) PRESTO_PAGE_NEXT_TOKEN(com.facebook.presto.client.PrestoHeaders.PRESTO_PAGE_NEXT_TOKEN) SessionPropertyManager(com.facebook.presto.metadata.SessionPropertyManager) Status(javax.ws.rs.core.Response.Status) POST(javax.ws.rs.POST) AsyncResponseHandler.bindAsyncResponse(com.facebook.airlift.http.server.AsyncResponseHandler.bindAsyncResponse) Executor(java.util.concurrent.Executor) Session(com.facebook.presto.Session) PRESTO_MAX_WAIT(com.facebook.presto.client.PrestoHeaders.PRESTO_MAX_WAIT) Futures(com.google.common.util.concurrent.Futures) PRESTO_PAGES(com.facebook.presto.PrestoMediaTypes.PRESTO_PAGES) TaskId(com.facebook.presto.execution.TaskId) TaskInfo(com.facebook.presto.execution.TaskInfo) SECONDS(java.util.concurrent.TimeUnit.SECONDS) Duration(io.airlift.units.Duration) AsyncResponse(javax.ws.rs.container.AsyncResponse) Response(javax.ws.rs.core.Response) AsyncResponseHandler.bindAsyncResponse(com.facebook.airlift.http.server.AsyncResponseHandler.bindAsyncResponse) BufferResult(com.facebook.presto.execution.buffer.BufferResult) SerializedPage(com.facebook.presto.spi.page.SerializedPage) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 29 with PathParam

use of javax.ws.rs.PathParam in project webpieces by deanhiller.

the class MetaLoader method loadInstIntoMeta.

public LoadedController loadInstIntoMeta(Object controllerInst, String methodStr) {
    Method[] methods = controllerInst.getClass().getMethods();
    List<Method> matches = new ArrayList<>();
    for (Method m : methods) {
        if (m.getName().equals(methodStr))
            matches.add(m);
    }
    String controllerStr = controllerInst.getClass().getSimpleName();
    if (matches.size() == 0)
        throw new IllegalArgumentException("Invalid Route.  Cannot find 'public' method='" + methodStr + "' on class=" + controllerStr);
    else if (matches.size() > 1)
        throw new UnsupportedOperationException("You have more than one 'public' method named=" + methodStr + " on class=" + controllerStr + "  This is not yet supported until we support method parameters(let us know you hit this and we will immediately implement)");
    // NOTE: Leave this here, BUT we do not check this as you can send in a url like
    // host.com/something?name=myname&secondparam=testing  rather than
    // host.com/something/myname/testing with captures /something/{name}/{secondparam}
    // so basically, we could get the argNames of the captures here but this doesn't help us....
    // List<String> argNames = meta.getRoute().getArgNames();
    Method controllerMethod = matches.get(0);
    Parameter[] parameters = controllerMethod.getParameters();
    List<String> paramNames = new ArrayList<>();
    for (Parameter p : parameters) {
        String value;
        String name = p.getName();
        if (matchesBadName(name)) {
            PathParam annotation = p.getAnnotation(PathParam.class);
            if (annotation == null)
                throw new IllegalArgumentException("Method='" + controllerMethod + "' has to have every argument annotated with @PathParam(paramName) since\n" + "you are not compiling with -parameters to enable the param names to be built into the *.class files.  Most likely, you " + "changed the build.gradle we generated or switched to a different build system and did not enable this compiler option");
            value = annotation.value();
        } else {
            // use the param name in the method...
            value = name;
        }
        paramNames.add(value);
    }
    return new LoadedController(controllerInst, controllerMethod, parameters, paramNames);
}
Also used : ArrayList(java.util.ArrayList) Parameter(java.lang.reflect.Parameter) Method(java.lang.reflect.Method) PathParam(javax.ws.rs.PathParam)

Example 30 with PathParam

use of javax.ws.rs.PathParam in project webpieces by deanhiller.

the class ParamMeta method getName.

public String getName() {
    PathParam annotation = paramMeta.getAnnotation(PathParam.class);
    String name = paramMeta.getName();
    if (annotation != null) {
        name = annotation.value();
    }
    return name;
}
Also used : PathParam(javax.ws.rs.PathParam)

Aggregations

PathParam (javax.ws.rs.PathParam)127 Path (javax.ws.rs.Path)105 GET (javax.ws.rs.GET)96 Produces (javax.ws.rs.Produces)96 Response (javax.ws.rs.core.Response)93 QueryParam (javax.ws.rs.QueryParam)82 List (java.util.List)72 MediaType (javax.ws.rs.core.MediaType)72 POST (javax.ws.rs.POST)71 DELETE (javax.ws.rs.DELETE)70 Consumes (javax.ws.rs.Consumes)66 Inject (javax.inject.Inject)62 Api (io.swagger.annotations.Api)60 ApiOperation (io.swagger.annotations.ApiOperation)59 Map (java.util.Map)59 ApiResponse (io.swagger.annotations.ApiResponse)58 ApiResponses (io.swagger.annotations.ApiResponses)57 Collectors (java.util.stream.Collectors)57 Logger (org.slf4j.Logger)52 LoggerFactory (org.slf4j.LoggerFactory)52