javax.ws.rs.DefaultValue Java Examples

The following examples show how to use javax.ws.rs.DefaultValue. 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: Namespaces.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/{tenant}/{namespace}/topics")
@ApiOperation(value = "Get the list of all the topics under a certain namespace.", response = String.class, responseContainer = "Set")
@ApiResponses(value = { @ApiResponse(code = 403, message = "Don't have admin permission"),
        @ApiResponse(code = 404, message = "Tenant or cluster or namespace doesn't exist") })
public void getTopics(@PathParam("tenant") String tenant,
                              @PathParam("namespace") String namespace,
                              @QueryParam("mode") @DefaultValue("PERSISTENT") Mode mode,
                              @Suspended AsyncResponse asyncResponse) {
    validateNamespaceName(tenant, namespace);
    validateNamespaceOperation(NamespaceName.get(tenant, namespace), NamespaceOperation.GET_TOPICS);

    // Validate that namespace exists, throws 404 if it doesn't exist
    getNamespacePolicies(namespaceName);

    pulsar().getNamespaceService().getListOfTopics(namespaceName, mode)
            .thenAccept(asyncResponse::resume)
            .exceptionally(ex -> {
                log.error("Failed to get topics list for namespace {}", namespaceName, ex);
                asyncResponse.resume(ex);
                return null;
            });
}
 
Example #2
Source File: ArtifactEndpoint.java    From pnc with Apache License 2.0 6 votes vote down vote up
@GET
public Response getAll(
        @QueryParam(PAGE_INDEX_QUERY_PARAM) @DefaultValue(PAGE_INDEX_DEFAULT_VALUE) int pageIndex,
        @QueryParam(PAGE_SIZE_QUERY_PARAM) @DefaultValue(PAGE_SIZE_DEFAULT_VALUE) int pageSize,
        @QueryParam(SORTING_QUERY_PARAM) String sort,
        @QueryParam(QUERY_QUERY_PARAM) String q,
        @QueryParam("sha256") String sha256,
        @QueryParam("md5") String md5,
        @QueryParam("sha1") String sha1) {
    return fromCollection(
            artifactProvider.getAll(
                    pageIndex,
                    pageSize,
                    sort,
                    q,
                    Optional.ofNullable(sha256),
                    Optional.ofNullable(md5),
                    Optional.ofNullable(sha1)));
}
 
Example #3
Source File: CatalogApi.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/** @deprecated since 0.11.0 use {@link #createFromYaml(String)} instead */
@Deprecated
@Consumes("application/json-deprecated")  // prevent this from taking things
@POST
@ApiOperation(
        value = "Add a catalog items (e.g. new type of entity, policy or location) by uploading YAML descriptor (deprecated, use POST of yaml or ZIP/JAR instead)",
        notes = "Return value is map of ID to CatalogItemSummary.",
        response = String.class,
        hidden = true
)
@ApiResponses(value = {
        @ApiResponse(code = 400, message = "Error processing the given YAML"),
        @ApiResponse(code = 201, message = "Catalog items added successfully")
})
public Response create(String yaml,
        @ApiParam(name="forceUpdate", value="Force update of catalog item (overwriting existing catalog items with same name and version)")
        @QueryParam("forceUpdate") @DefaultValue("false") boolean forceUpdate);
 
Example #4
Source File: UserResource.java    From usergrid with Apache License 2.0 6 votes vote down vote up
@CheckPermissionsForPath
@POST
@Path("deactivate")
@JSONP
@Produces({MediaType.APPLICATION_JSON, "application/javascript"})
public ApiResponse deactivate( @Context UriInfo ui, Map<String, Object> json,
                                   @QueryParam("callback") @DefaultValue("") String callback ) throws Exception {

    ApiResponse response = createApiResponse();
    response.setAction( "Deactivate user" );

    User user = management.deactivateUser( getApplicationId(), getUserUuid() );

    response.withEntity( user );

    return response;
}
 
Example #5
Source File: PersistentTopics.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/{property}/{cluster}/{namespace}/{topic}/subscriptions")
@ApiOperation(hidden = true, value = "Get the list of persistent subscriptions for a given topic.")
@ApiResponses(value = {
        @ApiResponse(code = 307, message = "Current broker doesn't serve the namespace of this topic"),
        @ApiResponse(code = 403, message = "Don't have admin permission"),
        @ApiResponse(code = 404, message = "Topic does not exist") })
