how to scan java properties file in sonarqube [closed] - properties

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
I am writing custom rules using SonarQube to scan properties and config files.
Can you please guide me how to write this custom code.

There is a plugin for java properties file https://github.com/racodond/sonar-jproperties-plugin. You can fork it and write your custom rules.
Here is an example rule wich checks for not allowed key and value combination
public class KeyValueCheck extends DoubleDispatchVisitorCheck {
private static final String SIMPLE_IS_PATTERN_TEMPLATE = "(%s)";
protected final Pattern patternKey;
protected final Pattern patternValue;
private final String VIOLATION_MESSAGE;
private final boolean matches;
boolean checkValue = false;
public KeyValueCheck(String key, String value, String message, boolean matches) {
VIOLATION_MESSAGE = message;
this.matches = matches;
this.patternKey = Pattern.compile(String.format(SIMPLE_IS_PATTERN_TEMPLATE, key), Pattern.CASE_INSENSITIVE);
this.patternValue = Pattern.compile(String.format(SIMPLE_IS_PATTERN_TEMPLATE, value), Pattern.CASE_INSENSITIVE);
}
#Override
public void visitKey(KeyTree tree) {
Matcher matcher = patternKey.matcher(tree.text());
if (matcher.matches()) {
checkValue = true;
}
super.visitKey(tree);
}
#Override
public void visitValue(ValueTree tree) {
if (checkValue) {
Matcher matcher = patternValue.matcher(tree.text());
if (matches == patternValue.matcher(tree.text()).matches()) {
addPreciseIssue(tree, VIOLATION_MESSAGE);
}
checkValue = false;
}
super.visitValue(tree);
}
}

Related

