Move articles out of java-strings part2

This commit is contained in:
catalin-burcea
2019-10-15 21:20:48 +03:00
parent 9199d0c895
commit a244dd2698
23 changed files with 111 additions and 41 deletions

View File

@@ -9,12 +9,10 @@ This module contains articles about strings in Java.
- [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords)
- [Java Generate Random String](https://www.baeldung.com/java-random-string)
- [Java Base64 Encoding and Decoding](https://www.baeldung.com/java-base64-encode-and-decode)
- [Generate a Secure Random Password in Java](https://www.baeldung.com/java-generate-secure-password)
- [Removing Repeated Characters from a String](https://www.baeldung.com/java-remove-repeated-char)
- [Join Array of Primitives with Separator in Java](https://www.baeldung.com/java-join-primitive-array)
- [Pad a String with Zeros or Spaces in Java](https://www.baeldung.com/java-pad-string)
- [Remove Emojis from a Java String](https://www.baeldung.com/java-string-remove-emojis)
- [Guide to java.util.Formatter](https://www.baeldung.com/java-string-formatter)
- [Remove Leading and Trailing Characters from a String](https://www.baeldung.com/java-remove-trailing-characters)
- [Concatenating Strings In Java](https://www.baeldung.com/java-strings-concatenation)
- [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions)
@@ -26,5 +24,4 @@ This module contains articles about strings in Java.
- [Checking If a String Is a Repeated Substring](https://www.baeldung.com/java-repeated-substring)
- [How to Reverse a String in Java](https://www.baeldung.com/java-reverse-string)
- [String toLowerCase and toUpperCase Methods in Java](https://www.baeldung.com/java-string-convert-case)
- [Guide to StreamTokenizer](https://www.baeldung.com/java-streamtokenizer)
- More articles: [[<-- prev>]](/java-strings) [[next -->]](/java-strings-3)

View File

@@ -1,152 +0,0 @@
package com.baeldung.string.password;
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;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.text.RandomStringGenerator;
import org.passay.CharacterData;
import org.passay.CharacterRule;
import org.passay.EnglishCharacterData;
import org.passay.PasswordGenerator;
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);
}
}

View File

@@ -1,76 +0,0 @@
package com.baeldung.string.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);
}
}

View File

@@ -1,3 +0,0 @@
3 quick brown foxes jump over the "lazy" dog!
#test1
//test2

View File

@@ -1,141 +0,0 @@
package com.baeldung.string.formatter;
import java.util.Calendar;
import java.util.Formatter;
import java.util.GregorianCalendar;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
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);
}
}

View File

@@ -1,64 +0,0 @@
package com.baeldung.string.password;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
/**
* 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);
}
}

View File

@@ -1,34 +0,0 @@
package com.baeldung.string.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());
}
}