public void getSubscriptions(@Suspended final AsyncResponse asyncResponse, @PathParam("property") String property,
        @PathParam("cluster") String cluster, @PathParam("namespace") String namespace,
        @PathParam("topic") @Encoded String encodedTopic,
        @QueryParam("authoritative") @DefaultValue("false") boolean authoritative) {
    try {
        validateTopicName(property, cluster, namespace, encodedTopic);
        internalGetSubscriptions(asyncResponse, authoritative);
    } catch (WebApplicationException wae) {
        asyncResponse.resume(wae);
    } catch (Exception e) {
        asyncResponse.resume(new RestException(e));
    }
}
 
Example #6
Source File: Search.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
@GET
@Path("{id}")
/*
 * Use UUIDParam instead of UUID, because we want to be explicit to the user of this API the request is not
 * supported. When UUID is used Jersery returns a '404 Not Found' if the request contains a malformed one. The
 * UUIDParam will return a '400 Bad Request' for malformed UUID's.
 * See: http://www.dropwizard.io/0.9.1/dropwizard-jersey/apidocs/io/dropwizard/jersey/params/AbstractParam.html
 * Or: http://codahale.com/what-makes-jersey-interesting-parameter-classes/
 */
public Response get(@PathParam("id") UUIDParam id,
                    @QueryParam("rows") @DefaultValue("10") int rows,
                    @QueryParam("start") @DefaultValue("0") int start) {
  Optional<SearchResult> searchResult = searchStore.getSearchResult(id.get());
  if (searchResult.isPresent()) {
    return Response.ok(searchResponseFactory.createResponse(searchResult.get(), rows, start)).build();
  }

  return Response
    .status(Response.Status.NOT_FOUND)
    .entity(new NotFoundMessage(id))
    .build();
}
 
Example #7
Source File: MultiDataSourcesDevModeEndpoint.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@GET
@Produces("text/plain")
public String locations(@QueryParam("name") @DefaultValue("default") String name) {
    Configuration configuration;
    if ("default".equals(name)) {
        configuration = flywayDefault.getConfiguration();
    } else if ("users".equals(name)) {
        configuration = flywayUsers.getConfiguration();
    } else if ("inventory".equals(name)) {
        configuration = flywayInventory.getConfiguration();
    } else {
        throw new RuntimeException("Flyway " + name + " not found");
    }

    return Arrays.stream(configuration.getLocations()).map(Location::getPath).collect(Collectors.joining(","));
}
 
Example #8
Source File: AdminResource.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/bundle/generate")
@ApiOperation(
    value = "Generates a new support bundle.",
    response = Object.class,
    authorizations = @Authorization(value = "basic")
)
@Consumes(MediaType.APPLICATION_JSON)
@Produces("application/octet-stream")
@RolesAllowed({
    AuthzRole.ADMIN,
    AuthzRole.ADMIN_REMOTE
})
public Response createSupportBundlesContentGenerators(
  @QueryParam("generators") @DefaultValue("") String generators
) throws IOException {
  SupportBundle bundle = supportBundleManager.generateNewBundle(getGeneratorList(generators), BundleType.SUPPORT);

  return Response
    .ok()
    .header("content-disposition", "attachment; filename=\"" + bundle.getBundleName() + "\"")
    .entity(bundle.getInputStream())
    .build();
}
 
Example #9
Source File: RepositoryService.java    From semanticMDR with GNU General Public License v3.0 6 votes vote down vote up
@GET
@Path("/cd")
@Produces(MediaType.APPLICATION_JSON)
public Response listConceptualDomains(
		@CookieParam(AuthenticationService.SID) String sessionID,
		@QueryParam("limit") @DefaultValue("10") Integer limit,
		@QueryParam("offset") @DefaultValue("0") Integer offset) {
	WebUtil.checkUserSession(sessionID);
	Repository repository = RepositoryManager.getInstance().getRepository();
	List<ConceptualDomain> cdList = repository.getConceptualDomains(limit,
			offset);

	List<ConceptualDomainModel> cdModelList = new ArrayList<ConceptualDomainModel>();
	for (ConceptualDomain cd : cdList) {
		if (cd instanceof EnumeratedConceptualDomain) {
			cdModelList.add(new ConceptualDomainModel(cd, true));
		} else {
			cdModelList.add(new ConceptualDomainModel(cd, false));
		}
	}

	return Response.ok(cdModelList).build();
}
 
