Java Code Examples for javax.ws.rs.Path

The following are top voted examples for showing how to use javax.ws.rs.Path. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.

Example 1
Project: osc-core   File: ApplianceApis.java   View source code 6 votes vote down vote up
@ApiOperation(value = "Creates a new appliance software version for a software function model",
        notes = "Creates a new appliance software version for a software function model",
        response = BaseResponse.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Successful operation"),
        @ApiResponse(code = 400, message = "In case of any error", response = ErrorCodeDto.class) })
@Path("/{applianceId}/versions")
@POST
public Response createApplianceSoftwareVersion(@Context HttpHeaders headers,
        @ApiParam(value = "Id of the Appliance Model", required = true) @PathParam("applianceId") Long applianceId, @ApiParam(required = true) ApplianceSoftwareVersionDto asvDto) {

    logger.info("Creating an Appliance Software Version");
    this.userContext.setUser(OscAuthFilter.getUsername(headers));
    this.apiUtil.setIdAndParentIdOrThrow(asvDto, null, applianceId, "Appliance Sofftware Version");

    return this.apiUtil.getResponseForBaseRequest(this.addApplianceSoftwareVersionService, new BaseRequest<ApplianceSoftwareVersionDto>(asvDto));
}
 
Example 2
Project: docker-kafka-streams   File: MetricsResource.java   View source code 6 votes vote down vote up
/**
 * Metrics for a machine
 *
 * @param machine
 * @return the metric
 */
@GET
@Path("{machine}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response getMachineMetric(@PathParam("machine") String machine) {
    LOGGER.log(Level.INFO, "Fetching metrics for machine {0}", machine);

    KafkaStreams ks = GlobalAppState.getInstance().getKafkaStreams();
    HostInfo thisInstance = GlobalAppState.getInstance().getHostPortInfo();

    Metrics metrics = null;

    StreamsMetadata metadataForMachine = ks.metadataForKey(storeName, machine, new StringSerializer());

    if (metadataForMachine.host().equals(thisInstance.host()) && metadataForMachine.port() == thisInstance.port()) {
        LOGGER.log(Level.INFO, "Querying local store for machine {0}", machine);
        metrics = getLocalMetrics(machine);
    } else {
        //LOGGER.log(Level.INFO, "Querying remote store for machine {0}", machine);
        String url = "http://" + metadataForMachine.host() + ":" + metadataForMachine.port() + "/metrics/remote/" + machine;
        metrics = Utils.getRemoteStoreState(url, 2, TimeUnit.SECONDS);
        LOGGER.log(Level.INFO, "Metric from remote store at {0} == {1}", new Object[]{url, metrics});
    }

    return Response.ok(metrics).build();
}
 
Example 3
Project: trabblex   File: ClientManagerResource.java   View source code 6 votes vote down vote up
/**
 * When a client has a chunk, it registers as a seeder
 */
@Path("registerclientseeder")
@Produces(MediaType.TEXT_PLAIN)
public String registerClientSeeder(@QueryParam("file_hash") String file_hash,
                                   @QueryParam("chunk_hash") String chunk_hash,
                                   @QueryParam("chunk_id") String chunk_id,
                                   @QueryParam("ip") String ip,
                                   @QueryParam("port") String port) {

    String query = "INSERT INTO chunk_owners(file_hash, chunk_hash, chunk_id, "
                                          + "owner_ip, owner_port, is_seeder)"

                 + "VALUES('%s', '%s', %s, '%s', %s, 'f');".format(file_hash,
                                                                   chunk_hash,
                                                                   chunk_id,
                                                                   ip,
                                                                   port);

    runUpdate(query);
    return null;
}
 
Example 4
Project: dremio-oss   File: DatasetVersionResource.java   View source code 6 votes vote down vote up
/**
 * Return complete results of a dataset version. Response contains a pagination URL to fetch the data in chunks.
 *
 * @return
 * @throws DatasetVersionNotFoundException
 * @throws InterruptedException
 */
@GET @Path("run")
@Produces(APPLICATION_JSON) @Consumes(APPLICATION_JSON)
public InitialRunResponse run(@QueryParam("tipVersion") DatasetVersion tipVersion) throws DatasetVersionNotFoundException, InterruptedException, NamespaceException {
  final VirtualDatasetUI virtualDatasetUI = getDatasetConfig();
  final SqlQuery query = new SqlQuery(virtualDatasetUI.getSql(), virtualDatasetUI.getState().getContextList(), securityContext);
  RunStartedListener listener = new RunStartedListener();
  final JobUI job = executor.runQueryWithListener(query, QueryType.UI_RUN, datasetPath, version, listener);
  // wait for job to start (or WAIT_FOR_RUN_HISTORY_S seconds).
  boolean success = listener.await(WAIT_FOR_RUN_HISTORY_S, TimeUnit.SECONDS);
  if (!success) {
    throw new InterruptedException("Starting a query timed out after " + WAIT_FOR_RUN_HISTORY_S +
        " seconds, please try again.");
  }

  // tip version is optional, as it is only needed when we are navigated back in history
  // otherwise assume the current version is at the tip of the history
  tipVersion = tipVersion != null ? tipVersion : virtualDatasetUI.getVersion();
  final History history = tool.getHistory(datasetPath, virtualDatasetUI.getVersion(), tipVersion);
  return InitialRunResponse.of(newDataset(virtualDatasetUI, tipVersion), job.getJobId(), history);
}
 
