asp.net core routing variable - rest

Is there a way to get a value from a route defined on the controller without adding the parameter to all http methods?
Example of what I'm trying to do.
calling localhost/api/test/client
[Route("api/{somevar}/[controller]")]
[ApiController]
public class ClientController : ControllerBase
{
private readonly MainContext fContext;
private string fSomeVar;
public ClientController(MainContext pContext)
{
fContext = pContext;
fSomeVar = somevar; <-- Is there a way to get "test" from the route?
}
// GET: api/Client
[HttpGet]
public async Task<ActionResult<IEnumerable<ClientDH>>> GetClients()
{
// use fSomeVar here.
}
// GET: api/Client
[HttpGet]
public async Task<ActionResult<IEnumerable<ClientDH>>> GetClients(string somevar)
{
// this works but I'm trying to avoid changing all the methods in all controllers.
}
}

My suggestion is below:
1.You can use IHttpContextAccessor to get the route value from the http request, code as below:
public DemoController(IHttpContextAccessor httpContextAccessor)
{
fSomeVar = httpContextAccessor.HttpContext.Request.RouteValues["somevar"].ToString();
}
and in startup.cs, you need to configure:
services.AddHttpContextAccessor();
2.Demo:
[Route("api/{somevar}/[controller]")]
[ApiController]
public class DemoController : ControllerBase
{
private string fSomeVar;
public DemoController(IHttpContextAccessor httpContextAccessor)
{
fSomeVar = httpContextAccessor.HttpContext.Request.RouteValues["somevar"].ToString();
}
[HttpGet]
public async Task<IActionResult> Demo1()
{
try
{
return Ok("Id: " + fSomeVar);
}
catch
{
return BadRequest();
}
}
[HttpGet("demo2/{id1}/{id2}")]
public async Task<IActionResult> Demo2(string id1, int id2)
{
try
{
return Ok("Id1: " + id1 + ", Id2: " + id2+ ", Id3: " + fSomeVar);
}
catch
{
return BadRequest();
}
}
}
Result:

Related

How to get state and code for redirect after login in auth code flow

