change method to return Optionals (#4464)
* change method to return Optionals * add check for empty Optional
This commit is contained in:
parent
ee77a84225
commit
974637a273
|
@ -3,18 +3,18 @@ package com.baeldung.extension;
|
||||||
import com.google.common.io.Files;
|
import com.google.common.io.Files;
|
||||||
import org.apache.commons.io.FilenameUtils;
|
import org.apache.commons.io.FilenameUtils;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
public class Extension {
|
public class Extension {
|
||||||
//Instead of file name we can also specify full path of a file eg. /baeldung/com/demo/abc.java
|
//Instead of file name we can also specify full path of a file eg. /baeldung/com/demo/abc.java
|
||||||
public String getExtensionByApacheCommonLib(String filename) {
|
public String getExtensionByApacheCommonLib(String filename) {
|
||||||
return FilenameUtils.getExtension(filename);
|
return FilenameUtils.getExtension(filename);
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getExtensionByStringHandling(String filename) {
|
public Optional<String> getExtensionByStringHandling(String filename) {
|
||||||
String fileExtension = "";
|
return Optional.ofNullable(filename)
|
||||||
if (filename.contains(".") && filename.lastIndexOf(".") != 0) {
|
.filter(f -> f.contains("."))
|
||||||
fileExtension = filename.substring(filename.lastIndexOf(".") + 1);
|
.map(f -> f.substring(filename.lastIndexOf(".") + 1));
|
||||||
}
|
|
||||||
return fileExtension;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getExtensionByGuava(String filename) {
|
public String getExtensionByGuava(String filename) {
|
||||||
|
|
|
@ -3,6 +3,8 @@ package com.baeldung.extension;
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
public class ExtensionUnitTest {
|
public class ExtensionUnitTest {
|
||||||
private Extension extension = new Extension();
|
private Extension extension = new Extension();
|
||||||
|
|
||||||
|
@ -16,8 +18,9 @@ public class ExtensionUnitTest {
|
||||||
@Test
|
@Test
|
||||||
public void getExtension_whenStringHandle_thenExtensionIsTrue() {
|
public void getExtension_whenStringHandle_thenExtensionIsTrue() {
|
||||||
String expectedExtension = "java";
|
String expectedExtension = "java";
|
||||||
String actualExtension = extension.getExtensionByStringHandling("Demo.java");
|
Optional<String> actualExtension = extension.getExtensionByStringHandling("Demo.java");
|
||||||
Assert.assertEquals(expectedExtension, actualExtension);
|
Assert.assertTrue(actualExtension.isPresent());
|
||||||
|
actualExtension.ifPresent(ext -> Assert.assertEquals(expectedExtension,ext));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|
Loading…
Reference in New Issue