Created
November 28, 2017 07:10
-
-
Save darekmydlarz/1bfd98dfb7e84eb73673f1786b758679 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.getbase.services.reach.api.dtos.request; | |
/** | |
* Put quotes around the given String if necessary. | |
* <p> | |
* If the argument doesn't include spaces or quotes, return it as is. If it | |
* contains double quotes, use single quotes - else surround the argument by | |
* double quotes. | |
* </p> | |
* <p> | |
* Copied from Apache Commons Exec: http://commons.apache.org/proper/commons-exec/ | |
*/ | |
class QuotedString { | |
private static final String SINGLE_QUOTE = "\'"; | |
private static final String DOUBLE_QUOTE = "\""; | |
private final String argument; | |
public QuotedString(String argument) { | |
this.argument = argument; | |
} | |
public String toString() { | |
String cleanedArgument = argument.trim(); | |
// strip the quotes from both ends | |
while (cleanedArgument.startsWith(SINGLE_QUOTE) || cleanedArgument.startsWith(DOUBLE_QUOTE)) { | |
cleanedArgument = cleanedArgument.substring(1); | |
} | |
while (cleanedArgument.endsWith(SINGLE_QUOTE) || cleanedArgument.endsWith(DOUBLE_QUOTE)) { | |
cleanedArgument = cleanedArgument.substring(0, cleanedArgument.length() - 1); | |
} | |
final StringBuilder buf = new StringBuilder(); | |
if (cleanedArgument.contains(DOUBLE_QUOTE)) { | |
if (cleanedArgument.contains(SINGLE_QUOTE)) { | |
throw new IllegalArgumentException("Can't handle single and double quotes in same argument"); | |
} | |
return buf.append(SINGLE_QUOTE).append(cleanedArgument).append( | |
SINGLE_QUOTE).toString(); | |
} else if (cleanedArgument.contains(SINGLE_QUOTE) || cleanedArgument.contains(" ")) { | |
return buf.append(DOUBLE_QUOTE).append(cleanedArgument).append( | |
DOUBLE_QUOTE).toString(); | |
} else { | |
return cleanedArgument; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The
quoting
part is taken from Apache Commons Exec.In the lib, you use this piece of code in a procedural way, e.g:
In my OOP version you just compose objects, e.g.:
Come up with benefits you gain:
new
is cheap in JavaQuotedString
is immutable - can be easily passed to multiple threads, etc.