Java Code Examples for javax.ws.rs.PathParam

The following are top voted examples for showing how to use javax.ws.rs.PathParam. 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: scott-eu   File: ServiceProviderService1.java   View source code 6 votes vote down vote up
@GET
@Path("{planId}")
@Produces({ MediaType.TEXT_HTML })
public Response getPlanAsHtml(
    @PathParam("serviceProviderId") final String serviceProviderId, @PathParam("planId") final String planId
    ) throws ServletException, IOException, URISyntaxException
{
    // Start of user code getPlanAsHtml_init
    // End of user code

    final Plan aPlan = PlannerReasonerManager.getPlan(httpServletRequest, serviceProviderId, planId);

    if (aPlan != null) {
        httpServletRequest.setAttribute("aPlan", aPlan);
        // Start of user code getPlanAsHtml_setAttributes
        // End of user code

        RequestDispatcher rd = httpServletRequest.getRequestDispatcher("/se/ericsson/cf/scott/sandbox/plan.jsp");
        rd.forward(httpServletRequest,httpServletResponse);
    }

    throw new WebApplicationException(Status.NOT_FOUND);
}
 
Example 3
Project: scott-eu   File: ServiceProviderService1.java   View source code 6 votes vote down vote up
@GET
@Path("places/{placeId}")
@Produces({ MediaType.TEXT_HTML })
public Response getPlaceAsHtml(
    @PathParam("serviceProviderId") final String serviceProviderId, @PathParam("placeId") final String placeId
    ) throws ServletException, IOException, URISyntaxException
{
    // Start of user code getPlaceAsHtml_init
    // End of user code

    final Place aPlace = WarehouseControllerManager.getPlace(httpServletRequest, serviceProviderId, placeId);

    if (aPlace != null) {
        httpServletRequest.setAttribute("aPlace", aPlace);
        // Start of user code getPlaceAsHtml_setAttributes
        // End of user code

        RequestDispatcher rd = httpServletRequest.getRequestDispatcher("/se/ericsson/cf/scott/sandbox/place.jsp");
        rd.forward(httpServletRequest,httpServletResponse);
    }

    throw new WebApplicationException(Status.NOT_FOUND);
}
 
Example 4
Project: lra-service   File: Coordinator.java   View source code 6 votes vote down vote up
@GET
@Path("{NestedLraId}/status")
public Response getNestedLRAStatus(@PathParam("NestedLraId")String nestedLraId) {
    if (!lraService.hasTransaction(nestedLraId)) {
        // it must have compensated TODO maybe it's better to keep nested LRAs in separate collection
        return Response.ok(CompensatorStatus.Compensated.name()).build();
    }

    Transaction lra = lraService.getTransaction(toURL(nestedLraId));
    CompensatorStatus status = lra.getLRAStatus();

    if (status == null || lra.getLRAStatus() == null) {
        LRALogger.i18NLogger.error_cannotGetStatusOfNestedLra(nestedLraId, lra.getId());
        throw new IllegalLRAStateException(nestedLraId, "The LRA is still active", "getNestedLRAStatus");
    }

    return Response.ok(lra.getLRAStatus().name()).build();
}
 
Example 5
Project: presto-manager   File: LogsAPI.java   View source code 6 votes vote down vote up
@GET
@Path("/{file}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Get Presto log file")
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Retrieved logs"),
        @ApiResponse(code = 400, message = "Invalid parameters"),
        @ApiResponse(code = 404, message = "Resource not found")})
public Response getLog(
        @PathParam("file") @ApiParam("The name of a file") String file,
        @QueryParam("from") @ApiParam("Ignore logs before this date") Instant fromDate,
        @QueryParam("to") @ApiParam("Ignore logs after this date") Instant toDate,
        @QueryParam("level") @ApiParam("Only get logs of this level") @DefaultValue(LogsHandler.DEFAULT_LOG_LEVEL) String level,
        @QueryParam("n") @ApiParam("The maximum number of log entries to get") Integer maxEntries)
{
    return logsHandler.getLogs(file, fromDate, toDate, level, maxEntries);
}
 
Example 6
Project: bootstrap   File: ApiTokenResource.java   View source code 6 votes vote down vote up
/**
 * Update a named token with a new generated one.
 * 
 * @param name
 *            Token to update.
 * @return the new generated token.
 */
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Path("{name:[\\w\\-\\.]+}")
public String update(@PathParam("name") final String name) throws GeneralSecurityException {
	final SystemApiToken entity = repository.findByUserAndName(securityHelper.getLogin(), name);
	if (entity == null) {
		// No token with given name
		throw new EntityNotFoundException();
	}

	// Token has been found, update it
	final String token = newToken(entity);
	repository.saveAndFlush(entity);
	return token;
}
 
