Java Code Examples for javax.ws.rs.Produces

The following are top voted examples for showing how to use javax.ws.rs.Produces. 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: 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 2
Project: dremio-oss   File: FolderResource.java   View source code 6 votes vote down vote up
@GET
@Path("/folder/{path: .*}")
@Produces(MediaType.APPLICATION_JSON)
public Folder getFolder(@PathParam("path") String path, @QueryParam("includeContents") @DefaultValue("true") boolean includeContents) throws NamespaceException, FolderNotFoundException, DatasetNotFoundException {
  FolderPath folderPath = FolderPath.fromURLPath(spaceName, path);
  try {
    final FolderConfig folderConfig = namespaceService.getFolder(folderPath.toNamespaceKey());
    final List<NamespaceKey> datasetPaths = namespaceService.getAllDatasets(folderPath.toNamespaceKey());
    final ExtendedConfig extendedConfig = new ExtendedConfig().setDatasetCount((long)datasetPaths.size())
      .setJobCount(datasetService.getJobsCount(datasetPaths));
    folderConfig.setExtendedConfig(extendedConfig);
    NamespaceTree contents = includeContents
        ? newNamespaceTree(namespaceService.list(folderPath.toNamespaceKey()))
        : null;
    return newFolder(folderPath, folderConfig, contents);
  } catch (NamespaceNotFoundException nfe) {
    throw new FolderNotFoundException(folderPath, nfe);
  }
}
 
Example 3
Project: elastest-instrumentation-manager   File: AgentconfigurationApi.java   View source code 6 votes vote down vote up
@GET

@Consumes({ "application/json" })
@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "Returns all existing agent configurations", notes = "Returns all agent configurations with all details", response = AgentConfigurationDatabase.class, responseContainer = "List", tags={ "AgentConfiguration", })
@io.swagger.annotations.ApiResponses(value = { 
    @io.swagger.annotations.ApiResponse(code = 200, message = "Successful operation", response = AgentConfigurationDatabase.class, responseContainer = "List"),
    
    @io.swagger.annotations.ApiResponse(code = 401, message = "Unauthorized", response = AgentConfigurationDatabase.class, responseContainer = "List"),
    
    @io.swagger.annotations.ApiResponse(code = 403, message = "Forbidden", response = AgentConfigurationDatabase.class, responseContainer = "List"),
    
    @io.swagger.annotations.ApiResponse(code = 404, message = "Not Found", response = AgentConfigurationDatabase.class, responseContainer = "List") })
public Response getAllAgentConfigurations(@Context SecurityContext securityContext)
throws NotFoundException {
    return delegate.getAllAgentConfigurations(securityContext);
}
 
Example 4
Project: ditb   File: SchemaResource.java   View source code 6 votes vote down vote up
@GET
@Produces({MIMETYPE_TEXT, MIMETYPE_XML, MIMETYPE_JSON, MIMETYPE_PROTOBUF,
  MIMETYPE_PROTOBUF_IETF})
public Response get(final @Context UriInfo uriInfo) {
  if (LOG.isDebugEnabled()) {
    LOG.debug("GET " + uriInfo.getAbsolutePath());
  }
  servlet.getMetrics().incrementRequests(1);
  try {
    ResponseBuilder response =
      Response.ok(new TableSchemaModel(getTableSchema()));
    response.cacheControl(cacheControl);
    servlet.getMetrics().incrementSucessfulGetRequests(1);
    return response.build();
  } catch (Exception e) {
    servlet.getMetrics().incrementFailedGetRequests(1);
    return processException(e);
  } 
}
 
Example 5
Project: dremio-oss   File: UserResource.java   View source code 6 votes vote down vote up
@RolesAllowed({"admin", "user"})
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public UserUI updateUser(UserForm userForm, @PathParam("userName") UserName userName)
  throws IOException, IllegalArgumentException, NamespaceException, UserNotFoundException, DACUnauthorizedException {
  checkUser(userName, "update");
  User userConfig = userForm.getUserConfig();
  if (userConfig != null && userConfig.getUserName() != null && !userConfig.getUserName().equals(userName.getName())) {
    final UserName newUserName = new UserName(userForm.getUserConfig().getUserName());
    userConfig = userService.updateUserName(userName.getName(),
      newUserName.getName(),
      userConfig, userForm.getPassword());
    // TODO: rename home space and all uploaded files along with it
    // new username
    return new UserUI(new UserResourcePath(newUserName), newUserName, userConfig);
  } else {
    User newUser = SimpleUser.newBuilder(userForm.getUserConfig()).setUserName(userName.getName()).build();
    newUser = userService.updateUser(newUser, userForm.getPassword());
    return new UserUI(new UserResourcePath(userName), userName, newUser);
  }
}
 