Which design pattern to use for using different subclasses based on input [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 months ago.
Improve this question
There is an interface called Processor, which has two implementations SimpleProcessor and ComplexProcessor.
Now I have a process, which consumes an input, and then using that input decides whether it should use SimpleProcessor or ComplexProcessor.
Current solution : I was thinking to use Abstract Factory, which will generate the instance on the basis of the input.
But the issue is that I don't want new instances. I want to use already instantiated objects. That is, I want to re-use the instances.
That means, Abstract factory is absolutely the wrong pattern to use here, as it is for generating objects on the basis of type.
Another thing, that our team normally does is to create a map from input to the corresponding processor instance. And at runtime, we can use that map to get the correct instance on the basis of input.
This feels like a adhoc solution.
I want this to be extendable : new input types can be mapped to new processor types.
Is there some standard way to solve this?
You can use a variation of the Chain of Responsibility pattern.
It will scale far better than using a Map (or hash table in general).
This variation will support dependency injection and is very easy to extend (without breaking any code or violating the Open-Closed principle).
Opposed to the classic version, handlers do not need to be explicitly chained. The classic version scales very bad.
The pattern uses polymorphism to enable extensibility and is therefore targeting an object oriented language.
The pattern is as follows:
The client API is a container class, that manages a collection of input handlers (for example SimnpleProcessor and ComplexProcessor).
Each handler is only known to the container by a common interface and unknown to the client.
The collection of handlers is passed to the container via the constructor (to enable optional dependency injection).
The container accepts the predicate (input) and passes it on to the anonymous handlers by iterating over the handler collection.
Each handler now decides based on the input if it can handle it (return true) or not (return false).
If a handler returns true (to signal that the input was successfully handled), the container will break further input processing by other handlers (alternatively, use a different criteria e.g., to allow multiple handlers to handle the input).
In the following very basic example implementation, the order of handler execution is simply defined by their position in their container (collection).
If this isn't sufficient, you can simply implement a priority algorithm.
Implementation (C#)
Below is the container. It manages the individual handler implementation using polymorphism. Since handler implementation are only known by their common interface, the container scales extremely well: simply add/inject an additional handler implementation.
The container is actually used directly by the client (whereas the handlers are hidden from the client, while anonymous to the container).
interface IInputProcessor
{
void Process(object input);
}
class InputProcessor : IInputProcessor
{
private IEnumerable<IInputHandler> InputHandlers { get; }
// Constructor.
// Optionally use an IoC container to inject the dependency (a collection of input handlers).
public InputProcessor(IEnumerable<IInputHandler> inputHandlers)
{
this.InputHandlers = inputHandlers;
}
// Method to handle the input.
// The input is then delegated to the input handlers.
public void Process(object input)
{
foreach (IInputHandler inputHandler in this.InputHandlers)
{
if (inputHandler.TryHandle(input))
{
return;
}
}
}
}
Below are the input handlers.
To add new handlers i.e. to extend input handling, simply implement the IInputHandler interface and add it to a collection which is passed/injected to the container (IInputProcessor):
interface IInputHandler
{
bool TryHandle(object input);
}
class SimpleProcessor : IInputHandler
{
public bool TryHandle(object input)
{
if (input == 1)
{
//TODO::Handle input
return true;
}
return false;
}
}
class ComplexProcessor : IInputHandler
{
public bool TryHandle(object input)
{
if (input == 3)
{
//TODO::Handle input
return true;
}
return false;
}
}
Usage Example
public class Program
{
public static void Main()
{
/* Setup Chain of Responsibility.
/* Preferably configure an IoC container. */
var inputHandlers = new List<IInputHandlers>
{
new SimpleProcessor(),
new ComplexProcessor()
};
IInputProcessor inputProcessor = new InputProcessor(inputHandlers);
/* Use the handler chain */
int input = 3;
inputProcessor.Pocess(input); // Will execute the ComplexProcessor
input = 1;
inputProcessor.Pocess(input); // Will execute the SimpleProcessor
}
}
It is possible to use Strategy pattern with combination of Factory pattern. Factory objects can be cached to have reusable objects without recreating them when objects are necessary.
As an alternative to caching, it is possible to use singleton pattern. In ASP.NET Core it is pretty simple. And if you have DI container, just make sure that you've set settings of creation instance to singleton
Let's start with the first example. We need some enum of ProcessorType:
public enum ProcessorType
{
Simple, Complex
}
Then this is our abstraction of processors:
public interface IProcessor
{
DateTime DateCreated { get; }
}
And its concrete implemetations:
public class SimpleProcessor : IProcessor
{
public DateTime DateCreated { get; } = DateTime.Now;
}
public class ComplexProcessor : IProcessor
{
public DateTime DateCreated { get; } = DateTime.Now;
}
Then we need a factory with cached values:
public class ProcessorFactory
{
private static readonly IDictionary<ProcessorType, IProcessor> _cache
= new Dictionary<ProcessorType, IProcessor>()
{
{ ProcessorType.Simple, new SimpleProcessor() },
{ ProcessorType.Complex, new ComplexProcessor() }
};
public IProcessor GetInstance(ProcessorType processorType)
{
return _cache[processorType];
}
}
And code can be run like this:
ProcessorFactory processorFactory = new ProcessorFactory();
Thread.Sleep(3000);
var simpleProcessor = processorFactory.GetInstance(ProcessorType.Simple);
Console.WriteLine(simpleProcessor.DateCreated); // OUTPUT: 2022-07-07 8:00:01
ProcessorFactory processorFactory_1 = new ProcessorFactory();
Thread.Sleep(3000);
var complexProcessor = processorFactory_1.GetInstance(ProcessorType.Complex);
Console.WriteLine(complexProcessor.DateCreated); // OUTPUT: 2022-07-07 8:00:01
The second way
The second way is to use DI container. So we need to modify our factory to get instances from dependency injection container:
public class ProcessorFactoryByDI
{
private readonly IDictionary<ProcessorType, IProcessor> _cache;
public ProcessorFactoryByDI(
SimpleProcessor simpleProcessor,
ComplexProcessor complexProcessor)
{
_cache = new Dictionary<ProcessorType, IProcessor>()
{
{ ProcessorType.Simple, simpleProcessor },
{ ProcessorType.Complex, complexProcessor }
};
}
public IProcessor GetInstance(ProcessorType processorType)
{
return _cache[processorType];
}
}
And if you use ASP.NET Core, then you can declare your objects as singleton like this:
services.AddSingleton<SimpleProcessor>();
services.AddSingleton<ComplexProcessor>();
Read more about lifetime of an object

How to get data from API before loading page [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
The community reviewed whether to reopen this question last month and left it closed:
Needs details or clarity Add details and clarify the problem by editing this post.
Improve this question
I am trying to get data from an API to show on screen. I created a function and call it from widget build function. I also try to call it from constructor, but it will call that function in the end, so list empty error comes.
I want to call the API before screen load and store data in the list.
You can do it by the below code:
First you have to Hit Api with a onPressed or onTap method within a Button like
onPressed: () {
getNutritionDetails(context,"2");
getDataFromMyApi(context);
},
Then make a function to make the code more clean and reader with any name, here i named the function as getDataFromMyApi
void getDataFromMyApi(BuildContext context) {
//Getting data from API and store it in String or Model or List whatever you required.
String myData;
//and then pass the data to your second activity
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
MyStatefulWidget(myData), // Your Api response myData is Passing to Stateful Widget
),
);
}
and then i made a Stateful Widget where you want to pass the data and wants it to load data before it is opened and there you can have your data before the page loads in myData var.
class MyStatefulWidget extends StatefulWidget {
String myData;
MyStatefulWidget(this.myData, {Key key}) : super(key: key);
#override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
#override
Widget build(BuildContext context) {
return Container(
height: double.infinity,
width: double.infinity,
child: Text(widget.myData),
);
}
}
OR
You Can Use Future Builder
Ques: What does Future Builder do?
Ans: It calls the future function to wait for the result, and as soon as it produces the result it calls the builder function where we build the widget.
class _ExampleState extends State<Example> {
#override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: downloadData(), // function where you call your api
builder: (BuildContext context, AsyncSnapshot<String> snapshot) { // AsyncSnapshot<Your object type>
if( snapshot.connectionState == ConnectionState.waiting){
return Center(child: Text('Please wait its loading...'));
}else{
if (snapshot.hasError)
return Center(child: Text('Error: ${snapshot.error}'));
else
return Center(child: new Text('${snapshot.data}')); // snapshot.data :- get your object which is pass from your downloadData() function
}
},
);
}
Future<String> downloadData()async{
// var response = await http.get('https://getProjectList');
return Future.value("Data download successfully"); // return your response
}
}