Example 5
Project: plugin-id   File: UserOrgResource.java   View source code 6 votes vote down vote up
/**
 * Return a specific user from his/her login. When user does not exist or is
 * within a non managed company, return a 404.
 *
 * @param user
 *            The user to find. A normalized form will be used for the
 *            search.
 * @return found user. Never <code>null</code>.
 */
@GET
@Path("{user:" + SimpleUser.USER_PATTERN + "}")
public UserOrg findById(@PathParam("user") final String user) {
	final UserOrg rawUserOrg = getUser().findByIdExpected(securityHelper.getLogin(), Normalizer.normalize(user));

	// User has been found, secure the object regarding the visible groups
	final UserOrg securedUserOrg = new UserOrg();
	rawUserOrg.copy(securedUserOrg);

	// Show only the groups of user that are also visible to current user
	final Set<GroupOrg> managedGroups = groupResource.getContainers();
	securedUserOrg.setGroups(managedGroups.stream().filter(mGroup -> rawUserOrg.getGroups().contains(mGroup.getId())).sorted()
			.map(GroupOrg::getName).collect(Collectors.toList()));
	return securedUserOrg;
}
 
Example 6
Project: soapbox-race-core   File: Personas.java   View source code 6 votes vote down vote up
@GET
@Secured
@Path("/inventory/objects")
@Produces(MediaType.APPLICATION_XML)
public InventoryTrans inventoryObjects() {
	InventoryTrans inventoryTrans = new InventoryTrans();
	ArrayOfInventoryItemTrans arrayOfInventoryItemTrans = new ArrayOfInventoryItemTrans();
	arrayOfInventoryItemTrans.getInventoryItemTrans().add(getPowerUpInventory("nosshot", -1681514783, 1842996427L, "0x9bc61ee1"));
	arrayOfInventoryItemTrans.getInventoryItemTrans().add(getPowerUpInventory("runflattires", -537557654, 2876729160L, "0xdff5856a"));
	arrayOfInventoryItemTrans.getInventoryItemTrans().add(getPowerUpInventory("instantcooldown", -1692359144, 2876729162L, "0x9b20a618"));
	arrayOfInventoryItemTrans.getInventoryItemTrans().add(getPowerUpInventory("shield", -364944936, 2876729163L, "0xea3f61d8"));
	arrayOfInventoryItemTrans.getInventoryItemTrans().add(getPowerUpInventory("slingshot", 2236629, 2876729164L, "0x2220d5"));
	arrayOfInventoryItemTrans.getInventoryItemTrans().add(getPowerUpInventory("ready", 957701799, 2876729165L, "0x39155ea7"));
	arrayOfInventoryItemTrans.getInventoryItemTrans().add(getPowerUpInventory("juggernaut", 1805681994, 2876729166L, "0x6ba0854a"));
	arrayOfInventoryItemTrans.getInventoryItemTrans().add(getPowerUpInventory("emergencyevade", -611661916, 2876729167L, "0xdb8ac7a4"));
	arrayOfInventoryItemTrans.getInventoryItemTrans().add(getPowerUpInventory("team_emergencyevade", -1564932069, 2876729168L, "0xa2b9081b"));
	arrayOfInventoryItemTrans.getInventoryItemTrans().add(getPowerUpInventory("onemorelap", 1627606782, 2876729170L, "0x61034efe"));
	arrayOfInventoryItemTrans.getInventoryItemTrans().add(getPowerUpInventory("team_slingshot", 1113720384, 2876729171L, "0x42620640"));
	arrayOfInventoryItemTrans.getInventoryItemTrans().add(getPowerUpInventory("trafficmagnet", 125509666, 2880783203L, "0x77b2022"));
	inventoryTrans.setInventoryItems(arrayOfInventoryItemTrans);
	return inventoryTrans;
}
 
Example 7
Project: launcher-backend   File: OpenShiftResource.java   View source code 6 votes vote down vote up
@GET
@Path("/clusters")
@Produces(MediaType.APPLICATION_JSON)
public JsonArray getSupportedOpenShiftClusters(@HeaderParam(HttpHeaders.AUTHORIZATION) final String authorization,
                                               @Context HttpServletRequest request) {
    JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
    Set<OpenShiftCluster> clusters = clusterRegistry.getClusters();
    if (request.getParameterMap().containsKey("all") || openShiftServiceFactory.getDefaultIdentity().isPresent()) {
        // Return all clusters
        clusters
                .stream()
                .map(OpenShiftCluster::getId)
                .forEach(arrayBuilder::add);
    } else {
        final KeycloakService keycloakService = this.keycloakServiceInstance.get();
        clusters.parallelStream().map(OpenShiftCluster::getId)
                .forEach(clusterId ->
                                 keycloakService.getIdentity(clusterId, authorization)
                                         .ifPresent(token -> arrayBuilder.add(clusterId)));
    }

    return arrayBuilder.build();
}
 