Example 6
Project: uavstack   File: GodEyeRestService.java   View source code 6 votes vote down vote up
@SuppressWarnings({ "unchecked" })
@POST
@Path("notify/q/stgy/hm")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public void noitifyStrategyQuery(String data, @Suspended AsyncResponse response) throws Exception {

    Map<String, Object> params = JSONHelper.toObject(data, Map.class);
    int pagesize = (int) params.get("pagesize");
    int pageindex = (int) params.get("pageindex");
    Map<String, String> strategyMap = new HashMap<String, String>();
    strategyMap.put("keys", String.valueOf(params.get("inputValue")));
    // 封装http请求数据
    UAVHttpMessage message = new UAVHttpMessage();
    message.putRequest("body", JSONHelper.toString(strategyMap));
    message.setIntent("strategy.query");

    NoitifyStrategyQuery callback = new NoitifyStrategyQuery();
    callback.setResponse(response);
    callback.setPageindex(pageindex);
    callback.setPagesize(pagesize);

    doHttpPost("uav.app.godeye.notify.strategy.http.addr", "/rtntf/oper", message, callback);
}
 
Example 7
Project: habot   File: HABotResource.java   View source code 6 votes vote down vote up
@POST
@RolesAllowed({ Role.USER, Role.ADMIN })
@Path("/chat")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Send a query to HABot to interpret.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = ChatReply.class),
        @ApiResponse(code = 500, message = "An interpretation error occured") })
public Response chat(@HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") String language,
        @ApiParam(value = "human language query", required = true) String query) throws Exception {

    final Locale locale = LocaleUtil.getLocale(language);

    // interpret
    OpenNLPInterpreter hli = (OpenNLPInterpreter) voiceManager.getHLI(OPENNLP_HLI);
    ChatReply reply = hli.reply(locale, query);

    return Response.ok(reply).build();
}
 
Example 8
Project: app-ms   File: HelloResource.java   View source code 6 votes vote down vote up
@ApiOperation(value = "displays openid config of google async",
    hidden = true)
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/async")
public void async(@Suspended final AsyncResponse asyncResponse) throws InterruptedException,
    ExecutionException {

    final Future<Response> futureResponseFromClient = jaxrsClient.target("https://accounts.google.com/.well-known/openid-configuration").request().header(javax.ws.rs.core.HttpHeaders.USER_AGENT, "curl/7.55.1").async().get();

    final Response responseFromClient = futureResponseFromClient.get();
    try {
        final String object = responseFromClient.readEntity(String.class);
        asyncResponse.resume(object);
    } finally {
        responseFromClient.close();
    }
}
 
Example 9
Project: E-Clinic   File: ClinicManagerRestEndPoint.java   View source code 6 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 {
        Clinicmanager get = clinicManagerService.get(Integer.valueOf(id));
        build = Json.createObjectBuilder()
                .add("firstname", get.getPersonId().getFirstName())
                .add("lastname", get.getPersonId().getLastName())
                .add("id", get.getManagerId())
                .add("genderId", get.getPersonId().getGenderId().getGenderId())
                .build();

    } catch (Exception ex) {
        return Response.ok().header("Exception", ex.getMessage()).build();
    }
    return Response.ok().entity(build == null ? "No data found" : build).build();
}
 
Example 10
Project: MaximoForgeViewerPlugin   File: ForgeRS.java   View source code 6 votes vote down vote up
@POST
   @Produces(MediaType.APPLICATION_JSON)
   @Path("bubble")
   @Consumes("*/*") 
   public Response bubbleDetails(
   	@Context HttpServletRequest request,
   	InputStream is
) 
	throws IOException, 
	       URISyntaxException 
   {
   	APIImpl impl = getAPIImpl( request );
   	if( impl == null )
   	{
           return Response.status( Response.Status.UNAUTHORIZED ).build();     
   	}
   	String urn = stream2string( is );
   	Result result = impl.viewableQuery( urn );
   	return formatReturn( result );
   }
 
Example 11
Project: ditb   File: NamespacesResource.java   View source code 6 votes vote down vote up
/**
 * Build a response for a list of all namespaces request.
 * @param context servlet context
 * @param uriInfo (JAX-RS context variable) request URL
 * @return a response for a version request
 */
@GET
@Produces({MIMETYPE_TEXT, MIMETYPE_XML, MIMETYPE_JSON, MIMETYPE_PROTOBUF,
  MIMETYPE_PROTOBUF_IETF})