Example #10
Source File: Services.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@PUT
@Path("/People(1)/Parent")
public Response changeSingleValuedNavigationPropertyReference(
    @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept,
    @HeaderParam("Content-Type") @DefaultValue(StringUtils.EMPTY) final String contentType,
    final String content) {

  try {
    final Accept contentTypeValue = Accept.parse(contentType);
    assert contentTypeValue == Accept.JSON;

    jsonDeserializer.toEntity(IOUtils.toInputStream(content, Constants.ENCODING));

    return Response.noContent().type(MediaType.APPLICATION_JSON).build();
  } catch (Exception e) {
    LOG.error("While update single property reference", e);
    return xml.createFaultResponse(accept, e);
  }
}
 
Example #11
Source File: EntityConfigApi.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/{config}")
@ApiOperation(value = "Manually set a config value")
@ApiResponses(value = {
        @ApiResponse(code = 404, message = "Could not find application, entity or config key")
})
public void set(
        @ApiParam(value = "Application ID or name", required = true)
        @PathParam("application") final String application,
        @ApiParam(value = "Entity ID or name", required = true)
        @PathParam("entity") final String entityToken,
        @ApiParam(value = "Config key name", required = true)
        @PathParam("config") String configName,
        @ApiParam(value = "Apply the config to all pre-existing descendants", required = false)
        @QueryParam("recurse") @DefaultValue("false") final Boolean recurse,
        @ApiParam(value = "Value to set")
        Object newValue);
 
Example #12
Source File: GlossaryREST.java    From atlas with Apache License 2.0 6 votes vote down vote up
/**
 * Get all terms associated with the specific category
 * @param categoryGuid unique identifier for glossary category
 * @param limit page size - by default there is no paging
 * @param offset offset for pagination purpose
 * @param sort ASC (default) or DESC
 * @return List of associated terms
 * @throws AtlasBaseException
 * @HTTP 200 List of terms for the given category or an empty list
 * @HTTP 404 If glossary category guid in invalid
 */
@GET
@Path("/category/{categoryGuid}/terms")
public List<AtlasRelatedTermHeader> getCategoryTerms(@PathParam("categoryGuid") String categoryGuid,
                                                     @DefaultValue("-1") @QueryParam("limit") String limit,
                                                     @DefaultValue("0") @QueryParam("offset") String offset,
                                                     @DefaultValue("ASC") @QueryParam("sort") final String sort) throws AtlasBaseException {
    Servlets.validateQueryParamLength("categoryGuid", categoryGuid);

    AtlasPerfTracer perf = null;
    try {
        if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
            perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "GlossaryREST.getCategoryTerms(" + categoryGuid + ")");
        }

        return glossaryService.getCategoryTerms(categoryGuid, Integer.parseInt(offset), Integer.parseInt(limit), toSortOrder(sort));

    } finally {
        AtlasPerfTracer.log(perf);
    }
}
 
Example #13
Source File: PersistentTopics.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/{property}/{cluster}/{namespace}/{topic}/subscription/{subName}/resetcursor/{timestamp}")
@ApiOperation(hidden = true, value = "Reset subscription to message position closest to absolute timestamp (in ms).", notes = "It fence cursor and disconnects all active consumers before reseting cursor.")
@ApiResponses(value = {
        @ApiResponse(code = 307, message = "Current broker doesn't serve the namespace of this topic"),
        @ApiResponse(code = 403, message = "Don't have admin permission"),
        @ApiResponse(code = 404, message = "Topic/Subscription does not exist") })
