commit
ddb724585b
|
@ -15,7 +15,7 @@ public class GreedyAlgorithm {
|
|||
this.fp = new FollowersPath();
|
||||
}
|
||||
|
||||
public long findMostFollowersPath(String account) throws Exception {
|
||||
public long findMostFollowersPath(String account) {
|
||||
long max = 0;
|
||||
SocialUser toFollow = null;
|
||||
|
||||
|
@ -31,12 +31,8 @@ public class GreedyAlgorithm {
|
|||
if (currentLevel < maxLevel - 1) {
|
||||
currentLevel++;
|
||||
max += findMostFollowersPath(toFollow.getUsername());
|
||||
//fp.addFollower(toFollow.getUsername(), max);
|
||||
//fp.addCount(max);
|
||||
return max;
|
||||
} else {
|
||||
//fp.addFollower(toFollow.getUsername(), max);
|
||||
//fp.addCount(max);
|
||||
return max;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -13,9 +13,8 @@ public class NonGreedyAlgorithm {
|
|||
this.tc = tc;
|
||||
this.currentLevel = level;
|
||||
}
|
||||
|
||||
|
||||
public long findMostFollowersPath(String account) throws Exception {
|
||||
|
||||
public long findMostFollowersPath(String account) {
|
||||
List<SocialUser> followers = tc.getFollowers(account);
|
||||
long total = currentLevel > 0 ? followers.size() : 0;
|
||||
|
||||
|
|
|
@ -20,9 +20,9 @@ public class SocialConnector {
|
|||
return this.isCounterEnabled;
|
||||
}
|
||||
|
||||
public List<SocialUser> getFollowers(String account) throws Exception {
|
||||
public List<SocialUser> getFollowers(String account) {
|
||||
if (counter < 0)
|
||||
throw new Exception ("API limit reached");
|
||||
throw new IllegalStateException ("API limit reached");
|
||||
else {
|
||||
if(this.isCounterEnabled) counter--;
|
||||
for(SocialUser user : users) {
|
||||
|
|
|
@ -35,21 +35,21 @@ public class GreedyAlgorithmUnitTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void greedyAlgorithmTest() throws Exception {
|
||||
public void greedyAlgorithmTest() {
|
||||
GreedyAlgorithm ga = new GreedyAlgorithm(prepareNetwork());
|
||||
assertEquals(ga.findMostFollowersPath("root"), 5);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void nongreedyAlgorithmTest() throws Exception {
|
||||
public void nongreedyAlgorithmTest() {
|
||||
NonGreedyAlgorithm nga = new NonGreedyAlgorithm(prepareNetwork(), 0);
|
||||
Assertions.assertThrows(Exception.class, () -> {
|
||||
Assertions.assertThrows(IllegalStateException.class, () -> {
|
||||
nga.findMostFollowersPath("root");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void nongreedyAlgorithmUnboundedTest() throws Exception {
|
||||
public void nongreedyAlgorithmUnboundedTest() {
|
||||
SocialConnector sc = prepareNetwork();
|
||||
sc.switchCounter();
|
||||
NonGreedyAlgorithm nga = new NonGreedyAlgorithm(sc, 0);
|
||||
|
|
|
@ -32,7 +32,7 @@
|
|||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<poi.version>3.15</poi.version>
|
||||
<poi.version>4.1.1</poi.version>
|
||||
<jexcel.version>1.0.6</jexcel.version>
|
||||
</properties>
|
||||
|
||||
|
|
|
@ -0,0 +1,83 @@
|
|||
package com.baeldung.poi.excel.read.cellvalueandnotformula;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
import org.apache.poi.ss.usermodel.CellType;
|
||||
import org.apache.poi.ss.usermodel.FormulaEvaluator;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.ss.usermodel.Workbook;
|
||||
import org.apache.poi.ss.util.CellAddress;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
|
||||
public class CellValueAndNotFormulaHelper {
|
||||
|
||||
public Object getCellValueByFetchingLastCachedValue(String fileLocation, String cellLocation) throws IOException {
|
||||
Object cellValue = new Object();
|
||||
|
||||
FileInputStream inputStream = new FileInputStream(new File(fileLocation));
|
||||
Workbook workbook = new XSSFWorkbook(inputStream);
|
||||
|
||||
Sheet sheet = workbook.getSheetAt(0);
|
||||
|
||||
CellAddress cellAddress = new CellAddress(cellLocation);
|
||||
Row row = sheet.getRow(cellAddress.getRow());
|
||||
Cell cell = row.getCell(cellAddress.getColumn());
|
||||
|
||||
if (cell.getCellType() == CellType.FORMULA) {
|
||||
switch (cell.getCachedFormulaResultType()) {
|
||||
case BOOLEAN:
|
||||
cellValue = cell.getBooleanCellValue();
|
||||
break;
|
||||
case NUMERIC:
|
||||
cellValue = cell.getNumericCellValue();
|
||||
break;
|
||||
case STRING:
|
||||
cellValue = cell.getStringCellValue();
|
||||
break;
|
||||
default:
|
||||
cellValue = null;
|
||||
}
|
||||
}
|
||||
|
||||
workbook.close();
|
||||
return cellValue;
|
||||
}
|
||||
|
||||
public Object getCellValueByEvaluatingFormula(String fileLocation, String cellLocation) throws IOException {
|
||||
Object cellValue = new Object();
|
||||
|
||||
FileInputStream inputStream = new FileInputStream(new File(fileLocation));
|
||||
Workbook workbook = new XSSFWorkbook(inputStream);
|
||||
|
||||
Sheet sheet = workbook.getSheetAt(0);
|
||||
FormulaEvaluator evaluator = workbook.getCreationHelper()
|
||||
.createFormulaEvaluator();
|
||||
|
||||
CellAddress cellAddress = new CellAddress(cellLocation);
|
||||
Row row = sheet.getRow(cellAddress.getRow());
|
||||
Cell cell = row.getCell(cellAddress.getColumn());
|
||||
|
||||
if (cell.getCellType() == CellType.FORMULA) {
|
||||
switch (evaluator.evaluateFormulaCell(cell)) {
|
||||
case BOOLEAN:
|
||||
cellValue = cell.getBooleanCellValue();
|
||||
break;
|
||||
case NUMERIC:
|
||||
cellValue = cell.getNumericCellValue();
|
||||
break;
|
||||
case STRING:
|
||||
cellValue = cell.getStringCellValue();
|
||||
break;
|
||||
default:
|
||||
cellValue = null;
|
||||
}
|
||||
}
|
||||
|
||||
workbook.close();
|
||||
return cellValue;
|
||||
}
|
||||
}
|
Binary file not shown.
|
@ -0,0 +1,39 @@
|
|||
package com.baeldung.poi.excel.read.cellvalueandnotformula;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class CellValueAndNotFormulaUnitTest {
|
||||
|
||||
private CellValueAndNotFormulaHelper readCellValueAndNotFormulaHelper;
|
||||
private String fileLocation;
|
||||
private static final String FILE_NAME = "test.xlsx";
|
||||
|
||||
@Before
|
||||
public void setup() throws URISyntaxException {
|
||||
fileLocation = Paths.get(ClassLoader.getSystemResource(FILE_NAME).toURI()).toString();
|
||||
readCellValueAndNotFormulaHelper = new CellValueAndNotFormulaHelper();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExcelCell_whenReadCellValueByLastCachedValue_thenProduceCorrectResult() throws IOException {
|
||||
final double expectedResult = 7.0;
|
||||
final Object cellValue = readCellValueAndNotFormulaHelper.getCellValueByFetchingLastCachedValue(fileLocation, "C2");
|
||||
|
||||
assertEquals(expectedResult, cellValue);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExcelCell_whenReadCellValueByEvaluatingFormula_thenProduceCorrectResult() throws IOException {
|
||||
final double expectedResult = 7.0;
|
||||
final Object cellValue = readCellValueAndNotFormulaHelper.getCellValueByEvaluatingFormula(fileLocation, "C2");
|
||||
|
||||
assertEquals(expectedResult, cellValue);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
## Apache RocketMQ
|
||||
|
||||
This module contains articles about Apache RocketMQ
|
||||
|
||||
### Relevant Articles:
|
|
@ -0,0 +1,27 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>apache-rocketmq</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>apache-rocketmq</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.rocketmq</groupId>
|
||||
<artifactId>rocketmq-spring-boot-starter</artifactId>
|
||||
<version>2.0.4</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<geode.core>1.6.0</geode.core>
|
||||
</properties>
|
||||
</project>
|
|
@ -0,0 +1,34 @@
|
|||
package com.baeldung.rocketmq.consumer;
|
||||
|
||||
import com.baeldung.rocketmq.event.CartItemEvent;
|
||||
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
|
||||
import org.apache.rocketmq.spring.core.RocketMQListener;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@SpringBootApplication
|
||||
public class CartEventConsumer {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(CartEventConsumer.class, args);
|
||||
}
|
||||
|
||||
@Service
|
||||
@RocketMQMessageListener(topic = "cart-item-add-topic", consumerGroup = "cart-consumer_cart-item-add-topic")
|
||||
public class CardItemAddConsumer implements RocketMQListener<CartItemEvent> {
|
||||
public void onMessage(CartItemEvent addItemEvent) {
|
||||
System.out.println("Adding item: " + addItemEvent);
|
||||
// logic
|
||||
}
|
||||
}
|
||||
|
||||
@Service
|
||||
@RocketMQMessageListener(topic = "cart-item-removed-topic", consumerGroup = "cart-consumer_cart-item-removed-topic")
|
||||
public class CardItemRemoveConsumer implements RocketMQListener<CartItemEvent> {
|
||||
public void onMessage(CartItemEvent removeItemEvent) {
|
||||
System.out.println("Removing item: " + removeItemEvent);
|
||||
// logic
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.rocketmq.event;
|
||||
|
||||
public class CartItemEvent {
|
||||
private String itemId;
|
||||
private int quantity;
|
||||
|
||||
public CartItemEvent(String itemId, int quantity) {
|
||||
this.itemId = itemId;
|
||||
this.quantity = quantity;
|
||||
}
|
||||
|
||||
public String getItemId() {
|
||||
return itemId;
|
||||
}
|
||||
|
||||
public void setItemId(String itemId) {
|
||||
this.itemId = itemId;
|
||||
}
|
||||
|
||||
public int getQuantity() {
|
||||
return quantity;
|
||||
}
|
||||
|
||||
public void setQuantity(int quantity) {
|
||||
this.quantity = quantity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "CartItemEvent{" + "itemId='" + itemId + '\'' + ", quantity=" + quantity + '}';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
package com.baeldung.rocketmq.producer;
|
||||
|
||||
|
||||
import com.baeldung.rocketmq.event.CartItemEvent;
|
||||
import org.apache.rocketmq.spring.core.RocketMQTemplate;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class CartEventProducer implements CommandLineRunner {
|
||||
|
||||
@Autowired
|
||||
private RocketMQTemplate rocketMQTemplate;
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(CartEventProducer.class, args);
|
||||
}
|
||||
|
||||
public void run(String... args) throws Exception {
|
||||
rocketMQTemplate.convertAndSend("cart-item-add-topic", new CartItemEvent("bike", 1));
|
||||
rocketMQTemplate.convertAndSend("cart-item-add-topic", new CartItemEvent("computer", 2));
|
||||
rocketMQTemplate.convertAndSend("cart-item-removed-topic", new CartItemEvent("bike", 1));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.rocketmq.transaction;
|
||||
|
||||
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
|
||||
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
|
||||
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
|
||||
import org.springframework.messaging.Message;
|
||||
|
||||
@RocketMQTransactionListener(txProducerGroup = "test-transaction")
|
||||
class TransactionListenerImpl implements RocketMQLocalTransactionListener {
|
||||
@Override
|
||||
public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
|
||||
// ... local transaction process, return ROLLBACK, COMMIT or UNKNOWN
|
||||
return RocketMQLocalTransactionState.UNKNOWN;
|
||||
}
|
||||
|
||||
@Override
|
||||
public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
|
||||
// ... check transaction status and return ROLLBACK, COMMIT or UNKNOWN
|
||||
return RocketMQLocalTransactionState.COMMIT;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
rocketmq.name-server=127.0.0.1:9876
|
||||
rocketmq.producer.group=my-group
|
||||
rocketmq.producer.send-message-timeout=300000
|
||||
rocketmq.producer.compress-message-body-threshold=4096
|
||||
rocketmq.producer.max-message-size=4194304
|
||||
rocketmq.producer.retry-times-when-send-async-failed=0
|
||||
rocketmq.producer.retry-next-server=true
|
||||
rocketmq.producer.retry-times-when-send-failed=2
|
||||
|
|
@ -2,10 +2,13 @@ package com.baeldung.metaprogramming.extension
|
|||
|
||||
import com.baeldung.metaprogramming.Employee
|
||||
|
||||
import java.time.LocalDate
|
||||
import java.time.Year
|
||||
|
||||
class BasicExtensions {
|
||||
|
||||
static int getYearOfBirth(Employee self) {
|
||||
return (new Date().getYear() + 1900) - self.age;
|
||||
return Year.now().value - self.age
|
||||
}
|
||||
|
||||
static String capitalize(String self) {
|
||||
|
|
|
@ -1,6 +1,9 @@
|
|||
package com.baeldung.metaprogramming
|
||||
|
||||
import groovy.time.TimeCategory
|
||||
|
||||
import java.time.LocalDate
|
||||
import java.time.Period
|
||||
import java.time.Year
|
||||
|
||||
class MetaprogrammingUnitTest extends GroovyTestCase {
|
||||
|
||||
|
@ -51,14 +54,16 @@ class MetaprogrammingUnitTest extends GroovyTestCase {
|
|||
|
||||
void testJavaMetaClass() {
|
||||
String.metaClass.capitalize = { String str ->
|
||||
str.substring(0, 1).toUpperCase() + str.substring(1);
|
||||
str.substring(0, 1).toUpperCase() + str.substring(1)
|
||||
}
|
||||
assert "norman".capitalize() == "Norman"
|
||||
}
|
||||
|
||||
void testEmployeeExtension() {
|
||||
Employee emp = new Employee(age: 28)
|
||||
assert emp.getYearOfBirth() == 1992
|
||||
def age = 28
|
||||
def expectedYearOfBirth = Year.now() - age
|
||||
Employee emp = new Employee(age: age)
|
||||
assert emp.getYearOfBirth() == expectedYearOfBirth.value
|
||||
}
|
||||
|
||||
void testJavaClassesExtensions() {
|
||||
|
|
|
@ -24,11 +24,21 @@ public class DuplicatesCounter {
|
|||
return resultMap;
|
||||
}
|
||||
|
||||
public static <T> Map<T, Long> countByClassicalLoopWithMapCompute(List<T> inputList) {
|
||||
public static <T> Map<T, Long> countByForEachLoopWithGetOrDefault(List<T> inputList) {
|
||||
Map<T, Long> resultMap = new HashMap<>();
|
||||
for (T element : inputList) {
|
||||
resultMap.compute(element, (k, v) -> v == null ? 1 : v + 1);
|
||||
}
|
||||
inputList.forEach(e -> resultMap.put(e, resultMap.getOrDefault(e, 0L) + 1L));
|
||||
return resultMap;
|
||||
}
|
||||
|
||||
public static <T> Map<T, Long> countByForEachLoopWithMapCompute(List<T> inputList) {
|
||||
Map<T, Long> resultMap = new HashMap<>();
|
||||
inputList.forEach(e -> resultMap.compute(e, (k, v) -> v == null ? 1L : v + 1L));
|
||||
return resultMap;
|
||||
}
|
||||
|
||||
public static <T> Map<T, Long> countByForEachLoopWithMapMerge(List<T> inputList) {
|
||||
Map<T, Long> resultMap = new HashMap<>();
|
||||
inputList.forEach(e -> resultMap.merge(e, 1L, Long::sum));
|
||||
return resultMap;
|
||||
}
|
||||
|
||||
|
|
|
@ -11,7 +11,6 @@ import static org.assertj.core.data.MapEntry.entry;
|
|||
|
||||
class DuplicatesCounterUnitTest {
|
||||
|
||||
|
||||
private static List<String> INPUT_LIST = Lists.list(
|
||||
"expect1",
|
||||
"expect2", "expect2",
|
||||
|
@ -24,10 +23,21 @@ class DuplicatesCounterUnitTest {
|
|||
verifyResult(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenInput_whenCountByForEachLoopWithGetOrDefault_thenGetResultMap() {
|
||||
Map<String, Long> result = DuplicatesCounter.countByForEachLoopWithGetOrDefault(INPUT_LIST);
|
||||
verifyResult(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenInput_whenCountByClassicalLoopWithMapCompute_thenGetResultMap() {
|
||||
Map<String, Long> result = DuplicatesCounter.countByClassicalLoopWithMapCompute(INPUT_LIST);
|
||||
void givenInput_whenCountByForEachLoopWithMapCompute_thenGetResultMap() {
|
||||
Map<String, Long> result = DuplicatesCounter.countByForEachLoopWithMapCompute(INPUT_LIST);
|
||||
verifyResult(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenInput_whenCountByForEachLoopWithMapMerge_thenGetResultMap() {
|
||||
Map<String, Long> result = DuplicatesCounter.countByForEachLoopWithMapMerge(INPUT_LIST);
|
||||
verifyResult(result);
|
||||
}
|
||||
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
## Java Date/time computations Cookbooks and Examples
|
||||
|
||||
This module contains articles about date and time computations in Java.
|
||||
## Core Date Operations (Part 1)
|
||||
This module contains articles about date operations in Java.
|
||||
|
||||
### Relevant Articles:
|
||||
- [Difference Between Two Dates in Java](http://www.baeldung.com/java-date-difference)
|
||||
|
@ -13,3 +12,4 @@ This module contains articles about date and time computations in Java.
|
|||
- [Increment Date in Java](http://www.baeldung.com/java-increment-date)
|
||||
- [Add Hours To a Date In Java](http://www.baeldung.com/java-add-hours-date)
|
||||
- [Introduction to Joda-Time](http://www.baeldung.com/joda-time)
|
||||
- [[Next -->]](/core-java-modules/core-java-date-operations-2)
|
|
@ -2,9 +2,9 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-datetime-computations</artifactId>
|
||||
<artifactId>core-java-date-operations-1</artifactId>
|
||||
<version>${project.parent.version}</version>
|
||||
<name>core-java-datetime-computations</name>
|
||||
<name>core-java-date-operations-1</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
|
@ -41,7 +41,7 @@
|
|||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-datetime-computations</finalName>
|
||||
<finalName>core-java-date-operations-1</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
|
@ -1,4 +1,4 @@
|
|||
## Core Date Operations
|
||||
## Core Date Operations (Part 2)
|
||||
This module contains articles about date operations in Java.
|
||||
|
||||
### Relevant Articles:
|
||||
|
@ -6,3 +6,4 @@ This module contains articles about date operations in Java.
|
|||
- [Skipping Weekends While Adding Days to LocalDate in Java 8](https://www.baeldung.com/java-localdate-add-days-skip-weekends)
|
||||
- [Checking If Two Java Dates Are on the Same Day](https://www.baeldung.com/java-check-two-dates-on-same-day)
|
||||
- [Converting Java Date to OffsetDateTime](https://www.baeldung.com/java-convert-date-to-offsetdatetime)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-date-operations-1)
|
|
@ -3,9 +3,9 @@
|
|||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-date-operations</artifactId>
|
||||
<artifactId>core-java-date-operations-2</artifactId>
|
||||
<version>${project.parent.version}</version>
|
||||
<name>core-java-date-operations</name>
|
||||
<name>core-java-date-operations-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
|
@ -1,65 +1,65 @@
|
|||
package com.baeldung.date.comparison;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import org.apache.commons.lang3.time.DateUtils;
|
||||
|
||||
import hirondelle.date4j.DateTime;
|
||||
|
||||
public class DateComparisonUtils {
|
||||
|
||||
public static boolean isSameDayUsingLocalDate(Date date1, Date date2) {
|
||||
LocalDate localDate1 = date1.toInstant()
|
||||
.atZone(ZoneId.systemDefault())
|
||||
.toLocalDate();
|
||||
LocalDate localDate2 = date2.toInstant()
|
||||
.atZone(ZoneId.systemDefault())
|
||||
.toLocalDate();
|
||||
return localDate1.isEqual(localDate2);
|
||||
}
|
||||
|
||||
public static boolean isSameDayUsingInstant(Date date1, Date date2) {
|
||||
Instant instant1 = date1.toInstant()
|
||||
.truncatedTo(ChronoUnit.DAYS);
|
||||
Instant instant2 = date2.toInstant()
|
||||
.truncatedTo(ChronoUnit.DAYS);
|
||||
return instant1.equals(instant2);
|
||||
}
|
||||
|
||||
public static boolean isSameDayUsingSimpleDateFormat(Date date1, Date date2) {
|
||||
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
|
||||
return fmt.format(date1)
|
||||
.equals(fmt.format(date2));
|
||||
}
|
||||
|
||||
public static boolean isSameDayUsingCalendar(Date date1, Date date2) {
|
||||
Calendar calendar1 = Calendar.getInstance();
|
||||
calendar1.setTime(date1);
|
||||
Calendar calendar2 = Calendar.getInstance();
|
||||
calendar2.setTime(date2);
|
||||
return calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR) && calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH) && calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH);
|
||||
}
|
||||
|
||||
public static boolean isSameDayUsingApacheCommons(Date date1, Date date2) {
|
||||
return DateUtils.isSameDay(date1, date2);
|
||||
}
|
||||
|
||||
public static boolean isSameDayUsingJoda(Date date1, Date date2) {
|
||||
org.joda.time.LocalDate localDate1 = new org.joda.time.LocalDate(date1);
|
||||
org.joda.time.LocalDate localDate2 = new org.joda.time.LocalDate(date2);
|
||||
return localDate1.equals(localDate2);
|
||||
}
|
||||
|
||||
public static boolean isSameDayUsingDate4j(Date date1, Date date2) {
|
||||
DateTime dateObject1 = DateTime.forInstant(date1.getTime(), TimeZone.getDefault());
|
||||
DateTime dateObject2 = DateTime.forInstant(date2.getTime(), TimeZone.getDefault());
|
||||
return dateObject1.isSameDayAs(dateObject2);
|
||||
}
|
||||
}
|
||||
package com.baeldung.date.comparison;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import org.apache.commons.lang3.time.DateUtils;
|
||||
|
||||
import hirondelle.date4j.DateTime;
|
||||
|
||||
public class DateComparisonUtils {
|
||||
|
||||
public static boolean isSameDayUsingLocalDate(Date date1, Date date2) {
|
||||
LocalDate localDate1 = date1.toInstant()
|
||||
.atZone(ZoneId.systemDefault())
|
||||
.toLocalDate();
|
||||
LocalDate localDate2 = date2.toInstant()
|
||||
.atZone(ZoneId.systemDefault())
|
||||
.toLocalDate();
|
||||
return localDate1.isEqual(localDate2);
|
||||
}
|
||||
|
||||
public static boolean isSameDayUsingInstant(Date date1, Date date2) {
|
||||
Instant instant1 = date1.toInstant()
|
||||
.truncatedTo(ChronoUnit.DAYS);
|
||||
Instant instant2 = date2.toInstant()
|
||||
.truncatedTo(ChronoUnit.DAYS);
|
||||
return instant1.equals(instant2);
|
||||
}
|
||||
|
||||
public static boolean isSameDayUsingSimpleDateFormat(Date date1, Date date2) {
|
||||
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
|
||||
return fmt.format(date1)
|
||||
.equals(fmt.format(date2));
|
||||
}
|
||||
|
||||
public static boolean isSameDayUsingCalendar(Date date1, Date date2) {
|
||||
Calendar calendar1 = Calendar.getInstance();
|
||||
calendar1.setTime(date1);
|
||||
Calendar calendar2 = Calendar.getInstance();
|
||||
calendar2.setTime(date2);
|
||||
return calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR) && calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH) && calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH);
|
||||
}
|
||||
|
||||
public static boolean isSameDayUsingApacheCommons(Date date1, Date date2) {
|
||||
return DateUtils.isSameDay(date1, date2);
|
||||
}
|
||||
|
||||
public static boolean isSameDayUsingJoda(Date date1, Date date2) {
|
||||
org.joda.time.LocalDate localDate1 = new org.joda.time.LocalDate(date1);
|
||||
org.joda.time.LocalDate localDate2 = new org.joda.time.LocalDate(date2);
|
||||
return localDate1.equals(localDate2);
|
||||
}
|
||||
|
||||
public static boolean isSameDayUsingDate4j(Date date1, Date date2) {
|
||||
DateTime dateObject1 = DateTime.forInstant(date1.getTime(), TimeZone.getDefault());
|
||||
DateTime dateObject2 = DateTime.forInstant(date2.getTime(), TimeZone.getDefault());
|
||||
return dateObject1.isSameDayAs(dateObject2);
|
||||
}
|
||||
}
|
|
@ -1,57 +1,57 @@
|
|||
package com.baeldung.date.comparison;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Date;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class DateComparisonUtilsUnitTest {
|
||||
|
||||
private Date day1Morning = toDate(LocalDateTime.of(2019, 10, 19, 6, 30, 40));
|
||||
private Date day1Evening = toDate(LocalDateTime.of(2019, 10, 19, 18, 30, 50));
|
||||
private Date day2Morning = toDate(LocalDateTime.of(2019, 10, 20, 6, 30, 50));
|
||||
|
||||
private Date toDate(LocalDateTime localDateTime) {
|
||||
return Date.from(localDateTime.atZone(ZoneId.systemDefault())
|
||||
.toInstant());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDatesWithDifferentTime_whenIsSameDay_thenReturnsTrue() {
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingLocalDate(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingInstant(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingSimpleDateFormat(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingCalendar(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingApacheCommons(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingJoda(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingDate4j(day1Morning, day1Evening));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDates_whenIsDifferentDay_thenReturnsFalse() {
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingLocalDate(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingLocalDate(day1Evening, day2Morning));
|
||||
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingInstant(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingInstant(day1Evening, day2Morning));
|
||||
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingSimpleDateFormat(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingSimpleDateFormat(day1Evening, day2Morning));
|
||||
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingCalendar(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingCalendar(day1Evening, day2Morning));
|
||||
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingApacheCommons(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingApacheCommons(day1Evening, day2Morning));
|
||||
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingJoda(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingJoda(day1Evening, day2Morning));
|
||||
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingDate4j(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingDate4j(day1Evening, day2Morning));
|
||||
}
|
||||
}
|
||||
package com.baeldung.date.comparison;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Date;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class DateComparisonUtilsUnitTest {
|
||||
|
||||
private Date day1Morning = toDate(LocalDateTime.of(2019, 10, 19, 6, 30, 40));
|
||||
private Date day1Evening = toDate(LocalDateTime.of(2019, 10, 19, 18, 30, 50));
|
||||
private Date day2Morning = toDate(LocalDateTime.of(2019, 10, 20, 6, 30, 50));
|
||||
|
||||
private Date toDate(LocalDateTime localDateTime) {
|
||||
return Date.from(localDateTime.atZone(ZoneId.systemDefault())
|
||||
.toInstant());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDatesWithDifferentTime_whenIsSameDay_thenReturnsTrue() {
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingLocalDate(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingInstant(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingSimpleDateFormat(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingCalendar(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingApacheCommons(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingJoda(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingDate4j(day1Morning, day1Evening));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDates_whenIsDifferentDay_thenReturnsFalse() {
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingLocalDate(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingLocalDate(day1Evening, day2Morning));
|
||||
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingInstant(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingInstant(day1Evening, day2Morning));
|
||||
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingSimpleDateFormat(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingSimpleDateFormat(day1Evening, day2Morning));
|
||||
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingCalendar(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingCalendar(day1Evening, day2Morning));
|
||||
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingApacheCommons(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingApacheCommons(day1Evening, day2Morning));
|
||||
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingJoda(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingJoda(day1Evening, day2Morning));
|
||||
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingDate4j(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingDate4j(day1Evening, day2Morning));
|
||||
}
|
||||
}
|
|
@ -1,7 +1,5 @@
|
|||
package com.baeldung.powerset;
|
||||
|
||||
import com.google.common.collect.Sets;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.util.AbstractSet;
|
||||
import java.util.ArrayList;
|
||||
|
@ -163,7 +161,7 @@ public class PowerSetUtility<T> {
|
|||
return unMapIndex(powerSetIndices);
|
||||
}
|
||||
|
||||
private List<List<Boolean>> iterativePowerSetByLoopOverNumbersWithReverseLexicographicalOrder(int n) {
|
||||
private List<List<Boolean>> iterativePowerSetByLoopOverNumbers(int n) {
|
||||
List<List<Boolean>> powerSet = new ArrayList<>();
|
||||
for (int i = 0; i < (1 << n); i++) {
|
||||
List<Boolean> subset = new ArrayList<>(n);
|
||||
|
@ -174,7 +172,7 @@ public class PowerSetUtility<T> {
|
|||
return powerSet;
|
||||
}
|
||||
|
||||
private List<List<Boolean>> iterativePowerSetByLoopOverNumbersWithGrayCodeOrder(int n) {
|
||||
private List<List<Boolean>> iterativePowerSetByLoopOverNumbersWithMinimalChange(int n) {
|
||||
List<List<Boolean>> powerSet = new ArrayList<>();
|
||||
for (int i = 0; i < (1 << n); i++) {
|
||||
List<Boolean> subset = new ArrayList<>(n);
|
||||
|
@ -195,32 +193,16 @@ public class PowerSetUtility<T> {
|
|||
|
||||
public List<List<T>> iterativePowerSetByLoopOverNumbers(Set<T> set) {
|
||||
initializeMap(set);
|
||||
List<List<Boolean>> sets = iterativePowerSetByLoopOverNumbersWithReverseLexicographicalOrder(set.size());
|
||||
List<List<Boolean>> sets = iterativePowerSetByLoopOverNumbers(set.size());
|
||||
return unMapListBinary(sets);
|
||||
}
|
||||
|
||||
public List<List<T>> iterativePowerSetByLoopOverNumbersMinimalChange(Set<T> set) {
|
||||
initializeMap(set);
|
||||
List<List<Boolean>> sets = iterativePowerSetByLoopOverNumbersWithGrayCodeOrder(set.size());
|
||||
List<List<Boolean>> sets = iterativePowerSetByLoopOverNumbersWithMinimalChange(set.size());
|
||||
return unMapListBinary(sets);
|
||||
}
|
||||
|
||||
public static int getRankInLexicographicalOrder(List<Boolean> subset) {
|
||||
int rank = 0;
|
||||
for (int i = 0; i < subset.size(); i++)
|
||||
if (subset.get(i))
|
||||
rank += (1 << (subset.size() - i - 1));
|
||||
return rank;
|
||||
}
|
||||
|
||||
public static List<Boolean> getSubsetForRankInLexicographicalOrder(int rank, int sizeOfSet) {
|
||||
Boolean[] subset = new Boolean[sizeOfSet];
|
||||
for(int j = 0; j < sizeOfSet; j++) {
|
||||
subset[sizeOfSet - j - 1] = ((rank & (1 << j)) > 0);
|
||||
}
|
||||
return Arrays.asList(subset);
|
||||
}
|
||||
|
||||
private Set<Set<Integer>> recursivePowerSetIndexRepresentation(int idx, int n) {
|
||||
if (idx == n) {
|
||||
Set<Set<Integer>> empty = new HashSet<>();
|
||||
|
|
|
@ -137,7 +137,7 @@ public class PowerSetUtilityUnitTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void givenSet_WhenPowerSetIsCalculatedIterativePowerSetByLoopOverNumbersMinimalChange_ThenItContainsAllSubsetsInGrayOrder() {
|
||||
public void givenSet_WhenPowerSetIsCalculatedIterativePowerSetByLoopOverNumbersWithMinimalChange_ThenItContainsAllSubsets() {
|
||||
|
||||
Set<String> set = RandomSetOfStringGenerator.generateRandomSet();
|
||||
List<List<String>> powerSet = new PowerSetUtility<String>().iterativePowerSetByLoopOverNumbersMinimalChange(set);
|
||||
|
@ -172,42 +172,6 @@ public class PowerSetUtilityUnitTest {
|
|||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSubset_WhenPowerSetIsInLexicographicalOrder_ReturnCorrectRank() {
|
||||
int n = new Random().nextInt(5) + 5; //a number in [5, 10)
|
||||
for(int i = 0; i < ( 1 << n); i++) {
|
||||
Boolean[] subset = new Boolean[n];
|
||||
for(int j=0; j < n; j++) {
|
||||
subset[n - j - 1] = ((i & (1 << j)) > 0);
|
||||
}
|
||||
Assertions.assertEquals(i, PowerSetUtility.getRankInLexicographicalOrder(Arrays.asList(subset)));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRanking_WhenPowerSetIsInLexicographicalOrder_ReturnTheSubset() {
|
||||
int n = new Random().nextInt(5) + 5; //a number in [5, 10)
|
||||
List<List<Boolean>> powerSet = new ArrayList<>();
|
||||
for(int i = 0; i < (1 << n); i++) {
|
||||
powerSet.add(PowerSetUtility.getSubsetForRankInLexicographicalOrder(i, n));
|
||||
}
|
||||
//To make sure that the size of power set is (2 power n)
|
||||
MatcherAssert.assertThat(powerSet, IsCollectionWithSize.hasSize((1 << n)));
|
||||
//To make sure that number of occurrence of each index is (2 power n-1)
|
||||
Map<Integer, Integer> counter = new HashMap<>();
|
||||
for (List<Boolean> subset : powerSet) {
|
||||
for (int i = 0; i < subset.size(); i++) {
|
||||
if(subset.get(i)) {
|
||||
int num = counter.getOrDefault(i, 0);
|
||||
counter.put(i, num + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
counter.forEach((k, v) -> Assertions.assertEquals((1 << (n - 1)), v.intValue()));
|
||||
//To make sure that one subset is not generated twice
|
||||
Assertions.assertEquals(powerSet.size(), new HashSet<>(powerSet).size());
|
||||
}
|
||||
|
||||
static class RandomSetOfStringGenerator {
|
||||
private static List<String> fruits = Arrays.asList("Apples", "Avocados", "Banana", "Blueberry", "Cherry", "Clementine", "Cucumber", "Date", "Fig",
|
||||
"Grapefruit"/*, "Grape", "Kiwi", "Lemon", "Mango", "Mulberry", "Melon", "Nectarine", "Olive", "Orange"*/);
|
||||
|
|
|
@ -1,3 +0,0 @@
|
|||
### Relevant Articles:
|
||||
|
||||
- [Intro to the Java SecurityManager](https://www.baeldung.com/java-security-manager)
|
|
@ -1,16 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-security-manager</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-security-manager</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
</project>
|
|
@ -1,35 +0,0 @@
|
|||
package com.baeldung.security.manager;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.net.URL;
|
||||
import java.security.AccessControlException;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
public class SecurityManagerUnitTest {
|
||||
|
||||
@Test(expected = AccessControlException.class)
|
||||
public void whenSecurityManagerIsActive_thenNetworkIsNotAccessibleByDefault() throws Exception {
|
||||
doTest(() -> {
|
||||
new URL("http://www.google.com").openConnection().connect();
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
@Test(expected = AccessControlException.class)
|
||||
public void whenUnauthorizedClassTriesToAccessProtectedOperation_thenAnExceptionIsThrown() throws Exception {
|
||||
doTest(() -> {
|
||||
new Service().operation();
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private void doTest(Callable<Void> action) throws Exception {
|
||||
System.setSecurityManager(new SecurityManager());
|
||||
try {
|
||||
action.call();
|
||||
} finally {
|
||||
System.setSecurityManager(null);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -15,4 +15,5 @@ This module contains articles about core Java Security
|
|||
- [The Java SecureRandom Class](https://www.baeldung.com/java-secure-random)
|
||||
- [An Introduction to Java SASL](https://www.baeldung.com/java-sasl)
|
||||
- [A Guide to Java GSS API](https://www.baeldung.com/java-gss)
|
||||
- [Intro to the Java SecurityManager](https://www.baeldung.com/java-security-manager)
|
||||
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.security.manager;
|
||||
package com.baeldung.securitymanager;
|
||||
|
||||
import java.security.BasicPermission;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.security.manager;
|
||||
package com.baeldung.securitymanager;
|
||||
|
||||
public class Service {
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package org.baeldung.java.md5;
|
||||
package com.baeldung.java.md5;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
package com.baeldung.securitymanager;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.security.AccessControlException;
|
||||
|
||||
public class SecurityManagerUnitTest {
|
||||
|
||||
private static final String TESTING_SECURITY_POLICY = "file:src/test/resources/testing.policy";
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
System.setProperty("java.security.policy", TESTING_SECURITY_POLICY);
|
||||
System.setSecurityManager(new SecurityManager());
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
System.setSecurityManager(null);
|
||||
}
|
||||
|
||||
@Test(expected = AccessControlException.class)
|
||||
public void whenSecurityManagerIsActive_thenNetworkIsNotAccessibleByDefault() throws IOException {
|
||||
new URL("http://www.google.com").openConnection().connect();
|
||||
}
|
||||
|
||||
@Test(expected = AccessControlException.class)
|
||||
public void whenUnauthorizedClassTriesToAccessProtectedOperation_thenAnExceptionIsThrown() {
|
||||
new Service().operation();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
grant {
|
||||
// This is for testing purposes only.
|
||||
// It allows us to properly reset the security manager after the unit test completes.
|
||||
permission java.lang.RuntimePermission "setSecurityManager";
|
||||
};
|
|
@ -18,8 +18,7 @@
|
|||
<module>core-java-optional</module>
|
||||
<module>core-java-lang-operators</module>
|
||||
<module>core-java-networking-2</module>
|
||||
<module>core-java-security-manager</module>
|
||||
<module>core-java-date-operations</module>
|
||||
<module>core-java-date-operations-2</module>
|
||||
</modules>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -5,4 +5,10 @@ This module contains articles about core Kotlin.
|
|||
### Relevant articles:
|
||||
|
||||
- [Kotlin Scope Functions](https://www.baeldung.com/kotlin-scope-functions)
|
||||
- [Kotlin Annotations](https://www.baeldung.com/kotlin-annotations)
|
||||
- [Split a List into Parts in Kotlin](https://www.baeldung.com/kotlin-split-list-into-parts)
|
||||
- [String Comparison in Kotlin](https://www.baeldung.com/kotlin-string-comparison)
|
||||
- [Guide to JVM Platform Annotations in Kotlin](https://www.baeldung.com/kotlin-jvm-annotations)
|
||||
- [Finding an Element in a List Using Kotlin](https://www.baeldung.com/kotlin-finding-element-in-list)
|
||||
- [Kotlin Ternary Conditional Operator](https://www.baeldung.com/kotlin-ternary-conditional-operator)
|
||||
- More articles: [[<-- prev]](/core-kotlin)
|
||||
|
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.ternary
|
||||
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class TernaryOperatorTest {
|
||||
|
||||
@Test
|
||||
fun `using If`() {
|
||||
val a = true
|
||||
val result = if (a) "yes" else "no"
|
||||
assertEquals("yes", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `using When`() {
|
||||
val a = true
|
||||
val result = when(a) {
|
||||
true -> "yes"
|
||||
false -> "no"
|
||||
}
|
||||
assertEquals("yes", result)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
## Core Kotlin
|
||||
|
||||
This module contains articles about Object-Oriented Programming in Kotlin
|
||||
|
||||
### Relevant articles:
|
||||
|
||||
- [Generics in Kotlin](https://www.baeldung.com/kotlin-generics)
|
||||
- [Delegated Properties in Kotlin](https://www.baeldung.com/kotlin-delegated-properties)
|
||||
- [Delegation Pattern in Kotlin](https://www.baeldung.com/kotlin-delegation-pattern)
|
||||
- [[<-- Prev]](/core-kotlin-lang-oop)
|
|
@ -0,0 +1,25 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-kotlin-lang-oop-2</artifactId>
|
||||
<name>core-kotlin-lang-oop-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-kotlin-modules</groupId>
|
||||
<artifactId>core-kotlin-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,17 @@
|
|||
## Core Kotlin Lang OOP
|
||||
|
||||
This module contains articles about Object-Oriented Programming in Kotlin
|
||||
|
||||
### Relevant articles:
|
||||
|
||||
- [Data Classes in Kotlin](https://www.baeldung.com/kotlin-data-classes)
|
||||
- [Sealed Classes in Kotlin](https://www.baeldung.com/kotlin-sealed-classes)
|
||||
- [Extension Methods in Kotlin](https://www.baeldung.com/kotlin-extension-methods)
|
||||
- [Objects in Kotlin](https://www.baeldung.com/kotlin-objects)
|
||||
- [Working with Enums in Kotlin](https://www.baeldung.com/kotlin-enum)
|
||||
- [Kotlin Constructors](https://www.baeldung.com/kotlin-constructors)
|
||||
- [Kotlin Nested and Inner Classes](https://www.baeldung.com/kotlin-inner-classes)
|
||||
- [Guide to Kotlin Interfaces](https://www.baeldung.com/kotlin-interfaces)
|
||||
- [Inline Classes in Kotlin](https://www.baeldung.com/kotlin-inline-classes)
|
||||
- [Static Methods Behavior in Kotlin](https://www.baeldung.com/kotlin-static-methods)
|
||||
- More articles: [[next -->]](/core-kotlin-lang-oop-2)
|
|
@ -0,0 +1,25 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-kotlin-lang-oop</artifactId>
|
||||
<name>core-kotlin-lang-oop</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-kotlin-modules</groupId>
|
||||
<artifactId>core-kotlin-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue