Move articles out of java-strings part2
This commit is contained in:
@@ -0,0 +1,152 @@
|
||||
package com.baeldung.password;
|
||||
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.apache.commons.text.RandomStringGenerator;
|
||||
import org.passay.CharacterRule;
|
||||
import org.passay.EnglishCharacterData;
|
||||
import org.passay.CharacterData;
|
||||
import org.passay.PasswordGenerator;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class RandomPasswordGenerator {
|
||||
|
||||
/**
|
||||
* Special characters allowed in password.
|
||||
*/
|
||||
public static final String ALLOWED_SPL_CHARACTERS = "!@#$%^&*()_+";
|
||||
|
||||
public static final String ERROR_CODE = "ERRONEOUS_SPECIAL_CHARS";
|
||||
|
||||
Random random = new SecureRandom();
|
||||
|
||||
public String generatePassayPassword() {
|
||||
PasswordGenerator gen = new PasswordGenerator();
|
||||
CharacterData lowerCaseChars = EnglishCharacterData.LowerCase;
|
||||
CharacterRule lowerCaseRule = new CharacterRule(lowerCaseChars);
|
||||
lowerCaseRule.setNumberOfCharacters(2);
|
||||
CharacterData upperCaseChars = EnglishCharacterData.UpperCase;
|
||||
CharacterRule upperCaseRule = new CharacterRule(upperCaseChars);
|
||||
upperCaseRule.setNumberOfCharacters(2);
|
||||
CharacterData digitChars = EnglishCharacterData.Digit;
|
||||
CharacterRule digitRule = new CharacterRule(digitChars);
|
||||
digitRule.setNumberOfCharacters(2);
|
||||
CharacterData specialChars = new CharacterData() {
|
||||
public String getErrorCode() {
|
||||
return ERROR_CODE;
|
||||
}
|
||||
|
||||
public String getCharacters() {
|
||||
return ALLOWED_SPL_CHARACTERS;
|
||||
}
|
||||
};
|
||||
CharacterRule splCharRule = new CharacterRule(specialChars);
|
||||
splCharRule.setNumberOfCharacters(2);
|
||||
String password = gen.generatePassword(10, splCharRule, lowerCaseRule, upperCaseRule, digitRule);
|
||||
return password;
|
||||
}
|
||||
|
||||
public String generateCommonTextPassword() {
|
||||
String pwString = generateRandomSpecialCharacters(2).concat(generateRandomNumbers(2))
|
||||
.concat(generateRandomAlphabet(2, true))
|
||||
.concat(generateRandomAlphabet(2, false))
|
||||
.concat(generateRandomCharacters(2));
|
||||
List<Character> pwChars = pwString.chars()
|
||||
.mapToObj(data -> (char) data)
|
||||
.collect(Collectors.toList());
|
||||
Collections.shuffle(pwChars);
|
||||
String password = pwChars.stream()
|
||||
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
|
||||
.toString();
|
||||
return password;
|
||||
}
|
||||
|
||||
public String generateCommonsLang3Password() {
|
||||
String upperCaseLetters = RandomStringUtils.random(2, 65, 90, true, true);
|
||||
String lowerCaseLetters = RandomStringUtils.random(2, 97, 122, true, true);
|
||||
String numbers = RandomStringUtils.randomNumeric(2);
|
||||
String specialChar = RandomStringUtils.random(2, 33, 47, false, false);
|
||||
String totalChars = RandomStringUtils.randomAlphanumeric(2);
|
||||
String combinedChars = upperCaseLetters.concat(lowerCaseLetters)
|
||||
.concat(numbers)
|
||||
.concat(specialChar)
|
||||
.concat(totalChars);
|
||||
List<Character> pwdChars = combinedChars.chars()
|
||||
.mapToObj(c -> (char) c)
|
||||
.collect(Collectors.toList());
|
||||
Collections.shuffle(pwdChars);
|
||||
String password = pwdChars.stream()
|
||||
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
|
||||
.toString();
|
||||
return password;
|
||||
}
|
||||
|
||||
public String generateSecureRandomPassword() {
|
||||
Stream<Character> pwdStream = Stream.concat(getRandomNumbers(2), Stream.concat(getRandomSpecialChars(2), Stream.concat(getRandomAlphabets(2, true), getRandomAlphabets(4, false))));
|
||||
List<Character> charList = pwdStream.collect(Collectors.toList());
|
||||
Collections.shuffle(charList);
|
||||
String password = charList.stream()
|
||||
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
|
||||
.toString();
|
||||
return password;
|
||||
}
|
||||
|
||||
public String generateRandomSpecialCharacters(int length) {
|
||||
RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(33, 45)
|
||||
.build();
|
||||
return pwdGenerator.generate(length);
|
||||
}
|
||||
|
||||
public String generateRandomNumbers(int length) {
|
||||
RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(48, 57)
|
||||
.build();
|
||||
return pwdGenerator.generate(length);
|
||||
}
|
||||
|
||||
public String generateRandomCharacters(int length) {
|
||||
RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(48, 57)
|
||||
.build();
|
||||
return pwdGenerator.generate(length);
|
||||
}
|
||||
|
||||
public String generateRandomAlphabet(int length, boolean lowerCase) {
|
||||
int low;
|
||||
int hi;
|
||||
if (lowerCase) {
|
||||
low = 97;
|
||||
hi = 122;
|
||||
} else {
|
||||
low = 65;
|
||||
hi = 90;
|
||||
}
|
||||
RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(low, hi)
|
||||
.build();
|
||||
return pwdGenerator.generate(length);
|
||||
}
|
||||
|
||||
public Stream<Character> getRandomAlphabets(int count, boolean upperCase) {
|
||||
IntStream characters = null;
|
||||
if (upperCase) {
|
||||
characters = random.ints(count, 65, 90);
|
||||
} else {
|
||||
characters = random.ints(count, 97, 122);
|
||||
}
|
||||
return characters.mapToObj(data -> (char) data);
|
||||
}
|
||||
|
||||
public Stream<Character> getRandomNumbers(int count) {
|
||||
IntStream numbers = random.ints(count, 48, 57);
|
||||
return numbers.mapToObj(data -> (char) data);
|
||||
}
|
||||
|
||||
public Stream<Character> getRandomSpecialChars(int count) {
|
||||
IntStream specialChars = random.ints(count, 33, 45);
|
||||
return specialChars.mapToObj(data -> (char) data);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.baeldung.streamtokenizer;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class StreamTokenizerDemo {
|
||||
|
||||
private static final String INPUT_FILE = "/stream-tokenizer-example.txt";
|
||||
private static final int QUOTE_CHARACTER = '\'';
|
||||
private static final int DOUBLE_QUOTE_CHARACTER = '"';
|
||||
|
||||
public static List<Object> streamTokenizerWithDefaultConfiguration(Reader reader) throws IOException {
|
||||
StreamTokenizer streamTokenizer = new StreamTokenizer(reader);
|
||||
List<Object> tokens = new ArrayList<>();
|
||||
|
||||
int currentToken = streamTokenizer.nextToken();
|
||||
while (currentToken != StreamTokenizer.TT_EOF) {
|
||||
|
||||
if (streamTokenizer.ttype == StreamTokenizer.TT_NUMBER) {
|
||||
tokens.add(streamTokenizer.nval);
|
||||
} else if (streamTokenizer.ttype == StreamTokenizer.TT_WORD
|
||||
|| streamTokenizer.ttype == QUOTE_CHARACTER
|
||||
|| streamTokenizer.ttype == DOUBLE_QUOTE_CHARACTER) {
|
||||
tokens.add(streamTokenizer.sval);
|
||||
} else {
|
||||
tokens.add((char) currentToken);
|
||||
}
|
||||
|
||||
currentToken = streamTokenizer.nextToken();
|
||||
}
|
||||
|
||||
return tokens;
|
||||
}
|
||||
|
||||
public static List<Object> streamTokenizerWithCustomConfiguration(Reader reader) throws IOException {
|
||||
StreamTokenizer streamTokenizer = new StreamTokenizer(reader);
|
||||
List<Object> tokens = new ArrayList<>();
|
||||
|
||||
streamTokenizer.wordChars('!', '-');
|
||||
streamTokenizer.ordinaryChar('/');
|
||||
streamTokenizer.commentChar('#');
|
||||
streamTokenizer.eolIsSignificant(true);
|
||||
|
||||
int currentToken = streamTokenizer.nextToken();
|
||||
while (currentToken != StreamTokenizer.TT_EOF) {
|
||||
|
||||
if (streamTokenizer.ttype == StreamTokenizer.TT_NUMBER) {
|
||||
tokens.add(streamTokenizer.nval);
|
||||
} else if (streamTokenizer.ttype == StreamTokenizer.TT_WORD
|
||||
|| streamTokenizer.ttype == QUOTE_CHARACTER
|
||||
|| streamTokenizer.ttype == DOUBLE_QUOTE_CHARACTER) {
|
||||
tokens.add(streamTokenizer.sval);
|
||||
} else {
|
||||
tokens.add((char) currentToken);
|
||||
}
|
||||
currentToken = streamTokenizer.nextToken();
|
||||
}
|
||||
|
||||
return tokens;
|
||||
}
|
||||
|
||||
public static Reader createReaderFromFile() throws FileNotFoundException {
|
||||
String inputFile = StreamTokenizerDemo.class.getResource(INPUT_FILE).getFile();
|
||||
return new FileReader(inputFile);
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
List<Object> tokens1 = streamTokenizerWithDefaultConfiguration(createReaderFromFile());
|
||||
List<Object> tokens2 = streamTokenizerWithCustomConfiguration(createReaderFromFile());
|
||||
|
||||
System.out.println(tokens1);
|
||||
System.out.println(tokens2);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.stringbuilderstringbuffer;
|
||||
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.Scope;
|
||||
import org.openjdk.jmh.annotations.State;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.RunnerException;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
public class StringBuilderStringBuffer {
|
||||
|
||||
public static void main(String[] args) throws RunnerException {
|
||||
|
||||
Options opt = new OptionsBuilder()
|
||||
.include(StringBuilderStringBuffer.class.getSimpleName())
|
||||
.build();
|
||||
|
||||
new Runner(opt).run();
|
||||
}
|
||||
|
||||
@State(Scope.Benchmark)
|
||||
public static class MyState {
|
||||
int iterations = 1000;
|
||||
String initial = "abc";
|
||||
String suffix = "def";
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public StringBuffer benchmarkStringBuffer(MyState state) {
|
||||
StringBuffer stringBuffer = new StringBuffer(state.initial);
|
||||
for (int i = 0; i < state.iterations; i++) {
|
||||
stringBuffer.append(state.suffix);
|
||||
}
|
||||
return stringBuffer;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public StringBuilder benchmarkStringBuilder(MyState state) {
|
||||
StringBuilder stringBuilder = new StringBuilder(state.initial);
|
||||
for (int i = 0; i < state.iterations; i++) {
|
||||
stringBuilder.append(state.suffix);
|
||||
}
|
||||
return stringBuilder;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.baeldung.stringtokenizer;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.StringTokenizer;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class MyTokenizer {
|
||||
|
||||
public List<String> getTokens(String str) {
|
||||
List<String> tokens = new ArrayList<>();
|
||||
// StringTokenizer tokenizer = new StringTokenizer( str );
|
||||
StringTokenizer tokenizer = new StringTokenizer(str, ",");
|
||||
// StringTokenizer tokenizer = new StringTokenizer( str , "," , true );
|
||||
while (tokenizer.hasMoreElements()) {
|
||||
tokens.add(tokenizer.nextToken());
|
||||
// tokens.add( tokenizer.nextToken("e") );
|
||||
}
|
||||
int tokenLength = tokens.size();
|
||||
return tokens;
|
||||
}
|
||||
|
||||
public List<String> getTokensWithCollection(String str) {
|
||||
return Collections.list(new StringTokenizer(str, ",")).stream().map(token -> (String) token).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public List<String> getTokensFromFile(String path, String delim) {
|
||||
List<String> tokens = new ArrayList<>();
|
||||
String currLine;
|
||||
StringTokenizer tokenizer;
|
||||
try (BufferedReader br = new BufferedReader(new InputStreamReader(MyTokenizer.class.getResourceAsStream("/" + path)))) {
|
||||
while ((currLine = br.readLine()) != null) {
|
||||
tokenizer = new StringTokenizer(currLine, delim);
|
||||
while (tokenizer.hasMoreElements()) {
|
||||
tokens.add(tokenizer.nextToken());
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.charsequence;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class CharSequenceVsStringUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenUsingString_whenInstantiatingString_thenWrong() {
|
||||
CharSequence firstString = "bealdung";
|
||||
String secondString = "baeldung";
|
||||
|
||||
assertNotEquals(firstString, secondString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIdenticalCharSequences_whenCastToString_thenEqual() {
|
||||
CharSequence charSequence1 = "baeldung_1";
|
||||
CharSequence charSequence2 = "baeldung_2";
|
||||
|
||||
assertTrue(charSequence1.toString().compareTo(charSequence2.toString()) < 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenAppended_thenUnmodified() {
|
||||
String test = "a";
|
||||
int firstAddressOfTest = System.identityHashCode(test);
|
||||
test += "b";
|
||||
int secondAddressOfTest = System.identityHashCode(test);
|
||||
|
||||
assertNotEquals(firstAddressOfTest, secondAddressOfTest);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringBuilder_whenAppended_thenModified() {
|
||||
StringBuilder test = new StringBuilder();
|
||||
test.append("a");
|
||||
int firstAddressOfTest = System.identityHashCode(test);
|
||||
test.append("b");
|
||||
int secondAddressOfTest = System.identityHashCode(test);
|
||||
|
||||
assertEquals(firstAddressOfTest, secondAddressOfTest);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package com.baeldung.formatter;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Formatter;
|
||||
import java.util.GregorianCalendar;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class StringFormatterExampleUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenString_whenFormatSpecifierForCalendar_thenGotExpected() {
|
||||
//Syntax of Format Specifiers for Date/Time Representation
|
||||
Calendar c = new GregorianCalendar(2017, 11, 10);
|
||||
String s = String.format("The date is: %tm %1$te,%1$tY", c);
|
||||
|
||||
|
||||
assertEquals("The date is: 12 10,2017", s);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenGeneralConversion_thenConvertedString() {
|
||||
//General Conversions
|
||||
String s = String.format("The correct answer is %s", false);
|
||||
assertEquals("The correct answer is false", s);
|
||||
|
||||
s = String.format("The correct answer is %b", null);
|
||||
assertEquals("The correct answer is false", s);
|
||||
|
||||
s = String.format("The correct answer is %B", true);
|
||||
assertEquals("The correct answer is TRUE", s);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenCharConversion_thenConvertedString() {
|
||||
//Character Conversions
|
||||
String s = String.format("The correct answer is %c", 'a');
|
||||
assertEquals("The correct answer is a", s);
|
||||
|
||||
s = String.format("The correct answer is %c", null);
|
||||
assertEquals("The correct answer is null", s);
|
||||
|
||||
s = String.format("The correct answer is %C", 'b');
|
||||
assertEquals("The correct answer is B", s);
|
||||
|
||||
s = String.format("The valid unicode character: %c", 0x0400);
|
||||
assertTrue(Character.isValidCodePoint(0x0400));
|
||||
assertEquals("The valid unicode character: Ѐ", s);
|
||||
}
|
||||
|
||||
@Test(expected = java.util.IllegalFormatCodePointException.class)
|
||||
public void givenString_whenIllegalCodePointForConversion_thenError() {
|
||||
String s = String.format("The valid unicode character: %c", 0x11FFFF);
|
||||
assertFalse(Character.isValidCodePoint(0x11FFFF));
|
||||
assertEquals("The valid unicode character: Ā", s);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenNumericIntegralConversion_thenConvertedString() {
|
||||
//Numeric Integral Conversions
|
||||
String s = String.format("The number 25 in decimal = %d", 25);
|
||||
assertEquals("The number 25 in decimal = 25", s);
|
||||
|
||||
s = String.format("The number 25 in octal = %o", 25);
|
||||
assertEquals("The number 25 in octal = 31", s);
|
||||
|
||||
s = String.format("The number 25 in hexadecimal = %x", 25);
|
||||
assertEquals("The number 25 in hexadecimal = 19", s);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenNumericFloatingConversion_thenConvertedString() {
|
||||
//Numeric Floating-point Conversions
|
||||
String s = String.format("The computerized scientific format of 10000.00 "
|
||||
+ "= %e", 10000.00);
|
||||
assertEquals("The computerized scientific format of 10000.00 = 1.000000e+04", s);
|
||||
|
||||
s = String.format("The decimal format of 10.019 = %f", 10.019);
|
||||
assertEquals("The decimal format of 10.019 = 10.019000", s);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenLineSeparatorConversion_thenConvertedString() {
|
||||
//Line Separator Conversion
|
||||
String s = String.format("First Line %nSecond Line");
|
||||
assertEquals("First Line " + System.getProperty("line.separator")
|
||||
+ "Second Line", s);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenSpecifyFlag_thenGotFormattedString() {
|
||||
//Without left-justified flag
|
||||
String s = String.format("Without left justified flag: %5d", 25);
|
||||
assertEquals("Without left justified flag: 25", s);
|
||||
|
||||
//Using left-justified flag
|
||||
s = String.format("With left justified flag: %-5d", 25);
|
||||
assertEquals("With left justified flag: 25 ", s);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenSpecifyPrecision_thenGotExpected() {
|
||||
|
||||
//Precision
|
||||
String s = String.format("Output of 25.09878 with Precision 2: %.2f", 25.09878);
|
||||
assertEquals("Output of 25.09878 with Precision 2: 25.10", s);
|
||||
|
||||
s = String.format("Output of general conversion type with Precision 2: %.2b", true);
|
||||
assertEquals("Output of general conversion type with Precision 2: tr", s);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenSpecifyArgumentIndex_thenGotExpected() {
|
||||
Calendar c = new GregorianCalendar(2017, 11, 10);
|
||||
//Argument_Index
|
||||
String s = String.format("The date is: %tm %1$te,%1$tY", c);
|
||||
assertEquals("The date is: 12 10,2017", s);
|
||||
|
||||
s = String.format("The date is: %tm %<te,%<tY", c);
|
||||
assertEquals("The date is: 12 10,2017", s);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAppendable_whenCreateFormatter_thenFormatterWorksOnAppendable() {
|
||||
//Using String Formatter with Appendable
|
||||
StringBuilder sb = new StringBuilder();
|
||||
Formatter formatter = new Formatter(sb);
|
||||
formatter.format("I am writting to a %s Instance.", sb.getClass());
|
||||
assertEquals("I am writting to a class java.lang.StringBuilder Instance.", sb.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenNoArguments_thenExpected() {
|
||||
//Using String Formatter without arguments
|
||||
String s = String.format("John scored 90%% in Fall semester");
|
||||
assertEquals("John scored 90% in Fall semester", s);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.baeldung.password;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
/**
|
||||
* Examples of passwords conforming to various specifications, using different libraries.
|
||||
*
|
||||
*/
|
||||
public class StringPasswordUnitTest {
|
||||
|
||||
RandomPasswordGenerator passGen = new RandomPasswordGenerator();
|
||||
|
||||
@Test
|
||||
public void whenPasswordGeneratedUsingPassay_thenSuccessful() {
|
||||
String password = passGen.generatePassayPassword();
|
||||
int specialCharCount = 0;
|
||||
for (char c : password.toCharArray()) {
|
||||
if (c >= 33 || c <= 47) {
|
||||
specialCharCount++;
|
||||
}
|
||||
}
|
||||
assertTrue("Password validation failed in Passay", specialCharCount >= 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPasswordGeneratedUsingCommonsText_thenSuccessful() {
|
||||
RandomPasswordGenerator passGen = new RandomPasswordGenerator();
|
||||
String password = passGen.generateCommonTextPassword();
|
||||
int lowerCaseCount = 0;
|
||||
for (char c : password.toCharArray()) {
|
||||
if (c >= 97 || c <= 122) {
|
||||
lowerCaseCount++;
|
||||
}
|
||||
}
|
||||
assertTrue("Password validation failed in commons-text ", lowerCaseCount >= 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPasswordGeneratedUsingCommonsLang3_thenSuccessful() {
|
||||
String password = passGen.generateCommonsLang3Password();
|
||||
int numCount = 0;
|
||||
for (char c : password.toCharArray()) {
|
||||
if (c >= 48 || c <= 57) {
|
||||
numCount++;
|
||||
}
|
||||
}
|
||||
assertTrue("Password validation failed in commons-lang3", numCount >= 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPasswordGeneratedUsingSecureRandom_thenSuccessful() {
|
||||
String password = passGen.generateSecureRandomPassword();
|
||||
int specialCharCount = 0;
|
||||
for (char c : password.toCharArray()) {
|
||||
if (c >= 33 || c <= 47) {
|
||||
specialCharCount++;
|
||||
}
|
||||
}
|
||||
assertTrue("Password validation failed in Secure Random", specialCharCount >= 2);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.streamtokenizer;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
|
||||
public class StreamTokenizerDemoUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenStreamTokenizerWithDefaultConfigurationIsCalled_ThenCorrectTokensAreReturned() throws IOException {
|
||||
Reader reader = StreamTokenizerDemo.createReaderFromFile();
|
||||
List<Object> expectedTokens = Arrays.asList(3.0, "quick", "brown", "foxes", "jump", "over", "the", "lazy", "dog", '!', '#', "test1");
|
||||
|
||||
List<Object> actualTokens = StreamTokenizerDemo.streamTokenizerWithDefaultConfiguration(reader);
|
||||
|
||||
assertArrayEquals(expectedTokens.toArray(), actualTokens.toArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStreamTokenizerWithCustomConfigurationIsCalled_ThenCorrectTokensAreReturned() throws IOException {
|
||||
Reader reader = StreamTokenizerDemo.createReaderFromFile();
|
||||
List<Object> expectedTokens = Arrays.asList(3.0, "quick", "brown", "foxes", "jump", "over", "the", "\"lazy\"", "dog!", '\n', '\n', '/', '/', "test2");
|
||||
|
||||
List<Object> actualTokens = StreamTokenizerDemo.streamTokenizerWithCustomConfiguration(reader);
|
||||
|
||||
assertArrayEquals(expectedTokens.toArray(), actualTokens.toArray());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package com.baeldung.stringjoiner;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.StringJoiner;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StringJoinerUnitTest {
|
||||
private final String DELIMITER_COMMA = ",";
|
||||
private final String DELIMITER_HYPHEN = "-";
|
||||
private final String PREFIX = "[";
|
||||
private final String SUFFIX = "]";
|
||||
private final String EMPTY_JOINER = "empty";
|
||||
|
||||
@Test
|
||||
public void whenJoinerWithoutPrefixSuffixWithoutEmptyValue_thenReturnDefault() {
|
||||
StringJoiner commaSeparatedJoiner = new StringJoiner(DELIMITER_COMMA);
|
||||
assertEquals(0, commaSeparatedJoiner.toString().length());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoinerWithPrefixSuffixWithoutEmptyValue_thenReturnDefault() {
|
||||
StringJoiner commaSeparatedPrefixSuffixJoiner = new StringJoiner(DELIMITER_COMMA, PREFIX, SUFFIX);
|
||||
assertEquals(commaSeparatedPrefixSuffixJoiner.toString(), PREFIX + SUFFIX);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoinerWithoutPrefixSuffixWithEmptyValue_thenReturnDefault() {
|
||||
StringJoiner commaSeparatedJoiner = new StringJoiner(DELIMITER_COMMA);
|
||||
commaSeparatedJoiner.setEmptyValue(EMPTY_JOINER);
|
||||
|
||||
assertEquals(commaSeparatedJoiner.toString(), EMPTY_JOINER);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoinerWithPrefixSuffixWithEmptyValue_thenReturnDefault() {
|
||||
StringJoiner commaSeparatedPrefixSuffixJoiner = new StringJoiner(DELIMITER_COMMA, PREFIX, SUFFIX);
|
||||
commaSeparatedPrefixSuffixJoiner.setEmptyValue(EMPTY_JOINER);
|
||||
|
||||
assertEquals(commaSeparatedPrefixSuffixJoiner.toString(), EMPTY_JOINER);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddElements_thenJoinElements() {
|
||||
StringJoiner rgbJoiner = new StringJoiner(DELIMITER_COMMA, PREFIX, SUFFIX);
|
||||
rgbJoiner.add("Red")
|
||||
.add("Green")
|
||||
.add("Blue");
|
||||
|
||||
assertEquals(rgbJoiner.toString(), "[Red,Green,Blue]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddListElements_thenJoinListElements() {
|
||||
List<String> rgbList = new ArrayList<String>();
|
||||
rgbList.add("Red");
|
||||
rgbList.add("Green");
|
||||
rgbList.add("Blue");
|
||||
|
||||
StringJoiner rgbJoiner = new StringJoiner(DELIMITER_COMMA, PREFIX, SUFFIX);
|
||||
|
||||
for (String color : rgbList) {
|
||||
rgbJoiner.add(color);
|
||||
}
|
||||
|
||||
assertEquals(rgbJoiner.toString(), "[Red,Green,Blue]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMergeJoiners_thenReturnMerged() {
|
||||
StringJoiner rgbJoiner = new StringJoiner(DELIMITER_COMMA, PREFIX, SUFFIX);
|
||||
StringJoiner cmybJoiner = new StringJoiner(DELIMITER_HYPHEN, PREFIX, SUFFIX);
|
||||
|
||||
rgbJoiner.add("Red")
|
||||
.add("Green")
|
||||
.add("Blue");
|
||||
cmybJoiner.add("Cyan")
|
||||
.add("Magenta")
|
||||
.add("Yellow")
|
||||
.add("Black");
|
||||
|
||||
rgbJoiner.merge(cmybJoiner);
|
||||
|
||||
assertEquals(rgbJoiner.toString(), "[Red,Green,Blue,Cyan-Magenta-Yellow-Black]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsedWithinCollectors_thenJoin() {
|
||||
List<String> rgbList = Arrays.asList("Red", "Green", "Blue");
|
||||
String commaSeparatedRGB = rgbList.stream()
|
||||
.map(color -> color.toString())
|
||||
.collect(Collectors.joining(","));
|
||||
|
||||
assertEquals(commaSeparatedRGB, "Red,Green,Blue");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.stringtokenizer;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class TokenizerUnitTest {
|
||||
|
||||
private final MyTokenizer myTokenizer = new MyTokenizer();
|
||||
private final List<String> expectedTokensForString = Arrays.asList("Welcome", "to", "baeldung.com");
|
||||
private final List<String> expectedTokensForFile = Arrays.asList("1", "IND", "India", "2", "MY", "Malaysia", "3", "AU", "Australia");
|
||||
|
||||
@Test
|
||||
public void givenString_thenGetListOfString() {
|
||||
String str = "Welcome,to,baeldung.com";
|
||||
List<String> actualTokens = myTokenizer.getTokens(str);
|
||||
assertEquals(expectedTokensForString, actualTokens);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFile_thenGetListOfString() {
|
||||
List<String> actualTokens = myTokenizer.getTokensFromFile("data.csv", "|");
|
||||
assertEquals(expectedTokensForFile, actualTokens);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
1|IND|India
|
||||
2|MY|Malaysia
|
||||
3|AU|Australia
|
||||
|
@@ -0,0 +1,3 @@
|
||||
3 quick brown foxes jump over the "lazy" dog!
|
||||
#test1
|
||||
//test2
|
||||
Reference in New Issue
Block a user