javax.ws.rs.core.UriBuilder Java Examples
The following examples show how to use
javax.ws.rs.core.UriBuilder.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PetApi.java From openapi-generator with Apache License 2.0 | 6 votes |
public HttpResponse uploadFileForHttpResponse(Long petId, String additionalMetadata, File file) throws IOException { // verify the required parameter 'petId' is set if (petId == null) { throw new IllegalArgumentException("Missing the required parameter 'petId' when calling uploadFile"); } // create a map of path variables final Map<String, Object> uriVariables = new HashMap<String, Object>(); uriVariables.put("petId", petId); UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/pet/{petId}/uploadImage"); String localVarUrl = uriBuilder.buildFromMap(uriVariables).toString(); GenericUrl genericUrl = new GenericUrl(localVarUrl); HttpContent content = new EmptyContent(); return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute(); }
Example #2
Source File: EmoUriBuilder.java From emodb with Apache License 2.0 | 6 votes |
@Override public UriBuilder replaceQueryParam(String name, Object... values) { checkSsp(); if (queryParams == null) { queryParams = EmoUriComponent.decodeQuery(query.toString(), false); query.setLength(0); } name = encode(name, EmoUriComponent.Type.QUERY_PARAM); queryParams.remove(name); if (values == null) { return this; } for (Object value : values) { if (value == null) { throw new IllegalArgumentException("One or more of query value parameters are null"); } queryParams.add(name, encode(value.toString(), EmoUriComponent.Type.QUERY_PARAM)); } return this; }
Example #3
Source File: HttpNotification.java From oink with Apache License 2.0 | 6 votes |
@Override public void run() { int maxRetry = 3; while(maxRetry > 0) { try { client.setReadTimeout(30000); client.setConnectTimeout(30000); URI uri = UriBuilder.fromUri(url).build(); WebResource service = client.resource(uri); responseBody = service.accept(MediaType.TEXT_PLAIN).get(String.class); responseCode = "200"; logger.info("Successfully called service for " + url); break; } catch(Exception e) { responseCode = "500"; responseBody = e.getMessage(); logger.error("Error occurred while contacting service " + url + " Msg :" + e.getMessage(), e); maxRetry--; } } }
Example #4
Source File: AbstractOIDCTest.java From cxf-fediz with Apache License 2.0 | 6 votes |
@org.junit.Test public void testOIDCLoginForConfidentialClientWithRoles() throws Exception { final UriBuilder authorizationUrl = oidcEndpointBuilder("/idp/authorize") .queryParam("client_id", confidentialClientId) .queryParam("response_type", "code") .queryParam("scope", "openid") .queryParam("claims", "roles"); // Login to the OIDC authorization endpoint + get the authorization code final String authorizationCode = loginAndGetAuthorizationCode(authorizationUrl, "alice", "ecila"); // Now use the code to get an IdToken final Map<String, Object> json = getTokenJson(authorizationCode, confidentialClientId, confidentialClientSecret); // Check the IdToken validateIdToken(getIdToken(json), confidentialClientId, "User"); }
Example #5
Source File: CassandraHealthCheckIntegrationTest.java From dropwizard-cassandra with Apache License 2.0 | 6 votes |
@Test public void reportsSuccess() throws Exception { final URI uri = UriBuilder.fromUri("http://localhost") .port(APP.getAdminPort()) .path("healthcheck") .build(); final WebTarget target = ClientBuilder.newClient().target(uri); final Map<String, Map<String, Object>> result = target.request().get(Map.class); final String healthCheckName = "cassandra.minimal-cluster"; assertThat(result).containsKey(healthCheckName); Map<String, Object> cassandraStatus = result.get(healthCheckName); assertThat(cassandraStatus).containsEntry("healthy", true); }
Example #6
Source File: PaginationImplementor.java From quarkus with Apache License 2.0 | 6 votes |
/** * Build a {@link URI} for the given page. Takes the absolute path from the given {@link UriInfo} and appends page and size * query parameters from the given {@link Page}. * * @param creator a bytecode creator to be used for code generation * @param uriInfo a {@link UriInfo} to be used for the absolute path extraction * @param page a {@link Page} to be used for getting page number and size * @return a page {@link URI} */ private static ResultHandle getPageUri(BytecodeCreator creator, ResultHandle uriInfo, ResultHandle page) { ResultHandle uriBuilder = creator.invokeInterfaceMethod( ofMethod(UriInfo.class, "getAbsolutePathBuilder", UriBuilder.class), uriInfo); // Add page query parameter ResultHandle index = creator.readInstanceField(FieldDescriptor.of(Page.class, "index", int.class), page); creator.invokeVirtualMethod( ofMethod(UriBuilder.class, "queryParam", UriBuilder.class, String.class, Object[].class), uriBuilder, creator.load("page"), creator.marshalAsArray(Object.class, index)); // Add size query parameter ResultHandle size = creator.readInstanceField(FieldDescriptor.of(Page.class, "size", int.class), page); creator.invokeVirtualMethod( ofMethod(UriBuilder.class, "queryParam", UriBuilder.class, String.class, Object[].class), uriBuilder, creator.load("size"), creator.marshalAsArray(Object.class, size)); return creator.invokeVirtualMethod( ofMethod(UriBuilder.class, "build", URI.class, Object[].class), uriBuilder, creator.newArray(Object.class, 0)); }
Example #7
Source File: FilterRestServiceImpl.java From camunda-bpm-platform with Apache License 2.0 | 6 votes |
public ResourceOptionsDto availableOperations(UriInfo context) { UriBuilder baseUriBuilder = context.getBaseUriBuilder() .path(relativeRootResourcePath) .path(FilterRestService.PATH); ResourceOptionsDto resourceOptionsDto = new ResourceOptionsDto(); // GET / URI baseUri = baseUriBuilder.build(); resourceOptionsDto.addReflexiveLink(baseUri, HttpMethod.GET, "list"); // GET /count URI countUri = baseUriBuilder.clone().path("/count").build(); resourceOptionsDto.addReflexiveLink(countUri, HttpMethod.GET, "count"); // POST /create if (isAuthorized(CREATE)) { URI createUri = baseUriBuilder.clone().path("/create").build(); resourceOptionsDto.addReflexiveLink(createUri, HttpMethod.POST, "create"); } return resourceOptionsDto; }
Example #8
Source File: OAuthProofKeyForCodeExchangeTest.java From keycloak with Apache License 2.0 | 6 votes |
@Test public void accessTokenRequestCodeChallengeMethodMismatchPkceEnforced() throws Exception { try { setPkceActivationSettings("test-app", OAuth2Constants.PKCE_METHOD_S256); String codeVerifier = "12345678e01234567890g2345678h012a4567j90123"; // 43 String codeChallenge = generateS256CodeChallenge(codeVerifier); oauth.codeChallenge(codeChallenge); oauth.codeChallengeMethod(OAuth2Constants.PKCE_METHOD_PLAIN); UriBuilder b = UriBuilder.fromUri(oauth.getLoginFormUrl()); driver.navigate().to(b.build().toURL()); OAuthClient.AuthorizationEndpointResponse errorResponse = new OAuthClient.AuthorizationEndpointResponse(oauth); Assert.assertTrue(errorResponse.isRedirected()); Assert.assertEquals(errorResponse.getError(), OAuthErrorException.INVALID_REQUEST); Assert.assertEquals(errorResponse.getErrorDescription(), "Invalid parameter: code challenge method is not configured one"); events.expectLogin().error(Errors.INVALID_REQUEST).user((String) null).session((String) null).clearDetails().assertEvent(); } finally { setPkceActivationSettings("test-app", null); } }
Example #9
Source File: UserVOFactory.java From olat with Apache License 2.0 | 6 votes |
public static UserVO link(final UserVO userVO, final UriInfo uriInfo) { if (uriInfo != null) { final UriBuilder baseUriBuilder = uriInfo.getBaseUriBuilder(); final URI getUri = baseUriBuilder.path("users").path(userVO.getKey().toString()).build(); userVO.getLink().add(new LinkVO("self", getUri.toString(), "")); userVO.getLink().add(new LinkVO("edit", getUri.toString(), "")); userVO.getLink().add(new LinkVO("delete", getUri.toString(), "")); final URI groupUri = baseUriBuilder.path("users").path(userVO.getKey().toString()).path("groups").build(); userVO.getLink().add(new LinkVO("self", groupUri.toString(), "Groups")); final URI portraitUri = baseUriBuilder.path("users").path(userVO.getKey().toString()).path("portrait").build(); userVO.getLink().add(new LinkVO("self", portraitUri.toString(), "Portrait")); } return userVO; }
Example #10
Source File: VirtualNetworkWebResource.java From onos with Apache License 2.0 | 6 votes |
/** * Creates a virtual network link from the JSON input stream. * * @param networkId network identifier * @param stream virtual link JSON stream * @return status of the request - CREATED if the JSON is correct, * BAD_REQUEST if the JSON is invalid * @onos.rsModel VirtualLink */ @POST @Path("{networkId}/links") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createVirtualLink(@PathParam("networkId") long networkId, InputStream stream) { try { ObjectNode jsonTree = readTreeFromStream(mapper(), stream); JsonNode specifiedNetworkId = jsonTree.get("networkId"); if (specifiedNetworkId == null || specifiedNetworkId.asLong() != (networkId)) { throw new IllegalArgumentException(INVALID_FIELD + "networkId"); } final VirtualLink vlinkReq = codec(VirtualLink.class).decode(jsonTree, this); vnetAdminService.createVirtualLink(vlinkReq.networkId(), vlinkReq.src(), vlinkReq.dst()); UriBuilder locationBuilder = uriInfo.getBaseUriBuilder() .path("vnets").path(specifiedNetworkId.asText()) .path("links"); return Response .created(locationBuilder.build()) .build(); } catch (IOException e) { throw new IllegalArgumentException(e); } }
Example #11
Source File: JerseyServerBootstrap.java From camunda-bpm-platform with Apache License 2.0 | 6 votes |
private void setupServer(Application application) { ResourceConfig rc = ResourceConfig.forApplication(application); Properties serverProperties = readProperties(); int port = Integer.parseInt(serverProperties.getProperty(PORT_PROPERTY)); URI serverUri = UriBuilder.fromPath(ROOT_RESOURCE_PATH).scheme("http").host("localhost").port(port).build(); final HttpServer grizzlyServer = GrizzlyHttpServerFactory.createHttpServer(serverUri, rc); try { grizzlyServer.start(); } catch (IOException e) { e.printStackTrace(); } server = grizzlyServer; }
Example #12
Source File: RepositoryEntriesResource.java From olat with Apache License 2.0 | 6 votes |
/** * List all entries in the OLAT repository * * @response.representation.200.qname {http://www.example.com}repositoryEntryVO * @response.representation.200.mediaType text/plain, text/html, application/xml, application/json * @response.representation.200.doc List all entries in the repository * @response.representation.200.example {@link org.olat.connectors.rest.support.vo.Examples#SAMPLE_REPOENTRYVOes} * @param uriInfo * The URI information * @param httpRequest * The HTTP request * @return */ @GET @Produces({ MediaType.TEXT_HTML, MediaType.TEXT_PLAIN }) public Response getEntriesText(@Context final UriInfo uriInfo, @Context final HttpServletRequest httpRequest) { try { // list of courses open for everybody final Roles roles = getRoles(httpRequest); final List<String> types = new ArrayList<String>(); final List<RepositoryEntry> coursRepos = RepositoryServiceImpl.getInstance().genericANDQueryWithRolesRestriction("*", "*", "*", types, roles, null); final StringBuilder sb = new StringBuilder(); sb.append("Course List\n"); for (final RepositoryEntry repoE : coursRepos) { final UriBuilder baseUriBuilder = uriInfo.getBaseUriBuilder(); final URI repoUri = baseUriBuilder.path(RepositoryEntriesResource.class).path(repoE.getKey().toString()).build(); sb.append("<a href=\"").append(repoUri).append(">").append(repoE.getDisplayname()).append("(").append(repoE.getKey()).append(")").append("</a>") .append("\n"); } return Response.ok(sb.toString()).build(); } catch (final Exception e) { throw new WebApplicationException(e); } }
Example #13
Source File: ClientFactory.java From oxAuth with MIT License | 5 votes |
public IntrospectionService createIntrospectionService(String p_url, ClientHttpEngine engine) { ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build(); ResteasyWebTarget target = client.target(UriBuilder.fromPath(p_url)); IntrospectionService proxy = target.proxy(IntrospectionService.class); return proxy; }
Example #14
Source File: PortalApiLinkHelper.java From gravitee-management-rest-api with Apache License 2.0 | 5 votes |
private static String resourcesURL(UriBuilder baseUriBuilder, String resourceId, String resourceName, String subResourceId, String subResourceName) { UriBuilder resourcesURLBuilder = baseUriBuilder.path("environments").path(GraviteeContext.getCurrentEnvironment()) .path(resourceName); if (resourceId != null && !resourceId.isEmpty()) { resourcesURLBuilder = resourcesURLBuilder.path(resourceId); } if (subResourceName != null && !subResourceName.isEmpty()) { resourcesURLBuilder = resourcesURLBuilder.path(subResourceName); } if (subResourceId != null && !subResourceId.isEmpty()) { resourcesURLBuilder = resourcesURLBuilder.path(subResourceId); } return resourcesURLBuilder.build().toString(); }
Example #15
Source File: UriBuilderRequestFilter.java From gravitee-management-rest-api with Apache License 2.0 | 5 votes |
@Override public void filter(ContainerRequestContext ctx) { UriBuilder baseBuilder = ctx.getUriInfo().getBaseUriBuilder(); UriBuilder requestBuilder = ctx.getUriInfo().getRequestUriBuilder(); // order matters as each process method may override values set by previous one(s) processProtocolHeader(ctx, baseBuilder, requestBuilder); processHostHeader(ctx, baseBuilder, requestBuilder); processPortHeader(ctx, baseBuilder, requestBuilder); }
Example #16
Source File: PreviewUrlLinksVariableGenerator.java From che with Eclipse Public License 2.0 | 5 votes |
/** * Takes commands from given {@code workspace}. For all commands that have defined previewUrl, * creates variable name in defined format and final preview url link. It updates the command so * it's `previewUrl` attribute will contain variable in proper format. Method then returns map of * all preview url links with these variables as keys: * * <pre> * links: * "previewURl/run_123": http://your.domain * command: * attributes: * previewUrl: '${previewUrl/run_123}/some/path' * </pre> * * @return map of all <commandPreviewUrlVariable, previewUrlFullLink> */ Map<String, String> genLinksMapAndUpdateCommands(WorkspaceImpl workspace, UriBuilder uriBuilder) { if (workspace == null || workspace.getRuntime() == null || workspace.getRuntime().getCommands() == null || uriBuilder == null) { return Collections.emptyMap(); } Map<String, String> links = new HashMap<>(); for (Command command : workspace.getRuntime().getCommands()) { Map<String, String> commandAttributes = command.getAttributes(); if (command.getPreviewUrl() != null && commandAttributes != null && commandAttributes.containsKey(PREVIEW_URL_ATTRIBUTE)) { String previewUrlLinkValue = createPreviewUrlLinkValue(uriBuilder, command); String previewUrlLinkKey = createPreviewUrlLinkKey(command); links.put(previewUrlLinkKey, previewUrlLinkValue); commandAttributes.replace( PREVIEW_URL_ATTRIBUTE, formatAttributeValue(previewUrlLinkKey, command.getPreviewUrl().getPath())); } } return links; }
Example #17
Source File: WebAppProxyServlet.java From sylph with Apache License 2.0 | 5 votes |
protected void doGet1(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { final String remoteUser = req.getRemoteUser(); final String pathInfo = req.getPathInfo(); String[] parts = pathInfo.split("/", 3); checkArgument(parts.length >= 2, remoteUser + " gave an invalid proxy path " + pathInfo); //parts[0] is empty because path info always starts with a / String jobIdOrRunId = parts[1]; String rest = parts.length > 2 ? parts[2] : ""; URI trackingUri = new URI(getJobUrl(jobIdOrRunId)); // Append the user-provided path and query parameter to the original // tracking url. String query = req.getQueryString() == null ? "" : req.getQueryString(); List<NameValuePair> queryPairs = URLEncodedUtils.parse(query, null); UriBuilder builder = UriBuilder.fromUri(trackingUri); for (NameValuePair pair : queryPairs) { builder.queryParam(pair.getName(), pair.getValue()); } URI toFetch = builder.path(rest).build(); proxyLink(req, resp, toFetch, null); } catch (URISyntaxException e) { throw new IOException(e); } }
Example #18
Source File: GuiceUriBuilderImpl.java From everrest with Eclipse Public License 2.0 | 5 votes |
@SuppressWarnings({"unchecked"}) @Override public UriBuilder path(Class resource) { if (resource == null) { throw new IllegalArgumentException("Resource is null"); } if (resource.getName().contains(PROXY_MARKER)) { return super.path(resource.getSuperclass()); } return super.path(resource); }
Example #19
Source File: RecipeRetriever.java From che with Eclipse Public License 2.0 | 5 votes |
private UriBuilder makeURIAbsolute(URI uri) { UriBuilder uriBuilder = UriBuilder.fromUri(uri); if (!uri.isAbsolute() && uri.getHost() == null) { uriBuilder .scheme(apiEndpoint.getScheme()) .host(apiEndpoint.getHost()) .port(apiEndpoint.getPort()) .replacePath(apiEndpoint.getPath() + uri.toString()); } return uriBuilder; }
Example #20
Source File: SamlProtocol.java From keycloak with Apache License 2.0 | 5 votes |
@Override public Response sendError(AuthenticationSessionModel authSession, Error error) { try { ClientModel client = authSession.getClient(); if ("true".equals(authSession.getClientNote(SAML_IDP_INITIATED_LOGIN))) { if (error == Error.CANCELLED_BY_USER) { UriBuilder builder = RealmsResource.protocolUrl(uriInfo).path(SamlService.class, "idpInitiatedSSO"); Map<String, String> params = new HashMap<>(); params.put("realm", realm.getName()); params.put("protocol", LOGIN_PROTOCOL); params.put("client", client.getAttribute(SAML_IDP_INITIATED_SSO_URL_NAME)); URI redirect = builder.buildFromMap(params); return Response.status(302).location(redirect).build(); } else { return ErrorPage.error(session, authSession, Response.Status.BAD_REQUEST, translateErrorToIdpInitiatedErrorMessage(error)); } } else { return samlErrorMessage( authSession, new SamlClient(client), isPostBinding(authSession), authSession.getRedirectUri(), translateErrorToSAMLStatus(error), authSession.getClientNote(GeneralConstants.RELAY_STATE) ); } } finally { new AuthenticationSessionManager(session).removeAuthenticationSession(realm, authSession, true); } }
Example #21
Source File: FakeApi.java From openapi-generator with Apache License 2.0 | 5 votes |
public HttpResponse testClientModelForHttpResponse(java.io.InputStream body, String mediaType) throws IOException { // verify the required parameter 'body' is set if (body == null) { throw new IllegalArgumentException("Missing the required parameter 'body' when calling testClientModel"); } UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake"); String localVarUrl = uriBuilder.build().toString(); GenericUrl genericUrl = new GenericUrl(localVarUrl); HttpContent content = body == null ? apiClient.new JacksonJsonHttpContent(null) : new InputStreamContent(mediaType == null ? Json.MEDIA_TYPE : mediaType, body); return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.PATCH, genericUrl, content).execute(); }
Example #22
Source File: TestDataTransferResource.java From localization_nifi with Apache License 2.0 | 5 votes |
private UriInfo mockUriInfo(final String locationUriStr) throws URISyntaxException { final UriInfo uriInfo = mock(UriInfo.class); final UriBuilder uriBuilder = mock(UriBuilder.class); final URI locationUri = new URI(locationUriStr); doReturn(uriBuilder).when(uriInfo).getBaseUriBuilder(); doReturn(uriBuilder).when(uriBuilder).path(any(String.class)); doReturn(locationUri).when(uriBuilder).build(); return uriInfo; }
Example #23
Source File: UserApi.java From openapi-generator with Apache License 2.0 | 5 votes |
public HttpResponse createUsersWithArrayInputForHttpResponse(List<User> body, Map<String, Object> params) throws IOException { // verify the required parameter 'body' is set if (body == null) { throw new IllegalArgumentException("Missing the required parameter 'body' when calling createUsersWithArrayInput"); } UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/user/createWithArray"); // Copy the params argument if present, to allow passing in immutable maps Map<String, Object> allParams = params == null ? new HashMap<String, Object>() : new HashMap<String, Object>(params); for (Map.Entry<String, Object> entry: allParams.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (key != null && value != null) { if (value instanceof Collection) { uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); } else if (value instanceof Object[]) { uriBuilder = uriBuilder.queryParam(key, (Object[]) value); } else { uriBuilder = uriBuilder.queryParam(key, value); } } } String localVarUrl = uriBuilder.build().toString(); GenericUrl genericUrl = new GenericUrl(localVarUrl); HttpContent content = apiClient.new JacksonJsonHttpContent(body); return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute(); }
Example #24
Source File: PublicDefaultResourceTest.java From secure-data-service with Apache License 2.0 | 5 votes |
private void setupMocks(String uri) throws URISyntaxException { requestURI = new java.net.URI(uri); MultivaluedMap map = new MultivaluedMapImpl(); uriInfo = mock(UriInfo.class); when(uriInfo.getRequestUri()).thenReturn(requestURI); when(uriInfo.getQueryParameters()).thenReturn(map); when(uriInfo.getBaseUriBuilder()).thenAnswer(new Answer<UriBuilder>() { @Override public UriBuilder answer(InvocationOnMock invocation) throws Throwable { return new UriBuilderImpl().path("base"); } }); }
Example #25
Source File: ApplicationWsDelegateTest.java From roboconf-platform with Apache License 2.0 | 5 votes |
@Before public void before() throws Exception { // Create the manager this.manager = new Manager(); this.manager.setMessagingType( MessagingConstants.FACTORY_TEST ); this.manager.setTargetResolver( new TestTargetResolver()); this.manager.configurationMngr().setWorkingDirectory( this.folder.newFolder()); this.manager.start(); // Create the wrapper and complete configuration this.managerWrapper = new TestManagerWrapper( this.manager ); this.managerWrapper.configureMessagingForTest(); this.manager.reconfigure(); // Get the messaging client this.msgClient = (TestClient) this.managerWrapper.getInternalMessagingClient(); this.msgClient.clearMessages(); // Disable the messages timer for predictability TestUtils.getInternalField( this.manager, "timer", Timer.class).cancel(); URI uri = UriBuilder.fromUri( REST_URI ).build(); RestApplication restApp = new RestApplication( this.manager ); this.httpServer = GrizzlyServerFactory.createHttpServer( uri, restApp );; // Load an application this.app = new TestApplication(); this.app.setDirectory( this.folder.newFolder()); this.ma = new ManagedApplication( this.app ); this.managerWrapper.addManagedApplication( this.ma ); this.client = new WsClient( REST_URI ); }
Example #26
Source File: RuleResource.java From localization_nifi with Apache License 2.0 | 5 votes |
@POST @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Path("/rules/actions") public Response createAction( @Context final UriInfo uriInfo, @PathParam("id") final String ruleId, final ActionEntity requestEntity) { // generate a new id final String uuid = UUID.randomUUID().toString(); final Action action; try { // create the condition object final UpdateAttributeModelFactory factory = new UpdateAttributeModelFactory(); action = factory.createAction(requestEntity.getAction()); action.setId(uuid); } catch (final IllegalArgumentException iae) { throw new WebApplicationException(iae, badRequest(iae.getMessage())); } // build the response final ActionEntity responseEntity = new ActionEntity(); responseEntity.setClientId(requestEntity.getClientId()); responseEntity.setProcessorId(requestEntity.getProcessorId()); responseEntity.setRevision(requestEntity.getRevision()); responseEntity.setAction(DtoFactory.createActionDTO(action)); // generate the response final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder(); final ResponseBuilder response = Response.created(uriBuilder.path(uuid).build()).entity(responseEntity); return noCache(response).build(); }
Example #27
Source File: CatalogITCase.java From olat with Apache License 2.0 | 5 votes |
@Test public void testGetChild() throws IOException { final HttpClient c = loginWithCookie("administrator", "olat"); final URI uri = UriBuilder.fromUri(getContextURI()).path("catalog").path(entry1.getKey().toString()).build(); final GetMethod method = createGet(uri, MediaType.APPLICATION_JSON, true); final int code = c.executeMethod(method); assertEquals(200, code); final String body = method.getResponseBodyAsString(); method.releaseConnection(); final CatalogEntryVO vo = parse(body, CatalogEntryVO.class); assertNotNull(vo); assertEquals(entry1.getName(), vo.getName()); assertEquals(entry1.getDescription(), vo.getDescription()); }
Example #28
Source File: UriComponent.java From everrest with Eclipse Public License 2.0 | 5 votes |
/** * Normalization URI according to rfc3986. For details see * http://www.unix.com.ua/rfc/rfc3986.html#s6.2.2 . * * @param uri * source URI * @return normalized URI */ public static URI normalize(URI uri) { String oldPath = uri.getRawPath(); if (Strings.isNullOrEmpty(oldPath)) { return uri; } String normalizedPath = normalize(oldPath); if (normalizedPath.equals(oldPath)) { // nothing to do, URI was normalized return uri; } return UriBuilder.fromUri(uri).replacePath(normalizedPath).build(); }
Example #29
Source File: PayrollAuApi.java From Xero-Java with MIT License | 5 votes |
public HttpResponse updateEmployeeForHttpResponse(String accessToken, String xeroTenantId, UUID employeeId, List<Employee> employee) throws IOException { // verify the required parameter 'xeroTenantId' is set if (xeroTenantId == null) { throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling updateEmployee"); }// verify the required parameter 'employeeId' is set if (employeeId == null) { throw new IllegalArgumentException("Missing the required parameter 'employeeId' when calling updateEmployee"); } if (accessToken == null) { throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling updateEmployee"); } HttpHeaders headers = new HttpHeaders(); headers.set("Xero-Tenant-Id", xeroTenantId); headers.setAccept("application/json"); headers.setUserAgent(this.getUserAgent()); // create a map of path variables final Map<String, Object> uriVariables = new HashMap<String, Object>(); uriVariables.put("EmployeeId", employeeId); UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/Employees/{EmployeeId}"); String url = uriBuilder.buildFromMap(uriVariables).toString(); GenericUrl genericUrl = new GenericUrl(url); if (logger.isDebugEnabled()) { logger.debug("POST " + genericUrl.toString()); } HttpContent content = null; content = apiClient.new JacksonJsonHttpContent(employee); Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken); HttpTransport transport = apiClient.getHttpTransport(); HttpRequestFactory requestFactory = transport.createRequestFactory(credential); return requestFactory.buildRequest(HttpMethods.POST, genericUrl, content).setHeaders(headers) .setConnectTimeout(apiClient.getConnectionTimeout()) .setReadTimeout(apiClient.getReadTimeout()).execute(); }
Example #30
Source File: OIDCIdentityProvider.java From keycloak with Apache License 2.0 | 5 votes |
@Override protected UriBuilder createAuthorizationUrl(AuthenticationRequest request) { UriBuilder uriBuilder = super.createAuthorizationUrl(request); String nonce = Base64Url.encode(KeycloakModelUtils.generateSecret(16)); AuthenticationSessionModel authenticationSession = request.getAuthenticationSession(); authenticationSession.setClientNote(BROKER_NONCE_PARAM, nonce); uriBuilder.queryParam(OIDCLoginProtocol.NONCE_PARAM, nonce); return uriBuilder; }