Catagorizing messages in chronicle queue for reading

I want to use chronicle queue to store messages using the high level API as mentioned in the answer of this question. But I also want some kind of key for my messages as mentioned here
1.) Firstly , is this the right/efficient way to read/write using high level API? - Code samples below
2.) How do I separate different category of messages? For example "get me all messages for a particular key , the key in code sample below being ric". Maybe use different topics in the same queue? But how would I do that?
Here's my test code to write to the queue:
public void saveHighLevel(MyInterface obj)
{
try (ChronicleQueue queue = ChronicleQueue.singleBuilder(_location).build()) {
ExcerptAppender appender = queue.acquireAppender();
MyInterface trade = appender.methodWriter(MyInterface.class);
// Write
trade.populate(obj);
}
}
And here's one to read:
public void readHighLevel()
{
try(ChronicleQueue queue = ChronicleQueue.singleBuilder(_location).build()) {
ExcerptTailer tailer = queue.createTailer();
MyInterface container = new MyData();
MethodReader reader = tailer.methodReader(container);
while (reader.readOne()) {
System.out.println(container);
}
}
}
MyInterface:
public interface MyInterface
{
public double getPrice();
public int getSize();
public String getRic();
public void populate(MyInterface obj);
}
Implementation of populate:
public void populate(MyInterface obj)
{
this.price = obj.getPrice();
this.ric = obj.getRic();
this.size = obj.getSize();
}
I found the answer for part (2) of my question in the question of this post.
Essentially by doing:
ChronicleQueue queue = ChronicleQueue.singleBuilder("Topic/SubTopic").build();
where Topic can be substituted with the key I'm looking for.