public Response get(final @Context ServletContext context, final @Context UriInfo uriInfo) {
  if (LOG.isDebugEnabled()) {
    LOG.debug("GET " + uriInfo.getAbsolutePath());
  }
  servlet.getMetrics().incrementRequests(1);
  try {
    NamespacesModel rowModel = null;
    rowModel = new NamespacesModel(servlet.getAdmin());
    servlet.getMetrics().incrementSucessfulGetRequests(1);
    return Response.ok(rowModel).build();
  } catch (IOException e) {
    servlet.getMetrics().incrementFailedGetRequests(1);
    throw new RuntimeException("Cannot retrieve list of namespaces.");
  }
}
 
Example 12
Project: syndesis   File: CustomConnectorHandler.java   View source code 6 votes vote down vote up
@POST
@Path("/info")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@ApiOperation("Provides a summary of the connector as it would be built using a ConnectorTemplate identified by the provided `connector-template-id` and the data given in `connectorSettings`")
public ConnectorSummary info(@MultipartForm final CustomConnectorFormData connectorFormData) {
    try {
        final String specification;
        try (BufferedSource source = Okio.buffer(Okio.source(connectorFormData.getSpecification()))) {
            specification = source.readUtf8();
        }

        final ConnectorSettings connectorSettings = new ConnectorSettings.Builder()
            .createFrom(connectorFormData.getConnectorSettings())
            .putConfiguredProperty("specification", specification)
            .build();

        return withGeneratorAndTemplate(connectorSettings.getConnectorTemplateId(),
            (generator, template) -> generator.info(template, connectorSettings));
    } catch (IOException e) {
        throw SyndesisServerException.launderThrowable("Failed to read specification", e);
    }
}
 
Example 13
Project: MaximoForgeViewerPlugin   File: ForgeRS.java   View source code 6 votes vote down vote up
@DELETE
   @Produces(MediaType.APPLICATION_JSON)
   @Path("bucket/{bucketKey}")
   public Response bucketDelete(
    	@Context HttpServletRequest request,
    	@PathParam("bucketKey") String bucketKey
) 
	throws IOException, 
	       URISyntaxException 
   {
   	APIImpl impl = getAPIImpl( request );
   	if( impl == null )
   	{
           return Response.status( Response.Status.UNAUTHORIZED ).build();     
   	}
   	Result result = impl.bucketDelete( bucketKey );
   	return formatReturn( result );
   }
 
Example 14
Project: appinventor-extensions   File: BuildServer.java   View source code 6 votes vote down vote up
@GET
@Path("health")
@Produces(MediaType.TEXT_PLAIN)
public Response health() throws IOException {
  ShutdownState shut = getShutdownState();
  if (shut == ShutdownState.UP) {
    LOG.info("Healthcheck: UP");
    return Response.ok("ok", MediaType.TEXT_PLAIN_TYPE).build();
  } else if (shut == ShutdownState.DOWN) {
    LOG.info("Healthcheck: DOWN");
    return Response.status(Response.Status.FORBIDDEN).type(MediaType.TEXT_PLAIN_TYPE).entity("Build Server is shutdown").build();
  } else if (shut == ShutdownState.DRAINING) {
    LOG.info("Healthcheck: DRAINING");
    return Response.status(Response.Status.FORBIDDEN).type(MediaType.TEXT_PLAIN_TYPE).entity("Build Server is draining").build();
  } else {
    LOG.info("Healthcheck: SHUTTING");
    return Response.status(Response.Status.FORBIDDEN).type(MediaType.TEXT_PLAIN_TYPE).entity("Build Server is shutting down").build();
  }
}
 
Example 15
Project: microprofile-jwt-auth   File: RequiredClaimsEndpoint.java   View source code 6 votes vote down vote up
@GET
@Path("/verifyAudience")
@Produces(MediaType.APPLICATION_JSON)
public JsonObject verifyAudience(@QueryParam("aud") String audience) {
    boolean pass = false;
    String msg;
    // aud
    final Set<String> audValue = rawTokenJson.getAudience();
    if (audValue != null) {
        msg = Claims.aud.name() + "value is NOT null, FAIL";
    }
    else {
        msg = Claims.aud.name() + " PASS";
        pass = true;
    }
    JsonObject result = Json.createObjectBuilder()
            .add("pass", pass)
            .add("msg", msg)
            .build();
    return result;
}
 
Example 16
Project: scott-eu   File: ServiceProviderService1.java   View source code 6 votes vote down vote up
@GET
@Path("missions/{missionId}")
@Produces({ MediaType.TEXT_HTML })
public Response getMissionAsHtml(
    @PathParam("serviceProviderId") final String serviceProviderId, @PathParam("missionId") final String missionId
    ) throws ServletException, IOException, URISyntaxException
{
    // Start of user code getMissionAsHtml_init
    // End of user code

    final Mission aMission = WarehouseControllerManager.getMission(httpServletRequest, serviceProviderId, missionId);

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

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

    throw new WebApplicationException(Status.NOT_FOUND);
}
 