Example 7
Project: xsharing-services-router   File: ControlResource.java   View source code 6 votes vote down vote up
@PUT
@Path("/log/change-level/{loggerName}/{newLevel}")
public Response changeLogLevel(@PathParam("loggerName") String loggerName,
                               @PathParam("newLevel") String newLevel) {

    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration config = ctx.getConfiguration();
    LoggerConfig loggerConfig = config.getLoggerConfig(loggerName);

    if (loggerConfig.getName().equals(LogManager.ROOT_LOGGER_NAME)) {
        return Response.ok("Not found", MediaType.TEXT_PLAIN).build();
    }

    loggerConfig.setLevel(Level.valueOf(newLevel));
    ctx.updateLoggers();  // This causes all Loggers to refetch information from their LoggerConfig.

    return Response.ok("Done", MediaType.TEXT_PLAIN).build();
}
 
Example 8
Project: dremio-oss   File: HomeResource.java   View source code 6 votes vote down vote up
@PUT
@Path("file_format/{path: .*}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public FileFormatUI saveFormatSettings(FileFormat fileFormat, @PathParam("path") String path)
    throws FileNotFoundException, HomeNotFoundException, NamespaceException {
  FilePath filePath = FilePath.fromURLPath(homeName, path);
  // merge file configs
  final DatasetConfig existingDSConfig = namespaceService.getDataset(filePath.toNamespaceKey());
  final FileConfig oldConfig = toFileConfig(existingDSConfig);
  final FileConfig newConfig = fileFormat.asFileConfig();
  newConfig.setCtime(oldConfig.getCtime());
  newConfig.setFullPathList(oldConfig.getFullPathList());
  newConfig.setName(oldConfig.getName());
  newConfig.setOwner(oldConfig.getOwner());
  newConfig.setLocation(oldConfig.getLocation());
  catalogService.createOrUpdateDataset(namespaceService, new NamespaceKey(HomeFileConfig.HOME_PLUGIN_NAME), filePath.toNamespaceKey(), toDatasetConfig(newConfig, DatasetType.PHYSICAL_DATASET_HOME_FILE,
    securityContext.getUserPrincipal().getName(), existingDSConfig.getId()));
  return new FileFormatUI(FileFormat.getForFile(newConfig), filePath);
}
 
Example 9
Project: osc-core   File: ApplianceApis.java   View source code 6 votes vote down vote up
@ApiOperation(value = "Deletes a Security Function Software Version",
        notes = "Deletes a Security Function Software Version if not referenced by any Distributed Appliances")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Successful operation"),
        @ApiResponse(code = 400, message = "In case of any error", response = ErrorCodeDto.class) })
@Path("/{applianceId}/versions/{ApplianceSoftwareVersionId}")
@DELETE
public Response deleteApplianceSoftwareVersion(@Context HttpHeaders headers,
        @ApiParam(value = "Id of the Appliance Model", required = true) @PathParam("applianceId") Long applianceId,
        @ApiParam(value = "Id of the Appliance Software Version",
        required = true) @PathParam("ApplianceSoftwareVersionId") Long applianceSoftwareVersionId) {
    logger.info(
            "Deleting Appliance Software Version " + applianceSoftwareVersionId + " from appliance " + applianceId);
    this.userContext.setUser(OscAuthFilter.getUsername(headers));
    return this.apiUtil.getResponseForBaseRequest(this.deleteApplianceSoftwareVersionService,
            new BaseIdRequest(applianceSoftwareVersionId, applianceId));
}
 
Example 10
Project: scott-eu   File: ResourceShapeService.java   View source code 6 votes vote down vote up
@GET
@Path("{resourceShapePath}")
@Produces({ MediaType.TEXT_HTML })
public Response getResourceShapeAsHtml(
        @PathParam("resourceShapePath") final String resourceShapePath
    ) throws ServletException, IOException, URISyntaxException, OslcCoreApplicationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException
{
    final Class<?> resourceClass = Application.getResourceShapePathToResourceClassMap().get(resourceShapePath);
    ResourceShape aResourceShape = null;
    
    if (resourceClass != null)
    {
        aResourceShape = (ResourceShape) resourceClass.getMethod("createResourceShape").invoke(null);
        httpServletRequest.setAttribute("aResourceShape", aResourceShape);
        
        RequestDispatcher rd = httpServletRequest.getRequestDispatcher("/se/ericsson/cf/scott/sandbox/resourceshape.jsp");
        rd.forward(httpServletRequest,httpServletResponse);
    }
    throw new WebApplicationException(Status.NOT_FOUND);
}
 
