Java Code Examples for javax.ws.rs.core.UriBuilder#fromPath()

The following examples show how to use javax.ws.rs.core.UriBuilder#fromPath() . 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: PentahoDiPlugin.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
/**
 * Create new instance using existing Client instance, and the URI from which the parameters will be extracted
 * 
 */
public PathIdVersioningConfiguration( com.sun.jersey.api.client.Client client, URI uri ) {
  _client = client;
  StringBuilder template = new StringBuilder( BASE_URI.toString() );
  if ( template.charAt( ( template.length() - 1 ) ) != '/' ) {
    template.append( "/pur-repository-plugin/api/revision/{pathId}/versioningConfiguration" );
  } else {
    template.append( "pur-repository-plugin/api/revision/{pathId}/versioningConfiguration" );
  }
  _uriBuilder = UriBuilder.fromPath( template.toString() );
  _templateAndMatrixParameterValues = new HashMap<String, Object>();
  com.sun.jersey.api.uri.UriTemplate uriTemplate = new com.sun.jersey.api.uri.UriTemplate( template.toString() );
  HashMap<String, String> parameters = new HashMap<String, String>();
  uriTemplate.match( uri.toString(), parameters );
  _templateAndMatrixParameterValues.putAll( parameters );
}
 
Example 2
Source File: MetricsEndpoint.java    From javametrics with Apache License 2.0 6 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getContexts(@Context UriInfo uriInfo) {
    Integer[] contextIds = mp.getContextIds();

    StringBuilder sb = new StringBuilder("{\"collectionUris\":[");
    boolean comma = false;
    for (Integer contextId : contextIds) {
        if (comma) {
            sb.append(',');
        }
        sb.append('\"');
        UriBuilder builder = UriBuilder.fromPath(uriInfo.getPath());
        builder.path(Integer.toString(contextId));
        URI uri = builder.build();
        sb.append(uri.toString());
        sb.append('\"');
        comma = true;
    }
    sb.append("]}");
    return Response.ok(sb.toString()).build();
}
 
Example 3
Source File: TenantController.java    From metamodel-membrane with Apache License 2.0 6 votes vote down vote up
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public GetTenantResponse getTenant(@PathVariable("tenant") String tenantName) {
    final TenantContext tenantContext = tenantRegistry.getTenantContext(tenantName);
    final String tenantNameNormalized = tenantContext.getTenantName();

    final UriBuilder uriBuilder = UriBuilder.fromPath("/{tenant}/{datasource}");

    final List<String> dataContextIdentifiers = tenantContext.getDataSourceRegistry().getDataSourceNames();
    final List<GetTenantResponseDatasources> dataSourceLinks = dataContextIdentifiers.stream().map(s -> {
        final String uri = uriBuilder.build(tenantNameNormalized, s).toString();
        return new GetTenantResponseDatasources().name(s).uri(uri);
    }).collect(Collectors.toList());

    final GetTenantResponse resp = new GetTenantResponse();
    resp.type("tenant");
    resp.name(tenantNameNormalized);
    resp.datasources(dataSourceLinks);
    return resp;
}
 
Example 4
Source File: BrooklynSecurityProviderFilterJersey.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("resource")
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    log.trace("BrooklynSecurityProviderFilterJersey.filter {}", requestContext);
    try {
        new BrooklynSecurityProviderFilterHelper().run(webRequest, mgmtC.getContext(ManagementContext.class));
    } catch (SecurityProviderDeniedAuthentication e) {
        Response rin = e.getResponse();
        if (rin==null) rin = Response.status(Status.UNAUTHORIZED).build();
        
        if (rin.getStatus()==Status.FOUND.getStatusCode()) {
            String location = rin.getHeaderString(HttpHeader.LOCATION.asString());
            if (location!=null) {
                log.trace("Redirect to {} for authentication",location);
                final UriBuilder uriBuilder = UriBuilder.fromPath(location);
                rin = Response.temporaryRedirect(uriBuilder.build()).entity("Authentication is required at "+location).build();
            } else {
                log.trace("Unauthorized");
                rin = Response.status(Status.UNAUTHORIZED).entity("Authentication is required").build();
            }
        }
        requestContext.abortWith(rin);
    }
}
 
Example 5
Source File: RecoverableTokenHandler.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
private void sendUserToSSOServer(HttpServletRequest request, HttpServletResponse response)
    throws IOException {
  UriBuilder redirectUrl = UriBuilder.fromPath("/api/internal/sso/server/refresh");
  redirectUrl.queryParam(
      "redirect_url",
      encode(
          UriBuilder.fromUri(request.getRequestURL().toString())
              .replaceQuery(request.getQueryString())
              .replaceQueryParam("token")
              .build()
              .toString(),
          "UTF-8"));
  redirectUrl.queryParam("client_url", encode(clientUrlExtractor.getClientUrl(request), "UTF-8"));
  redirectUrl.queryParam("allowAnonymous", allowAnonymous);
  response.sendRedirect(redirectUrl.build().toString());
}
 