Example 17
Project: hadoop   File: RMWebServices.java   View source code 6 votes vote down vote up
@GET
@Path("/apps/{appid}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public AppInfo getApp(@Context HttpServletRequest hsr,
    @PathParam("appid") String appId) {
  init();
  if (appId == null || appId.isEmpty()) {
    throw new NotFoundException("appId, " + appId + ", is empty or null");
  }
  ApplicationId id;
  id = ConverterUtils.toApplicationId(recordFactory, appId);
  if (id == null) {
    throw new NotFoundException("appId is null");
  }
  RMApp app = rm.getRMContext().getRMApps().get(id);
  if (app == null) {
    throw new NotFoundException("app with id: " + appId + " not found");
  }
  return new AppInfo(rm, app, hasAccess(app, hsr), hsr.getScheme() + "://");
}
 
Example 18
Project: lemon   File: PartyJsonpResource.java   View source code 6 votes vote down vote up
/**
 * TODO: replace JSONWithPadding to JSONPObject
 */
@GET
@Path("search")
@Produces(MediaType.APPLICATION_JSON)
public JSONPObject getPartyEntitiesByType(
        @QueryParam("callback") String callback,
        @QueryParam("typeId") long typeId, @QueryParam("q") String q) {
    String hql = "from PartyEntity where partyType.id=? and name like ? order by name";
    Page page = partyEntityManager.pagedQuery(hql, 1, DFAULT_PAGE_SIZE,
            typeId, q.replace("_", "\\_") + "%");
    List<PartyEntity> partyEntities = (List<PartyEntity>) page.getResult();

    List<PartyEntityDTO> partyEntityDtos = new ArrayList<PartyEntityDTO>();

    for (PartyEntity partyEntity : partyEntities) {
        PartyEntityDTO partyEntityDto = new PartyEntityDTO();
        partyEntityDto.setId(partyEntity.getId());
        partyEntityDto.setName(partyEntity.getName());

        partyEntityDtos.add(partyEntityDto);
    }

    return new JSONPObject(callback, partyEntityDtos);
}
 
Example 19
Project: microprofile-open-api   File: AirlinesResource.java   View source code 6 votes vote down vote up
@GET
@APIResponse(
        ref = "FoundAirlines"
    )
@APIResponse(
        responseCode = "404",
        description = "No airlines found",
        content = @Content(
            mediaType = "n/a"
        )
    )
@Operation(
    summary = "Retrieve all available airlines",
    operationId = "getAirlines")
@Produces("application/json")
public Response getAirlines(){
    return Response.ok().entity(airlines.values()).build();
}
 
Example 20
Project: presto-manager   File: ControllerConnectorAPI.java   View source code 6 votes vote down vote up
@GET
@Path("/{file}/{property}")
@Produces(MediaType.TEXT_PLAIN)
@ApiOperation(value = "Get connector property by file")
@ApiResponses(value = {
        @ApiResponse(code = 207, message = "Multiple responses available"),
        @ApiResponse(code = 400, message = "Request contains invalid parameters")})
public Response getConnectorProperty(
        @PathParam("file") String file,
        @PathParam("property") String property,
        @QueryParam("scope") String scope,
        @QueryParam("nodeId") List<String> nodeId)
{
    ApiRequester apiRequester = requesterBuilder(ControllerConnectorAPI.class)
            .pathMethod("getConnectorProperty")
            .httpMethod(GET)
            .resolveTemplate("file", file)
            .resolveTemplate("property", property)
            .accept(MediaType.TEXT_PLAIN)
            .build();

    return forwardRequest(scope, apiRequester, nodeId);
}
 
Example 21
Project: redirector   File: RedirectorUI.java   View source code 6 votes vote down vote up
@GET
@Produces(MediaType.TEXT_HTML)
public Response defaultPage(@Context UriInfo ui) throws URISyntaxException {
    /*
    * This redirect is required due to change of "Jersey" version from "1.17" to "2.13".
    * The "1.*" version of jersey has property "FEATURE_REDIRECT".
    * For example, when making request "localhost:8888/context/dev", Jersey checks whether "FEATURE_REDIRECT" is set to "true" in ServletContainer and request does not end with '/'.
    * If so, trailing slash is added and redirect is occurred to "localhost:8888/context/dev/"
    *
    * Jersey "2.*" does not contain property "FEATURE_REDIRECT".
    * The code that made redirect in "1.*" jersey is commented out in ServletContainer.java:504
    * Jersey "2.*" resolves request even if '/' was not present in the end.
    * But all links in our *.jsp and *.html to *.js and *.css are relative. So without adding '/' in the end, files can not be opened.
    * To solve it, we introduced this redirect
    */
    if (!ui.getAbsolutePath().toString().endsWith("/")) {
        return Response.temporaryRedirect(new URI(ui.getAbsolutePath().toString() + "/")).build();
    } else {
        return Response.ok(new Viewable("/index.jsp", new HashMap<String, Object>())).build();
    }
}
 