How to implement oop solution for menu [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
can u suggest a oo design for this problem:
need to implememt a menu.
the menu has n options: (from 0-n)
0 - is exit from current level into the last level.
[1-n] are actions.
action can be:
1) open a new sub menu with the same behavior.
2) execution a task (lets say with by interface contract named: doAction().
So you need hierarchically organized "nodes" and each of them has some action associated with it. I would create such a single MenuItem model that contains all this behavior (in java):
public interface MenuItem {
MenuItem parent();
Iterable<MenuItem> children();
String name();
void proceed();
}
The 'parent()' and 'children()' methods navigate up or down the tree, name() is just a printable name of the node and proceed() actually runs a procedure. A possible implementation would be to encapsulate an XML document, which is hierarchical by design, with nodes containing names and ids and a map associating ids with actions, so something like the following code (in java):
public final class XmlMenuItem implements MenuItem {
private final String id;
private final Document xml;
private final Map<String, Runnable> actions;
public XmlMenuItem(String id, Document xml, Map<String, Runnable> actions) {
this.id = id;
this.xml = xml;
this.actions = actions;
}
#Override
public MenuItem parent() {
Element parent = Element.class.cast(xml.getElementById(id).getParentNode());
return new XmlMenuItem(parent.getAttribute("id"), xml, actions);
}
#Override
public Iterable<MenuItem> children() {
List<MenuItem> result = new ArrayList<>();
NodeList children = xml.getElementById(id).getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
result.add(new XmlMenuItem(Element.class.cast(children.item(0)).getAttribute("id"), xml, actions);
}
return result;
}
#Override
public String name() {
return xml.getElementById(id).getTextContent();
}
#Override
public void proceed() {
actions.get(id).run();
}
}

Jackson vector serialization exception

I have the following code with a simple class and a method for writing and then reading:
ObjectMapper mapper = new ObjectMapper();
try{
DataStore testOut = new DataStore();
DataStore.Checklist ch1 = testOut.addChecklist();
ch1.SetTitle("Checklist1");
String output = mapper.writeValueAsString(testOut);
JsonNode rootNode = mapper.readValue(output, JsonNode.class);
Map<String,Object> userData = mapper.readValue(output, Map.class);
}
public class DataStore {
public static class Checklist
{
public Checklist()
{
}
private String _title;
public String GetTitle()
{
return _title;
}
public void SetTitle(String title)
{
_title = title;
}
}
//Checklists
private Vector<Checklist> _checklists = new Vector<Checklist>();
public Checklist addChecklist()
{
Checklist ch = new Checklist();
ch.SetTitle("New Checklist");
_checklists.add(ch);
return ch;
}
public Vector<Checklist> getChecklists()
{
return _checklists;
}
public void setChecklists(Vector<Checklist> checklists)
{
_checklists = checklists;
}
}
The line:
String output = mapper.writeValueAsString(testOut);
causes an exception that has had me baffled for hours and about to abandon using this at all.
Any hints are appreciated.
Here is the exception:
No serializer found for class DataStore$Checklist and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: DataStore["checklists"]->java.util.Vector[0])
There are multiple ways to do it, but I will start with what you are doing wrong: your naming of getter and setter method is wrong -- in Java one uses "camel-case", so you should be using "getTitle". Because of this, properties are not found.
Besides renaming methods to use Java-style names, there are alternatives:
You can use annotation JsonProperty("title") for GetTitle(), so that property is recognized
If you don't want the wrapper object, you could alternatively just add #JsonValue for GetTitle(), in which case value used for the whole object would be return value of that method.
The answer seems to be: You can't do that with Json. I've seen comments in the Gson tutorial as well, that state that some serialization just doesn't work. I downloaded XStream and spat it out with XML in a few minutes of work and a lot less construction around what I really wanted to persist. In the process, I was able to delete a lot of code.