public void resetCursor(@Suspended final AsyncResponse asyncResponse, @PathParam("property") String property,
        @PathParam("cluster") String cluster, @PathParam("namespace") String namespace,
        @PathParam("topic") @Encoded String encodedTopic, @PathParam("subName") String encodedSubName,
        @PathParam("timestamp") long timestamp,
        @QueryParam("authoritative") @DefaultValue("false") boolean authoritative) {
    try {
        validateTopicName(property, cluster, namespace, encodedTopic);
        internalResetCursor(asyncResponse, decode(encodedSubName), timestamp, authoritative);
    } catch (WebApplicationException wae) {
        asyncResponse.resume(wae);
    } catch (Exception e) {
        asyncResponse.resume(new RestException(e));
    }
}
 
Example #14
Source File: ImportResource.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
@POST
@Path(ImportResourceApi.BATCH_PATH)
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public SmartGwtResponse<BatchView> newBatch(
        @FormParam(ImportResourceApi.IMPORT_BATCH_FOLDER) @DefaultValue("") String path,
        @FormParam(ImportResourceApi.NEWBATCH_DEVICE_PARAM) String device,
        @FormParam(ImportResourceApi.NEWBATCH_INDICES_PARAM) @DefaultValue("true") boolean indices,
        @FormParam(ImportResourceApi.IMPORT_BATCH_PROFILE) String profileId
        ) throws URISyntaxException, IOException {
    
    LOG.log(Level.FINE, "import path: {0}, indices: {1}, device: {2}",
            new Object[] {path, indices, device});
    String folderPath = validateParentPath(path);
    URI userRoot = user.getImportFolder();
    URI folderUri = (folderPath != null)
            // URI multi param constructor escapes input unlike single param constructor or URI.create!
            ? userRoot.resolve(new URI(null, null, folderPath, null))
            : userRoot;
    File folder = new File(folderUri);
    ConfigurationProfile profile = findImportProfile(null, profileId);
    ImportProcess process = ImportProcess.prepare(folder, folderPath, user,
            importManager, device, indices, appConfig.getImportConfiguration(profile));
    ImportDispatcher.getDefault().addImport(process);
    Batch batch = process.getBatch();
    return new SmartGwtResponse<BatchView>(importManager.viewBatch(batch.getId()));
}
 
Example #15
Source File: CollectionController.java    From AIDR with GNU Affero General Public License v3.0 6 votes vote down vote up
@RequestMapping(value = "/generateJsonTweetIdsLink.action", method = RequestMethod.GET)
@ResponseBody
public Map<String,Object> generateJsonTweetIdsLink(@RequestParam String code,
		@DefaultValue(DownloadType.TEXT_JSON) @QueryParam("jsonType") String jsonType) throws Exception {
	Map<String, Object> result = null;
	try {
		result = collectionLogService.generateJsonTweetIdsLink(code, jsonType);
		if (result != null && result.get("url") != null) {
			return getUIWrapper(result.get("url"),true, null, (String)result.get("message"));
		} else {
			return getUIWrapper(false, "Something wrong - no file generated!");
		}
	} catch (Exception e) {
		logger.error("Error while generating JSON Tweet Ids Link for collection: "+code +"and jsonType: "+jsonType, e);
		return getUIWrapper(false, "System is down or under maintenance. For further inquiries please contact admin.");
	}
}
 
Example #16
Source File: OrderService.java    From qcon-microservices with Apache License 2.0 6 votes vote down vote up
/**
 * Perform a "Long-Poll" styled get. This method will attempt to get the value for the passed key
 * blocking until the key is available or passed timeout is reached. Non-blocking IO is used to
 * implement this, but the API will block the calling thread if no data is available
 *
 * @param id - the key of the value to retrieve
 * @param timeout - the timeout for the long-poll
 * @param asyncResponse - async response used to trigger the poll early should the appropriate
 * value become available
 */