Example 6
Source File: ClientBase.java    From conductor with Apache License 2.0 6 votes vote down vote up
private UriBuilder getURIBuilder(String path, Object[] queryParams) {
    if (path == null) {
        path = "";
    }
    UriBuilder builder = UriBuilder.fromPath(path);
    if (queryParams != null) {
        for (int i = 0; i < queryParams.length; i += 2) {
            String param = queryParams[i].toString();
            Object value = queryParams[i + 1];
            if (value != null) {
                if (value instanceof Collection) {
                    Object[] values = ((Collection<?>) value).toArray();
                    builder.queryParam(param, values);
                } else {
                    builder.queryParam(param, value);
                }
            }
        }
    }
    return builder;
}
 
Example 7
Source File: PentahoDiPlugin.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
/**
 * Create new instance using existing Client instance, and the URI from which the parameters will be extracted
 * 
 */
public PathIdPurge( com.sun.jersey.api.client.Client client, URI uri ) {
  _client = client;
  StringBuilder template = new StringBuilder( BASE_URI.toString() );
  if ( template.charAt( ( template.length() - 1 ) ) != '/' ) {
    template.append( "/pur-repository-plugin/api/purge/{pathId : .+}/purge" );
  } else {
    template.append( "pur-repository-plugin/api/purge/{pathId : .+}/purge" );
  }
  _uriBuilder = UriBuilder.fromPath( template.toString() );
  _templateAndMatrixParameterValues = new HashMap<String, Object>();
  com.sun.jersey.api.uri.UriTemplate uriTemplate = new com.sun.jersey.api.uri.UriTemplate( template.toString() );
  HashMap<String, String> parameters = new HashMap<String, String>();
  uriTemplate.match( uri.toString(), parameters );
  _templateAndMatrixParameterValues.putAll( parameters );
}
 
Example 8
Source File: PentahoDiPlugin.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
/**
 * Create new instance using existing Client instance, and the URI from which the parameters will be extracted
 * 
 */
public PathIdRevisions( com.sun.jersey.api.client.Client client, URI uri ) {
  _client = client;
  StringBuilder template = new StringBuilder( BASE_URI.toString() );
  if ( template.charAt( ( template.length() - 1 ) ) != '/' ) {
    template.append( "/pur-repository-plugin/api/revision/{pathId : .+}/revisions" );
  } else {
    template.append( "pur-repository-plugin/api/revision/{pathId : .+}/revisions" );
  }
  _uriBuilder = UriBuilder.fromPath( template.toString() );
  _templateAndMatrixParameterValues = new HashMap<String, Object>();
  com.sun.jersey.api.uri.UriTemplate uriTemplate = new com.sun.jersey.api.uri.UriTemplate( template.toString() );
  HashMap<String, String> parameters = new HashMap<String, String>();
  uriTemplate.match( uri.toString(), parameters );
  _templateAndMatrixParameterValues.putAll( parameters );
}
 
Example 9
Source File: UriBuilderImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildWithNonEncodedSubstitutionValue7() {
    UriBuilder ub = UriBuilder.fromPath("/");
    URI uri = ub.replaceQueryParam("a", "%").buildFromEncoded();
    assertEquals("/?a=%25", uri.toString());
    uri = ub.replaceQueryParam("a2", "{token}").buildFromEncoded("{}");
    assertEquals("/?a=%25&a2=%7B%7D", uri.toString());
}
 
Example 10
Source File: UriBuilderImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildWithNonEncodedSubstitutionValue3() {
    UriBuilder ub = UriBuilder.fromPath("/");
    URI uri = ub.path("{a}").buildFromEncoded("%");
    assertEquals("/%25", uri.toString());
    uri = ub.path("{token}").buildFromEncoded("%", "{}");
    assertEquals("/%25/%7B%7D", uri.toString());
}
 
Example 11
Source File: JAXBElementProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected String resolveXMLResourceURI(String path) {
    MessageContext mc = getContext();
    if (mc != null) {
        String httpBasePath = (String)mc.get("http.base.path");
        UriBuilder builder = null;
        if (httpBasePath != null) {
            builder = UriBuilder.fromPath(httpBasePath);
        } else {
            builder = mc.getUriInfo().getBaseUriBuilder();
        }
        return builder.path(path).path(xmlResourceOffset).build().toString();
    }
    return path;
}
 
Example 12
Source File: ConsulAdvertiser.java    From dropwizard-consul with Apache License 2.0 5 votes vote down vote up
/**
 * Return the health check URL for the service
 *
 * @param applicationScheme Scheme the server is listening on
 * @return health check URL
 */