Example 22
Project: plugin-bt-jira   File: JiraExportPluginResource.java   View source code 6 votes vote down vote up
/**
 * Return SLA computations as XLS input stream.
 * 
 * @param subscription
 *            The subscription identifier.
 * @param file
 *            The user file name to use in download response.
 * @return the stream ready to be read during the serialization.
 */
@GET
@Path("{subscription:\\d+}/{file:.*.xml}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getSlaComputationsXls(@PathParam("subscription") final int subscription,
		@PathParam("file") final String file) {
	final JiraSlaComputations slaComputations = getSlaComputations(subscription, false);
	final Map<String, Processor<?>> tags = mapTags(slaComputations);

	// Get the template data
	return AbstractToolPluginResource.download(output -> {
		final InputStream template = new ClassPathResource("csv/template/template-sla.xml").getInputStream();
		try {
			final PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8));
			new Template<JiraSlaComputations>(IOUtils.toString(template, StandardCharsets.UTF_8)).write(writer,
					tags, slaComputations);
			writer.flush();
		} finally {
			IOUtils.closeQuietly(template);
		}
	}, file).build();

}
 
Example 23
Project: kafka-streams-example   File: MetricsResource.java   View source code 6 votes vote down vote up
/**
 * Remote interface for fetching metrics
 *
 * @return Metrics
 */
@GET
@Path("remote")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Metrics remote() {
    LOGGER.info("Remote interface invoked");
    Metrics metrics = null;
    try {
        metrics = getLocalMetrics();
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "Error - {0}", e.getMessage());
        e.printStackTrace();
    }

    return metrics;

}
 
Example 24
Project: search-doc   File: ConsultaCpfResource.java   View source code 6 votes vote down vote up
@GET
@Path("/{cpf}/{nascimento}")
@Produces("application/json; charset=UTF-8")
public Response buscar(@PathParam("cpf") String cpf, @PathParam("nascimento") String nascimento) {

    PessoaFisica pf = service.buscarPessoa(cpf, nascimento, null);

    if (pf != null && pf.getNumeroCpf() != null && !pf.getNumeroCpf().isEmpty()) {

        Gson gson = new GsonBuilder()
                .setExclusionStrategies(new AnnotationExclusionStrategy())
                .registerTypeAdapter(LocalDate.class, new LocalDateDeserializer())
                .registerTypeAdapter(ConstaObito.class, new ConstaObitoDeserializer())
                .create();

        String json = gson.toJson(pf);
                  
        return Response.ok(json).build();
    }
    
    return Response.status(Status.NOT_FOUND).build();

}
 
Example 25
Project: opencps-v2   File: DossierTemplateManagement.java   View source code 5 votes vote down vote up
@PUT
@Path("/{id}")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "Update a DossierTemplate", response = DossierTemplateInputModel.class)
@ApiResponses(value = {
		@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the DossierTemplate was update", response = DossierTemplateInputModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal error", response = ExceptionModel.class) })

public Response updateDossierTemplateDetail(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context Company company, @Context Locale locale, @Context User user,
		@Context ServiceContext serviceContext, @PathParam("id") long id,
		@BeanParam DossierTemplateInputModel input);
 
Example 26
Project: aws-photosharing-example   File: UserService.java   View source code 5 votes vote down vote up
@POST
@Path("/register")
@Produces(MediaType.APPLICATION_JSON)    
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response register(@FormParam("username") String p_username, @FormParam("password") String p_password, @FormParam("email") String p_email) {    	
	return Response.ok(_facade.register(new User(p_username, p_password, p_email))).build();
}
 
Example 27
Project: cf-mta-deploy-service   File: OperationsApi.java   View source code 5 votes vote down vote up
@GET
@Path("/{operationId}/logs/{logId}/content")
@Consumes({ "application/json" })
@Produces({ "text/plain" })
@ApiOperation(value = "", notes = "Retrieves the log content for Multi-Target Application operation ", response = String.class, authorizations = {
    @Authorization(value = "oauth2", scopes = {
        
    })
}, tags={  })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "OK", response = String.class) })
public Response getMtaOperationLogContent(@ApiParam(value = "",required=true) @PathParam("operationId") String operationId, @ApiParam(value = "",required=true) @PathParam("logId") String logId) {
    return delegate.getMtaOperationLogContent(operationId, logId, securityContext, spaceGuid);
}
 