Example 11
Project: gitplex-mit   File: CommitStatusResource.java   View source code 6 votes vote down vote up
@Consumes(MediaType.APPLICATION_JSON)
@Path("/{projectName}/statuses/{commit}")
   @POST
   public Response save(@PathParam("projectName") String projectName, @PathParam("commit") String commit, 
   		Map<String, String> commitStatus, @Context UriInfo uriInfo) {

	Project project = getProject(projectName);
   	if (!SecurityUtils.canWrite(project))
   		throw new UnauthorizedException();
   	
   	String state = commitStatus.get("state").toUpperCase();
   	if (state.equals("PENDING"))
   		state = "RUNNING";
   	Verification verification = new Verification(Verification.Status.valueOf(state), 
   			new Date(), commitStatus.get("description"), commitStatus.get("target_url"));
   	String context = commitStatus.get("context");
   	if (context == null)
   		context = "default";
   	verificationManager.saveVerification(project, commit, context, verification);
   	UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
   	uriBuilder.path(context);
   	commitStatus.put("id", "1");
   	
   	return Response.created(uriBuilder.build()).entity(commitStatus).type(RestConstants.JSON_UTF8).build();
   }
 
Example 12
Project: marathonv5   File: LiveSalesListFacadeREST.java   View source code 6 votes vote down vote up
@GET
@Produces({"application/xml", "application/json"})
@Path("/recent/region/producttype/{regionName}/{productTypeId}")
public List<LiveSalesList> findRecentRegionProductType(@PathParam("regionName") String regionName, @PathParam("productTypeId") Integer productTypeId) {
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    javax.persistence.criteria.CriteriaQuery cq = cb.createQuery();
    Root<LiveSalesList> liveSalesList = cq.from(LiveSalesList.class);
    cq.select(liveSalesList);
    cq.where(cb.and(
            cb.equal(liveSalesList.get(LiveSalesList_.productTypeId), productTypeId), 
            cb.equal(liveSalesList.get(LiveSalesList_.region), regionName)
    ));
    Query q = getEntityManager().createQuery(cq);
    q.setMaxResults(500);
    return q.getResultList();
}
 
Example 13
Project: dremio-oss   File: HomeResource.java   View source code 6 votes vote down vote up
@POST
@Path("/folder/{path: .*}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Folder createFolder(FolderName name, @PathParam("path") String path) throws Exception  {
  String fullPath = PathUtils.toFSPathString(Arrays.asList(path, name.toString()));
  FolderPath folderPath = FolderPath.fromURLPath(homeName, fullPath);

  final FolderConfig folderConfig = new FolderConfig();
  folderConfig.setFullPathList(folderPath.toPathList());
  folderConfig.setName(folderPath.getFolderName().getName());
  try {
    namespaceService.addOrUpdateFolder(folderPath.toNamespaceKey(), folderConfig);
  } catch(NamespaceNotFoundException nfe) {
    throw new ClientErrorException("Parent folder doesn't exist", nfe);
  }

  return newFolder(folderPath, folderConfig, null);
}
 
Example 14
Project: marathonv5   File: LiveSalesListFacadeREST.java   View source code 6 votes vote down vote up
@GET
@Produces({"application/xml", "application/json"})
@Path("/recent/region/producttype/{regionName}/{productTypeId}/{orderLineId}")
public List<LiveSalesList> findRecentRegionProductTypeFrom(@PathParam("regionName") String regionName, @PathParam("productTypeId") Integer productTypeId, @PathParam("orderLineId") Integer orderLineId) {
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    javax.persistence.criteria.CriteriaQuery cq = cb.createQuery();
    Root<LiveSalesList> liveSalesList = cq.from(LiveSalesList.class);
    cq.select(liveSalesList);
    cq.where(cb.and(
        cb.equal(liveSalesList.get(LiveSalesList_.productTypeId), productTypeId),
        cb.equal(liveSalesList.get(LiveSalesList_.region), regionName),
        cb.gt(liveSalesList.get(LiveSalesList_.orderLineId), orderLineId)
    ));
    Query q = getEntityManager().createQuery(cq);
    q.setMaxResults(500);
    return q.getResultList();
}
 