protected String getHealthCheckUrl(String applicationScheme) {
  final UriBuilder builder = UriBuilder.fromPath(environment.getAdminContext().getContextPath());
  builder.path("healthcheck");
  builder.scheme(applicationScheme);
  if (serviceAddress.get() == null) {
    builder.host("127.0.0.1");
  } else {
    builder.host(serviceAddress.get());
  }
  builder.port(serviceAdminPort.get());
  return builder.build().toString();
}
 
Example 13
Source File: TableController.java    From metamodel-membrane with Apache License 2.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public GetTableResponse get(@PathVariable("tenant") String tenantId,
        @PathVariable("dataContext") String dataSourceName, @PathVariable("schema") String schemaId,
        @PathVariable("table") String tableId) {
    final TenantContext tenantContext = tenantRegistry.getTenantContext(tenantId);
    final DataContext dataContext = tenantContext.getDataSourceRegistry().openDataContext(dataSourceName);

    final DataContextTraverser traverser = new DataContextTraverser(dataContext);

    final Table table = traverser.getTable(schemaId, tableId);

    final String tenantName = tenantContext.getTenantName();
    final UriBuilder uriBuilder = UriBuilder.fromPath("/{tenant}/{dataContext}/s/{schema}/t/{table}/c/{column}");

    final String tableName = table.getName();
    final String schemaName = table.getSchema().getName();
    final List<GetTableResponseColumns> columnsLinks = table.getColumnNames().stream().map(c -> {
        final String uri = uriBuilder.build(tenantName, dataSourceName, schemaName, tableName, c).toString();
        return new GetTableResponseColumns().name(c).uri(uri);
    }).collect(Collectors.toList());

    final GetTableResponse resp = new GetTableResponse();
    resp.type("table");
    resp.name(tableName);
    resp.schema(schemaName);
    resp.datasource(dataSourceName);
    resp.tenant(tenantName);
    resp.columns(columnsLinks);
    return resp;
}
 
Example 14
Source File: SchemaController.java    From metamodel-membrane with Apache License 2.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public GetSchemaResponse get(@PathVariable("tenant") String tenantId,
        @PathVariable("dataContext") String dataSourceName, @PathVariable("schema") String schemaId) {
    final TenantContext tenantContext = tenantRegistry.getTenantContext(tenantId);
    final DataContext dataContext = tenantContext.getDataSourceRegistry().openDataContext(dataSourceName);

    final DataContextTraverser traverser = new DataContextTraverser(dataContext);

    final Schema schema = traverser.getSchema(schemaId);
    final String tenantName = tenantContext.getTenantName();
    final UriBuilder uriBuilder = UriBuilder.fromPath("/{tenant}/{dataContext}/s/{schema}/t/{table}");

    final String schemaName = schema.getName();
    final List<GetSchemaResponseTables> tableLinks = schema.getTableNames().stream().map(t -> {
        final String uri = uriBuilder.build(tenantName, dataSourceName, schemaName, t).toString();
        return new GetSchemaResponseTables().name(String.valueOf(t)).uri(uri);
    }).collect(Collectors.toList());

    final GetSchemaResponse resp = new GetSchemaResponse();
    resp.type("schema");
    resp.name(schemaName);
    resp.datasource(dataSourceName);
    resp.tenant(tenantName);
    resp.tables(tableLinks);
    return resp;
}
 
Example 15
Source File: DataSourceController.java    From metamodel-membrane with Apache License 2.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public GetDatasourceResponse get(@PathVariable("tenant") String tenantId,
        @PathVariable("datasource") String dataSourceName) {
    final TenantContext tenantContext = tenantRegistry.getTenantContext(tenantId);

    final String tenantName = tenantContext.getTenantName();
    final UriBuilder uriBuilder = UriBuilder.fromPath("/{tenant}/{dataContext}/s/{schema}");

    List<GetDatasourceResponseSchemas> schemaLinks;
    Boolean updateable;
    try {
        final DataContext dataContext = tenantContext.getDataSourceRegistry().openDataContext(dataSourceName);
        updateable = dataContext instanceof UpdateableDataContext;
        schemaLinks = dataContext.getSchemaNames().stream().map(s -> {
            final String uri = uriBuilder.build(tenantName, dataSourceName, s).toString();
            return new GetDatasourceResponseSchemas().name(s).uri(uri);
        }).collect(Collectors.toList());
    } catch (Exception e) {
        logger.warn("Failed to open for GET datasource '{}/{}'. No schemas will be listed.", tenantId,
                dataSourceName, e);
        updateable = null;
        schemaLinks = null;
    }

    final GetDatasourceResponse resp = new GetDatasourceResponse();
    resp.type("datasource");
    resp.name(dataSourceName);
    resp.tenant(tenantName);
    resp.updateable(updateable);
    resp.queryUri(
            UriBuilder.fromPath("/{tenant}/{dataContext}/query").build(tenantName, dataSourceName).toString());
    resp.schemas(schemaLinks);
    return resp;
}
 