My login endpoint can redirect to the redirect_uri, but I don't find how to get code and state so it becomes
"redirect:" + savedRequest.getParameterValues("redirect_uri") + "&code=" + code + "&state" = state;
login endpoint
#PostMapping("/login")
public String login(final HttpServletRequest request, String username) {
authService.authenticate(username);
SavedRequest savedRequest: = request.session.getAttribute("SPRING_SECURITY_SAVED_REQUEST") as SavedRequest;
return "redirect:" + savedRequest.getParameterValues("redirect_uri");
// it's missing state and code. state can be found in savedRequest, but how to find the code and is there a better way?
}
SecurityConfig
#Autowired
private lateinit var passwordEncoder: PasswordEncoder
#Bean
#Order(1)
fun authorizationServerSecurityFilterChain(http: HttpSecurity): SecurityFilterChain {
OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http)
http.getConfigurer(OAuth2AuthorizationServerConfigurer::class.java)
.oidc(Customizer.withDefaults())
http
.exceptionHandling { exceptions ->
exceptions.authenticationEntryPoint(LoginUrlAuthenticationEntryPoint ("/login"))
}
.oauth2ResourceServer {
it.jwt()
}
return http.build()
}
#Bean
fun authorizationServerSettings(): AuthorizationServerSettings {
return AuthorizationServerSettings.builder().build()
}
#Bean
fun authorizationService(): OAuth2AuthorizationService {
return InMemoryOAuth2AuthorizationService()
}
#Bean
fun registeredClientRepository(): RegisteredClientRepository {
val registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
.clientId("oauth-dev")
.clientSecret(passwordEncoder.encode("secret"))
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri("https://example.com")
.clientSettings(ClientSettings.builder()
.requireAuthorizationConsent(false)
.requireProofKey(false).build())
.build()
return InMemoryRegisteredClientRepository(registeredClient)
}
#Bean
fun jwkSource(): JWKSource<SecurityContext> {
val rsaKey = Jwks.generateRsa()
val jwkSet = JWKSet(rsaKey)
return JWKSource { jwkSelector: JWKSelector, securityContext: SecurityContext? -> jwkSelector.select(jwkSet) }
}
#Bean
fun jwtDecoder(jwkSource: JWKSource<SecurityContext>): JwtDecoder {
return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource)
}
I can see OAuth2AuthorizationCodeRequestAuthenticationToken has a attribute authorizationCode, but it's null
class AuthenticationSuccessEventListener : ApplicationListener<AuthenticationSuccessEvent> {
override fun onApplicationEvent(e: AuthenticationSuccessEvent) {
if (e.authentication is OAuth2AuthorizationCodeRequestAuthenticationToken) {
val token = e.authentication as OAuth2AuthorizationCodeRequestAuthenticationToken
logger.info("Successful authentication: ${e.authentication}")
}

showing items of picker while consuming web service xamarin

i want to show the items of picker from consuming Restful webservice, but i have an error !
<Picker x:Name="natures" ItemsSource="{Binding Naturee}" SelectedItem="ItemNature"
ItemDisplayBinding="{Binding Name}"
Title="choisir votre nature de dépense"
SelectedIndexChanged="natures_SelectedIndexChanged"/>
my modal PickerModelNature
public class PickerModelNature
{
public class NatureD
{
public string Label;
}
public class ResponseDataN
{
public RootModel Data;
}
public class RootModel : INotifyPropertyChanged
{
List<NatureD> natureList;
[JsonProperty("natureList")]
public List<NatureD> NatureList
{
get { return natureList; }
set
{
if (natureList != value)
{
natureList = value;
OnPropertyChanged();
}
}
}
NatureD itemNature;
public NatureD ItemNature
{
get { return itemNature; }
set
{
if (itemNature != value)
{
itemNature = value;
OnPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
var changed = PropertyChanged;
if (changed == null)
return;
changed.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
and the xaml.cs
public partial class CreerDepense : ContentPage
{
public CreerDepense()
{
InitializeComponent();
this.BindingContext = new RootModel();
GetExpenseNature();
} private async void GetExpenseNature()
{
HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new Uri("http://192.168.1.6:3000/api/adepApi/GetExpensesNatureList");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await httpClient.GetAsync("http://192.168.1.6:3000/api/adepApi/GetExpensesNatureList");
var content = await response.Content.ReadAsStringAsync();
ResponseDataN EL = JsonConvert.DeserializeObject<ResponseDataN>(content);
// var Items = JsonConvert.DeserializeObject<List<NatureD>>(content);
//listexpense.ItemsSource = Items;
natures.ItemsSource = EL.Data.NatureList;
}
the error is:
Java.Lang.NullPointerException: 'Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference'
what should i do ?

Pass ID once to a controller and have all controller methods remember boolean check

I just created a simple web API using .NetCore 2.2 and Entity Framework.
I added a bit of security, by passing in a userID to each controller that the user accesses.
But I noticed that it starts getting messy when I have to add the userID to every controller in my app and the run my user check to make sure the user can access that content.
Below you'll see an example of what I mean.
I'm wondering, is there a way to add it once and then have every controller check for it?
Thanks!
[Route("api/[controller]")]
[ApiController]
public class EngineController : ControllerBase
{
private readonly engineMaker_Context _context;
public EngineController(engineMaker_Context context)
{
_context = context;
}
// GET: api/Engine
[HttpGet("{userID}")]
public async Task<ActionResult<IEnumerable<Engine>>> GetEngine(string userID)
{
if(!CanAccessContent(userID))
{
return Unauthorized();
}
return await _context.Engine.ToListAsync();
}
// GET: api/Engine/123/5
[HttpGet("{userID}/{id}")]
public async Task<ActionResult<Engine>> GetEngine(string userID, string id)
{
if(!CanAccessContent(userID))
{
return Unauthorized();
}
var engine = await _context.Engine.FindAsync(id);
if (engine == null)
{
return NotFound();
}
return engine;
}
// PUT: api/Engine/123/5
[HttpPut("{userID}/{id}")]
public async Task<IActionResult> PutEngine(string userID, string id, Engine engine)
{
if(!CanAccessContent(userID))
{
return Unauthorized();
}
if (id != engine.ObjectId)
{
return BadRequest();
}
_context.Entry(engine).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!EngineExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
private bool CanAccessContent(string userID)
{
return _context.AllowedUsers.Any(e => e.UserId == userID);
}
}
You could try IAsyncAuthorizationFilter to check the userID.
IAsyncAuthorizationFilter
public class UserIdFilter : IAsyncAuthorizationFilter
{
public Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
var dbContext = context.HttpContext.RequestServices.GetRequiredService<ApplicationDbContext>();
var userId = context.RouteData.Values["userID"] as string;
if (!dbContext.Users.Any(u => u.Email == userId))
{
context.Result = new UnauthorizedResult();
}
return Task.CompletedTask;
}
}
Regiter UserIdFilter for all action.
services.AddMvc(options =>
{
options.Filters.Add(typeof(UserIdFilter));
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

Is there any REST API to fetch all rules from Repository in Drools

As you can see, all rules can be listed in project explorer, i am wondering Drools workbench has such a Rest API for this, but I went through online document document, there is no such API. any suggestion on this? thanks in advance.
https://docs.jboss.org/drools/release/latest/drools-docs/html/ch20.html#d0e22619
Best Regards
Yuhua
As far as I know, there is no REST API to do that (public at least). One option do you have though is to use git to get that information from the workbench.
The storage of the workbench is based on git. Each repository in the workbench is actually a git repository. The workbench allows you to clone those repositories and to do whatever you need with them just as with any other git repo out there.
Inside each of the git repositories you will find zero or more maven projects. Indeed, each of the projects you see in the workbench is a real maven project. The different assets in your projects (drl rules, guided rules, decision table, etc.) will be available under the resources directory of the corresponding project.
Hope it helps,
As Esteban Aliverti mentioned, there is no ready to use API to achieve this. However, we can write a custom extension to KIE Server to fetch all the rules deployed.
It is explained in detailed here.
I have similar use case in my application and did the following implementation for fetching rules.
CusomtDroolsKieServerApplicationComponentsService
public class CusomtDroolsKieServerApplicationComponentsService implements KieServerApplicationComponentsService {
private static final String OWNER_EXTENSION = "Drools";
public Collection<Object> getAppComponents(String extension, SupportedTransports type, Object... services) {
// skip calls from other than owning extension
if (!OWNER_EXTENSION.equals(extension)) {
return Collections.emptyList();
}
RulesExecutionService rulesExecutionService = null;
KieServerRegistry context = null;
for (Object object : services) {
if (RulesExecutionService.class.isAssignableFrom(object.getClass())) {
rulesExecutionService = (RulesExecutionService) object;
continue;
} else if (KieServerRegistry.class.isAssignableFrom(object.getClass())) {
context = (KieServerRegistry) object;
continue;
}
}
List<Object> components = new ArrayList<Object>(1);
if (SupportedTransports.REST.equals(type)) {
components.add(new RuleRESTService(rulesExecutionService, context));
}
return components;
}
RuleRestService
#Path("server/containers/instances/{id}/ksession")
public class RuleRESTService {
private RulesExecutionService rulesExecutionService;
private KieServerRegistry registry;
public RuleRESTService() {
}
public RuleRESTService(RulesExecutionService rulesExecutionService, KieServerRegistry registry) {
this.rulesExecutionService = rulesExecutionService;
this.registry = registry;
}
public RulesExecutionService getRulesExecutionService() {
return rulesExecutionService;
}
public void setRulesExecutionService(RulesExecutionService rulesExecutionService) {
this.rulesExecutionService = rulesExecutionService;
}
public KieServerRegistry getRegistry() {
return registry;
}
public void setRegistry(KieServerRegistry registry) {
this.registry = registry;
}
#POST
#Path("/{ksessionId}")
#Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
#Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response fetchAllRules(#Context HttpHeaders headers, #PathParam("id") String id,
#PathParam("ksessionId") String ksessionId, String cmdPayload) {
Variant v = getVariant(headers);
try {
System.out.println("CREATING KieContainerInstance ");
KieContainerInstance kci = registry.getContainer(id);
String contentType = getContentType(headers);
MarshallingFormat format = MarshallingFormat.fromType(contentType);
if (format == null) {
format = MarshallingFormat.valueOf(contentType);
}
Marshaller marshaller = kci.getMarshaller(format);
RuleAccessor accessor = new RuleAccessor();
List<RuleData> rules = accessor.fetchAllRules(kci.getKieContainer());
String result = marshaller.marshall(rules);
return createResponse(result, v, Response.Status.OK);
} catch (Exception ex) {
ex.printStackTrace();
String response = "Execution failed with error : " + ex.getMessage();
System.out.println("Returning Failure response with content '{}' :" + response);
return createResponse(response, v, Response.Status.INTERNAL_SERVER_ERROR);
}
}
RuleAccessor
public class RuleAccessor {
public List<RuleData> fetchAllRules(KieContainer kContainer) {
kContainer.getKieBaseNames().stream()
.forEach(kieBase -> rules.addAll(fetchRules(kContainer1.getKieBase(kieBase))));
return rules;
}
public List<RuleData> fetchRules(KieBase kieBase) {
List<RuleData> ruleData = new ArrayList<>();
for (KiePackage kp : kieBase.getKiePackages()) {
RuleData data = new RuleData();
for (Rule r1 : kp.getRules()) {
RuleImpl r = (RuleImpl) r1;
data.agendaGroup(r.getAgendaGroup()).packageId(r.getPackageName()).ruleName(r.getName())
.enabled(Boolean.getBoolean((((EnabledBoolean) r.getEnabled()).toString())))
.effectiveDate(String.valueOf(r.getDateEffective()))
.dateExpires(String.valueOf(r.getDateExpires())).dialect(r.getDialect())
.salience(r.getSalienceValue()).metaData(r.getMetaData());
try {
Resource resource = r.getResource();
Reader reader = resource.getReader();
BufferedReader bufferedReader = new BufferedReader(reader);
String line = null;
StringBuilder builder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
data.ruleContent(builder.toString());
ruleData.add(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
return ruleData;
}
public static class RuleData {
private String packageId;
private String ruleName;
private String type;
private String agendaGroup;
private String ruleContent;
private boolean isEnabled;
private String effectiveDate;
private String dateExpires;
private String dialect;
private int salience;
private Map<String, Object> metaData;
public boolean isEnabled() {
return isEnabled;
}
public RuleData enabled(boolean isEnabled) {
this.isEnabled = isEnabled;
return this;
}
public String effectiveDate() {
return effectiveDate;
}
public RuleData effectiveDate(String effectiveDate) {
this.effectiveDate = effectiveDate;
return this;
}
public String getDateExpires() {
return dateExpires;
}
public RuleData dateExpires(String dateExpires) {
this.dateExpires = dateExpires;
return this;
}
public String getDialect() {
return dialect;
}
public RuleData dialect(String dialect) {
this.dialect = dialect;
return this;
}
public int getSalience() {
return salience;
}
public RuleData salience(int salience) {
this.salience = salience;
return this;
}
public Map<String, Object> getMetaData() {
return metaData;
}
public RuleData metaData(Map<String, Object> metaData) {
this.metaData = metaData;
return this;
}
public String getRuleContent() {
return ruleContent;
}
public RuleData ruleContent(String ruleContent) {
this.ruleContent = ruleContent;
return this;
}
public String getPackageId() {
return packageId;
}
public RuleData packageId(String packageId) {
this.packageId = packageId;
return this;
}
public String getRuleName() {
return ruleName;
}
public RuleData ruleName(String ruleName) {
this.ruleName = ruleName;
return this;
}
public String getType() {
return type;
}
public RuleData type(String type) {
this.type = type;
return this;
}
public String getAgendaGroup() {
return agendaGroup;
}
public RuleData agendaGroup(String agendaGroup) {
this.agendaGroup = agendaGroup;
return this;
}
}
}
You can make a REST call to Kie Server from you application to access all the rules available for the given container.
http://localhost:8080/kie-server/services/rest/server/containers/instances/<container-id>/ksession/<session-id>

Netbeans QuickSearch Result to Lookup

Well, I'd like to provide QuickSearch result inside application, and, of course, through the lookup.
Searching works well, but found result is not visible through global lookup.
Can someone help to overcome this issue ?
Here is th code for a quicksearch :
public class QSERSCompany implements SearchProvider {
#Override
public void evaluate(SearchRequest request, SearchResponse response) {
try {
for (Company k : queries.ERSQuery.allCompanies()) {
if (k.getCompanyName().toLowerCase().contains(request.getText().toLowerCase())) {
if (!response.addResult(new SearchResult(k), k.getCompanyName())) {
return;
}
}
}
} catch (NullPointerException npe) {
}
}
private static class SearchResult implements Runnable, Lookup.Provider {
private final Company company;
private final InstanceContent ic = new InstanceContent();
private final Lookup lookup = new AbstractLookup(ic);
public SearchResult(Company c) {
this.company= c;
}
#Override
public void run() {
ic.add(company);
try {
StatusDisplayer.getDefault().setStatusText(
company.getCompanyName()
+ ", " + company.getAddress()
+ ", " + company.getCity());
} catch (NullPointerException npe) {
}
}
#Override
public Lookup getLookup() {
return lookup;
}
}
}
And this is partof the code which listens for a Company object :
public final class ManagementPodatakaTopComponent extends TopComponent {
private Lookup.Result<Company> companyLookup = null;
...
private Company selectedCompany;
...
#Override
public void componentOpened() {
companyLookup = Utilities.actionsGlobalContext().lookupResult(Company.class);
companyLookup .addLookupListener(new LookupListener() {
#Override
public void resultChanged(LookupEvent le) {
Lookup.Result k = (Lookup.Result) le.getSource();
Collection<Company> cs = k.allInstances();
for (Company k1 : cs) {
selectedCompany = k1;
}
setCompanyTextFields(selectedCompany);
jTP_DataManagement.setVisible(true);
jPanel_Entiteti.setVisible(true);
}
});
}
A SearchResult which provides a lookup? Never seen this in the wild.
Please ask at nbdev#netbeans.org to get better feedback (probably from one of the NB devs)
I finally managed somehow to get what I want :
First off, define interface:
public interface ICodes {
public Code getCode();
}
Then, we implement quick search :
#ServiceProvider(service = ICodes.class)
public class ClientServicesQS implements SearchProvider, ICodes {
private static Code code = null;
#Override
public void evaluate(SearchRequest request, SearchResponse response) {
try {
for (Code c : INFSYS.queries.INFSistemQuery.ByersByName(request.getText())) {
if (!response.addResult(new SearchResult(c),
c.getName() + " ,Code: " + c.getByerCode()
+ (c.getAddress() != null ? ", " + c.getAddress() : ""))) {
return;
}
}
} catch (NullPointerException npe) {
StatusDisplayer.getDefault().setStatusText("Error." + npe.getMessage());
}
}
#Override
public Code getCode() {
return ClientServicesQS.sifra;
}
private static class SearchResult implements Runnable {
private final Code code;
public SearchResult(Code code) {
this.code= code;
}
#Override
public void run() {
try {
ClientServicesQS.code= this.code;
OpenTopComponent("ClientServicesTopComponent");
} catch (NullPointerException e) {
Display.messageBaloon("Error.", e.toString() + ", " + e.getMessage(), Display.TYPE_MESSAGE.ERROR);
}
}
}
}
Finally, we implement lookup in other module through platform.
Because I want to call lookup whenever componentOpen, oe componentActivated is invoked, it is usefull first to define :
private void QSCodeSearch() {
try {
ICode ic= Lookup.getDefault().lookup(ICode.class);
if ((code = ic.getCode()) != null) {
.
.
.
// setup UI components with data from lookup
.
.
.
}
} catch (Exception e) {
}
}
And when topcomponent is activated, we call QSCodeSearch() in :
#Override
public void componentOpened() {
...
QSCodeSearch()
...
}
...
#Override
public void requestActive() {
...
QSCodeSearch()
...
}