Example 28
Project: oryx2   File: ErrorResource.java   View source code 5 votes vote down vote up
@GET
@Produces(MediaType.TEXT_PLAIN)
public Response errorText(@Context HttpServletRequest request) {
  StringBuilder text = new StringBuilder(1000);

  text.append("Error");
  Number statusCode = (Number) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
  if (statusCode != null) {
    text.append(' ').append(statusCode);
  }
  Object requestURI = request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI);
  if (requestURI != null) {
    text.append(" : ");
    text.append(requestURI);
  }
  text.append('\n');

  Object message = request.getAttribute(RequestDispatcher.ERROR_MESSAGE);
  if (message != null) {
    text.append(message).append('\n');
  }

  Throwable throwable = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
  if (throwable != null) {
    StringWriter sw = new StringWriter();
    throwable.printStackTrace(new PrintWriter(sw));
    text.append(sw);
  }

  Response.Status finalStatus = statusCode == null ?
      Response.Status.OK : Response.Status.fromStatusCode(statusCode.intValue());
  return Response.status(finalStatus).entity(text.toString()).build();
}
 
Example 29
Project: vc   File: Product_TypeResource.java   View source code 5 votes vote down vote up
@DELETE
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Product_Type deleteProduct_Type(@PathParam("id") String id) {
    Product_Type Product_TypeResponse = Product_Type_Service.deleteProduct_Type(id);
    return Product_TypeResponse;
}
 
Example 30
Project: holon-examples   File: ProductEndpoint.java   View source code 5 votes vote down vote up
@ApiOperation("Get all the products")
@ProductModel
@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public List<PropertyBox> getProducts() {
	return datastore.query().target(TARGET).list(PRODUCT);
}
 
Example 31
Project: E-Clinic   File: ClinicManagerRestEndPoint.java   View source code 5 votes vote down vote up
@PUT
@Path("update")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response update(ClinicManagerForm value) throws Throwable {
    try {
        clinicManagerService.update(value);
    } catch (Exception ex) {
        return Response.ok().header("Exception", ex.getMessage()).build();
    }
    return Response.ok().entity("Date is updated").build();
}
 
Example 32
Project: ctsms   File: ProbandResource.java   View source code 5 votes vote down vote up
@GET
@Produces({ MediaType.APPLICATION_JSON })
@Path("{id}")
public ProbandOutVO getProband(@PathParam("id") Long id) throws AuthenticationException, AuthorisationException, ServiceException {
	return WebUtil.getServiceLocator().getProbandService().getProband(auth, id,
			Settings.getIntNullable(SettingCodes.API_GRAPH_MAX_PROBAND_INSTANCES, Bundle.SETTINGS, DefaultSettings.API_GRAPH_MAX_PROBAND_INSTANCES),
			Settings.getIntNullable(SettingCodes.API_GRAPH_MAX_PROBAND_PARENTS_DEPTH, Bundle.SETTINGS, DefaultSettings.API_GRAPH_MAX_PROBAND_PARENTS_DEPTH),
			Settings.getIntNullable(SettingCodes.API_GRAPH_MAX_PROBAND_CHILDREN_DEPTH, Bundle.SETTINGS, DefaultSettings.API_GRAPH_MAX_PROBAND_CHILDREN_DEPTH));
}
 
Example 33
Project: GitHub   File: Resource.java   View source code 5 votes vote down vote up
@Path("/booleanInMapTest")
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public MapTest getBooleanInMapTest() {

  return ImmutableMapTest.builder()
      .putMapBoolean("boolean", true)
      .build();
}
 
Example 34
Project: opencps-v2   File: PaymentConfigManagement.java   View source code 5 votes vote down vote up
@POST
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "Add a PaymentConfig", response = PaymentConfigInputModel.class)
@ApiResponses(value = {
		@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the PaymentConfig was created", response = PaymentConfigInputModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal error", response = ExceptionModel.class) })

public Response addPaymentConfig(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context Company company, @Context Locale locale, @Context User user,
		@Context ServiceContext serviceContext, @BeanParam PaymentConfigInputModel input);
 
Example 35
Project: graphiak   File: MetricsResource.java   View source code 5 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response root(
        @QueryParam("wildcards") @DefaultValue("0") IntParam wildcards,
        @QueryParam("from") @DefaultValue("-1") IntParam from,
        @QueryParam("until") @DefaultValue("-1") IntParam until,
        @QueryParam("position") @DefaultValue("-1") IntParam position,
        @QueryParam("format") @DefaultValue("treejson") String format,
        @QueryParam("query") String query) {
    return find(wildcards, from, until, position, format, query);
}
 