Example 15
Project: personium-core   File: RoleResource.java   View source code 5 votes vote down vote up
/**
     * Box単位のRoleリソースのルート.
     * Boxに紐付いたロール一覧を返す。
     * Box名として__を指定されたときは、Cellレベルのロールとみなす。
     * @param boxName boxName
     * @param authzHeader authzHeader
     * @return JAXRS Response
     */
    @Path("{box}")
    @GET
    public final Response cellRole(
            @PathParam("box") String boxName,
            @HeaderParam(HttpHeaders.AUTHORIZATION) final String authzHeader) {
        // アクセス制御
        this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), CellPrivilege.AUTH_READ);
        // BoxパスがCell Levelであれば、Cell レベルロールを検索して一覧で返す。
        if (BOX_PATH_CELL_LEVEL.equals(boxName)) {
            // TODO Bodyの生成
//            EntitiesResponse er = this.op.getEntities(Role.EDM_TYPE_NAME, null);
            return Response.ok().entity(boxName).build();
        }
        try {
//            EntityResponse boxEr = op.getEntity(Box.EDM_TYPE_NAME, OEntityKey.create(boxName), null);
//            EntitiesResponse rolesEr = (EntitiesResponse) op.getNavProperty(Role.EDM_TYPE_NAME,
//                    OEntityKey.create(boxName),
//                    "_role",  null);
            // TODO Bodyの生成
            return Response.ok().entity(boxName).build();
        } catch (PersoniumCoreException pce) {
            if (PersoniumCoreException.OData.NO_SUCH_ENTITY == pce) {
                throw PersoniumCoreException.Dav.BOX_NOT_FOUND;
            }
            throw pce;
        }
    }
 
Example 16
Project: syndesis   File: JsonDBResource.java   View source code 5 votes vote down vote up
@Path("/{path: .*}.json")
@Consumes(APPLICATION_JSON)
@DELETE
public Response delete(@PathParam("path") String path) {
    Response.Status status;
    if( jsondb.delete(path) ) {
        status = Response.Status.NO_CONTENT;
    } else {
        status = Response.Status.NOT_FOUND;
    }
    return Response.status(status).build();
}
 
Example 17
Project: E-Clinic   File: ContactRestEndPoint.java   View source code 5 votes vote down vote up
@DELETE
@Path("delete/{id}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response delete(@PathParam("id") String id) throws Throwable {
    try {
        Contact get = contactService.get(Integer.valueOf(id));
        contactService.delete(get);
    } catch (Exception ex) {
        return Response.ok().header("Exception", ex.getMessage()).build();
    }
    return Response.ok().entity("Data is deleted").build();
}
 
Example 18
Project: verify-hub   File: IdentityProviderResource.java   View source code 5 votes vote down vote up
@GET
@Path(Urls.ConfigUrls.ENABLED_ID_PROVIDERS_FOR_SIGN_IN_PATH)
@Timed
public Collection<String> getEnabledIdentityProviderEntityIdsForSignIn(
        @PathParam(Urls.ConfigUrls.ENTITY_ID_PATH_PARAM) final String transactionEntityId) {
    return getIdpListForSignIn(transactionEntityId).stream().map(idp -> idp.getEntityId()).collect(Collectors.toList());
}
 
Example 19
Project: E-Clinic   File: PharmacistRestEndPoint.java   View source code 5 votes vote down vote up
@GET
@Path("find/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response find(@PathParam("id") @Valid String id) {
    JsonObject build = null;
    try {
        Pharmacist get = pharmacistService.get(Integer.valueOf(id));
        build = Json.createObjectBuilder().add("id", get.getPharmacistId()).add("name", get.getPersonId().getFirstName()).build();

    } catch (Exception ex) {
        return Response.ok().header("Exception", ex.getMessage()).build();
    }
    return Response.ok().entity(build == null ? "No data found" : build).build();
}
 
Example 20
Project: mid-tier   File: LocationEventServiceExposure.java   View source code 5 votes vote down vote up
@GET
@Path("{category}")
@Produces({ "application/hal+json", "application/hal+json;concept=eventcategory;v=1"})
@ApiOperation(value = "obtain all events scoped to a certain category", response = EventsRepresentation.class,
        notes = " the events are signalled by this resource as this this is the authoritative resource for all events that " +
                "subscribers to the customer service should be able to listen for and react to. In other words this is the authoritative" +
                "feed for the customer service, allowing for subscribers to have these grouped into categories",
        authorizations = {
                @Authorization(value = "oauth2", scopes = {}),
                @Authorization(value = "oauth2-cc", scopes = {}),
                @Authorization(value = "oauth2-ac", scopes = {}),
                @Authorization(value = "oauth2-rop", scopes = {}),
                @Authorization(value = "Bearer")
        },
        tags = {"interval", "events"},
        produces = "application/hal+json,  application/hal+json;concept=eventcategory;v=1",
        nickname = "getlocationEventsByCategory"
    )
@ApiResponses(value = {
        @ApiResponse(code = 415, message = "Content type not supported.")
    })