Example 8
Project: dremio-oss   File: SourceResource.java   View source code 6 votes vote down vote up
@PUT
@Path("/folder_format/{path: .*}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public FileFormatUI saveFolderFormat(FileFormat fileFormat, @PathParam("path") String path)
    throws NamespaceException, SourceNotFoundException {
  SourceFolderPath folderPath = SourceFolderPath.fromURLPath(sourceName, path);
  sourceService.checkSourceExists(folderPath.getSourceName());
  fileFormat.setFullPath(folderPath.toPathList());

  PhysicalDatasetConfig physicalDatasetConfig = new PhysicalDatasetConfig();
  physicalDatasetConfig.setName(folderPath.getFolderName().getName());
  physicalDatasetConfig.setFormatSettings(fileFormat.asFileConfig());
  physicalDatasetConfig.setType(DatasetType.PHYSICAL_DATASET_SOURCE_FOLDER);
  physicalDatasetConfig.setFullPathList(folderPath.toPathList());
  physicalDatasetConfig.setVersion(fileFormat.getVersion());
  sourceService.createPhysicalDataset(folderPath, physicalDatasetConfig);
  fileFormat.setVersion(physicalDatasetConfig.getVersion());
  return new FileFormatUI(fileFormat, folderPath);
}
 
Example 9
Project: microprofile-jwt-auth   File: JsonValuejectionEndpoint.java   View source code 6 votes vote down vote up
@GET
@Path("/verifyInjectedAuthTime")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("Tester")
public JsonObject verifyInjectedAuthTime(@QueryParam("auth_time") Long authTime) {
    boolean pass = false;
    String msg;
    // auth_time
    Long authTimeValue = this.authTime.longValue();
    if(authTimeValue == null) {
        msg = Claims.auth_time.name()+" value is null or missing, FAIL";
    }
    else if(authTimeValue.equals(authTime)) {
        msg = Claims.auth_time.name()+" PASS";
        pass = true;
    }
    else {
        msg = String.format("%s: %s != %s", Claims.auth_time.name(), authTimeValue, authTime);
    }
    JsonObject result = Json.createObjectBuilder()
        .add("pass", pass)
        .add("msg", msg)
        .build();
    return result;
}
 
Example 10
Project: dremio-oss   File: DatasetsResource.java   View source code 6 votes vote down vote up
/**
 * Create a new query of SELECT * from [parentDataset].
 *
 * @param parentDataset
 * @return
 * @throws DatasetNotFoundException
 * @throws NamespaceException
 */
@POST @Path("new_untitled") @Produces(MediaType.APPLICATION_JSON)
public InitialPreviewResponse newUntitledFromParent(
    @QueryParam("parentDataset") DatasetPath parentDataset,
    @QueryParam("newVersion") DatasetVersion newVersion,
    @QueryParam("limit") Long limit)
  throws DatasetNotFoundException, DatasetVersionNotFoundException, NamespaceException, NewDatasetQueryException {
  Preconditions.checkNotNull(newVersion, "newVersion should not be null");
  try {
    return newUntitled(new FromTable(parentDataset.toPathString()), newVersion, parentDataset.toParentPathList());
  } catch (DatasetNotFoundException | NamespaceException e) {
    // TODO: this should really be a separate API from the UI.
    // didn't find as virtual dataset, let's return as opaque sql (as this could be a source) .
    return newUntitled(new FromTable(parentDataset.toPathString()), newVersion, parentDataset.toParentPathList());
  }
}
 
Example 11
Project: Celebino   File: UserController.java   View source code 6 votes vote down vote up
/**
 * Cadastra usuario
 * 
 * @param User
 * @return Response
 */
@PermitAll
@POST
@Path("/")
@Consumes("application/json")
@Produces("application/json")
public Response insert(User user) {

	ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST);
	builder.expires(new Date());

	try {

		Long idUser = (long) UserDao.getInstance().insertU(user);
		user.setId(idUser);
		builder.status(Response.Status.OK).entity(user);

	} catch (SQLException e) {

		builder.status(Response.Status.INTERNAL_SERVER_ERROR);
	}

	return builder.build();
}
 
Example 12
Project: verify-hub   File: TestSessionResource.java   View source code 6 votes vote down vote up
@Path(IDP_SELECTED_STATE)
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response createStateInIdpSelectedState(TestSessionDto testSessionDto) {
    testSessionRepository.createSession(testSessionDto.getSessionId(),
            new IdpSelectedState(testSessionDto.getRequestId(),
                    testSessionDto.getIdentityProviderEntityId(),
                    testSessionDto.getMatchingServiceEntityId(),
                    testSessionDto.getLevelsOfAssurance(),
                    testSessionDto.getUseExactComparisonType(),
                    testSessionDto.getForceAuthentication(),
                    testSessionDto.getAssertionConsumerServiceUri(),
                    testSessionDto.getRequestIssuerId(),
                    testSessionDto.getRelayState(),
                    testSessionDto.getSessionExpiryTimestamp(),
                    testSessionDto.isRegistering(),
                    testSessionDto.getSessionId(),
                    testSessionDto.getAvailableIdentityProviders(),
                    testSessionDto.getTransactionSupportsEidas())
    );
    return Response.ok().build();
}
 