Example 36
Project: ctsms   File: StaffResource.java   View source code 5 votes vote down vote up
@GET
@Produces({ MediaType.APPLICATION_JSON })
@Path("{id}/files/pdf/head")
public FilePDFVO aggregatePDFFilesHead(@PathParam("id") Long id, @Context UriInfo uriInfo)
		throws AuthenticationException, AuthorisationException, ServiceException {
	FilePDFVO result = WebUtil.getServiceLocator().getFileService().aggregatePDFFiles(auth, fileModule, id, null, null, new PSFUriPart(uriInfo));
	result.setDocumentDatas(null);
	return result;
}
 
Example 37
Project: opencps-v2   File: CommentManagement.java   View source code 5 votes vote down vote up
@PUT
@Path("/{id}/upvotes")
@Consumes({ MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response updateUpvoteCount(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context ServiceContext serviceContext, @Context User user,
		@ApiParam(value = "id of comment for delete user from") @PathParam("id") long commentId,
		@ApiParam(value = "json object store CommentInputModel") @BeanParam CommentInputModel commentInputModel);
 
Example 38
Project: abhot   File: MetricsResource.java   View source code 5 votes vote down vote up
@OPTIONS
@Produces(MediaType.APPLICATION_JSON + "; charset=UTF-8")
@Path("/metricnames")
public Response corsPreflightMetricNames(@HeaderParam("Access-Control-Request-Headers") final String requestHeaders,
		@HeaderParam("Access-Control-Request-Method") final String requestMethod)
{
	ResponseBuilder responseBuilder = getCorsPreflightResponseBuilder(requestHeaders, requestMethod);
	return (responseBuilder.build());
}
 
Example 39
Project: neo4j-sparql-extension-yars   File: GraphStore.java   View source code 5 votes vote down vote up
/**
 * Indirect HTTP GET
 *
 * @see <a href="http://www.w3.org/TR/sparql11-http-rdf-update/#http-get">
 * Section 5.2 "HTTP GET"
 * </a>
 * @param req JAX-RS {@link Request} object
 * @param graphString the "graph" query parameter
 * @param def the "default" query parameter
 * @return the content of the request graph as HTTP response
 */
@GET
@Produces({
	RDFMediaType.RDF_TURTLE,
	RDFMediaType.RDF_YARS,
	RDFMediaType.RDF_XML,
	RDFMediaType.RDF_NTRIPLES,
	RDFMediaType.RDF_JSON
})
public Response graphIndirectGet(
		@Context Request req,
		@QueryParam("graph") String graphString,
		@QueryParam("default") String def) {
	return handleGet(req, def, graphString);
}
 
Example 40
Project: athena   File: FlowsWebResource.java   View source code 5 votes vote down vote up
/**
 * Gets flow rules generated by an application.
 * Returns the flow rule specified by the application id.
 *
 * @param appId application identifier
 * @return 200 OK with a collection of flows of given application id
 * @onos.rsModel FlowRules
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("application/{appId}")
public Response getFlowByAppId(@PathParam("appId") String appId) {
    final ApplicationService appService = get(ApplicationService.class);
    final ApplicationId idInstant = nullIsNotFound(appService.getId(appId), APP_ID_NOT_FOUND);
    final Iterable<FlowRule> flowRules = service.getFlowRulesById(idInstant);

    flowRules.forEach(flow -> flowsNode.add(codec(FlowRule.class).encode(flow, this)));
    return ok(root).build();
}
 
Example 41
Project: marathonv5   File: FullProductListingFacadeREST.java   View source code 5 votes vote down vote up
@GET
@Path("{from}/{to}")
@Produces({"application/xml", "application/json"})
public List<FullProductListing> findRange(@PathParam("from")
Integer from, @PathParam("to")
Integer to) {
    return super.findRange(new int[]{from, to});
}
 
Example 42
Project: presto-manager   File: ConfigAPI.java   View source code 5 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Get available configuration files")
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Retrieved configuration")})
public synchronized Response getConfig()
{
    return apiFileHandler.getFileNameList();
}
 
Example 43
Project: opencps-v2   File: ServiceConfigManagement.java   View source code 5 votes vote down vote up
@GET
@Path("/govagencies")
@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 all ServiceConfigs", response = ServiceConfigResultsModel.class)
@ApiResponses(value = {
		@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a list of ServiceConfig", response = ServiceConfigResultsModel.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 getServiceConfigsByGovAgency(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context Company company, @Context Locale locale, @Context User user,
		@Context ServiceContext serviceContext, @BeanParam ServiceInfoSearchModel query);
 
Example 44
Project: Equella   File: TaxonomyResource.java   View source code 5 votes vote down vote up
/**
 * Remove term
 * 
 * @param uuid
 * @param termBean
 * @return
 */
@DELETE
@Path("/{uuid}/term/{termUuid}")
@Produces("application/json")
@ApiOperation(value = "Remove term")
public Response rmTaxonomyTerm(
	@ApiParam(value = "Taxonomy uuid", required = true) @PathParam("uuid") String taxonomyUuid,
	@ApiParam(value = "Term uuid", required = true) @PathParam("termUuid") String termUuid)
{
	if( taxonomyService.isTaxonomyReadonly(taxonomyUuid) )
	{
		throw new WebException(Status.METHOD_NOT_ALLOWED.getStatusCode(),
			Status.METHOD_NOT_ALLOWED.getReasonPhrase(), "Taxonomy is readonly");
	}

	final Taxonomy taxonomy = ensureTaxonomy(taxonomyUuid, PrivCheck.EDIT);

	TermResult term = taxonomyService.getTermResultByUuid(taxonomyUuid, termUuid);
	if( term == null )
	{
		throw new WebException(Status.NOT_FOUND.getStatusCode(), Status.NOT_FOUND.getReasonPhrase(),
			"termUuid given is not valid");
	}
	termService.deleteTerm(taxonomy, term.getFullTerm());

	return Response.ok().build();
}
 
Example 45
Project: beadledom   File: HealthResource.java   View source code 5 votes vote down vote up
@ApiOperation(value = "Primary Health Check",
    notes =
        "The response JSON will contain a message and the results of checking the health of "
            + "primary dependencies, although stack traces will be excluded.",
    response = HealthDto.class)
@ApiResponses(value = {
    @ApiResponse(code = 503, message = "unhealthy", response = HealthDto.class),
    @ApiResponse(code = 200, message = "healthy", response = HealthDto.class)})
@GET
@Produces(MediaType.APPLICATION_JSON)
@JsonView(HealthJsonViews.Primary.class)
Response getPrimaryHealthCheck();
 
Example 46
Project: nifi-registry   File: AccessPolicyResource.java   View source code 5 votes vote down vote up
/**
 * Remove a specified access policy.
 *
 * @param httpServletRequest request
 * @param identifier         The id of the access policy to remove.
 * @return The deleted access policy
 */
@DELETE
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
@ApiOperation(
        value = "Deletes an access policy",
        response = AccessPolicy.class
)
@ApiResponses({
        @ApiResponse(code = 401, message = HttpStatusMessages.MESSAGE_401),
        @ApiResponse(code = 403, message = HttpStatusMessages.MESSAGE_403),
        @ApiResponse(code = 404, message = HttpStatusMessages.MESSAGE_404),
        @ApiResponse(code = 409, message = HttpStatusMessages.MESSAGE_409 + " The NiFi Registry might not be configured to use a ConfigurableAccessPolicyProvider.") })
public Response removeAccessPolicy(
        @Context final HttpServletRequest httpServletRequest,
        @ApiParam(value = "The access policy id.", required = true)
        @PathParam("id")
        final String identifier) {

    verifyAuthorizerSupportsConfigurablePolicies();
    authorizeAccess(RequestAction.DELETE);
    AccessPolicy deletedPolicy = authorizationService.deleteAccessPolicy(identifier);
    if (deletedPolicy == null) {
        throw new ResourceNotFoundException("No access policy found with ID + " + identifier);
    }
    return generateOkResponse(deletedPolicy).build();
}
 
Example 47
Project: opencps-v2   File: DataManagement.java   View source code 5 votes vote down vote up
@GET
@Path("/{code}/dictgroups")
@Consumes({ MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response getDictgroups(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context Company company, @Context Locale locale, @Context User user, @Context ServiceContext serviceContext,
		@PathParam("code") String code, @BeanParam DataSearchModel query);
 
Example 48
Project: ctsms   File: JournalResource.java   View source code 5 votes vote down vote up
@GET
@Produces({ MediaType.APPLICATION_JSON })
@Path("user")
public Page<JournalEntryOutVO> getUserJournal(@Context UriInfo uriInfo)
		throws AuthenticationException, AuthorisationException, ServiceException {
	PSFUriPart psf;
	return new Page<JournalEntryOutVO>(WebUtil.getServiceLocator().getJournalService().getJournal(auth, JournalModule.USER_JOURNAL, null, psf = new PSFUriPart(uriInfo)), psf);
}
 
Example 49
Project: cf-mta-deploy-service   File: InfoApi.java   View source code 5 votes vote down vote up
@GET

    @Consumes({ "application/json" })
    @Produces({ "application/json" })
    @ApiOperation(value = "", notes = "Retrieve information about the Deploy Service application ", response = Info.class, authorizations = {
        @Authorization(value = "oauth2", scopes = {

        }) }, tags = {})
    @ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = Info.class) })
    public Response getInfo() {
        return delegate.getInfo(securityContext);
    }
 
Example 50
Project: vertx-zero   File: User.java   View source code 5 votes vote down vote up
@GET
@Path("/hello")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public String sayHello() {
    return "Hello";
}