public Response getByCategory(@Context UriInfo uriInfo, @Context Request request,
                              @HeaderParam("Accept") String accept, @PathParam("category") String category,
                              @QueryParam("interval") String interval) {
    return eventCategoryProducers.getOrDefault(accept, this::handleUnsupportedContentType)
            .getResponse(uriInfo, request, category, interval);
}
 
Example 21
Project: flightmanager   File: CompanyResource.java   View source code 5 votes vote down vote up
/**
 * PUT method for updating or creating an instance of CompanyResource
 *
 * @param content representation for the resource
 */
@PUT
@Path("{id}")
@Consumes(MediaType.APPLICATION_JSON)
public void putCompany(@PathParam("id") long id, Company content) {
    content.setId(id);
    DAOFactory.INSTANCE.getCompanyDAO().update(content);
}
 
Example 22
Project: E-Clinic   File: ClinicManagerRestEndPoint.java   View source code 5 votes vote down vote up
@DELETE
@Path("delete/{id}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response delete(@PathParam("id") String id) throws Throwable {
    try {
        Clinicmanager get = clinicManagerService.get(Integer.valueOf(id));
        clinicManagerService.delete(get);
    } catch (Exception ex) {
        return Response.ok().header("Exception", ex.getMessage()).build();
    }
    return Response.ok().entity("Data is deleted").build();
}
 