Example 13
Project: athena   File: VirtualPortWebResource.java   View source code 6 votes vote down vote up
@DELETE
@Path("{portUUID}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response deletePorts(@PathParam("portUUID") String id) {
    Set<VirtualPortId> vPortIds = new HashSet<>();
    try {
        if (id != null) {
            vPortIds.add(VirtualPortId.portId(id));
        }
        Boolean issuccess = nullIsNotFound(get(VirtualPortService.class)
                .removePorts(vPortIds), VPORT_NOT_FOUND);
        if (!issuccess) {
            return Response.status(INTERNAL_SERVER_ERROR)
                    .entity(VPORT_ID_NOT_EXIST).build();
        }
        return ok(issuccess.toString()).build();
    } catch (Exception e) {
        log.error("Deletes VirtualPort failed because of exception {}",
                  e.toString());
        return Response.status(INTERNAL_SERVER_ERROR).entity(e.toString())
                .build();
    }
}
 
Example 14
Project: verify-hub   File: TestSessionResource.java   View source code 6 votes vote down vote up
@Path(COUNTRY_SELECTED_STATE)
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response createStateInCountrySelectingState(TestSessionDto testSessionDto) {
    testSessionRepository.createSession(testSessionDto.getSessionId(),
            new SessionStartedState(testSessionDto.getRequestId(),
                    testSessionDto.getRelayState(),
                    testSessionDto.getRequestIssuerId(),
                    testSessionDto.getAssertionConsumerServiceUri(),
                    Optional.<Boolean>absent(),
                    Collections.<String>emptyList(),
                    testSessionDto.getSessionExpiryTimestamp(),
                    testSessionDto.getSessionId(),
                    testSessionDto.getTransactionSupportsEidas()));
    return Response.ok().build();
}
 
