rspec/rules/S5883/java/how-to-fix-it/apache-commons.adoc

42 lines
1.1 KiB
Plaintext
Raw Normal View History

=== How to fix it in Apache Commons
include::../../common/fix/code-rationale.adoc[]
2022-10-18 16:03:10 +02:00
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
@Controller
public class ExampleController
{
@GetMapping(value = "/find")
public void find(@RequestParam("filename") String filename) throws IOException {
CommandLine cmd = new CommandLine("/usr/bin/find . -iname " + filename);
}
}
----
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
@Controller
public class ExampleController
{
@GetMapping(value = "/find")
public void find(@RequestParam("filename") String filename) throws IOException {
CommandLine cmd = new CommandLine("/usr/bin/find");
cmd.addArguments(new String[] {"/usr/bin/find", ".", "-iname", filename});
}
}
----
=== How does this work?
include::../../common/fix/introduction.adoc[]
Here `org.apache.commons.exec.CommandLine.addArguments(String[] addArguments)` takes care of escaping the passed arguments and internally
creates a single string given to the operating system to be executed.