Example 23
Project: opencps-v2   File: DossierManagement.java   View source code 5 votes vote down vote up
@GET
@Path("/{id}/correcting")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "Owner requset correcting for Dossier", response = DossierDetailModel.class)
@ApiResponses(value = {
		@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a Dossier has been correcting requested", response = DossierDetailModel.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 correctingDossier(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context Company company, @Context Locale locale, @Context User user,
		@Context ServiceContext serviceContext, @PathParam("id") String id);
 
Example 24
Project: paraflow   File: HelloWorldService.java   View source code 5 votes vote down vote up
@GET
@Path("/{param}")
public Response getMsg(@PathParam("param") String msg)
{
    String output = "Hello say : " + msg;
    return Response.status(200).entity(output).build();
}
 
Example 25
Project: javaee8-jaxrs-sample   File: CommentsResource.java   View source code 5 votes vote down vote up
@Path("{commentId}")
@DELETE
public Response deleteComment(@PathParam("commentId") Long commentId) {
    return comments.findOptionalById(commentId)
        .map(c -> comments.delete(c))
        .map(c -> Response.noContent().build())
        .orElseThrow(() -> new CommentNotFoundException(commentId));

}
 
Example 26
Project: plugin-vm-vcloud   File: VCloudPluginResource.java   View source code 5 votes vote down vote up
/**
 * Find the virtual machines matching to the given criteria. Look into
 * virtual machine name only.
 * 
 * @param node
 *            the node to be tested with given parameters.
 * @param criteria
 *            the search criteria. Case is insensitive.
 * @return virtual machines.
 */
@GET
@Path("{node:[a-z].*}/{criteria}")
@Consumes(MediaType.APPLICATION_JSON)
public List<VCloudVm> findAllByName(@PathParam("node") final String node, @PathParam("criteria") final String criteria)
		throws IOException, SAXException, ParserConfigurationException {
	// Check the node exists
	if (nodeRepository.findOneVisible(node, securityHelper.getLogin()) == null) {
		return Collections.emptyList();
	}

	// Get the VMs and parse them
	return toVms(getVCloudResource(pvResource.getNodeParameters(node),
			"/query?type=vm&format=idrecords&filter=name==*" + criteria + "*&sortAsc=name&fields=name,guestOs&pageSize=10"));
}
 
Example 27
Project: gitplex-mit   File: PullRequestResource.java   View source code 5 votes vote down vote up
@Path("/{name}/pulls/{pullRequestNumber}/commits")
@GET
public Response getCommits(@PathParam("name") String projectName, 
		@PathParam("pullRequestNumber") Long pullRequestNumber) {
	Project project = getProject(projectName);

	if (!SecurityUtils.canRead(project))
   		throw new UnauthorizedException("Unauthorized access to project '" + projectName + "'");
	
	PullRequest request = pullRequestManager.find(project, pullRequestNumber);
	List<Map<String, Object>> entity = new ArrayList<>();
	for (RevCommit commit: request.getCommits()) {
		Map<String, Object> commitMap = new HashMap<>();
		commitMap.put("sha", commit.name());
		
		Map<String, Object> commitDetailMap = new HashMap<>();
		Map<String, String> authorMap = new HashMap<>();
		authorMap.put("name", commit.getAuthorIdent().getName());
		authorMap.put("email", commit.getAuthorIdent().getEmailAddress());
		authorMap.put("date", new SimpleDateFormat(RestConstants.DATE_FORMAT).format(commit.getAuthorIdent().getWhen()));
		commitDetailMap.put("author", authorMap);
		
		Map<String, String> committerMap = new HashMap<>();
		committerMap.put("name", commit.getCommitterIdent().getName());
		committerMap.put("email", commit.getCommitterIdent().getEmailAddress());
		committerMap.put("date", new SimpleDateFormat(RestConstants.DATE_FORMAT).format(commit.getCommitterIdent().getWhen()));
		commitDetailMap.put("committer", authorMap);
		
		commitMap.put("commit", commitDetailMap);
		
		entity.add(commitMap);
	}
   	return Response.ok(entity, RestConstants.JSON_UTF8).build();
}
 
Example 28
Project: dremio-oss   File: ProvisioningResource.java   View source code 5 votes vote down vote up
@GET
@Path("/cluster/{id}")
@Produces(MediaType.APPLICATION_JSON)
public ClusterResponse getClusterInfo(@PathParam("id") final String id) throws Exception {
  ClusterEnriched cluster = service.getClusterInfo(new ClusterId(id));
  return toClusterResponse(cluster);
}
 
Example 29
Project: opencps-v2   File: DeliverablesManagement.java   View source code 5 votes vote down vote up
@GET
@Path("/deliverables/{id}/preview")
@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 info preview for deliverable id")
@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 defined", response = ExceptionModel.class) })
public Response getPreview(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context Company company, @Context Locale locale, @Context User user, @Context ServiceContext serviceContext,
		@ApiParam(value = "id of Deliverable", required = true) @PathParam("id") Long id);
 
Example 30
Project: athena   File: FlowsWebResource.java   View source code 5 votes vote down vote up
/**
 * Removes flow rules by application ID.
 * Removes a collection of flow rules generated by the given application.
 *
 * @param appId application identifier
 * @return 204 NO CONTENT
 */
@DELETE
@Produces(MediaType.APPLICATION_JSON)
@Path("application/{appId}")
public Response removeFlowByAppId(@PathParam("appId") String appId) {
    final ApplicationService appService = get(ApplicationService.class);
    final ApplicationId idInstant = nullIsNotFound(appService.getId(appId), APP_ID_NOT_FOUND);
    service.removeFlowRulesById(idInstant);
    return Response.noContent().build();
}
 
Example 31
Project: vc   File: PersonResource.java   View source code 5 votes vote down vote up
@DELETE
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Person deletePerson(@PathParam("id") String id) {
    Person PersonResponse = Person_Service.deletePerson(id);
    return PersonResponse;
}
 
Example 32
Project: E-Clinic   File: NurseRestEndPoint.java   View source code 5 votes vote down vote up
@DELETE
@Path("delete/{id}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response delete(@PathParam("id") String id) throws Throwable {
    System.out.println("delete"+ id);
    try {
        Nurse get = nurseService.get(Integer.valueOf(id));
        nurseService.delete(get);
    } catch (Exception ex) {
        return Response.ok().header("Exception", ex.getMessage()).build();
    }
    return Response.ok().entity("Data is deleted").build();
}
 
Example 33
Project: athena   File: MastershipWebResource.java   View source code 5 votes vote down vote up
/**
 * Abandons mastership of the specified device on the local node thus
 * forcing selection of a new master. If the local node is not a master
 * for this device, no master selection will occur.
 *
 * @param deviceId device identifier
 * @return status of the request - CREATED if the JSON is correct
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{deviceId}/relinquish")
public Response relinquishMastership(@PathParam("deviceId") String deviceId) {
    DeviceId id = DeviceId.deviceId(deviceId);
    mastershipService.relinquishMastershipSync(id);
    return Response.created(id.uri()).build();
}
 
Example 34
Project: ZooKeeper   File: SessionsResource.java   View source code 5 votes vote down vote up
@PUT
@Produces( { MediaType.APPLICATION_JSON, "application/javascript",
        MediaType.APPLICATION_XML })
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
public Response keepAliveSession(@PathParam("session") String session,
        @Context UriInfo ui, byte[] data) {

    if (!ZooKeeperService.isConnected(contextPath, session)) {
        throwNotFound(session, ui);
    }

    ZooKeeperService.resetTimer(contextPath, session);
    return Response.status(Response.Status.OK).build();
}
 
Example 35
Project: dremio-oss   File: StorageResource.java   View source code 5 votes vote down vote up
@GET
@Path("/{name}.json")
@Produces(APPLICATION_JSON)
public PluginConfigWrapper getStoragePluginJSON(@PathParam("name") String name) {
  try {
    StoragePlugin plugin = pluginConfiguration.getPlugin(name);
    if (plugin != null) {
      return new PluginConfigWrapper(name, plugin.getConfig());
    }
  } catch (Exception e) {
    throw new BadRequestException("Failure while trying to access storage config: " + name, e);
  }
  return new PluginConfigWrapper(name, null);
}
 
Example 36
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 37
Project: ctsms   File: SearchResource.java   View source code 5 votes vote down vote up
@GET
@Produces({ MediaType.APPLICATION_JSON })
@Path("user/{id}/search")
public Page<NoShortcutSerializationWrapper<UserOutVO>> searchUserByCriteria(@PathParam("id") Long id, @Context UriInfo uriInfo)
		throws AuthenticationException, AuthorisationException, ServiceException {
	PSFUriPart psf = new PSFUriPart(uriInfo);
	Collection result = WebUtil.getServiceLocator().getSearchService().searchUserByCriteria(auth, id, ResourceUtils.LIST_GRAPH_MAX_USER_INSTANCES, psf);
	NoShortcutSerializationWrapper.transformVoCollection(result);
	return new Page<NoShortcutSerializationWrapper<UserOutVO>>(result, psf);
}
 
Example 38
Project: opencps-v2   File: DossierManagement.java   View source code 5 votes vote down vote up
@GET
@Path("/{id}/cancelling")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "Owner requset cancalling for Dossier", response = DossierDetailModel.class)
@ApiResponses(value = {
		@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a Dossier has been cancelled", response = DossierDetailModel.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 cancellingDossier(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context Company company, @Context Locale locale, @Context User user,
		@Context ServiceContext serviceContext, @PathParam("id") String id);
 
Example 39
Project: oryx2   File: Preference.java   View source code 5 votes vote down vote up
@POST
@Path("{userID}/{itemID}")
@Consumes({MediaType.TEXT_PLAIN, "text/csv", MediaType.APPLICATION_JSON})
public void post(
    @PathParam("userID") String userID,
    @PathParam("itemID") String itemID,
    Reader reader) throws IOException, OryxServingException {
  checkNotReadOnly();
  BufferedReader bufferedReader = maybeBuffer(reader);
  String line = bufferedReader.readLine();
  String value = validateAndStandardizeStrength(line);
  sendToTopic(userID, itemID, value);
}
 
Example 40
Project: hadoop   File: RMWebServices.java   View source code 5 votes vote down vote up
@GET
@Path("/nodes/{nodeId}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public NodeInfo getNode(@PathParam("nodeId") String nodeId) {
  init();
  if (nodeId == null || nodeId.isEmpty()) {
    throw new NotFoundException("nodeId, " + nodeId + ", is empty or null");
  }
  ResourceScheduler sched = this.rm.getResourceScheduler();
  if (sched == null) {
    throw new NotFoundException("Null ResourceScheduler instance");
  }
  NodeId nid = ConverterUtils.toNodeId(nodeId);
  RMNode ni = this.rm.getRMContext().getRMNodes().get(nid);
  boolean isInactive = false;
  if (ni == null) {
    ni = this.rm.getRMContext().getInactiveRMNodes().get(nid.getHost());
    if (ni == null) {
      throw new NotFoundException("nodeId, " + nodeId + ", is not found");
    }
    isInactive = true;
  }
  NodeInfo nodeInfo = new NodeInfo(ni, sched);
  if (isInactive) {
    nodeInfo.setNodeHTTPAddress(EMPTY);
  }
  return nodeInfo;
}
 
Example 41
Project: ctsms   File: UserResource.java   View source code 5 votes vote down vote up
@GET
@Produces({ MediaType.APPLICATION_JSON })
@Path("{id}/journal")
public Page<JournalEntryOutVO> getJournal(@PathParam("id") Long id, @Context UriInfo uriInfo)
		throws AuthenticationException, AuthorisationException, ServiceException {
	PSFUriPart psf;
	return new Page<JournalEntryOutVO>(WebUtil.getServiceLocator().getJournalService().getJournal(auth, journalModule, id, psf = new PSFUriPart(uriInfo)), psf);
}
 
Example 42
Project: rebase-server   File: UserResource.java   View source code 5 votes vote down vote up
@GET @Path("{username}")
@Produces(MediaType.APPLICATION_JSON)
public Response userDetail(@Username @PathParam("username") String username) {
    Document user = MongoDBs.users().find(eq(User.USERNAME, username))
        .projection(exclude(User.PASSWORD, User.AUTHORIZATION))
        .limit(1)
        .first();
    RebaseAsserts.notNull(user, "user");
    return Response.ok(user).build();
}
 
Example 43
Project: athena   File: MastershipWebResource.java   View source code 5 votes vote down vote up
/**
 * Returns the mastership status of the local controller for a given
 * device forcing master selection if necessary.
 *
 * @param deviceId device identifier
 * @return 200 OK with the role of this controller instance
 * @onos.rsModel MastershipRole
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{deviceId}/request")
public Response requestRoleFor(@PathParam("deviceId") String deviceId) {
    MastershipRole role = nullIsNotFound(mastershipService.requestRoleForSync(
                            DeviceId.deviceId(deviceId)), MASTERSHIP_ROLE_NOT_FOUND);
    ObjectNode root = codec(MastershipRole.class).encode(role, this);
    return ok(root).build();
}
 
Example 44
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 45
Project: opencps-v2   File: EmployeeManagement.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 })
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 46
Project: ctsms   File: EcrfStatusEntryResource.java   View source code 5 votes vote down vote up
@POST
@Produces({ MediaType.APPLICATION_JSON })
@Path("{listEntryId}/{ecrfId}")
public ECRFStatusEntryVO setEcrfStatusEntry(@PathParam("listEntryId") Long listEntryId, @PathParam("ecrfId") Long ecrfId,
		@QueryParam("version") Long version, @QueryParam("ecrf_status_type_id") Long ecrfStatusTypeId, @QueryParam("proband_list_status_entry_id") Long probandListStatusEntryId)
				throws AuthenticationException, AuthorisationException, ServiceException {
	return WebUtil.getServiceLocator().getTrialService().setEcrfStatusEntry(auth, ecrfId, listEntryId, version, ecrfStatusTypeId, probandListStatusEntryId);
}
 
Example 47
Project: osc-core   File: VirtualSystemApis.java   View source code 5 votes vote down vote up
@ApiOperation(value = "Deletes a Deployment Specification",
        notes = "Deletes a Deployment Specification",
        response = BaseJobResponse.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Successful operation"),
        @ApiResponse(code = 400, message = "In case of any error", response = ErrorCodeDto.class) })
@Path("/{vsId}/deploymentSpecs/{dsId}")
@DELETE
public Response deleteDeploymentSpec(@Context HttpHeaders headers,
        @ApiParam(value = "The Virtual System Id") @PathParam("vsId") Long vsId,
        @ApiParam(value = "The Deployment Specification Id") @PathParam("dsId") Long dsId) {
    logger.info("Deleting Deployment Spec " + dsId);
    this.userContext.setUser(OscAuthFilter.getUsername(headers));
    return this.apiUtil.getResponseForBaseRequest(this.deleteDeploymentSpecService,
            new BaseDeleteRequest(dsId, vsId, false));// false as this is not force delete
}
 
Example 48
Project: ctsms   File: InventoryResource.java   View source code 5 votes vote down vote up
@GET
@Produces({ MediaType.APPLICATION_JSON })
@Path("{id}/children")
public Collection<InventoryOutVO> getChildren(@PathParam("id") Long id) throws AuthenticationException, AuthorisationException, ServiceException {
	return WebUtil
			.getServiceLocator()
			.getInventoryService()
			.getInventory(auth, id,
					Settings.getIntNullable(SettingCodes.API_GRAPH_MAX_INVENTORY_INSTANCES, Bundle.SETTINGS, DefaultSettings.API_GRAPH_MAX_INVENTORY_INSTANCES),
					Settings.getIntNullable(SettingCodes.API_GRAPH_MAX_INVENTORY_PARENT_DEPTH, Bundle.SETTINGS, DefaultSettings.API_GRAPH_MAX_INVENTORY_PARENT_DEPTH))
					.getChildren();
}
 
Example 49
Project: EJB-CON-DTO   File: PaisResource.java   View source code 5 votes vote down vote up
@GET
@Path("getById/{idPais}")
@Produces(MediaType.APPLICATION_JSON)
public PaisDTO getById(@PathParam("idPais") int idPais) throws Exception {
    PaisDTO paisDTO = new PaisDTO();
    System.out.println("Inicio metodo ");
    paisDTO = paisController.getById(idPais);
    return paisDTO;
    
}
 
Example 50
Project: InComb   File: UserLocalesService.java   View source code 5 votes vote down vote up
/**
 * Adds a new Locale (Language) to a given user
 * @param userId of the user to add the locale
 * @param userLocale to add
 * @param con Connection to use - is injected automatically
 * @return the added {@link UserLocale}
 */
@POST
public Response addLocale(@PathParam("userId") final long userId, final UserLocale userLocale,
		@Context final Connection con) {
	getAccessChecker().checkLoggedInUser(userId);

	userLocale.setUserId(userId);
	new UserLocaleDao(con).addUserLocale(userLocale);
	return ok(userLocale);
}