Example 15
Project: athena   File: SubnetWebResource.java   View source code 6 votes vote down vote up
@DELETE
@Path("{subnetUUID}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response deleteSingleSubnet(@PathParam("subnetUUID") String id)
        throws IOException {
    try {
        SubnetId subId = SubnetId.subnetId(id);
        Set<SubnetId> subIds = new HashSet<>();
        subIds.add(subId);
        get(SubnetService.class).removeSubnets(subIds);
        return Response.noContent().entity("SUCCESS").build();
    } catch (Exception e) {
        return Response.status(INTERNAL_SERVER_ERROR).entity(e.toString())
                .build();
    }
}
 
Example 16
Project: redpipe   File: FCSPlugin.java   View source code 6 votes vote down vote up
@Override
public Single<Void> deployToResteasy(VertxResteasyDeployment deployment) {
	JsonArray packages = AppGlobals.get().getConfig().getJsonArray("scan");
	if(packages == null) {
		System.err.println("Not scanning any packages, please specify the 'scan' array of packages in configuration");
	}else {
		String[] packagesToScan = (String[]) packages.getList().toArray(new String[packages.size()+1]);
		packagesToScan[packagesToScan.length-1] = "net.redpipe.engine";
		new FastClasspathScanner(packagesToScan)
			.matchClassesWithAnnotation(Path.class, klass -> {
				if(!Modifier.isAbstract(klass.getModifiers()))
					deployment.getActualResourceClasses().add(klass);
			})
			.matchClassesWithAnnotation(Provider.class, klass -> {
				if(!Modifier.isAbstract(klass.getModifiers()))
					deployment.getActualProviderClasses().add(klass);
			})
			.scan();
	}
	return Single.just(null);
}
 
Example 17
Project: athena   File: EventExporterWebResource.java   View source code 6 votes vote down vote up
/**
 * Deletes subscription from a specific Onos event.
 *
 * @param input data in json format
 * @return 200 OK if successful or 400 BAD REQUEST
 * @onos.rsModel KafkaSubscription
 */
@DELETE
@Consumes(MediaType.APPLICATION_JSON)
@Path("unsubscribe")
public Response unsubscribe(InputStream input) {

    EventExporterService service = get(EventExporterService.class);

    try {
        EventSubscriber sub = parseSubscriptionData(input);
        service.subscribe(sub);
    } catch (Exception e) {
        log.error(e.getMessage());
        return Response.status(BAD_REQUEST).entity(e.getMessage()).build();
    }

    return ok(EVENT_SUBSCRIPTION_REMOVED).build();
}
 
Example 18
Project: microprofile-jwt-auth   File: ClaimValueInjectionEndpoint.java   View source code 6 votes vote down vote up
@GET
@Path("/verifyInjectedAudienceStandard")
@Produces(MediaType.APPLICATION_JSON)
public JsonObject verifyInjectedAudienceStandard(@QueryParam("aud") String audience) {
    boolean pass = false;
    String msg;
    // aud
    Set<String> audValue = audStandard.getValue();
    if(audValue == null || audValue.size() == 0) {
        msg = Claims.aud.name()+"value is null or empty, FAIL";
    }
    else if(audValue.contains(audience)) {
        msg = Claims.aud.name()+" PASS";
        pass = true;
    }
    else {
        msg = String.format("%s: %s != %s", Claims.aud.name(), audValue, audience);
    }
    JsonObject result = Json.createObjectBuilder()
        .add("pass", pass)
        .add("msg", msg)
        .build();
    return result;
}
 
Example 19
Project: athena   File: StatisticsWebResource.java   View source code 6 votes vote down vote up
/**
 * Gets table statistics for all tables of a specified device.
 *
 * @onos.rsModel StatisticsFlowsTables
 * @param deviceId device ID
 * @return 200 OK with JSON encoded array of table statistics
 */
@GET
@Path("flows/tables/{deviceId}")
@Produces(MediaType.APPLICATION_JSON)
public Response getTableStatisticsByDeviceId(@PathParam("deviceId") String deviceId) {
    final FlowRuleService service = get(FlowRuleService.class);
    final Iterable<TableStatisticsEntry> tableStatisticsEntries =
            service.getFlowTableStatistics(DeviceId.deviceId(deviceId));
    final ObjectNode root = mapper().createObjectNode();
    final ArrayNode rootArrayNode = root.putArray("statistics");

    final ObjectNode deviceStatsNode = mapper().createObjectNode();
    deviceStatsNode.put("device", deviceId);
    final ArrayNode statisticsNode = deviceStatsNode.putArray("table");
    for (final TableStatisticsEntry entry : tableStatisticsEntries) {
        statisticsNode.add(codec(TableStatisticsEntry.class).encode(entry, this));
    }
    rootArrayNode.add(deviceStatsNode);
    return ok(root).build();
}
 
Example 20
Project: InComb   File: ContentVotesService.java   View source code 6 votes vote down vote up
/**
 * Returns a {@link SimpleSearchResult} of all (see <code>offset</code> and <code>count</code>) news on which the user gave a "in".<br>
 * Returns a 200 Response.
 *
 * @param userId - Id for which the ins are loaded
 * @param loggedInUserId - Logged in user
 * @param offset - Start Index for search
 * @param count - Result count
 * @param con - Connection to DB
 * @return
 */
@GET
@Path("/ins")
public Response getIns(@PathParam("userId") final long userId, @QueryParam("loggedInUserId") final long loggedInUserId,
		@QueryParam("offset") final int offset, @QueryParam("count") final int count, @Context final Connection con) {
	getAccessChecker().checkPrivateProfile(userId);

	final ContentVoteDao contentVoteDao = new ContentVoteDao(con);
	final List<News> items = contentVoteDao.getNewsWithInsOfUser(userId, offset, count);

	final SimpleSearchResult<News> ssr = new SimpleSearchResult<>();
	for (final News news : items) {
		ssr.addResult(new NewsModel(news, loggedInUserId, con));
	}
	ssr.setTotalHits(contentVoteDao.getInsAmountForUser(userId)); //Used for paging
	return ok(ssr);
}
 
Example 21
Project: presto-manager   File: ControllerConnectorAPI.java   View source code 6 votes vote down vote up
@POST
@Path("/{file}")
@Produces(MediaType.TEXT_PLAIN)
@ApiOperation(value = "Replace this file with the file at the given URL")
@ApiResponses(value = {
        @ApiResponse(code = 207, message = "Multiple responses available"),
        @ApiResponse(code = 400, message = "Request contains invalid parameters")})
public Response setConnectorFileByURL(
        String url,
        @PathParam("file") String file,
        @QueryParam("scope") String scope,
        @QueryParam("nodeId") List<String> nodeId)
{
    ApiRequester apiRequester = requesterBuilder(ControllerConnectorAPI.class)
            .pathMethod("setConnectorFileByURL")
            .httpMethod(POST)
            .resolveTemplate("file", file)
            .accept(MediaType.TEXT_PLAIN)
            .entity(Entity.entity(url, MediaType.TEXT_PLAIN))
            .build();

    return forwardRequest(scope, apiRequester, nodeId);
}
 
Example 22
Project: opencps-v2   File: DeliverableTypesManagement.java   View source code 5 votes vote down vote up
@PUT
@Path("/{id}")
@Consumes({ MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "update Deliverabletypes")
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns", response = DeliverableTypesModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })
public Response updateDeliverableType(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context Company company, @Context Locale locale, @Context User user,
		@Context ServiceContext serviceContext, @BeanParam DeliverableTypeInputModel input,
		@ApiParam(value = "id of dossier", required = true) @PathParam("id") long id);
 
Example 23
Project: netty-jersey-guice-swagger   File: PingResource.java   View source code 5 votes vote down vote up
@GET
@Path("/async")
public void asyncPing(@Suspended final AsyncResponse response) {
    new Thread(() ->
        response.resume(Response.ok(pongService.getPong()).build())
    ).start();
}
 
Example 24
Project: Equella   File: EquellaItemResource.java   View source code 5 votes vote down vote up
@PUT
@Path("/quick/{filename}")
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Quick contribute a new item")
Response newItemQuick(
	@Context 
		UriInfo info,
	@ApiParam(value = "Filename", defaultValue = "") 
	@PathParam("filename") 
		String filename,
	InputStream binaryData);
 
Example 25
Project: javaee-calculator   File: CircuitBreakersAdmin.java   View source code 5 votes vote down vote up
@GET
@Path("{name}")
public Response find(@PathParam("name") String name) {
    if(!this.counters.containsKey(name))
        return Response.noContent().build();
    AtomicInteger atomicLong = this.counters.get(name);
    return Response.ok(atomicLong.longValue()).build();
}
 
Example 26
Project: scott-eu   File: ServiceProviderService.java   View source code 5 votes vote down vote up
/**
 * RDF/XML, XML and JSON representations of a single OSLC Service Provider
 *
 * @param serviceProviderId
 * @return
 */
@GET
@Path("{serviceProviderId}")
@Produces({OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_XML, OslcMediaType.APPLICATION_JSON})
public ServiceProvider getServiceProvider(@PathParam("serviceProviderId") final String serviceProviderId)
{
    httpServletResponse.addHeader("Oslc-Core-Version","2.0");
    return ServiceProviderCatalogSingleton.getServiceProvider(httpServletRequest, serviceProviderId);
}
 
Example 27
Project: presto-manager   File: ControlAPI.java   View source code 5 votes vote down vote up
@GET
@Path("/status")
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Get Presto status")
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Successfully retrieved Presto status")})
public synchronized Response prestoStatus()
{
    return controller.status();
}
 
Example 28
Project: Equella   File: EquellaTaskResource.java   View source code 5 votes vote down vote up
@GET
@Path("/filter")
@ApiOperation(value = "Get the counts for each task type")
public Response getTaskFilters(
	// @formatter:off
	@ApiParam(value = "Do not return task filters that contain no tasks. Implies includeCounts=true.", allowableValues = "true,false", defaultValue = "false", required = false)
	@QueryParam("ignoreZero")
		boolean ignoreZeroStr,
	@ApiParam(value = "Include task counts against each filter name.", allowableValues = "true,false", defaultValue = "false", required = false)
	@QueryParam("includeCounts")
		boolean includeCounts
	);
 
Example 29
Project: Pet-Supply-Store   File: AbstractCRUDEndpoint.java   View source code 5 votes vote down vote up
/**
 * Retreive and entity with the provided ID.
 * @param id ID of the entity to find.
 * @return A Response containing the entity.
 */
@GET
@Path("/{id:[0-9][0-9]*}")
public Response findById(@PathParam("id") final Long id) {
	if (id == null) {
		return Response.status(Status.NOT_FOUND).build();
	}
	T entity = findEntityById(id);
	if (entity == null) {
		return Response.status(Status.NOT_FOUND).build();
	}
	return Response.ok(entity).build();
}
 
Example 30
Project: athena   File: DevicesWebResource.java   View source code 5 votes vote down vote up
/**
 * Gets details of infrastructure device.
 * Returns details of the specified infrastructure device.
 *
 * @param id device identifier
 * @return 200 OK with a device
 * @onos.rsModel DeviceGet
 */
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response getDevice(@PathParam("id") String id) {
    Device device = nullIsNotFound(get(DeviceService.class).getDevice(deviceId(id)),
                                   DEVICE_NOT_FOUND);
    return ok(codec(Device.class).encode(device, this)).build();
}
 
Example 31
Project: opencps-v2   File: DeliverablesManagement.java   View source code 5 votes vote down vote up
@POST
@Path("/deliverables/agency/{agencyNo}/type/{typeCode}")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
@ApiOperation(value = "Get list dataform by agencyNo and typeCode")
@ApiResponses(value = {
		@ApiResponse (code = HttpURLConnection.HTTP_OK, message = "Return a list dataform"),
		@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not Found", response = ExceptionModel.class),
		@ApiResponse (code = HttpURLConnection.HTTP_FORBIDDEN, message = "Accsess denied", response = ExceptionModel.class) })
public Response getDataFormByTypeCode (@Context HttpServletRequest request, @Context HttpHeaders header, @Context Company company,
		@Context Locale locale, @Context User user, @Context ServiceContext serviceContext,
		@ApiParam(value = "id for agency", required = true) @PathParam("agencyNo") String agencyNo,
		@ApiParam(value = "id for type", required = true) @PathParam("typeCode") String typeCode,
		@FormParam("keyword") String keyword);
 
Example 32
Project: opencps-v2   File: DossierFileManagement.java   View source code 5 votes vote down vote up
@GET
@Path("/{id}/files/{referenceUid}/formdata")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
@ApiOperation(value = "getDossierFilesByDossierReferenceUid", response = JSONObject.class)
@ApiResponses(value = {
		@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a formdata", response = JSONObject.class),
		@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })
public Response getFormDataByDossierId_ReferenceUid(@Context HttpServletRequest request,
		@Context HttpHeaders header, @Context Company company, @Context Locale locale, @Context User user,
		@Context ServiceContext serviceContext,
		@ApiParam(value = "id of dossier", required = true) @PathParam("id") long id,
		@ApiParam(value = "referenceUid of dossierfile", required = true) @PathParam("referenceUid") String referenceUid);
 
Example 33
Project: dust-api   File: DeviceResource.java   View source code 5 votes vote down vote up
@GET
@Path("/{id:\\d+}/details-qr")
@Produces("image/png")
public Response deviceDetailsLinkQrCode(
        @PathParam("id") final Long id,
        @QueryParam("baseUrl") @DefaultValue(DEFAULT_BASE_URL) final String baseUrl
) throws IOException {
    final Device device = deviceRepo.findById(id);
    final byte[] detailsQr = qrCodeAsPng(baseUrl, device.nickname, "");
    return Response.ok(new ByteArrayInputStream(detailsQr)).build();
}
 
Example 34
Project: camunda-bpm-swagger   File: PathAnnotationStep.java   View source code 5 votes vote down vote up
public JMethod annotate(final String parentPathPrefix, final Method method) {

    this.path = path(parentPathPrefix, method);
    if (!TypeHelper.isResource(methodStep.getReturnType())) {
      getMethod().annotate(Path.class).param("value", this.path);
    }
    return getMethod();
  }
 
Example 35
Project: GoHost   File: UserFacadeREST.java   View source code 5 votes vote down vote up
@PUT
@Path("{id}")
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public void editIdprofile(@PathParam("id") Integer id, User entity) {
    super.edit(entity);

}
 
Example 36
Project: holon-examples   File: ProductEndpoint.java   View source code 5 votes vote down vote up
@POST
@Path("/products")
@Consumes(MediaType.APPLICATION_JSON)
public Response addProduct(@PropertySetRef(Product.class) PropertyBox product) {
	if (product == null) {
		return Response.status(Status.BAD_REQUEST).entity("Missing product").build();
	}
	// set id
	long nextId = getProductStore().nextId();
	product.setValue(ID, nextId);
	getProductStore().put(product);
	return Response.created(URI.create("/api/products/" + nextId)).build();
}
 
Example 37
Project: athena   File: ApiDocResource.java   View source code 5 votes vote down vote up
/**
 * Get REST API model schema.
 *
 * @param key REST API web context
 * @return 200 OK
 */
@GET
@Path("apis/{key: .*?}/model.json")
public Response getApiModel(@PathParam("name") String key) {
    String k = key.startsWith("/") ? key : "/" + key;
    InputStream stream = nullIsNotFound(get(ApiDocService.class).getDocProvider(k),
                                        "REST API not found for " + k).model();
    return ok(nullIsNotFound(stream, "REST API model not found for " + k))
            .header(CONTENT_TYPE, APPLICATION_JSON).build();
}
 
Example 38
Project: comdor   File: ChatResource.java   View source code 5 votes vote down vote up
/**
 * Consumes a JsonArray consisting of Github notifications json objects.
 * The <b>notifications are simplified</b>: a notification json looks
 * like this:
 * <pre>
 * {
 *     "repoFullName":"amihaiemil/myrepo",
 *     "issueNumber":23
 * }
 * </pre>
 * This info is enough. Since we have the repo and the issue that
 * triggered the notification, we can easily find out the earliest
 * comment where the Github agent was tagged.
 * <br><br>
 * <b>IMPORTANT:</b><br>
 * Each call to this endpoint has to contain the <b>Authorization
 * http header</b>, with a token <b>agreed upon</b> by this service
 * and the notification checker.<br>Technically, it might as well be the
 * Github auth token since it has to be the same on both parties,
 * but this is really sensitive information
 * and we should pass it around as little as possible.<br><br>
 * 
 * @param notifications Json array of simplified Github notifications.
 * @return Http Response.
 */
@POST
@Path("notifications")
public Response postNotifications(final String notifications) {
    final String token = this.request.getHeader(HttpHeaders.AUTHORIZATION);
    final int status;
    if(token == null || token.isEmpty()) {
        status = HttpURLConnection.HTTP_FORBIDDEN;
    } else {
        final String key = System.getProperty(GITHUB_API_TOKEN);
        if(token.equals(key)) {
            final boolean startedHandling = this.handleNotifications(
                new SimplifiedNotifications(notifications)
            );
            if(startedHandling) {
                status = HttpURLConnection.HTTP_OK;
            } else {
                status = HttpURLConnection.HTTP_INTERNAL_ERROR;
            }
        } else {
            LOG.error(
                "Missing or incorrect comdor.auth.token! "
                + "Notifications post is FORBIDDEN!"
            );
            status = HttpURLConnection.HTTP_FORBIDDEN;
        }
    }
    return Response.status(status).build();
}
 
Example 39
Project: athena   File: OpenstackFloatingIpWebResource.java   View source code 5 votes vote down vote up
/**
 * Delete FloatingIP.
 *
 * @param id FloatingIP identifier
 * @return 204 OK
 */
@DELETE
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response deleteFloatingIp(@PathParam("id") String id) {
    checkNotNull(id);

    OpenstackRoutingService routingService =
            getService(OpenstackRoutingService.class);
    routingService.deleteFloatingIP(id);

    log.debug("REST API DELETE floatingip is called {}", id);

    return Response.noContent().build();
}
 
Example 40
Project: opencps-v2   File: DossierLogManagement.java   View source code 5 votes vote down vote up
@GET
@Path("/{id}/logs")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "Get DossierLog by Id", response = DossierLogSearchIdResultsModel.class)
@ApiResponses(value = {
		@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a list of all DossierLogs", response = DossierLogSearchIdResultsModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })
public Response getDossierLogById(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context Company company, @Context Locale locale, @Context User user,
		@Context ServiceContext serviceContext, @BeanParam DossierLogSearchModel query,
		@ApiParam(value = "id of dossier", required = true) @PathParam("id") long dossierId,
		@ApiParam(value = "password for access dossier log", required = false) @PathParam("password") String password);
 
Example 41
Project: ctsms   File: EcrfStatusEntryResource.java   View source code 5 votes vote down vote up
@GET
@Produces({ MediaType.APPLICATION_JSON })
@Path("{listEntryId}/ecrffieldvalue/{ecrfFieldId}")
public JsValuesOutVOPage<ECRFFieldValueOutVO, ECRFFieldValueJsonVO> getEcrfFieldValue(@PathParam("listEntryId") Long listEntryId, @PathParam("ecrfFieldId") Long ecrfFieldId)
		throws AuthenticationException, AuthorisationException, ServiceException {
	ECRFFieldValuesOutVO values = WebUtil.getServiceLocator().getTrialService().getEcrfFieldValue(auth, listEntryId, ecrfFieldId, null);
	return new JsValuesOutVOPage<ECRFFieldValueOutVO, ECRFFieldValueJsonVO>(values.getPageValues(), values.getJsValues(), null);
}
 
Example 42
Project: opencps-v2   File: OfficeSiteManagement.java   View source code 5 votes vote down vote up
@PUT
@Path("/{id}/preferences/{key}")
@Consumes({ MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response updateOfficeSitePreferencesByKey(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context Company company, @Context Locale locale, @Context User user,
		@Context ServiceContext serviceContext, @PathParam("id") long id, @PathParam("key") String key, @FormParam("value") String value);
 
Example 43
Project: ctsms   File: TrialResource.java   View source code 5 votes vote down vote up
@GET
@Produces({ MediaType.APPLICATION_JSON })
@Path("signup")
public Page<TrialOutVO> getTrialListSignup(@QueryParam("department_id") Long departmentId, @Context UriInfo uriInfo)
		throws AuthenticationException, AuthorisationException, ServiceException {
	PSFUriPart psf = new PSFUriPart(uriInfo, "department_id");
	return new Page<TrialOutVO>(WebUtil.getServiceLocator().getTrialService().getSignupTrialList(auth, departmentId, psf), psf);
}
 
Example 44
Project: personium-core   File: ODataEntityResource.java   View source code 5 votes vote down vote up
/**
 * $links/{navProp} というパスの処理.
 * ODataLinksResourceに処理を委譲.
 * @param targetNavProp Navigation Property
 * @return ODataLinksResource オブジェクト
 */
@Path("{first: \\$}links/{targetNavProp:.+?}")
public ODataLinksResource links(@PathParam("targetNavProp") final String targetNavProp) {
    OEntityKey oeKey = OEntityKey.parse(this.keyString);
    OEntityId oeId = OEntityIds.create(getEntitySetName(), oeKey);
    return new ODataLinksResource(this.odataResource, oeId, targetNavProp, null);
}
 
Example 45
Project: presto-manager   File: ConnectorsAPI.java   View source code 5 votes vote down vote up
@GET
@Path("/{file}")
@Produces(MediaType.TEXT_PLAIN)
@ApiOperation(value = "Get contents of a connector file")
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Retrieved file"),
        @ApiResponse(code = 404, message = "Resource not found")})
public synchronized Response getConnectorFile(
        @PathParam("file") @ApiParam("The name of a file") String file)
{
    return apiFileHandler.getFile(file);
}
 
Example 46
Project: holon-jaxrs   File: TestAuthJwt.java   View source code 5 votes vote down vote up
@RolesAllowed({ "R1", "R3" })
@GET
@Path("r13")
@Produces(MediaType.TEXT_PLAIN)
public String r13() {
	return "r13";
}
 
Example 47
Project: oscm   File: BillingAppResource.java   View source code 5 votes vote down vote up
@GET
@Path("ping")
@Produces(MediaType.TEXT_PLAIN)
public Response ping() {
    FileBilling fb = new FileBilling();
    return Response.ok(fb.getSuccessfulConnectionMsg()).build();
}
 
Example 48
Project: app-ms   File: SwaggerResource.java   View source code 5 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{version}")
public Swagger swagger(@PathParam("version") final String version,
    @Context final UriInfo uriInfo) {

    if (!collator.isPathExists(version)) {
        throw new NotFoundException();
    }
    return collator.getSwagger(version, uriInfo);
}
 
Example 49
Project: opencps-v2   File: DeliverableTypesManagement.java   View source code 5 votes vote down vote up
@PUT
@Path("/{id}/mappingdata")
@Consumes({ MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "update mappingdata")
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns"),
		@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })
public Response updateDeliverableTypeMappingData(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context Company company, @Context Locale locale, @Context User user,
		@Context ServiceContext serviceContext,
		@ApiParam(value = "id of DeliverableType", required = true) @PathParam("id") long deliverableTypeId,
		@ApiParam(value = "MappingData of dossierfile", required = true) @FormParam("mappingData") String mappingData);
 
Example 50
Project: security-mgr-sample-plugin   File: DeviceApis.java   View source code 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Path("/{deviceId}/members")
@GET
public List<String> getDeviceMembersIds(@PathParam("deviceId") Long deviceId) throws Exception {
    LOG.info(String.format("Getting the device members ids for deviceid %s ", "" + Long.toString(deviceId)));
    List<DeviceMemberEntity> deviceMembers = new ArrayList<DeviceMemberEntity>();
    List<String> members = new ArrayList<String>();
    deviceMembers = (List<DeviceMemberEntity>) this.api.listDeviceMembers(deviceId);
    if (!deviceMembers.isEmpty()) {
        members = deviceMembers.stream().map(DeviceMemberEntity::getId).collect(Collectors.toList());
    }
    return members;
}