Example 16
Source File: MetricsEndpoint.java    From javametrics with Apache License 2.0 5 votes vote down vote up
private URI getCollectionIDFromURIInfo(UriInfo uriInfo, int contextId) {
    // remove parameters from url
    String urlPath = uriInfo.getPath();
    UriBuilder builder = UriBuilder.fromPath(urlPath.substring(0,urlPath.indexOf("/")));
    builder.path(Integer.toString(contextId));
    return builder.build();
}
 
Example 17
Source File: MetricsEndpoint.java    From javametrics with Apache License 2.0 5 votes vote down vote up
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response newContext(@Context UriInfo uriInfo) {
    if (mp.getContextIds().length > 9) {
        return Response.status(Status.BAD_REQUEST).build();
    }
    int contextId = mp.addContext();
    UriBuilder builder = UriBuilder.fromPath(uriInfo.getPath());
    builder.path(Integer.toString(contextId));
    URI uri = builder.build();
    return Response.status(Status.CREATED).header("Location", uri).entity("{\"uri\":\"" + uri + "\"}").build();
}
 
Example 18
Source File: Connection.java    From ecs-cf-service-broker with Apache License 2.0 4 votes vote down vote up
protected UriBuilder getUriBuilder() {
    return UriBuilder.fromPath(endpoint);
}
 
Example 19
Source File: UriBuilderUtils.java    From govpay with GNU General Public License v3.0 4 votes vote down vote up
private static UriBuilder getBasePath() {
	UriBuilder fromPath = UriBuilder.fromPath("/");
	return fromPath;
}
 
Example 20
Source File: StudentEnrolmentsDA.java    From fenixedu-academic with GNU Lesser General Public License v3.0 4 votes vote down vote up
public ActionForward editEnrolment(final ActionMapping mapping, final ActionForm form, final HttpServletRequest request,
                                          final HttpServletResponse response) {

    final EditEnrolmentBean enrolmentBean = getRenderedObject();
    final Enrolment enrolment = enrolmentBean.getEnrolment();

    final Double newWeight = enrolmentBean.getWeight();
    final EctsConversionTable newEctsConversionTable = enrolmentBean.getEctsConversionTable();
    final Grade newNormalizedGrade = enrolmentBean.getNormalizedGrade();

    Double oldWeight = enrolment.getWeigth();

    RenderUtils.invalidateViewState();
    
    FenixFramework.atomic(() -> {
        if (newEctsConversionTable instanceof EmptyConversionTable) {
            if (newNormalizedGrade.isEmpty()) {
                // use default table
                enrolment.setEctsConversionTable(null);
                enrolment.setEctsGrade(null);
            } else {
                enrolment.setEctsGrade(newNormalizedGrade);
                enrolment.setEctsConversionTable(newEctsConversionTable);
            }
        } else {
            // default to the selected table
            enrolment.setEctsGrade(null);
            enrolment.setEctsConversionTable(newEctsConversionTable);
        }

        enrolment.setWeigth(newWeight);
    });

    LOGGER.info("Changed enrolment {} of student {} by user {}", enrolmentBean.getEnrolment().getExternalId(),
                enrolmentBean.getEnrolment().getStudent().getPerson().getUsername(), Authenticate.getUser().getUsername());
    LOGGER.info("\t newEctsConversionTable: {}", newEctsConversionTable == null ? "-" : newEctsConversionTable
                                                                                            .getPresentationName().getContent());
    LOGGER.info("\t newEctsGrade: {}", newNormalizedGrade == null ? "-" : newNormalizedGrade.getValue());
    if (!oldWeight.equals(newWeight)) {
        LOGGER.info("\t oldWeight: {} newWeight: {}", oldWeight.toString(), newWeight.toString());
    }


    final UriBuilder builder = UriBuilder.fromPath("/academicAdministration/studentEnrolments.do");
    builder.queryParam("method", "prepare");
    final String scpID = request.getParameter("scpID");
    final String executionPeriodId = request.getParameter("executionPeriodId");

    if (!Strings.isNullOrEmpty(scpID)) {
        builder.queryParam("scpID", scpID);
    }

    if (!Strings.isNullOrEmpty(executionPeriodId)) {
        builder.queryParam("executionPeriodId", executionPeriodId);
    }

    final String redirectTo = GenericChecksumRewriter.injectChecksumInUrl(request.getContextPath(), builder.toString(), request.getSession(false));
    
    final ActionForward actionForward = new ActionForward();
    actionForward.setModule("/");
    actionForward.setPath(redirectTo);
    actionForward.setRedirect(true);

    return actionForward;
}