@GET
@ManagedAsync
@Path("/orders/{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN})
public void getWithTimeout(@PathParam("id") final String id,
                           @QueryParam("timeout") @DefaultValue(CALL_TIMEOUT) Long timeout,
                           @Suspended final AsyncResponse asyncResponse) {
    setTimeout(timeout, asyncResponse);

    log.info("running GET on this node");
    try {
        Order order = ordersStore().get(id);
        if (order == null) {
            log.info("Delaying get as order not present for id " + id);
            outstandingRequests.put(id, new FilteredResponse<>(asyncResponse, (k, v) -> true));
        } else {
            asyncResponse.resume(order);
        }
    } catch (InvalidStateStoreException e) {
        //Store not ready so delay
        log.info("Delaying request for " + id + " because state store is not ready.");
        outstandingRequests.put(id, new FilteredResponse<>(asyncResponse, (k, v) -> true));
    }
}
 
Example #17
Source File: Services.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
/**
 * Replace property.
 *
 * @param accept
 * @param entitySetName
 * @param entityId
 * @param path
 * @param format
 * @param changes
 * @return response
 */
@PUT
@Path("/{entitySetName}({entityId})/{path:.*}")
public Response replaceProperty(
    @Context final UriInfo uriInfo,
    @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept,
    @HeaderParam("Content-Type") @DefaultValue(StringUtils.EMPTY) final String contentType,
    @HeaderParam("Prefer") @DefaultValue(StringUtils.EMPTY) final String prefer,
    @PathParam("entitySetName") final String entitySetName,
    @PathParam("entityId") final String entityId,
    @PathParam("path") final String path,
    @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format,
    final String changes) {

  if (xml.isMediaContent(entitySetName + "/" + path)) {
    return replaceMediaProperty(prefer, entitySetName, entityId, path, changes);
  } else {
    return replaceProperty(uriInfo.getRequestUri().toASCIIString(),
        accept, contentType, prefer, entitySetName, entityId, path, format, changes, false);
  }
}
 
Example #18
Source File: ManagerResource.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Path("/pipeline/{pipelineId}/alerts")
@DELETE
@ApiOperation(value = "Delete alert by Pipeline name, revision and Alert ID", response = Boolean.class,
  authorizations = @Authorization(value = "basic"))
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed({
    AuthzRole.MANAGER,
    AuthzRole.ADMIN,
    AuthzRole.MANAGER_REMOTE,
    AuthzRole.ADMIN_REMOTE
})
public Response deleteAlert(
  @PathParam("pipelineId") String pipelineId,
  @QueryParam("rev") @DefaultValue("0") String rev,
  @QueryParam("alertId") String alertId
) throws PipelineException {
  PipelineInfo pipelineInfo = store.getInfo(pipelineId);
  RestAPIUtils.injectPipelineInMDC(pipelineInfo.getTitle(), pipelineInfo.getPipelineId());
  return Response.ok().type(MediaType.APPLICATION_JSON).entity(
    manager.getRunner(pipelineId, rev).deleteAlert(alertId)).build();
}
 
Example #19
Source File: BookStoreOpenApi.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Produces({ MediaType.APPLICATION_JSON })
@GET
@Operation(
    description = "Get books",
    responses = @ApiResponse(
        responseCode = "200", 
        content = @Content(
            mediaType = MediaType.APPLICATION_JSON,
            array = @ArraySchema(schema = @Schema(implementation = Book.class))
        )
    )
)
public Response getBooks(
    @Parameter(description = "Page to fetch", required = true) @QueryParam("page") @DefaultValue("1") int page) {
    return Response.ok(
        Arrays.asList(
            new Book("Book 1", 1),
            new Book("Book 2", 2)
        )
    ).build();
}
 
Example #20
Source File: ApplicationApi.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/{application}/descendants/sensor/{sensor}")
        @ApiOperation(value = "Fetch values of a given sensor for all (or filtered) descendants")
@ApiResponses(value = {
        @ApiResponse(code = 404, message = "Application or entity missing")
})
public Map<String,Object> getDescendantsSensor(
        @ApiParam(value = "Application ID or name", required = true)
        @PathParam("application") String application,
        @ApiParam(value = "Sensor name", required = true)
        @PathParam("sensor") String sensor,
        @ApiParam(value="Regular expression for an entity type which must be matched", required=false)
        @DefaultValue(".*")
        @QueryParam("typeRegex") String typeRegex);
 
Example #21
Source File: DelimitedRest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Maps the data in an uploaded delimited document into RDF in the requested format
 * using a MappingRecord's Mapping and downloads the result in a file with the requested
 * name. The file must be present in the data/tmp/ directory.
 *
 * @param fileName the name of the delimited document in the data/tmp/ directory
 * @param mappingRecordIRI the id of the MappingRecord
 * @param format the RDF serialization to use
 * @param containsHeaders whether the delimited file has headers
 * @param separator the character the columns are separated by if it is a CSV
 * @param downloadFileName the name for the downloaded file
 * @return a Response with the converted data in the requested format to download
 */
@GET
@javax.ws.rs.Path("{documentName}/map")
@Produces({MediaType.APPLICATION_OCTET_STREAM, "text/*", "application/*"})
@RolesAllowed("user")
@ApiOperation("ETL an uploaded delimited document using an uploaded Mapping file and download the data")
public Response etlFile(@PathParam("documentName") String fileName,
                 @QueryParam("mappingRecordIRI") String mappingRecordIRI,
                 @DefaultValue("jsonld") @QueryParam("format") String format,
                 @DefaultValue("true") @QueryParam("containsHeaders") boolean containsHeaders,
                 @DefaultValue(",") @QueryParam("separator") String separator,
                 @QueryParam("fileName") String downloadFileName) {
    checkStringParam(mappingRecordIRI, "Must provide the IRI of a mapping record");

    // Convert the data
    Model data = etlFile(fileName, () -> getUploadedMapping(mappingRecordIRI), containsHeaders, separator, false);
    String result = groupedModelToString(data, format, transformer);

    // Write data into a stream
    StreamingOutput stream = os -> {
        Writer writer = new BufferedWriter(new OutputStreamWriter(os));
        writer.write(result);
        writer.flush();
        writer.close();
    };
    String fileExtension = getRDFFormat(format).getDefaultFileExtension();
    String mimeType = getRDFFormat(format).getDefaultMIMEType();
    String dataFileName = downloadFileName == null ? fileName : downloadFileName;
    Response response = Response.ok(stream).header("Content-Disposition", "attachment;filename=" + dataFileName
            +  "." + fileExtension).header("Content-Type", mimeType).build();

    // Remove temp file
    removeTempFile(fileName);

    return response;
}
 
Example #22
Source File: TablesResource.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/tables/{tableName}/segments/{segmentName}/metadata")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Provide segment metadata", notes = "Provide segments metadata for the segment on server")
@ApiResponses(value = {@ApiResponse(code = 200, message = "Success"), @ApiResponse(code = 500, message = "Internal server error", response = ErrorInfo.class), @ApiResponse(code = 404, message = "Table or segment not found", response = ErrorInfo.class)})
public String getSegmentMetadata(
    @ApiParam(value = "Table name including type", required = true, example = "myTable_OFFLINE") @PathParam("tableName") String tableName,
    @ApiParam(value = "Segment name", required = true) @PathParam("segmentName") String segmentName,
    @ApiParam(value = "Column name", allowMultiple = true) @QueryParam("columns") @DefaultValue("") List<String> columns) {
  TableDataManager tableDataManager = checkGetTableDataManager(tableName);
  SegmentDataManager segmentDataManager = tableDataManager.acquireSegment(segmentName);
  if (segmentDataManager == null) {
    throw new WebApplicationException(String.format("Table %s segments %s does not exist", tableName, segmentName),
        Response.Status.NOT_FOUND);
  }
  try {
    SegmentMetadataImpl segmentMetadata = (SegmentMetadataImpl) segmentDataManager.getSegment().getSegmentMetadata();
    Set<String> columnSet;
    if (columns.size() == 1 && columns.get(0).equals("*")) {
      columnSet = null;
    } else {
      columnSet = new HashSet<>(columns);
    }
    try {
      return segmentMetadata.toJson(columnSet).toString();
    } catch (Exception e) {
      LOGGER.error("Failed to convert table {} segment {} to json", tableName, segmentMetadata);
      throw new WebApplicationException("Failed to convert segment metadata to json",
          Response.Status.INTERNAL_SERVER_ERROR);
    }
  } finally {
    tableDataManager.releaseSegment(segmentDataManager);
  }
}
 
