public String getOverview(UriInfo uriInfo) { // verify interaction URI is valid findInteraction(); StringBuilder buffer = new StringBuilder(); buffer .append("<html>") .append("<head></head>") .append("<body>") .append("<p><a href='") .append(uriInfo.getAbsolutePath()) .append("/definition'>Show Interaction Definition</a></p>") .append("<p><a href='") .append(uriInfo.getAbsolutePath()) .append("/owner'>Show Interaction Owner</a></p>") .append("<p><a href='") .append(uriInfo.getAbsolutePath()) .append("/inData'>Show In Data Values</a></p>") .append("<p><a href='") .append(uriInfo.getAbsolutePath()) .append("/outData'>Submit Out Data Values</a></p>") .append("</body></html>"); return buffer.toString(); }
@POST @Path("blueprint/{name}") public Response createBlueprint( @Context UriInfo uri, @PathParam("name") String name, ConfigManifest blueprint) { Response res; try { ZooKeeper zk = Controller.getInstance().getZKInstance(); blueprint.setUrl(uri.getAbsolutePath().toURL()); byte[] data = JAXBUtil.write(blueprint); Stat stat = zk.exists( CommonConfigurationKeys.ZOOKEEPER_CONFIG_BLUEPRINT_PATH_DEFAULT + '/' + name, false); if (stat == null) { zk.create( CommonConfigurationKeys.ZOOKEEPER_CONFIG_BLUEPRINT_PATH_DEFAULT + '/' + name, data, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } else { throw new WebApplicationException(409); } res = Response.created(uri.getAbsolutePath()).build(); return res; } catch (WebApplicationException e) { throw e; } catch (Exception e) { LOG.error(ExceptionUtil.getStackTrace(e)); throw new WebApplicationException(500); } }
/** * POST method for creating an instance of ContactResource * * @param content representation for the new resource * @return an HTTP response with content of the created resource */ @POST // Create @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN, MediaType.TEXT_HTML }) @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN, MediaType.TEXT_HTML }) public Response postXmlOrJson(PhoneDirectoryEntry myEntry) { String phoneNo = myEntry.getPhoneNo(); boolean recordExist = phoneDirectoryDAO.checkPhoneNoExist(phoneNo); if (recordExist == true) { return Response.status(Response.Status.CONFLICT) // .CONFLICT .header( "Location ", String.format("%s%s", context.getAbsolutePath().toString(), myEntry.getPhoneNo())) .entity("<PhoneNumber_AlreadyExists PhoneNumber = '" + phoneNo + "'>") .build(); } else { phoneDirectoryDAO.addPhoneNumber(myEntry); return Response.status(Response.Status.CREATED) .header( "Location ", String.format("%s%s", context.getAbsolutePath().toString(), myEntry.getPhoneNo())) .entity(myEntry) .build(); } }
@Test public void testConstructSelfUri() { String id = UUID.randomUUID().toString(); URI self = InstanceResource.constructSelfUri(INSTANCE_URI_INFO, id); assertEquals(id, Strings.commonSuffix(id, self.getPath())); assertEquals( INSTANCE_URI_INFO.getAbsolutePath().toString(), Strings.commonPrefix(INSTANCE_URI_INFO.getAbsolutePath().toString(), self.toString())); }
/** * Builds the references of the PublicPlans of a CSAR and a plan type defined due the constructor. * * @param uriInfo * @return Response */ @GET @Produces(ResourceConstants.LINKED_XML) public Response getReferences(@Context UriInfo uriInfo) { if (this.csarID == null) { return Response.status(404).build(); } CSARPublicPlansResource.LOG.debug( "Return available management plans for CSAR {} and type {} .", this.csarID, this.publicPlanType); References refs = new References(); PublicPlanTypes type = PublicPlanTypes.isPlanTypeEnumRepresentation(this.publicPlanType); LinkedHashMap<Integer, PublicPlan> linkedMapOfPublicPlans = ToscaServiceHandler.getToscaEngineService() .getToscaReferenceMapper() .getCSARIDToPublicPlans(this.csarID) .get(type); CSARPublicPlansResource.LOG.debug( "Getting the list of PublicPlan of the type \"" + type + "\" for CSAR \"" + this.csarID.getFileName() + "\"."); for (Integer itr : linkedMapOfPublicPlans.keySet()) { PublicPlan plan = linkedMapOfPublicPlans.get(itr); refs.getReference() .add( new Reference( Utilities.buildURI(uriInfo.getAbsolutePath().toString(), Integer.toString(itr)), XLinkConstants.SIMPLE, plan.getPlanID().toString())); } CSARPublicPlansResource.LOG.info( "Number of References in Root: {}", refs.getReference().size()); // selflink refs.getReference() .add( new Reference( uriInfo.getAbsolutePath().toString(), XLinkConstants.SIMPLE, XLinkConstants.SELF)); return Response.ok(refs.getXMLString()).build(); }
/** * For test purpose only * * @param entities * @return */ @POST @Consumes({"application/json"}) @Produces({"application/json"}) public Response post(List<Product> entities, @Context UriInfo info) throws UnknownResourceException { if (entities == null) { return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build(); } int previousRows = productInventoryFacade.count(); int affectedRows = 0; // Try to persist entities try { for (Product entitie : entities) { productInventoryFacade.checkCreation(entitie); productInventoryFacade.create(entitie); entitie.setHref(info.getAbsolutePath() + "/" + Long.toString(entitie.getId())); productInventoryFacade.edit(entitie); affectedRows = affectedRows + 1; // publisher.createNotification(entitie, new Date()); } } catch (BadUsageException e) { return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build(); } Report stat = new Report(productInventoryFacade.count()); stat.setAffectedRows(affectedRows); stat.setPreviousRows(previousRows); // 201 OK return Response.created(null).entity(stat).build(); }
@GET @Path("/forward/object/{id}") public Response forwardObject( @PathParam("id") Integer id, @Context InternalDispatcher dispatcher) { uriStack.push(uriInfo.getAbsolutePath().toString()); return dispatcher.getResponse("/object/" + id); }
@POST @Consumes("text/plain") @Path("/forward/basic") public void postForwardBasic(String basic, @Context InternalDispatcher dispatcher) { uriStack.push(uriInfo.getAbsolutePath().toString()); dispatcher.postEntity("/basic", basic); }
@GET @Produces("text/plain") @Path("/forward/basic") public String forwardBasic(@Context InternalDispatcher dispatcher) { uriStack.push(uriInfo.getAbsolutePath().toString()); return (String) dispatcher.getEntity("/basic"); }
@GET @Produces("text/plain") @Path("/basic") public String getBasic() { uriStack.push(uriInfo.getAbsolutePath().toString()); return basic; }
@PUT @Consumes(MediaType.APPLICATION_XML) public Response putTaskData(String value) { Response res = null; // add your code here // first check if the Entity exists in the datastore DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService(); syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO)); Key entKey = KeyFactory.createKey("TaskData", keyname); Date date = new Date(); try { // if it is, signal that we updated the entity Entity ts = datastore.get(entKey); ts.setProperty("value", value); ts.setProperty("date", date); datastore.put(ts); res = Response.noContent().build(); } catch (EntityNotFoundException e) { // if it is not, create it and // signal that we created the entity in the datastore Entity taskdata = new Entity("TaskData", keyname); taskdata.setProperty("value", value); taskdata.setProperty("date", date); datastore.put(taskdata); res = Response.created(uriInfo.getAbsolutePath()).build(); } TaskData td = new TaskData(keyname, value, date); syncCache.put(keyname, td); return res; }
@POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(BeeterMediaType.BEETER_AUTH_TOKEN) public Response registerUser( @FormParam("loginid") String loginid, @FormParam("password") String password, @FormParam("email") String email, @FormParam("fullname") String fullname, @Context UriInfo uriInfo) throws URISyntaxException { if (loginid == null || password == null || email == null || fullname == null) throw new BadRequestException("all parameters are mandatory"); UserDAO userDAO = new UserDAOImpl(); User user = null; AuthToken authToken = null; try { user = userDAO.createUser(loginid, password, email, fullname); authToken = (new AuthTokenDAOImpl()).createAuthToken(user.getId()); } catch (UserAlreadyExistsException e) { throw new WebApplicationException("loginid already exists", Response.Status.CONFLICT); } catch (SQLException e) { throw new InternalServerErrorException(); } URI uri = new URI(uriInfo.getAbsolutePath().toString() + "/" + user.getId()); return Response.created(uri).type(BeeterMediaType.BEETER_AUTH_TOKEN).entity(authToken).build(); }
@POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(GrouptalkMediaType.GROUPTALK_AUTH_TOKEN) public Response createJoinGroup( @FormParam("userid") String userid, @FormParam("groupid") String groupid, @Context UriInfo uriInfo) throws URISyntaxException { if (userid == null || groupid == null) throw new BadRequestException("all parameters are mandatory"); JoinGroupDAO joinGroupDAO = new JoinGroupDAOImpl(); JoinGroup joinGroup = null; AuthToken authenticationToken = null; try { joinGroup = joinGroupDAO.createJoinGroup(securityContext.getUserPrincipal().getName(), groupid); } catch (SQLException e) { throw new InternalServerErrorException(); } URI uri = new URI(uriInfo.getAbsolutePath().toString() + "/" + joinGroup.getUserid()); return Response.created(uri) .type(GrouptalkMediaType.GROUPTALK_InterestGroups) .entity(joinGroup) .build(); }
@Override public void filter(ContainerRequestContext rc) throws IOException { checkSecurityContextStart(rc); UriInfo ui = rc.getUriInfo(); String absoluteRequestUri = ui.getAbsolutePath().toString(); boolean sameUriRedirect = false; if (completeUri == null) { String referer = rc.getHeaderString("Referer"); if (referer != null && referer.startsWith(authorizationServiceUri)) { completeUri = absoluteRequestUri; sameUriRedirect = true; } } if (!sameUriRedirect && absoluteRequestUri.endsWith(startUri)) { ClientTokenContext request = getClientTokenContext(rc); if (request != null) { setClientCodeRequest(request); if (completeUri != null) { rc.setRequestUri(URI.create(completeUri)); } return; } Response codeResponse = createCodeResponse(rc, ui); rc.abortWith(codeResponse); } else if (absoluteRequestUri.endsWith(completeUri)) { MultivaluedMap<String, String> requestParams = toRequestState(rc, ui); processCodeResponse(rc, ui, requestParams); checkSecurityContextEnd(rc, requestParams); } }
/** * Redirects to the overview page * * @return {@link Response} */ @GET public Response redirectToHomePage(@Context UriInfo uriInfo) { if (uriInfo.getAbsolutePath().toString().endsWith("/")) { return RedirectUtil.createSeeOtherResponse("overview", uriInfo); } return RedirectUtil.createSeeOtherResponse("dashboard/overview", uriInfo); }
@Test public void testContextUriInfoUtil2nd2ndPassPathParamsQueryParams() throws URISyntaxException { String dasBaseUri = "http://localhost:port/"; Map<String, String> pathParams = new HashMap<String, String>(); pathParams.put("aa", "2.16.840.1.113883.4.349"); pathParams.put("pid", "1012581676V377802"); pathParams.put("profile", "benefits"); pathParams.put("domain", "integratedCare"); pathParams.put("speciality", "careCoordinatorProfiles"); pathParams.put("homeCommunityId", "2.16.840.1.113883.4.349.3"); pathParams.put("remoteRepositoryId", "3.33.333.3.333333.3.333"); pathParams.put("documentUniqueId", "1001"); pathParams.put("fileExtension", "xml"); Map<String, String> queryParams = new HashMap<String, String>(); queryParams.put("queryParamName1", "queryParamValue1"); queryParams.put("queryParamName2", "queryParamValue2"); queryParams.put("queryParamName3", "queryParamValue3"); javax.ws.rs.core.UriInfo contextUriInfo = ContextUriInfoUtil.createUriInfo(dasBaseUri, pathParams, queryParams); System.out.println("baseUri: " + contextUriInfo.getBaseUri()); System.out.println("path: " + contextUriInfo.getPath()); System.out.println("absolutePath: " + contextUriInfo.getAbsolutePath()); System.out.println("requestUri: " + contextUriInfo.getRequestUri()); System.out.println(""); }
/** * Creates a new agreement * * <pre> * POST /agreements * * Request: * POST /agreements HTTP/1.1 * Accept: application/xml * * Response: * HTTP/1.1 201 Created * Content-type: application/xml * Location: http://.../agreements/$uuid * * {@code * <?xml version="1.0" encoding="UTF-8" standalone="yes"?> * <message code="201" message= "The agreement has been stored successfully in the SLA Repository Database"/> * } * * </pre> * * Example: * <li>curl -H "Content-type: application/xml" [email protected] * localhost:8080/sla-service/agreements -X POST * * @return XML information with the different details of the agreement */ @POST @Consumes(MediaType.APPLICATION_XML) @Produces(MediaType.APPLICATION_XML) public Response createAgreement( @Context HttpHeaders hh, @Context UriInfo uriInfo, String payload) { logger.debug("StartOf createAgreement - Insert /agreements"); String location = null; try { AgreementHelper agreementRestService = getAgreementHelper(); location = agreementRestService.createAgreement(hh, uriInfo.getAbsolutePath().toString(), payload); } catch (HelperException e) { logger.info("createAgreement exception", e); return buildResponse(e); } Response result = buildResponsePOST( HttpStatus.CREATED, printMessage( HttpStatus.CREATED, "The agreement has been stored successfully in the SLA Repository Database with location:" + location), location); logger.debug("EndOf createAgreement"); return result; }
@Test public void testContextUriInfoUtil1stPassPathParamsQueryP() throws URISyntaxException { String dasBaseUri = "http://localhost:port/"; Map<String, String> pathParams = new HashMap<String, String>(); pathParams.put("aa", "2.16.840.1.113883.4.349"); pathParams.put("pid", "1012581676V377802"); pathParams.put("profile", "benefits"); pathParams.put("domain", "integratedCare"); pathParams.put("speciality", "careCoordinatorProfiles"); String queryP = "?zzzzzz=3333333&xxxxx=111111&yyyy=22222"; Map<String, String> queryParams = new HashMap<String, String>(); queryParams.put("zzzzzz", "3333333"); queryParams.put("xxxxx", "111111"); queryParams.put("yyyy", "22222"); javax.ws.rs.core.UriInfo contextUriInfo = ContextUriInfoUtil.createUriInfo(dasBaseUri, null, pathParams, queryP, queryParams); System.out.println("baseUri: " + contextUriInfo.getBaseUri()); System.out.println("path: " + contextUriInfo.getPath()); System.out.println("absolutePath: " + contextUriInfo.getAbsolutePath()); System.out.println("requestUri: " + contextUriInfo.getRequestUri()); System.out.println(""); }
@GET public IpsPoolManagementDto getIPAddresses( @PathParam(VirtualDatacenterResource.VIRTUAL_DATACENTER) final Integer vdcId, @PathParam(PrivateNetworkResource.PRIVATE_NETWORK) final Integer vlanId, @QueryParam(START_WITH) @DefaultValue("0") @Min(0) final Integer startwith, @QueryParam(BY) @DefaultValue("ip") final String orderBy, @QueryParam(FILTER) @DefaultValue("") final String filter, @QueryParam(LIMIT) @Min(0) @DefaultValue(DEFAULT_PAGE_LENGTH_STRING) final Integer limit, @QueryParam(ASC) @DefaultValue("true") final Boolean descOrAsc, @QueryParam(ONLYAVAILABLE) @DefaultValue("false") final Boolean available, @Context final IRESTBuilder restBuilder) throws Exception { List<IpPoolManagement> all = service.getListIpPoolManagementByVlan( vdcId, vlanId, startwith, orderBy, filter, limit, descOrAsc); IpsPoolManagementDto ips = new IpsPoolManagementDto(); for (IpPoolManagement ip : all) { ips.add(createTransferObject(ip, restBuilder)); } ips.addLinks( restBuilder.buildPaggingLinks(uriInfo.getAbsolutePath().toString(), (PagedList) all)); ips.setTotalSize(((PagedList) all).getTotalResults()); return ips; }
@PUT public Response putItem(@Context HttpHeaders headers, byte[] data) { System.out.println("PUT ITEM " + container + " " + item); URI uri = uriInfo.getAbsolutePath(); MediaType mimeType = headers.getMediaType(); GregorianCalendar gc = new GregorianCalendar(); gc.set(GregorianCalendar.MILLISECOND, 0); Item i = new Item(item, uri.toString(), mimeType.toString(), gc); String digest = computeDigest(data); i.setDigest(digest); Response r; if (!MemoryStore.MS.hasItem(container, item)) { r = Response.created(uri).build(); } else { r = Response.noContent().build(); } Item ii = MemoryStore.MS.createOrUpdateItem(container, i, data); if (ii == null) { // Create the container if one has not been created URI containerUri = uriInfo.getAbsolutePathBuilder().path("..").build().normalize(); Container c = new Container(container, containerUri.toString()); MemoryStore.MS.createContainer(c); i = MemoryStore.MS.createOrUpdateItem(container, i, data); if (i == null) throw new NotFoundException("Container not found"); } return r; }
@GET @Produces(MIMETYPE_BINARY) public Response getBinary(final @Context UriInfo uriInfo) { if (LOG.isDebugEnabled()) { LOG.debug("GET " + uriInfo.getAbsolutePath() + " as " + MIMETYPE_BINARY); } servlet.getMetrics().incrementRequests(1); try { KeyValue value = generator.next(); if (value == null) { LOG.info("generator exhausted"); return Response.noContent().build(); } ResponseBuilder response = Response.ok(value.getValue()); response.cacheControl(cacheControl); response.header("X-Row", Base64.encodeBytes(value.getRow())); response.header( "X-Column", Base64.encodeBytes(KeyValue.makeColumn(value.getFamily(), value.getQualifier()))); response.header("X-Timestamp", value.getTimestamp()); return response.build(); } catch (IllegalStateException e) { ScannerResource.delete(id); throw new WebApplicationException(Response.Status.GONE); } }
/** * Post method for creating an instance of Network using XML as the input format. * * @param data an NetworkConverter entity that is deserialized from an XML stream * @return an instance of NetworkConverter */ @POST @Consumes({"application/xml", "application/json"}) public Response post(NetworkConverter data) { Network entity = data.getEntity(); createEntity(entity); return Response.created(uriInfo.getAbsolutePath().resolve(entity.getId() + "/")).build(); }
@Path(("/registrar")) @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MusicloudMediaType.MUSICLOUD_AUTH_TOKEN) public Response registerUser( @FormParam("login") String login, @FormParam("nombre") String nombre, @FormParam("apellidos") String apellidos, @FormParam("email") String email, @FormParam("password") String password, @Context UriInfo uriInfo) throws URISyntaxException { if (login == null || nombre == null || apellidos == null || password == null || email == null) throw new BadRequestException("Se necesitan todos los parametros"); UserDAO userDAO = new UserDAOImpl(); User user = null; try { user = userDAO.crear_usuario_registrado(login, nombre, apellidos, email, password); } catch (UserAlreadyExistsException e) { throw new WebApplicationException("Este login ya existe ", Response.Status.CONFLICT); } catch (SQLException e) { throw new InternalServerErrorException(); } URI uri = new URI(uriInfo.getAbsolutePath().toString() + "/" + user.getId()); return Response.ok().build(); }
@GET @Produces("text/plain") @Path("/object/{id}") public Response getObject(@PathParam("id") Integer id) { uriStack.push(uriInfo.getAbsolutePath().toString()); if (id == 0) return Response.noContent().build(); else return Response.ok("object" + id).build(); }
@PUT @POST @Consumes("text/plain") @Path("/basic") public void putBasic(String basic) { uriStack.push(uriInfo.getAbsolutePath().toString()); this.basic = basic; }
@PUT @Consumes(MediaType.APPLICATION_JSON) public Response updateClient( final Client client, @Context final UriInfo uriInfo, @Context final HttpHeaders headers) { clientService.updateClient(client); return Response.ok( new StatusEntity("200", uriInfo.getAbsolutePath() + "/" + client.getClientID())) .build(); }
private Response putAndGetResponse(Todo todo) { Response res; if (TodoDao.instance.getModel().containsKey(todo.getId())) { res = Response.noContent().build(); } else { res = Response.created(uriInfo.getAbsolutePath()).build(); } TodoDao.instance.getModel().put(todo.getId(), todo); return res; }
private Response getResponse(Senzor senzor) { Response raspuns; if (ListaSenzor.instance.getModel().containsKey(senzor.getId())) { raspuns = Response.noContent().build(); } else { raspuns = Response.created(uriInfo.getAbsolutePath()).build(); } ListaSenzor.instance.getModel().put(senzor.getId(), senzor); return raspuns; }
/** * Eine neue Lokalitaet abspeichern. * * @param person Das Person-Objekt * @param uriInfo Info-Objekt zur aufgerufenen URI * @param headers * @return * @return * @throws URISyntaxException */ @POST @XmlElement(type = Location.class) @Consumes({MediaType.APPLICATION_XML, MediaType.TEXT_XML, MediaType.APPLICATION_JSON}) @Produces public Response createLocation( Location location, @Context UriInfo uriInfo, @Context HttpHeaders headers) { dao.create(location.getBeschreibung()); return Response.created(uriInfo.getAbsolutePath()).build(); }
/** * Get method for retrieving a collection of Network instance in XML format. * * @return an instance of NetworksConverter */ @GET @Produces({"application/xml", "application/json"}) public NetworksConverter get( @QueryParam("start") @DefaultValue("0") int start, @QueryParam("max") @DefaultValue("10") int max, @QueryParam("expandLevel") @DefaultValue("1") int expandLevel, @QueryParam("query") @DefaultValue("SELECT e FROM Network e") String query) { return new NetworksConverter( getEntities(start, max, query), uriInfo.getAbsolutePath(), expandLevel); }