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

45 lines
1.1 KiB
Plaintext
Raw Normal View History

=== How to fix it in Apache Commons
include::../../common/fix/code-rationale.adoc[]
[cols="a"]
|===
h| Non-compliant code example
|
[source,java]
----
@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); // Noncompliant
}
}
----
h| Compliant solution
|
[source,java]
----
@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.