Example #23
Source File: Namespaces.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@POST
@Path("/{tenant}/{namespace}/{bundle}/clearBacklog/{subscription}")
@ApiOperation(value = "Clear backlog for a given subscription on all topics on a namespace bundle.")
@ApiResponses(value = {
        @ApiResponse(code = 307, message = "Current broker doesn't serve the namespace"),
        @ApiResponse(code = 403, message = "Don't have admin permission"),
        @ApiResponse(code = 404, message = "Namespace does not exist") })
public void clearNamespaceBundleBacklogForSubscription(@PathParam("tenant") String tenant,
        @PathParam("namespace") String namespace, @PathParam("subscription") String subscription,
        @PathParam("bundle") String bundleRange,
        @QueryParam("authoritative") @DefaultValue("false") boolean authoritative) {
    validateNamespaceName(tenant, namespace);
    internalClearNamespaceBundleBacklogForSubscription(subscription, bundleRange, authoritative);
}
 
Example #24
Source File: TenantsHandler.java    From hawkular-metrics with Apache License 2.0 5 votes vote down vote up
@Deprecated
@POST
@ApiOperation(value = "Create a new tenant.", notes = "Clients are not required to create explicitly create a "
        + "tenant before starting to store metric data. It is recommended to do so however to ensure that there "
        + "are no tenant id naming collisions and to provide default data retention settings.")
