How can I make Caffeine async? - caffeine-cache

#Bean
public CacheManager cacheManager() {
CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();
caffeineCacheManager.getCache("addresses");
caffeineCacheManager.setCacheLoader(cacheLoader());
caffeineCacheManager.setCaffeine(caffeineConfig());
return caffeineCacheManager;
}
Caffeine caffeineConfig() {
return Caffeine.newBuilder().expireAfterAccess(Duration.ofSeconds(5));
}
public CacheLoader<Object, Object> cacheLoader() {
return string -> {
return string;
};
}
And I'm using it like this: cacheManager is autowired:
cacheManager.getCache("cacheKey").get(123)
How can I make change it to async?

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>

Jenkins plugin development - persistence

I'm still learning plugin dev. This is my first one.
I would like to persist the configuration of my plugin, but it won't work.
Could you please tell me, what am I doing wrong?
I have tried debuging the process, starting from the addition of the plugin to the job 'til the saving of the job config.
I have found, that inside the load() method of the descriptor, no xml file is found!
The path it is looking for is something like: c:\users\Peter\workspace\r-script.\work\whatEverDir\xy.xml
I don't think that the .\ part is causing the config file not to be found, but since it is a Jenkins class generating this path, I would not bet on it. Although the system might have tried to create it here at the first place.
Thanks in advance!
Scriptrunner.jelly
<f:block>
<f:entry title="RScript" field="command">
<f:textarea style="width:99%" />
</f:entry>
</f:block>
<f:entry field="installedPackages" title="Installed packages">
<f:select style="width:40%" />
</f:entry>
<f:entry field="mirrors" title="Choose a mirror">
<f:select style="width:40%" />
</f:entry>
<f:entry>
<f:repeatableProperty field="availablePackages" minimum="1"/>
</f:entry>
AvailablePackage.jelly
<f:entry field="availablePackages">
<f:select style="width:40%" />
<f:repeatableDeleteButton />
</f:entry>
ScriptRunner.java
public class ScriptRunner extends Builder {
private static final String fileExtension = ".R";
private ArrayList<AvailablePackage> availablePackages;
private String command;
private String chosenMirror;
private List<String> mirrorList = new ArrayList<String>();
#DataBoundConstructor
public ScriptRunner(String command, ArrayList<String> installedPackages, ArrayList<String> mirrors, ArrayList<AvailablePackage> availablePackages) {
this.chosenMirror = mirrors.get(0);
this.availablePackages = availablePackages;
this.command = command;
}
public final String getCommand() {
return command;
}
#Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher,
BuildListener listener) throws InterruptedException {
return perform(build, launcher, (TaskListener) listener);
}
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher,
TaskListener listener) throws InterruptedException {
FilePath workSpace = build.getWorkspace();
FilePath rScript = null;
if (workSpace == null) {
try {
throw new NoSuchFileException("Workspace could not be set!");
} catch (NoSuchFileException e) {
e.printStackTrace();
}
}
try {
try {
String fullScript;
if (command.contains("options(repos=structure(")) {
fullScript = PackagesManager.singleton().createFullScript(availablePackages, "", command);
} else {
fullScript = PackagesManager.singleton().createFullScript(availablePackages, chosenMirror, command);
}
rScript = workSpace.createTextTempFile("RScriptTemp",
getFileExtension(), fullScript, false);
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError(Messages
.CommandInterpreter_UnableToProduceScript()));
return false;
}
boolean successfullyRan = false;
try {
EnvVars envVars = build.getEnvironment(listener);
for (Map.Entry<String, String> e : build.getBuildVariables()
.entrySet()) {
envVars.put(e.getKey(), e.getValue());
}
if (launcher.launch().cmds(buildCommandLine(rScript))
.envs(envVars).stdout(listener).pwd(workSpace).join() == 1) {
successfullyRan = true;
}
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError(Messages
.CommandInterpreter_CommandFailed()));
}
return successfullyRan;
} finally {
try {
if (rScript != null) {
rScript.delete();
}
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError(Messages
.CommandInterpreter_UnableToDelete(rScript)));
} catch (Exception e) {
e.printStackTrace(listener.fatalError(Messages
.CommandInterpreter_UnableToDelete(rScript)));
}
}
}
public String[] buildCommandLine(FilePath script) {
return new String[] { "Rscript", script.getRemote() };
}
protected String getFileExtension() {
return fileExtension;
}
public List<String> getMirrorList() {
return mirrorList;
}
public void setMirrorList(List<String> mirrorList) {
this.mirrorList = mirrorList;
}
public String getChosenMirror() {
return chosenMirror;
}
public void setChosenMirror(String chosenMirror) {
this.chosenMirror = chosenMirror;
}
public ArrayList<AvailablePackage> getAvailablePackages() {
return availablePackages;
}
#Override
public ScriptBuildStepDescriptorImplementation getDescriptor() {
return (ScriptBuildStepDescriptorImplementation)super.getDescriptor();
}
#Extension
public static class ScriptBuildStepDescriptorImplementation extends
BuildStepDescriptor<Builder> {
private boolean showInstalled;
private String command;
private String chosenMirror;
private ArrayList<AvailablePackage> availablePackages;
public ScriptBuildStepDescriptorImplementation() {
load();
}
#Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
req.bindJSON(this, formData);
save();
return super.configure(req,formData);
}
#Override
public String getDisplayName() {
return "Advanced R script runner";
}
#Override
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return true;
}
public ListBoxModel doFillInstalledPackagesItems() {
ListBoxModel mirrors = new ListBoxModel();
Set<String> mirrorsList = PackagesManager.singleton()
.getInstalledPackages();
for (String entry : mirrorsList) {
mirrors.add(entry);
}
return mirrors;
}
public ListBoxModel doFillAvailablePackagesItems() {
ListBoxModel packages = new ListBoxModel();
List<String> packageList = PackagesManager.singleton().getAvailablePackages();
Set<String> alreadyInstalled = PackagesManager.singleton().getInstalledPackages();
for (String entry : packageList) {
if (!alreadyInstalled.contains(entry)) {
packages.add(entry);
}
}
return packages;
}
public ListBoxModel doFillMirrorsItems() {
ListBoxModel mirrors = new ListBoxModel();
String[] mirrorsList = MirrorManager.singleton().getMirrors();
int selected = 34;
for (int i = 0; i < mirrorsList.length; i++) {
String[] splitCurrent = mirrorsList[i].split(" - ");
if (chosenMirror != null && chosenMirror.equals(splitCurrent[1])) {
selected = i;
}
mirrors.add(splitCurrent[1], splitCurrent[0]);
}
mirrors.get(selected).selected = true;
return mirrors;
}
public boolean getShowInstalled() {
return showInstalled;
}
public void setShowInstalled(boolean showInstalled) {
this.showInstalled = showInstalled;
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
public String getChosenMirror() {
return chosenMirror;
}
public void setChosenMirror(String chosenMirror) {
this.chosenMirror = chosenMirror;
}
}
}
AvailablePackage.java
public class AvailablePackage extends AbstractDescribableImpl<AvailablePackage> {
private String name;
#DataBoundConstructor
public AvailablePackage(String availablePackages) {
this.name = availablePackages;
}
public String getName() {
return name;
}
#Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl)super.getDescriptor();
}
#Extension
public static class DescriptorImpl extends Descriptor<AvailablePackage> {
private String name;
public DescriptorImpl() {
load();
}
#Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
req.bindJSON(this, formData);
save();
return super.configure(req,formData);
}
public ListBoxModel doFillAvailablePackagesItems() {
return PackagesManager.singleton().getAvailablePackagesAsListBoxModel(name);
}
#Override
public String getDisplayName() {
return "";
}
public String getName() {
return name;
}
}
}
Sorry for the code formatting! First timer at stackoverflow code posting.
I think you may need to comment this line out
#Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
req.bindJSON(this, formData);
save();
//return super.configure(req,formData);
return true;
}
as it will then save again but with no fields.
A good place to locate Jenkins plugin examples is in https://github.com/jenkinsci