@ApiResponses(value = {
        @ApiResponse(code = 201, message = "Tenant has been succesfully created."),
        @ApiResponse(code = 400, message = "Missing or invalid retention properties. ",
                response = ApiError.class),
        @ApiResponse(code = 409, message = "Given tenant id has already been created.",
                response = ApiError.class),
        @ApiResponse(code = 500, message = "An unexpected error occured while trying to create a tenant.",
                response = ApiError.class)
})
public void createTenant(
        @Suspended AsyncResponse asyncResponse,
        @ApiParam(required = true) TenantDefinition tenantDefinition,
        @ApiParam(value = "Overwrite previously created tenant configuration if it exists. "
                + "Only data retention settings are overwriten; existing metrics and data points are unnafected. "
                + "Defaults to false.",
                required = false) @DefaultValue("false") @QueryParam("overwrite") Boolean overwrite,
        @Context UriInfo uriInfo
) {
    logger.warn("The create tenant endpoint is deprecated");
    URI location = uriInfo.getBaseUriBuilder().path("/tenants").build();
    metricsService.createTenant(tenantDefinition.toTenant(), overwrite)
            .subscribe(new TenantCreatedObserver(asyncResponse, location));
}
 
Example #25
Source File: EmployeeManagement.java    From opencps-v2 with GNU Affero General Public License v3.0 5 votes vote down vote up
@PUT
@Path("/{id}")
@Consumes({ MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response update(@Context HttpServletRequest request, @Context HttpHeaders header, @Context Company company,
		@Context Locale locale, @Context User user, @Context ServiceContext serviceContext,
		@DefaultValue("0") @PathParam("id") long id, @BeanParam EmployeeInputModel input);
 
Example #26
Source File: Domini.java    From govpay with GNU General Public License v3.0 5 votes vote down vote up
@GET
@Path("/")

@Produces({ "application/json" })
public Response findDomini(@Context UriInfo uriInfo, @Context HttpHeaders httpHeaders, @QueryParam(value=Costanti.PARAMETRO_PAGINA) @DefaultValue(value="1")  Integer pagina, @QueryParam(value=Costanti.PARAMETRO_RISULTATI_PER_PAGINA) @DefaultValue(value="25")  Integer risultatiPerPagina, @QueryParam("campi") String campi, @QueryParam("abilitato") Boolean abilitato, @QueryParam("ordinamento") String ordinamento, @QueryParam("idStazione") String idStazione, @QueryParam("associati") Boolean associati){
    this.buildContext();
    return this.controller.findDomini(this.getUser(), uriInfo, httpHeaders, pagina, risultatiPerPagina, campi, abilitato, ordinamento, idStazione, associati);
}
 
Example #27
Source File: ManagerResource.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Path("/pipeline/{pipelineId}/snapshot/{snapshotName}")
@PUT
@ApiOperation(value = "Capture Snapshot", authorizations = @Authorization(value = "basic"))
@RolesAllowed({ AuthzRole.MANAGER, AuthzRole.ADMIN, AuthzRole.MANAGER_REMOTE, AuthzRole.ADMIN_REMOTE })
public Response captureSnapshot(
    @PathParam("pipelineId") String pipelineId,
    @PathParam("snapshotName") String snapshotName,
    @QueryParam("snapshotLabel") String snapshotLabel,
    @QueryParam("rev") @DefaultValue("0") String rev,
    @QueryParam("batches") @DefaultValue("1") int batches,
    @QueryParam("batchSize") @DefaultValue("10") int batchSize,
    @QueryParam("startPipeline") @DefaultValue("false") boolean startPipeline,
    Map<String, Object> runtimeParameters
) throws PipelineException, StageException {
  PipelineInfo pipelineInfo = store.getInfo(pipelineId);
  RestAPIUtils.injectPipelineInMDC(pipelineInfo.getTitle(), pipelineInfo.getPipelineId());
  Runner runner = manager.getRunner(pipelineId, rev);
  if (startPipeline && runner != null) {
    runner.startAndCaptureSnapshot(
        new StartPipelineContextBuilder(user).withRuntimeParameters(runtimeParameters).build(),
        snapshotName,
        snapshotLabel,
        batches,
        batchSize
      );
  } else {
    Utils.checkState(runner != null && runner.getState().getStatus() == PipelineStatus.RUNNING,
        "Pipeline doesn't exist or it is not running currently");
    runner.captureSnapshot(user, snapshotName, snapshotLabel, batches, batchSize);
  }
  return Response.ok().build();
}
 
Example #28
Source File: ResourceDefinitions.java    From linstor-server with GNU General Public License v3.0 5 votes vote down vote up
@GET
public Response listResourceDefinitions(
    @Context Request request,
    @QueryParam("resource_definitions") List<String> rscDfnNames,
    @QueryParam("with_volume_definitions") boolean withVlmDfns,
    @QueryParam("vlmNr") Integer vlmNr,
    @QueryParam("props") List<String> propFilters,
    @DefaultValue("0") @QueryParam("limit") int limit,
    @DefaultValue("0") @QueryParam("offset") int offset
)
{
    return listResourceDefinitionsOneOrMany(request, null, rscDfnNames, withVlmDfns, propFilters, limit, offset);
}
 
Example #29
Source File: JSONPService.java    From dexter with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/get-id")
@ApiOperation(value = "Provides the wiki-id of an entity", response = ArticleDescription.class)
@Produces({ MediaType.APPLICATION_JSON })
public String getDescription(
		@QueryParam("callback") @DefaultValue("callback") String callback,
		@QueryParam("title") String title) {
	return addCallback(callback, r.getDescription(title));

}
 
Example #30
Source File: PipelineStoreResource.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Path("/pipeline/{pipelineId}/import")
@POST
@ApiOperation(value = "Import Pipeline Configuration & Rules", response = PipelineEnvelopeJson.class,
    authorizations = @Authorization(value = "basic"))
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed({
    AuthzRole.CREATOR, AuthzRole.ADMIN, AuthzRole.CREATOR_REMOTE, AuthzRole.ADMIN_REMOTE
})
public Response importPipeline(
    @PathParam("pipelineId") String name,
    @QueryParam("rev") @DefaultValue("0") String rev,
    @QueryParam("overwrite") @DefaultValue("false") boolean overwrite,
    @QueryParam("autoGeneratePipelineId") @DefaultValue("false") boolean autoGeneratePipelineId,
    @QueryParam("draft") @DefaultValue("false") boolean draft,
    @QueryParam("includeLibraryDefinitions") @DefaultValue("true") boolean includeLibraryDefinitions,
    @QueryParam("encryptCredentials") @DefaultValue("false") boolean encryptCredentials,
    @ApiParam(name="pipelineEnvelope", required = true) PipelineEnvelopeJson pipelineEnvelope
) throws PipelineException {
  RestAPIUtils.injectPipelineInMDC("*");
  pipelineEnvelope = importPipelineEnvelope(
      name,
      rev,
      overwrite,
      autoGeneratePipelineId,
      pipelineEnvelope,
      draft,
      includeLibraryDefinitions,
      encryptCredentials
  );
  return Response.ok().
      type(MediaType.APPLICATION_JSON).entity(pipelineEnvelope).build();
}