diff --git a/README.md b/README.md index 378d77196a..1030cbb09c 100644 --- a/README.md +++ b/README.md @@ -20,17 +20,22 @@ In additional to Spring, the following technologies are in focus: `core Java`, ` Building the project ==================== -To do the full build, do: `mvn install -Pdefault -Dgib.enabled=false` +To do the full build, do: `mvn clean install` Building a single module ==================== -To build a specific module run the command: `mvn clean install -Dgib.enabled=false` in the module directory +To build a specific module run the command: `mvn clean install` in the module directory Running a Spring Boot module ==================== -To run a Spring Boot module run the command: `mvn spring-boot:run -Dgib.enabled=false` in the module directory +To run a Spring Boot module run the command: `mvn spring-boot:run` in the module directory + +#Running Tests + +The command `mvn clean install` will run the unit tests in a module. +To run the integration tests, use the command `mvn clean install -Pintegration-lite-first` diff --git a/apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesIntegrationTest.java b/apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesLiveTest.java similarity index 98% rename from apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesIntegrationTest.java rename to apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesLiveTest.java index b96d2c9b6a..359568db98 100644 --- a/apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesIntegrationTest.java +++ b/apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesLiveTest.java @@ -21,7 +21,7 @@ import java.util.stream.Stream; import static org.junit.Assert.assertEquals; -public class GeodeSamplesIntegrationTest { +public class GeodeSamplesLiveTest { ClientCache cache = null; Region region = null; diff --git a/apache-olingo/README.md b/apache-olingo/README.md new file mode 100644 index 0000000000..bfbdc97700 --- /dev/null +++ b/apache-olingo/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [OData Protocol Guide](https://www.baeldung.com/odata) diff --git a/apache-olingo/olingo2/pom.xml b/apache-olingo/olingo2/pom.xml index 4fc81e5e49..1efd4ea602 100644 --- a/apache-olingo/olingo2/pom.xml +++ b/apache-olingo/olingo2/pom.xml @@ -44,11 +44,6 @@ spring-boot-configuration-processor true - - org.projectlombok - lombok - true - org.springframework.boot spring-boot-starter-test @@ -68,16 +63,6 @@ - - org.apache.olingo - olingo-odata2-api - ${olingo2.version} - - - org.apache.olingo - olingo-odata2-jpa-processor-api - ${olingo2.version} - org.apache.olingo olingo-odata2-jpa-processor-core diff --git a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarMaker.java b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarMaker.java index 42a3eaa59d..e66d266062 100644 --- a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarMaker.java +++ b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarMaker.java @@ -12,25 +12,104 @@ import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; -import lombok.Data; - @Entity -@Data -@Table(name="car_maker") +@Table(name = "car_maker") public class CarMaker { - + @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; - + @NotNull - @Column(name="name") + @Column(name = "name") private String name; - - @OneToMany(mappedBy="maker", - orphanRemoval = true, - cascade=CascadeType.ALL) + + @OneToMany(mappedBy = "maker", orphanRemoval = true, cascade = CascadeType.ALL) private List models; - + + /** + * @return the id + */ + public Long getId() { + return id; + } + + /** + * @param id the id to set + */ + public void setId(Long id) { + this.id = id; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the models + */ + public List getModels() { + return models; + } + + /** + * @param models the models to set + */ + public void setModels(List models) { + this.models = models; + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((models == null) ? 0 : models.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + CarMaker other = (CarMaker) obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (models == null) { + if (other.models != null) + return false; + } else if (!models.equals(other.models)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } } diff --git a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarModel.java b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarModel.java index a4f2a04f6e..f9f563e01e 100644 --- a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarModel.java +++ b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarModel.java @@ -1,6 +1,5 @@ package org.baeldung.examples.olingo2.domain; - import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; @@ -11,28 +10,150 @@ import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.validation.constraints.NotNull; -import lombok.Data; - @Entity -@Data -@Table(name="car_model") +@Table(name = "car_model") public class CarModel { @Id - @GeneratedValue(strategy=GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.AUTO) private Long id; - + @NotNull private String name; - + @NotNull private Integer year; - + @NotNull private String sku; - - @ManyToOne(optional=false, fetch= FetchType.LAZY) - @JoinColumn(name="maker_fk") + + @ManyToOne(optional = false, fetch = FetchType.LAZY) + @JoinColumn(name = "maker_fk") private CarMaker maker; + /** + * @return the id + */ + public Long getId() { + return id; + } + + /** + * @param id the id to set + */ + public void setId(Long id) { + this.id = id; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the year + */ + public Integer getYear() { + return year; + } + + /** + * @param year the year to set + */ + public void setYear(Integer year) { + this.year = year; + } + + /** + * @return the sku + */ + public String getSku() { + return sku; + } + + /** + * @param sku the sku to set + */ + public void setSku(String sku) { + this.sku = sku; + } + + /** + * @return the maker + */ + public CarMaker getMaker() { + return maker; + } + + /** + * @param maker the maker to set + */ + public void setMaker(CarMaker maker) { + this.maker = maker; + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((maker == null) ? 0 : maker.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((sku == null) ? 0 : sku.hashCode()); + result = prime * result + ((year == null) ? 0 : year.hashCode()); + return result; + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + CarModel other = (CarModel) obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (maker == null) { + if (other.maker != null) + return false; + } else if (!maker.equals(other.maker)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (sku == null) { + if (other.sku != null) + return false; + } else if (!sku.equals(other.sku)) + return false; + if (year == null) { + if (other.year != null) + return false; + } else if (!year.equals(other.year)) + return false; + return true; + } + } diff --git a/apache-olingo/olingo2/src/main/resources/application.yml b/apache-olingo/olingo2/src/main/resources/application.yml index 21563a94fe..71df0c4166 100644 --- a/apache-olingo/olingo2/src/main/resources/application.yml +++ b/apache-olingo/olingo2/src/main/resources/application.yml @@ -1,5 +1,5 @@ server: - port: 8180 + port: 8080 spring: jersey: diff --git a/apache-olingo/olingo4/.gitignore b/apache-olingo/olingo4/.gitignore deleted file mode 100644 index 153c9335eb..0000000000 --- a/apache-olingo/olingo4/.gitignore +++ /dev/null @@ -1,29 +0,0 @@ -HELP.md -/target/ -!.mvn/wrapper/maven-wrapper.jar - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -/nbproject/private/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ -/build/ - -### VS Code ### -.vscode/ diff --git a/apache-olingo/olingo4/pom.xml b/apache-olingo/olingo4/pom.xml deleted file mode 100644 index 794aee0711..0000000000 --- a/apache-olingo/olingo4/pom.xml +++ /dev/null @@ -1,95 +0,0 @@ - - - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 2.1.3.RELEASE - - - org.baeldung.examples.olingo4 - olingo4-sample - 0.0.1-SNAPSHOT - olingo4-sample - Sample Olingo 4 Project - - - 1.8 - 4.5.0 - - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - - org.springframework.boot - spring-boot-configuration-processor - true - - - - com.h2database - h2 - runtime - - - - org.projectlombok - lombok - true - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.boot - spring-boot-starter-web - - - - org.apache.olingo - odata-server-api - ${odata.version} - - - org.apache.olingo - odata-server-core - ${odata.version} - runtime - - - - org.apache.olingo - odata-commons-api - ${odata.version} - - - org.apache.olingo - odata-commons-core - ${odata.version} - - - - commons-beanutils - commons-beanutils - 1.9.3 - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/DefaultODataFactory.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/DefaultODataFactory.java deleted file mode 100644 index 18f7f8ba24..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/DefaultODataFactory.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.baeldung.examples.olingo4; - -import org.apache.olingo.server.api.OData; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.stereotype.Component; - -/** - * Default implementation for ODataFactory - * @author Philippe - * - */ -@Component -public class DefaultODataFactory implements ODataFactory { - - @Override - public OData newInstance() { - return OData.newInstance(); - } - -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataFactory.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataFactory.java deleted file mode 100644 index 9acb4b8c5e..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataFactory.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung.examples.olingo4; - -import org.apache.olingo.server.api.OData; - -public interface ODataFactory { - - public OData newInstance(); -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataHttpHandlerFactory.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataHttpHandlerFactory.java deleted file mode 100644 index 27d0737c24..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataHttpHandlerFactory.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung.examples.olingo4; - -import org.apache.olingo.server.api.ODataHttpHandler; - -public interface ODataHttpHandlerFactory { - - ODataHttpHandler newInstance(); -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataHttpHandlerFactoryImpl.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataHttpHandlerFactoryImpl.java deleted file mode 100644 index 68d39dc052..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataHttpHandlerFactoryImpl.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.baeldung.examples.olingo4; - -import java.util.Collections; -import java.util.List; - -import org.apache.olingo.commons.api.edm.provider.CsdlEdmProvider; -import org.apache.olingo.server.api.OData; -import org.apache.olingo.server.api.ODataHttpHandler; -import org.apache.olingo.server.api.ServiceMetadata; -import org.apache.olingo.server.api.processor.Processor; - -import lombok.Builder; - -@Builder -public class ODataHttpHandlerFactoryImpl implements ODataHttpHandlerFactory { - - - private final ODataFactory odataFactory; - private final CsdlEdmProvider edmProvider; - private final List processors; - - public ODataHttpHandlerFactoryImpl(ODataFactory odataFactory,CsdlEdmProvider edmProvider, List processors) { - this.odataFactory = odataFactory; - this.edmProvider = edmProvider; - this.processors = processors; - } - - @Override - public ODataHttpHandler newInstance() { - - OData odata = odataFactory.newInstance(); - ServiceMetadata metadata = odata.createServiceMetadata(edmProvider, Collections.emptyList()); - ODataHttpHandler handler = odata.createHandler(metadata); - - // Register all available processors - processors.forEach(p -> handler.register(p)); - - - return handler; - } - -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataServiceConfiguration.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataServiceConfiguration.java deleted file mode 100644 index 0cde665359..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataServiceConfiguration.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.baeldung.examples.olingo4; - -import java.util.List; - -import javax.persistence.EntityManagerFactory; -import javax.servlet.http.HttpServlet; - -import org.apache.olingo.commons.api.edm.provider.CsdlEdmProvider; -import org.apache.olingo.server.api.processor.Processor; -import org.baeldung.examples.olingo4.ODataHttpHandlerFactoryImpl.ODataHttpHandlerFactoryImplBuilder; -import org.springframework.boot.web.servlet.ServletRegistrationBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class ODataServiceConfiguration { - - @Bean - public ServletRegistrationBean odataServletRegistration(ODataHttpHandlerFactory factory) { - ServletRegistrationBean srb = - new ServletRegistrationBean<>(new ODataServlet(factory), "/odata/*"); - srb.setLoadOnStartup(1); - return srb; - } - - @Bean - public ODataHttpHandlerFactory httpHandlerFactory(CsdlEdmProvider edmProvider, ODataFactory odataFactory, List processors) { - return new ODataHttpHandlerFactoryImplBuilder() - .edmProvider(edmProvider) - .odataFactory(odataFactory) - .processors(processors) - .build(); - } - -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataServlet.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataServlet.java deleted file mode 100644 index c379124541..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataServlet.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * - */ -package org.baeldung.examples.olingo4; - -import java.io.IOException; - -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.EntityTransaction; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.olingo.server.api.ODataHttpHandler; - -/** - * @author Philippe - * - */ -public class ODataServlet extends HttpServlet { - - private static final long serialVersionUID = 1L; - private final ODataHttpHandlerFactory odataHttpHandlerFactory; - - - public ODataServlet(ODataHttpHandlerFactory factory) { - this.odataHttpHandlerFactory = factory; - } - - @Override - protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - - ODataHttpHandler handler = odataHttpHandlerFactory.newInstance(); - handler.process(req, resp); - } -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarMaker.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarMaker.java deleted file mode 100644 index 79825b4556..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarMaker.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.baeldung.examples.olingo4.domain; - -import java.util.List; - -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToMany; -import javax.persistence.Table; -import javax.validation.constraints.NotNull; - -import lombok.Data; - -@Entity -@Data -@Table(name="car_maker") -public class CarMaker { - - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - private Long id; - - @NotNull - @Column(name="name") - private String name; - - @OneToMany(mappedBy="maker", - orphanRemoval = true, - cascade=CascadeType.ALL) - private List models; - - -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarModel.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarModel.java deleted file mode 100644 index a9254e48b9..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarModel.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.baeldung.examples.olingo4.domain; - - -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; -import javax.validation.constraints.NotNull; - -import lombok.Data; - -@Entity -@Data -@Table(name="car_model") -public class CarModel { - - @Id - @GeneratedValue(strategy=GenerationType.AUTO) - private Long id; - - @NotNull - private String name; - - @NotNull - private Integer year; - - @NotNull - private String sku; - - @ManyToOne(optional=false, fetch= FetchType.EAGER ) - @JoinColumn(name="maker_fk") - private CarMaker maker; - -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/EdmTypeMapper.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/EdmTypeMapper.java deleted file mode 100644 index 95797752a2..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/EdmTypeMapper.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.baeldung.examples.olingo4.edm; - -import java.util.Collections; -import java.util.Date; -import java.util.Map; -import java.util.UUID; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import java.sql.Time; -import java.util.AbstractMap.SimpleEntry; - -import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind; -import org.springframework.stereotype.Component; - -@Component -public class EdmTypeMapper { - - public EdmPrimitiveTypeKind java2edm(Class clazz) { - EdmPrimitiveTypeKind result = java2edm.get(clazz); - if ( result == null ) { - throw new IllegalArgumentException("[E19] Unsupported class mapping: class=" + clazz); - } - else { - return result; - } - } - - // Static map used generate attribute metadada based on Java types - static Map,EdmPrimitiveTypeKind> java2edm = Collections - .unmodifiableMap(Stream.of( - new SimpleEntry<>(Boolean.class,EdmPrimitiveTypeKind.Boolean), - new SimpleEntry<>(Byte.class,EdmPrimitiveTypeKind.SByte), - new SimpleEntry<>(Date.class,EdmPrimitiveTypeKind.Date), - new SimpleEntry<>(Time.class,EdmPrimitiveTypeKind.TimeOfDay), - new SimpleEntry<>(Number.class,EdmPrimitiveTypeKind.Decimal), - new SimpleEntry<>(Float.class,EdmPrimitiveTypeKind.Single), - new SimpleEntry<>(Double.class,EdmPrimitiveTypeKind.Double), - new SimpleEntry<>(UUID.class,EdmPrimitiveTypeKind.Guid), - new SimpleEntry<>(Short.class,EdmPrimitiveTypeKind.Int16), - new SimpleEntry<>(Integer.class,EdmPrimitiveTypeKind.Int32), - new SimpleEntry<>(Long.class,EdmPrimitiveTypeKind.Int64), - new SimpleEntry<>(String.class,EdmPrimitiveTypeKind.String) - - ).collect(Collectors.toMap((e)-> e.getKey(),(e)-> e.getValue()))); - -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/JpaEdmProvider.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/JpaEdmProvider.java deleted file mode 100644 index 4cd979e931..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/JpaEdmProvider.java +++ /dev/null @@ -1,269 +0,0 @@ -package org.baeldung.examples.olingo4.edm; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import javax.persistence.EntityManagerFactory; -import javax.persistence.metamodel.Attribute.PersistentAttributeType; -import javax.persistence.metamodel.EntityType; -import javax.persistence.metamodel.Metamodel; -import javax.persistence.metamodel.PluralAttribute; -import javax.persistence.metamodel.SingularAttribute; - -import org.apache.olingo.commons.api.edm.FullQualifiedName; -import org.apache.olingo.commons.api.edm.provider.CsdlAbstractEdmProvider; -import org.apache.olingo.commons.api.edm.provider.CsdlEntityContainer; -import org.apache.olingo.commons.api.edm.provider.CsdlEntityContainerInfo; -import org.apache.olingo.commons.api.edm.provider.CsdlEntitySet; -import org.apache.olingo.commons.api.edm.provider.CsdlEntityType; -import org.apache.olingo.commons.api.edm.provider.CsdlNavigationProperty; -import org.apache.olingo.commons.api.edm.provider.CsdlProperty; -import org.apache.olingo.commons.api.edm.provider.CsdlPropertyRef; -import org.apache.olingo.commons.api.edm.provider.CsdlSchema; -import org.apache.olingo.commons.api.ex.ODataException; -import org.springframework.stereotype.Component; - -@Component -public class JpaEdmProvider extends CsdlAbstractEdmProvider { - - EntityManagerFactory emf; - - // - private EdmTypeMapper typeMapper; - - // Service Namespace - public static final String NAMESPACE = "Baeldung.OData"; - - // EDM Container - public static final String CONTAINER_NAME = "Cars"; - public static final FullQualifiedName CONTAINER = new FullQualifiedName(NAMESPACE, CONTAINER_NAME); - - // Caches of OData types by it fully qualified name - private Map cdslName2Type = new HashMap<>(); - - public JpaEdmProvider(EntityManagerFactory emf, EdmTypeMapper mapper) { - this.emf = emf; - this.typeMapper = mapper; - } - - /* (non-Javadoc) - * @see org.apache.olingo.commons.api.edm.provider.CsdlAbstractEdmProvider#getEntitySet(org.apache.olingo.commons.api.edm.FullQualifiedName, java.lang.String) - */ - @Override - public CsdlEntitySet getEntitySet(FullQualifiedName entityContainer, String entitySetName) throws ODataException { - - if (entityContainer.equals(CONTAINER)) { - - EntityType e = emf.getMetamodel() - .getEntities() - .stream() - .filter((ent) -> (ent.getName() + "s") - .equals(entitySetName)) - .findFirst() - .orElse(null); - - if (e != null) { - CsdlEntitySet entitySet = new CsdlEntitySet(); - entitySet - .setName(entitySetName) - .setType(new FullQualifiedName(NAMESPACE, e.getName())); - return entitySet; - } - } - - return null; - } - - /* (non-Javadoc) - * @see org.apache.olingo.commons.api.edm.provider.CsdlAbstractEdmProvider#getEntityContainerInfo(org.apache.olingo.commons.api.edm.FullQualifiedName) - */ - @Override - public CsdlEntityContainerInfo getEntityContainerInfo(FullQualifiedName entityContainerName) throws ODataException { - - // This method is invoked when displaying the Service Document at e.g. http://localhost:8080/DemoService/DemoService.svc - if (entityContainerName == null || entityContainerName.equals(CONTAINER)) { - CsdlEntityContainerInfo entityContainerInfo = new CsdlEntityContainerInfo(); - entityContainerInfo.setContainerName(CONTAINER); - return entityContainerInfo; - } - - return null; - } - - /* (non-Javadoc) - * @see org.apache.olingo.commons.api.edm.provider.CsdlAbstractEdmProvider#getSchemas() - */ - @Override - public List getSchemas() throws ODataException { - // create Schema - CsdlSchema schema = new CsdlSchema(); - schema.setNamespace(NAMESPACE); - - // add EntityTypes - List entityTypes = emf.getMetamodel() - .getEntities() - .stream() - .map((e) -> { - try { - return getEntityType(new FullQualifiedName(NAMESPACE, e.getName())); - } catch (ODataException oe) { - throw new RuntimeException(oe); - } - }) - .collect(Collectors.toList()); - - schema.setEntityTypes(entityTypes); - - // add EntityContainer - schema.setEntityContainer(getEntityContainer()); - - // finally - List schemas = new ArrayList(); - schemas.add(schema); - - return schemas; - } - - /* (non-Javadoc) - * @see org.apache.olingo.commons.api.edm.provider.CsdlAbstractEdmProvider#getEntityContainer() - */ - @Override - public CsdlEntityContainer getEntityContainer() throws ODataException { - - - // add EntityTypes - List entitySets = emf.getMetamodel() - .getEntities() - .stream() - .map((e) -> { - try { - // Here we use a simple mapping strategy to map entity types to entity set names: - return getEntitySet(CONTAINER, e.getName() + "s"); - } catch (ODataException oe) { - throw new RuntimeException(oe); - } - }) - .collect(Collectors.toList()); - - // create EntityContainer - CsdlEntityContainer entityContainer = new CsdlEntityContainer(); - entityContainer.setName(CONTAINER_NAME); - entityContainer.setEntitySets(entitySets); - - return entityContainer; - } - - @Override - public CsdlEntityType getEntityType(FullQualifiedName entityTypeName) throws ODataException { - - CsdlEntityType result = cdslName2Type.get(entityTypeName); - if ( result != null ) { - return result; - } - - Metamodel mm = emf.getMetamodel(); - result = mm.getEntities() - .stream() - .filter(et -> entityTypeName.equals(new FullQualifiedName(NAMESPACE, et.getName()))) - .map(et -> buildODataType(et)) - .findFirst() - .orElse(null); - - // save for future use - cdslName2Type.put(entityTypeName, result); - return result; - - } - - /** - * Maps a JPA type to its OData counterpart. - * @param et - * @return - */ - protected CsdlEntityType buildODataType(EntityType et) { - - CsdlEntityType result = new CsdlEntityType(); - result.setName(et.getName()); - - // Process simple properties - List properties = et.getDeclaredSingularAttributes() - .stream() - .filter(attr -> attr.getPersistentAttributeType() == PersistentAttributeType.BASIC) - .map(attr -> buildBasicAttribute(et, attr)) - .collect(Collectors.toList()); - - result.setProperties(properties); - - // Process Ids - List ids = et.getDeclaredSingularAttributes() - .stream() - .filter(attr -> attr.getPersistentAttributeType() == PersistentAttributeType.BASIC && attr.isId()) - .map(attr -> buildRefAttribute(et, attr)) - .collect(Collectors.toList()); - - result.setKey(ids); - - // Process 1:N navs - List navs = et.getDeclaredPluralAttributes() - .stream() - .map(attr -> buildNavAttribute(et, attr)) - .collect(Collectors.toList()); - result.setNavigationProperties(navs); - - // Process N:1 navs - List navs2 = et.getDeclaredSingularAttributes() - .stream() - .filter(attr -> attr.getPersistentAttributeType() == PersistentAttributeType.MANY_TO_ONE) - .map(attr -> buildNavAttribute(et, attr)) - .collect(Collectors.toList()); - - result.getNavigationProperties().addAll(navs2); - - - return result; - } - - private CsdlProperty buildBasicAttribute(EntityType et, SingularAttribute attr) { - - CsdlProperty p = new CsdlProperty().setName(attr.getName()) - .setType(typeMapper.java2edm(attr.getJavaType()) - .getFullQualifiedName()) - .setNullable(et.getDeclaredSingularAttribute(attr.getName()) - .isOptional()); - - return p; - } - - private CsdlPropertyRef buildRefAttribute(EntityType et, SingularAttribute attr) { - - CsdlPropertyRef p = new CsdlPropertyRef().setName(attr.getName()); - - return p; - } - - // Build NavProperty for 1:N or M:N associations - private CsdlNavigationProperty buildNavAttribute(EntityType et, PluralAttribute attr) { - - CsdlNavigationProperty p = new CsdlNavigationProperty().setName(attr.getName()) - .setType(new FullQualifiedName(NAMESPACE, attr.getBindableJavaType().getSimpleName())) - .setCollection(true) - .setNullable(false); - - return p; - } - - // Build NavProperty for N:1 associations - private CsdlNavigationProperty buildNavAttribute(EntityType et, SingularAttribute attr) { - - CsdlNavigationProperty p = new CsdlNavigationProperty().setName(attr.getName()) - .setType(new FullQualifiedName(NAMESPACE, attr.getBindableJavaType().getSimpleName())) - .setCollection(false) - .setNullable(attr.isOptional()); - - return p; - } - -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityCollectionProcessor.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityCollectionProcessor.java deleted file mode 100644 index 4a4e5026f3..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityCollectionProcessor.java +++ /dev/null @@ -1,161 +0,0 @@ -package org.baeldung.examples.olingo4.processor; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.lang.reflect.InvocationTargetException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Collection; -import java.util.List; - -import javax.persistence.EntityManagerFactory; -import javax.persistence.metamodel.EntityType; -import javax.persistence.metamodel.SingularAttribute; - -import org.apache.commons.beanutils.PropertyUtils; -import org.apache.olingo.commons.api.data.ContextURL; -import org.apache.olingo.commons.api.data.Entity; -import org.apache.olingo.commons.api.data.EntityCollection; -import org.apache.olingo.commons.api.data.Property; -import org.apache.olingo.commons.api.data.ValueType; -import org.apache.olingo.commons.api.edm.EdmEntitySet; -import org.apache.olingo.commons.api.edm.EdmEntityType; -import org.apache.olingo.commons.api.edm.EdmNavigationProperty; -import org.apache.olingo.commons.api.ex.ODataRuntimeException; -import org.apache.olingo.commons.api.format.ContentType; -import org.apache.olingo.commons.api.http.HttpHeader; -import org.apache.olingo.commons.api.http.HttpStatusCode; -import org.apache.olingo.server.api.OData; -import org.apache.olingo.server.api.ODataApplicationException; -import org.apache.olingo.server.api.ODataLibraryException; -import org.apache.olingo.server.api.ODataRequest; -import org.apache.olingo.server.api.ODataResponse; -import org.apache.olingo.server.api.ServiceMetadata; -import org.apache.olingo.server.api.processor.CountEntityCollectionProcessor; -import org.apache.olingo.server.api.processor.EntityCollectionProcessor; -import org.apache.olingo.server.api.serializer.EntityCollectionSerializerOptions; -import org.apache.olingo.server.api.serializer.ODataSerializer; -import org.apache.olingo.server.api.serializer.SerializerResult; -import org.apache.olingo.server.api.uri.UriInfo; -import org.apache.olingo.server.api.uri.UriParameter; -import org.apache.olingo.server.api.uri.UriResource; -import org.apache.olingo.server.api.uri.UriResourceEntitySet; -import org.baeldung.examples.olingo4.repository.RepositoryRegistry; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Component; - -@Component -public class JpaEntityCollectionProcessor implements CountEntityCollectionProcessor { - - private OData odata; - private ServiceMetadata serviceMetadata; - private EntityManagerFactory emf; - private RepositoryRegistry repositoryRegistry; - private JpaEntityMapper entityMapper; - - public JpaEntityCollectionProcessor(EntityManagerFactory emf, RepositoryRegistry repositoryRegistry, JpaEntityMapper entityMapper) { - this.emf = emf; - this.repositoryRegistry = repositoryRegistry; - this.entityMapper = entityMapper; - } - - @Override - public void init(OData odata, ServiceMetadata serviceMetadata) { - this.odata = odata; - this.serviceMetadata = serviceMetadata; - } - - @Override - public void readEntityCollection(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType responseFormat) throws ODataApplicationException, ODataLibraryException { - - // 1st we have retrieve the requested EntitySet from the uriInfo object (representation of the parsed service URI) - List resourcePaths = uriInfo.getUriResourceParts(); - UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths.get(0); // in our example, the first segment is the EntitySet - EdmEntitySet edmEntitySet = uriResourceEntitySet.getEntitySet(); - - // 2nd: fetch the data from backend for this requested EntitySetName - // it has to be delivered as EntitySet object - EntityCollection entitySet = getData(edmEntitySet, uriInfo); - - // 3rd: create a serializer based on the requested format (json) - ODataSerializer serializer = odata.createSerializer(responseFormat); - - // 4th: Now serialize the content: transform from the EntitySet object to InputStream - EdmEntityType edmEntityType = edmEntitySet.getEntityType(); - ContextURL contextUrl = ContextURL.with() - .entitySet(edmEntitySet) - .build(); - - final String id = request.getRawBaseUri() + "/" + edmEntitySet.getName(); - EntityCollectionSerializerOptions opts = EntityCollectionSerializerOptions.with() - .id(id) - .contextURL(contextUrl) - .build(); - SerializerResult serializerResult = serializer.entityCollection(serviceMetadata, edmEntityType, entitySet, opts); - InputStream serializedContent = serializerResult.getContent(); - - // Finally: configure the response object: set the body, headers and status code - response.setContent(serializedContent); - response.setStatusCode(HttpStatusCode.OK.getStatusCode()); - response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString()); - - } - - @Override - public void countEntityCollection(ODataRequest request, ODataResponse response, UriInfo uriInfo) throws ODataApplicationException, ODataLibraryException { - - // 1st we have retrieve the requested EntitySet from the uriInfo object (representation of the parsed service URI) - List resourcePaths = uriInfo.getUriResourceParts(); - UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths.get(0); // in our example, the first segment is the EntitySet - EdmEntitySet edmEntitySet = uriResourceEntitySet.getEntitySet(); - - // 2nd: fetch the data from backend for this requested EntitySetName - Long count = getCount(edmEntitySet, uriInfo); - - // Finally: configure the response object: set the body, headers and status code - response.setContent(new ByteArrayInputStream(count.toString().getBytes())); - response.setStatusCode(HttpStatusCode.OK.getStatusCode()); - response.setHeader(HttpHeader.CONTENT_TYPE, "text/plain"); - - } - - /** - * Helper method to retrieve all entities of an entity set from an the backend database - * @param edmEntitySet - * @param uriInfo - * @return - */ - protected EntityCollection getData(EdmEntitySet edmEntitySet, UriInfo uriInfo) { - - EdmEntityType type = edmEntitySet.getEntityType(); - JpaRepository repo = (JpaRepository)repositoryRegistry.getRepositoryForEntity(type); - EntityCollection result = new EntityCollection(); - - repo.findAll() - .stream() - .forEach((it) -> result.getEntities() - .add(entityMapper.map2entity(edmEntitySet, it))); - - return result; - } - - - /** - * Helper method to get the total size of an entity set - * @param edmEntitySet - * @param uriInfo - * @return - */ - protected Long getCount(EdmEntitySet edmEntitySet, UriInfo uriInfo) { - - EdmEntityType type = edmEntitySet.getEntityType(); - JpaRepository repo = (JpaRepository)repositoryRegistry.getRepositoryForEntity(type); - EntityCollection result = new EntityCollection(); - - return repo.count(); - } - - - - -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityMapper.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityMapper.java deleted file mode 100644 index 1978aa4fd6..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityMapper.java +++ /dev/null @@ -1,93 +0,0 @@ -/** - * - */ -package org.baeldung.examples.olingo4.processor; - -import java.lang.reflect.InvocationTargetException; -import java.net.URI; -import java.net.URISyntaxException; - -import javax.persistence.EntityManagerFactory; -import javax.persistence.metamodel.EntityType; - -import org.apache.commons.beanutils.PropertyUtils; -import org.apache.olingo.commons.api.data.Entity; -import org.apache.olingo.commons.api.data.Property; -import org.apache.olingo.commons.api.data.ValueType; -import org.apache.olingo.commons.api.edm.EdmEntitySet; -import org.apache.olingo.commons.api.ex.ODataRuntimeException; -import org.springframework.stereotype.Component; - -/** - *

Helper class that converts a JPA entity into an OData entity using - * available metadata from the JPA's EntityManagerFactory.

- * - * @author Philippe - * - */ -@Component -public class JpaEntityMapper { - - private EntityManagerFactory emf; - - public JpaEntityMapper(EntityManagerFactory emf) { - this.emf = emf; - } - - - public Entity map2entity(EdmEntitySet edmEntitySet, Object entry) { - - EntityType et = emf.getMetamodel() - .entity(entry.getClass()); - - - Entity e = new Entity(); - try { - et.getDeclaredSingularAttributes().stream() - .forEach( (attr) -> { - if ( !attr.isAssociation()) { - Object v = getPropertyValue(entry,attr.getName()); - Property p = new Property(null, attr.getName(),ValueType.PRIMITIVE,v); - e.addProperty(p); - - if ( attr.isId()) { - e.setId(createId(edmEntitySet.getName(),v)); - } - } - }); - } catch (Exception ex) { - throw new ODataRuntimeException("[E141] Unable to create OData entity", ex); - } - - return e; - } - - - public Object getPropertyValue(Object entry, String name) { - try { - return PropertyUtils.getProperty(entry,name); - } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - throw new ODataRuntimeException("[E141] Unable to read property from entity, property=" + name, e); - } - } - - public void setPropertyValue(Object entry, String name,Object value) { - try { - PropertyUtils.setProperty(entry,name,value); - } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - throw new ODataRuntimeException("[E141] Unable to read property from entity, property=" + name, e); - } - } - - - private URI createId(String entitySetName, Object id) { - try { - return new URI(entitySetName + "(" + String.valueOf(id) + ")"); - } catch (URISyntaxException e) { - throw new ODataRuntimeException("[E177] Unable to create URI", e); - } - } - - - -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityProcessor.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityProcessor.java deleted file mode 100644 index 719e5de160..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityProcessor.java +++ /dev/null @@ -1,304 +0,0 @@ -/** - * - */ -package org.baeldung.examples.olingo4.processor; - -import java.io.InputStream; -import java.util.List; -import java.util.Locale; -import java.util.Optional; - -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.metamodel.SingularAttribute; - -import org.apache.olingo.commons.api.data.ContextURL; -import org.apache.olingo.commons.api.data.Entity; -import org.apache.olingo.commons.api.edm.EdmEntitySet; -import org.apache.olingo.commons.api.edm.EdmEntityType; -import org.apache.olingo.commons.api.edm.EdmNavigationProperty; -import org.apache.olingo.commons.api.ex.ODataRuntimeException; -import org.apache.olingo.commons.api.format.ContentType; -import org.apache.olingo.commons.api.http.HttpHeader; -import org.apache.olingo.commons.api.http.HttpStatusCode; -import org.apache.olingo.server.api.OData; -import org.apache.olingo.server.api.ODataApplicationException; -import org.apache.olingo.server.api.ODataLibraryException; -import org.apache.olingo.server.api.ODataRequest; -import org.apache.olingo.server.api.ODataResponse; -import org.apache.olingo.server.api.ServiceMetadata; -import org.apache.olingo.server.api.processor.EntityProcessor; -import org.apache.olingo.server.api.serializer.EntitySerializerOptions; -import org.apache.olingo.server.api.serializer.ODataSerializer; -import org.apache.olingo.server.api.serializer.SerializerResult; -import org.apache.olingo.server.api.uri.UriInfo; -import org.apache.olingo.server.api.uri.UriParameter; -import org.apache.olingo.server.api.uri.UriResource; -import org.apache.olingo.server.api.uri.UriResourceEntitySet; -import org.apache.olingo.server.api.uri.UriResourceNavigation; -import org.baeldung.examples.olingo4.repository.EdmEntityRepository; -import org.baeldung.examples.olingo4.repository.RepositoryRegistry; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Component; - -/** - * JpaEntityProcessor adapter. - *

This implementation is heavily based on the Tutorial available - * at Olingo's site. It is meant to be an starting point for an actual implementation.

- *

Please note that many features from a full-fledged are missing - * @author Philippe - * - */ -@Component -public class JpaEntityProcessor implements EntityProcessor { - - private EntityManagerFactory emf; - private OData odata; - private ServiceMetadata serviceMetadata; - private RepositoryRegistry registry; - private JpaEntityMapper entityMapper; - - public JpaEntityProcessor(EntityManagerFactory emf, RepositoryRegistry registry, JpaEntityMapper entityMapper) { - this.emf = emf; - this.registry = registry; - this.entityMapper = entityMapper; - } - - /* (non-Javadoc) - * @see org.apache.olingo.server.api.processor.Processor#init(org.apache.olingo.server.api.OData, org.apache.olingo.server.api.ServiceMetadata) - */ - @Override - public void init(OData odata, ServiceMetadata serviceMetadata) { - this.odata = odata; - this.serviceMetadata = serviceMetadata; - - } - - /* (non-Javadoc) - * @see org.apache.olingo.server.api.processor.EntityProcessor#readEntity(org.apache.olingo.server.api.ODataRequest, org.apache.olingo.server.api.ODataResponse, org.apache.olingo.server.api.uri.UriInfo, org.apache.olingo.commons.api.format.ContentType) - */ - @Override - public void readEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType responseFormat) throws ODataApplicationException, ODataLibraryException { - - // First, we have to figure out which entity is requested - List resourceParts = uriInfo.getUriResourceParts(); - InputStream entityStream; - - UriResourceEntitySet rootResourceEntitySet = (UriResourceEntitySet) resourceParts.get(0); - EdmEntitySet rootEntitySet = rootResourceEntitySet.getEntitySet(); - List rootPredicates = rootResourceEntitySet.getKeyPredicates(); - - if ( resourceParts.size() == 1 ) { - entityStream = readRootEntity(rootEntitySet,rootPredicates,responseFormat); - } - else if ( resourceParts.size() == 2 ) { - UriResource part = resourceParts.get(1); - if ( !(part instanceof UriResourceNavigation)) { - throw new ODataRuntimeException("[E103] part type not supported: class=" + part.getClass().getName()); - } - - UriResourceNavigation navSegment = (UriResourceNavigation)part; - entityStream = readRelatedEntity(request, rootEntitySet,rootPredicates,navSegment.getProperty(),navSegment.getKeyPredicates(),responseFormat); - } - else { - // For now, we'll only allow navigation just to directly linked navs - throw new ODataApplicationException("[E109] Multi-level navigation not supported", HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), Locale.ROOT); - } - - //4. configure the response object - response.setContent(entityStream); - response.setStatusCode(HttpStatusCode.OK.getStatusCode()); - response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString()); - - } - - - // Lookup the EntitySet associated with an EntityType - // In our example, we assume we have only one entityset for each entity type - private EdmEntitySet entitySetFromType(EdmEntityType type) { - return serviceMetadata - .getEdm() - .getEntityContainer() - .getEntitySets() - .stream() - .filter((s) -> s.getEntityType().getName().equals(type.getName())) - .findFirst() - .orElseThrow(() -> new ODataRuntimeException("[E144] No entity set found for type " + type.getFullQualifiedName())); - } - - // - // private boolean isOne2ManyProperty(EdmEntityType entityType, EdmNavigationProperty property) { - // return entityType.getProperty(property.getName()) != null && property.isCollection(); - //} - - @SuppressWarnings({ "rawtypes", "unchecked" }) - private InputStream readRootEntity(EdmEntitySet entitySet, List keyPredicates,ContentType responseFormat) throws ODataApplicationException, ODataLibraryException { - EdmEntityType type = entitySet.getEntityType(); - JpaRepository repo = registry.getRepositoryForEntity(type); - - // Get key value - Long keyValue = getEntityKey(keyPredicates); - Optional entry = repo.findById(keyValue); - if ( !entry.isPresent()) { - throw new ODataApplicationException( - "[E116] NO entity found for the given key", - HttpStatusCode.NOT_FOUND.getStatusCode(), - Locale.ENGLISH); - } - - Entity e = entityMapper.map2entity(entitySet, entry.get()); - return serializeEntity(entitySet,e,responseFormat); - } - - private InputStream serializeEntity(EdmEntitySet entitySet, Entity entity,ContentType responseFormat) throws ODataApplicationException, ODataLibraryException { - ContextURL contextUrl = ContextURL.with().entitySet(entitySet).build(); - // expand and select currently not supported - EntitySerializerOptions options = EntitySerializerOptions - .with() - .contextURL(contextUrl) - .build(); - - ODataSerializer serializer = odata.createSerializer(responseFormat); - - SerializerResult serializerResult = serializer.entity(serviceMetadata, entitySet.getEntityType(), entity, options); - return serializerResult.getContent(); - - } - -// @SuppressWarnings("unchecked") -// protected InputStream readRelatedEntities(EdmEntitySet rootEntitySet, List rootPredicates, EdmNavigationProperty property, ContentType responseFormat) throws ODataApplicationException { -// -// Object jpaEntity = readJPAEntity(rootEntitySet, rootPredicates); -// try { -// Collection set = (Collection)PropertyUtils.getProperty(jpaEntity, property.getName()); -// EdmEntitySet entitySet = entitySetFromType(property.getType()); -// ContextURL contextUrl = ContextURL -// .with() -// .entitySet(entitySet) -// .build(); -// -// EntityCollectionSerializerOptions options = EntityCollectionSerializerOptions -// .with() -// .contextURL(contextUrl) -// .build(); -// -// EntityCollection result = new EntityCollection(); -// -// set.stream() -// .map((o) -> this.entityMapper.map2entity(entitySet, o)) -// .forEach((e) -> result.getEntities().add(e)); -// -// ODataSerializer serializer = odata.createSerializer(responseFormat); -// SerializerResult serializerResult = serializer.entityCollection(serviceMetadata, property.getType(), result, options); -// return serializerResult.getContent(); -// } -// catch(Exception ex) { -// throw new ODataRuntimeException("[E181] Error accessing database", ex); -// } -// } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - private InputStream readRelatedEntity(ODataRequest request, EdmEntitySet entitySet, List rootPredicates, EdmNavigationProperty property, List parentPredicates, ContentType responseFormat) throws ODataApplicationException, ODataLibraryException { - - - JpaRepository repo = (JpaRepository)registry.getRepositoryForEntity(entitySet.getEntityType()); - EdmEntityRepository relatedRepo = (EdmEntityRepository)registry.getRepositoryForEntity(property.getType()); - - // We assume here that we have a bi-directional 1:N relationship, so we'll - // always have a property in the child entity that points to the parent - Class rootClass = ((EdmEntityRepository)repo).getEntityClass(); - Class relatedClass = ((EdmEntityRepository)relatedRepo).getEntityClass(); - - SingularAttribute fk = emf.getMetamodel() - .entity(rootClass) - .getSingularAttributes() - .stream() - .filter((attr) -> { - boolean b = attr.isAssociation() && attr.getJavaType().isAssignableFrom(relatedClass); - return b; - }) - .findFirst() - .orElse(null); - - if ( fk == null ) { - throw new ODataRuntimeException("[E230] No singular attribute of child class '" + relatedClass.getName() + "' found" ); - } - - Long pkValue = getEntityKey(rootPredicates); - EntityManager em = this.emf.createEntityManager(); - try { - // Read data from DB - Object root = em.find(rootClass, pkValue); - Object related = this.entityMapper.getPropertyValue(root, fk.getName()); - - EdmEntitySet relatedEntitySet = entitySetFromType(property.getType()); - Entity e = entityMapper.map2entity(relatedEntitySet, related); - return serializeEntity(relatedEntitySet,e,responseFormat); - } - finally { - em.close(); - } - } - -// @SuppressWarnings("unchecked") -// private Object readJPAEntity(EdmEntitySet edmEntitySet, List keyPredicates) throws ODataApplicationException { -// EdmEntityType type = edmEntitySet.getEntityType(); -// JpaRepository repo = (JpaRepository)registry.getRepositoryForEntity(type); -// -// // Get key value -// Object keyValue = getEntityKey(type,keyPredicates); -// Object entry = repo -// .findById(keyValue) -// .orElseThrow( -// () -> new ODataApplicationException("[E116] NO entity found for the given key", -// HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ENGLISH)); -// -// return entry; -// } - - private Long getEntityKey(List keyPredicates) { - - if ( keyPredicates.size() > 1 ) { - throw new ODataRuntimeException("[E131] Composite keys are not supported"); - } - - // For now, we'll assume we only have numeric keys. - UriParameter keyParam = keyPredicates.get(0); - try { - return Long.parseLong(keyParam.getText()); - } - catch(NumberFormatException nfe) { - throw new ODataRuntimeException("[E140] Invalid key value. Only numeric keys are supported by this service"); - } - - - } - - /* (non-Javadoc) - * @see org.apache.olingo.server.api.processor.EntityProcessor#createEntity(org.apache.olingo.server.api.ODataRequest, org.apache.olingo.server.api.ODataResponse, org.apache.olingo.server.api.uri.UriInfo, org.apache.olingo.commons.api.format.ContentType, org.apache.olingo.commons.api.format.ContentType) - */ - @Override - public void createEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType requestFormat, ContentType responseFormat) throws ODataApplicationException, ODataLibraryException { - // TODO Auto-generated method stub - - } - - /* (non-Javadoc) - * @see org.apache.olingo.server.api.processor.EntityProcessor#updateEntity(org.apache.olingo.server.api.ODataRequest, org.apache.olingo.server.api.ODataResponse, org.apache.olingo.server.api.uri.UriInfo, org.apache.olingo.commons.api.format.ContentType, org.apache.olingo.commons.api.format.ContentType) - */ - @Override - public void updateEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType requestFormat, ContentType responseFormat) throws ODataApplicationException, ODataLibraryException { - // TODO Auto-generated method stub - - } - - /* (non-Javadoc) - * @see org.apache.olingo.server.api.processor.EntityProcessor#deleteEntity(org.apache.olingo.server.api.ODataRequest, org.apache.olingo.server.api.ODataResponse, org.apache.olingo.server.api.uri.UriInfo) - */ - @Override - public void deleteEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo) throws ODataApplicationException, ODataLibraryException { - // TODO Auto-generated method stub - - } - -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/CarMakerRepository.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/CarMakerRepository.java deleted file mode 100644 index 1bde9f148c..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/CarMakerRepository.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.examples.olingo4.repository; - -import org.baeldung.examples.olingo4.domain.CarMaker; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -import org.springframework.stereotype.Repository; - -@Repository -public interface CarMakerRepository extends EdmEntityRepository, JpaRepository, JpaSpecificationExecutor { - - public default String getEdmEntityName() { return CarMaker.class.getSimpleName();} - @Override - default Class getEntityClass() { - return CarMaker.class; - } -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/CarModelRepository.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/CarModelRepository.java deleted file mode 100644 index 247bf6e77b..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/CarModelRepository.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.baeldung.examples.olingo4.repository; - -import java.util.List; - -import org.baeldung.examples.olingo4.domain.CarModel; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -import org.springframework.stereotype.Repository; - -@Repository -public interface CarModelRepository extends EdmEntityRepository, JpaRepository, JpaSpecificationExecutor { - - public List findByMakerId(Long makerId); - - public default String getEdmEntityName() { return CarModel.class.getSimpleName();} - - @Override - default Class getEntityClass() { - return CarModel.class; - } - -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/EdmEntityRepository.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/EdmEntityRepository.java deleted file mode 100644 index dbfd0e6f93..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/EdmEntityRepository.java +++ /dev/null @@ -1,17 +0,0 @@ -/** - * - */ -package org.baeldung.examples.olingo4.repository; - - -/** - * @author Philippe - * - */ -public interface EdmEntityRepository { - - public String getEdmEntityName(); - public Class getEntityClass(); - - -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/RepositoryRegistry.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/RepositoryRegistry.java deleted file mode 100644 index e3bb172e3a..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/RepositoryRegistry.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.baeldung.examples.olingo4.repository; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.olingo.commons.api.edm.EdmEntityType; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Component; - -@Component -public class RepositoryRegistry { - - private Map> repositoriesByClassName = new HashMap<>(); - - public RepositoryRegistry(List> allRepositories) { - - allRepositories.stream() - .forEach((r) -> - repositoriesByClassName.put(r.getEdmEntityName(),(JpaRepository)r)); - - } - - - public JpaRepository getRepositoryForEntity(EdmEntityType entityType) { - JpaRepository repo = repositoriesByClassName.get(entityType.getName()); - return repo; - } -} diff --git a/apache-olingo/olingo4/src/main/resources/application.properties b/apache-olingo/olingo4/src/main/resources/application.properties deleted file mode 100644 index 02c7fe5c4d..0000000000 --- a/apache-olingo/olingo4/src/main/resources/application.properties +++ /dev/null @@ -1,9 +0,0 @@ -server: - port: 8080 - -spring: - jpa: - show-sql: true - open-in-view: true - hibernate: - ddl-auto: update diff --git a/apache-olingo/olingo4/src/main/resources/data.sql b/apache-olingo/olingo4/src/main/resources/data.sql deleted file mode 100644 index 327f2688c5..0000000000 --- a/apache-olingo/olingo4/src/main/resources/data.sql +++ /dev/null @@ -1,12 +0,0 @@ -insert into car_maker(id,name) values (1,'Special Motors'); -insert into car_maker(id,name) values (2,'BWM'); -insert into car_maker(id,name) values (3,'Dolores'); - -insert into car_model(id,maker_fk,name,sku,year) values(1,1,'Muze','SM001',2018); -insert into car_model(id,maker_fk,name,sku,year) values(2,1,'Empada','SM002',2008); - -insert into car_model(id,maker_fk,name,sku,year) values(4,2,'BWM-100','BWM100',2008); -insert into car_model(id,maker_fk,name,sku,year) values(5,2,'BWM-200','BWM200',2009); -insert into car_model(id,maker_fk,name,sku,year) values(6,2,'BWM-300','BWM300',2008); - -alter sequence hibernate_sequence restart with 100; \ No newline at end of file diff --git a/apache-olingo/olingo4/src/test/java/org/baeldung/examples/olingo4/Olingo4SampleApplicationTests.java b/apache-olingo/olingo4/src/test/java/org/baeldung/examples/olingo4/Olingo4SampleApplicationTests.java deleted file mode 100644 index 5d23a4148e..0000000000 --- a/apache-olingo/olingo4/src/test/java/org/baeldung/examples/olingo4/Olingo4SampleApplicationTests.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.examples.olingo4; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class Olingo4SampleApplicationTests { - - @Test - public void contextLoads() { - } - -} diff --git a/clojure/ring/.gitignore b/clojure/ring/.gitignore new file mode 100644 index 0000000000..d18f225992 --- /dev/null +++ b/clojure/ring/.gitignore @@ -0,0 +1,12 @@ +/target +/classes +/checkouts +profiles.clj +pom.xml +pom.xml.asc +*.jar +*.class +/.lein-* +/.nrepl-port +.hgignore +.hg/ diff --git a/clojure/ring/README.md b/clojure/ring/README.md new file mode 100644 index 0000000000..20263c6b95 --- /dev/null +++ b/clojure/ring/README.md @@ -0,0 +1,19 @@ +# Clojure Ring Examples + +This project acts as a set of examples for the Clojure Ring library. + +## Runing the examples + +The examples can all be run from the Leiningen REPL. + +Firstly, start the REPL with `lein repl`. Then the examples can be executed with: + +* `(run simple-handler)` - A simple handler that just echos a constant string to the client +* `(run check-ip-handler)` - A handler that echos the clients IP Address back to them +* `(run echo-handler)` - A handler that echos the value of the "input" parameter back +* `(run request-count-handler)` - A handler with a session that tracks how many times this session has requested this handler + +In all cases, the handlers can be accessed on http://localhost:3000. + +## Relevant Articles +- [Writing Clojure Webapps with Ring](https://www.baeldung.com/clojure-ring) diff --git a/clojure/ring/project.clj b/clojure/ring/project.clj new file mode 100644 index 0000000000..7f2fcc4263 --- /dev/null +++ b/clojure/ring/project.clj @@ -0,0 +1,8 @@ +(defproject baeldung-ring "0.1.0-SNAPSHOT" + :dependencies [[org.clojure/clojure "1.10.0"] + [ring/ring-core "1.7.1"] + [ring/ring-jetty-adapter "1.7.1"] + [ring/ring-devel "1.7.1"]] + :plugins [[lein-ring "0.12.5"]] + :ring {:handler ring.core/simple-handler} + :repl-options {:init-ns ring.core}) diff --git a/clojure/ring/src/ring/core.clj b/clojure/ring/src/ring/core.clj new file mode 100644 index 0000000000..a56e2f2bde --- /dev/null +++ b/clojure/ring/src/ring/core.clj @@ -0,0 +1,48 @@ +(ns ring.core + (:use ring.adapter.jetty + [ring.middleware.content-type] + [ring.middleware.cookies] + [ring.middleware.params] + [ring.middleware.session] + [ring.middleware.session.cookie] + [ring.util.response])) + +;; Handler that just echos back the string "Hello World" +(defn simple-handler [request] + {:status 200 + :headers {"Content-Type" "text/plain"} + :body "Hello World"}) + +;; Handler that echos back the clients IP Address +;; This demonstrates building responses properly, and extracting values from the request +(defn check-ip-handler [request] + (content-type + (response (:remote-addr request)) + "text/plain")) + +;; Handler that echos back the incoming parameter "input" +;; This demonstrates middleware chaining and accessing parameters +(def echo-handler + (-> (fn [{params :params}] + (content-type + (response (get params "input")) + "text/plain")) + (wrap-params {:encoding "UTF-8"}) + )) + +;; Handler that keeps track of how many times each session has accessed the service +;; This demonstrates cookies and sessions +(def request-count-handler + (-> (fn [{session :session}] + (let [count (:count session 0) + session (assoc session :count (inc count))] + (-> (response (str "You accessed this page " count " times.")) + (assoc :session session)))) + wrap-cookies + (wrap-session {:cookie-attrs {:max-age 3600}}) + )) + +;; Run the provided handler on port 3000 +(defn run + [h] + (run-jetty h {:port 3000})) diff --git a/core-java-lang/src/main/java/com/baeldung/error/ErrorGenerator.java b/core-java-lang/src/main/java/com/baeldung/error/ErrorGenerator.java new file mode 100644 index 0000000000..58cbe22df5 --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/error/ErrorGenerator.java @@ -0,0 +1,15 @@ +package com.baeldung.error; + +public class ErrorGenerator { + public void throwException() throws Exception { + throw new Exception("checked"); + } + + public void throwRuntimeException() { + throw new RuntimeException("unchecked"); + } + + public void throwError() { + throw new Error("unchecked"); + } +} diff --git a/core-java-lang/src/test/java/com/baeldung/error/ErrorGeneratorUnitTest.java b/core-java-lang/src/test/java/com/baeldung/error/ErrorGeneratorUnitTest.java new file mode 100644 index 0000000000..2a7c24f5fa --- /dev/null +++ b/core-java-lang/src/test/java/com/baeldung/error/ErrorGeneratorUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.error; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class ErrorGeneratorUnitTest { + + private ErrorGenerator errorGenerator; + + @Before + public void setUp() { + errorGenerator = new ErrorGenerator(); + } + + @Test + public void whenCheckedException_thenIsCaughtByCatchException() { + try { + errorGenerator.throwException(); + } catch (Exception e) { + // caught! -> test pass + } + } + + @Test + public void whenUncheckedException_thenIsCaughtByCatchException() { + try { + errorGenerator.throwRuntimeException(); + } catch (Exception e) { + // caught! -> test pass + } + } + + @Test(expected = Error.class) + public void whenError_thenIsNotCaughtByCatchException() { + try { + errorGenerator.throwError(); + } catch (Exception e) { + Assert.fail(); // errors are not caught by catch exception + } + } + + @Test + public void whenError_thenIsCaughtByCatchError() { + try { + errorGenerator.throwError(); + } catch (Error e) { + // caught! -> test pass + } + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-9/README.md b/core-java-modules/core-java-9/README.md index 5715520bae..8b52ce79b4 100644 --- a/core-java-modules/core-java-9/README.md +++ b/core-java-modules/core-java-9/README.md @@ -28,6 +28,6 @@ - [Java 9 Convenience Factory Methods for Collections](https://www.baeldung.com/java-9-collections-factory-methods) - [Java 9 Stream API Improvements](https://www.baeldung.com/java-9-stream-api) - [A Guide to Java 9 Modularity](https://www.baeldung.com/java-9-modularity) -- [Java 9 Platform Module API](https://www.baeldung.com/java-9-module-api) +- [Java 9 java.lang.Module API](https://www.baeldung.com/java-9-module-api) - [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api) - [Filtering a Stream of Optionals in Java](https://www.baeldung.com/java-filter-stream-of-optional) diff --git a/core-java-modules/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLogger.java b/core-java-modules/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLogger.java index df41e071fd..db19613c94 100644 --- a/core-java-modules/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLogger.java +++ b/core-java-modules/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLogger.java @@ -4,6 +4,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ResourceBundle; +import java.text.MessageFormat; public class Slf4jLogger implements System.Logger { @@ -74,26 +75,27 @@ public class Slf4jLogger implements System.Logger { if (!isLoggable(level)) { return; } + String message = MessageFormat.format(format, params); switch (level) { case TRACE: - logger.trace(format, params); + logger.trace(message); break; case DEBUG: - logger.debug(format, params); + logger.debug(message); break; case INFO: - logger.info(format, params); + logger.info(message); break; case WARNING: - logger.warn(format, params); + logger.warn(message); break; case ERROR: - logger.error(format, params); + logger.error(message); break; case ALL: default: - logger.info(format, params); + logger.info(message); } } } diff --git a/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/java/list/WaysToIterateUnitTest.java b/core-java-modules/core-java-collections-list-2/src/test/java/com/baeldung/java/list/WaysToIterateUnitTest.java similarity index 100% rename from core-java-modules/core-java-collections-list/src/test/java/com/baeldung/java/list/WaysToIterateUnitTest.java rename to core-java-modules/core-java-collections-list-2/src/test/java/com/baeldung/java/list/WaysToIterateUnitTest.java diff --git a/core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exception/numberformat/NumberFormatExceptionUnitTest.java b/core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exception/numberformat/NumberFormatExceptionUnitTest.java index a1e8c7c30f..cb26bf451a 100644 --- a/core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exception/numberformat/NumberFormatExceptionUnitTest.java +++ b/core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exception/numberformat/NumberFormatExceptionUnitTest.java @@ -36,7 +36,7 @@ public class NumberFormatExceptionUnitTest { @Test(expected = NumberFormatException.class) public void givenParseIntMethod_whenUnderscoreInInput_thenFail() { - int bIntPrim = Integer.parseInt("6_000"); + int bIntPrim = Integer.parseInt("_6000"); } @Test(expected = NumberFormatException.class) @@ -51,7 +51,7 @@ public class NumberFormatExceptionUnitTest { @Test(expected = NumberFormatException.class) public void givenDecodeMethod_whenAlphabetInInput_thenFail() { - Long decodeInteger = Long.decode("64403L"); + Long decodedLong = Long.decode("64403L"); } /* ---INTEGER PASS CASES--- */ @@ -72,7 +72,7 @@ public class NumberFormatExceptionUnitTest { int aIntPrim = Integer.parseInt("6000 ".trim()); assertEquals(6000, aIntPrim); - int bIntPrim = Integer.parseInt("6_000".replaceAll("_", "")); + int bIntPrim = Integer.parseInt("_6000".replaceAll("_", "")); assertEquals(6000, bIntPrim); int cIntPrim = Integer.parseInt("-6000"); diff --git a/core-java-modules/core-java-lambdas/README.MD b/core-java-modules/core-java-lambdas/README.MD new file mode 100644 index 0000000000..31790ffbb1 --- /dev/null +++ b/core-java-modules/core-java-lambdas/README.MD @@ -0,0 +1,3 @@ +### Relevant Articles + +- [Why Do Local Variables Used in Lambdas Have to Be Final or Effectively Final?](https://www.baeldung.com/java-lambda-effectively-final-local-variables) diff --git a/core-java-modules/core-java-lambdas/README.md b/core-java-modules/core-java-lambdas/README.md new file mode 100644 index 0000000000..10b876735e --- /dev/null +++ b/core-java-modules/core-java-lambdas/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Why Do Local Variables Used in Lambdas Have to Be Final or Effectively Final?](https://www.baeldung.com/java-lambda-effectively-final-local-variables) diff --git a/core-java-modules/core-java-nio/.gitignore b/core-java-modules/core-java-nio/.gitignore new file mode 100644 index 0000000000..c61d35324d --- /dev/null +++ b/core-java-modules/core-java-nio/.gitignore @@ -0,0 +1,5 @@ +0.* + +# Files generated by integration tests +# *.txt +/temp \ No newline at end of file diff --git a/core-java-modules/core-java-nio/pom.xml b/core-java-modules/core-java-nio/pom.xml new file mode 100644 index 0000000000..36d6848998 --- /dev/null +++ b/core-java-modules/core-java-nio/pom.xml @@ -0,0 +1,16 @@ + + 4.0.0 + core-java-nio + 0.1.0-SNAPSHOT + core-java-nio + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + \ No newline at end of file diff --git a/core-java-modules/core-java-nio/src/test/java/com/baeldung/filechannel/FileChannelUnitTest.java b/core-java-modules/core-java-nio/src/test/java/com/baeldung/filechannel/FileChannelUnitTest.java new file mode 100644 index 0000000000..d661b8f7fb --- /dev/null +++ b/core-java-modules/core-java-nio/src/test/java/com/baeldung/filechannel/FileChannelUnitTest.java @@ -0,0 +1,165 @@ +package com.baeldung.filechannel; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.io.ByteArrayOutputStream; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.nio.ByteBuffer; +import java.nio.MappedByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.channels.FileLock; +import java.nio.charset.StandardCharsets; + +import org.junit.Test; + +public class FileChannelUnitTest { + + @Test + public void givenFile_whenReadWithFileChannelUsingRandomAccessFile_thenCorrect() throws IOException { + + try (RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "r"); + FileChannel channel = reader.getChannel(); + ByteArrayOutputStream out = new ByteArrayOutputStream()) { + + int bufferSize = 1024; + if (bufferSize > channel.size()) { + bufferSize = (int) channel.size(); + } + ByteBuffer buff = ByteBuffer.allocate(bufferSize); + + while (channel.read(buff) > 0) { + out.write(buff.array(), 0, buff.position()); + buff.clear(); + } + + String fileContent = new String(out.toByteArray(), StandardCharsets.UTF_8); + + assertEquals("Hello world", fileContent); + } + } + + @Test + public void givenFile_whenReadWithFileChannelUsingFileInputStream_thenCorrect() throws IOException { + + try (ByteArrayOutputStream out = new ByteArrayOutputStream(); + FileInputStream fin = new FileInputStream("src/test/resources/test_read.in"); + FileChannel channel = fin.getChannel()) { + + int bufferSize = 1024; + if (bufferSize > channel.size()) { + bufferSize = (int) channel.size(); + } + ByteBuffer buff = ByteBuffer.allocate(bufferSize); + + while (channel.read(buff) > 0) { + out.write(buff.array(), 0, buff.position()); + buff.clear(); + } + String fileContent = new String(out.toByteArray(), StandardCharsets.UTF_8); + + assertEquals("Hello world", fileContent); + } + } + + @Test + public void givenFile_whenReadAFileSectionIntoMemoryWithFileChannel_thenCorrect() throws IOException { + + try (RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "r"); + FileChannel channel = reader.getChannel(); + ByteArrayOutputStream out = new ByteArrayOutputStream()) { + + MappedByteBuffer buff = channel.map(FileChannel.MapMode.READ_ONLY, 6, 5); + + if (buff.hasRemaining()) { + byte[] data = new byte[buff.remaining()]; + buff.get(data); + assertEquals("world", new String(data, StandardCharsets.UTF_8)); + } + } + } + + @Test + public void whenWriteWithFileChannelUsingRandomAccessFile_thenCorrect() throws IOException { + String file = "src/test/resources/test_write_using_filechannel.txt"; + try (RandomAccessFile writer = new RandomAccessFile(file, "rw"); + FileChannel channel = writer.getChannel()) { + ByteBuffer buff = ByteBuffer.wrap("Hello world".getBytes(StandardCharsets.UTF_8)); + + channel.write(buff); + + // now we verify whether the file was written correctly + RandomAccessFile reader = new RandomAccessFile(file, "r"); + assertEquals("Hello world", reader.readLine()); + reader.close(); + } + } + + @Test + public void givenFile_whenWriteAFileUsingLockAFileSectionWithFileChannel_thenCorrect() throws IOException { + try (RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "rw"); + FileChannel channel = reader.getChannel(); + FileLock fileLock = channel.tryLock(6, 5, Boolean.FALSE);) { + + assertNotNull(fileLock); + } + } + + @Test + public void givenFile_whenReadWithFileChannelGetPosition_thenCorrect() throws IOException { + + try (ByteArrayOutputStream out = new ByteArrayOutputStream(); + RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "r"); + FileChannel channel = reader.getChannel()) { + + int bufferSize = 1024; + if (bufferSize > channel.size()) { + bufferSize = (int) channel.size(); + } + ByteBuffer buff = ByteBuffer.allocate(bufferSize); + + while (channel.read(buff) > 0) { + out.write(buff.array(), 0, buff.position()); + buff.clear(); + } + + // the original file is 11 bytes long, so that's where the position pointer should be + assertEquals(11, channel.position()); + + channel.position(4); + assertEquals(4, channel.position()); + } + } + + @Test + public void whenGetFileSize_thenCorrect() throws IOException { + + try (RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "r"); + FileChannel channel = reader.getChannel()) { + + // the original file is 11 bytes long, so that's where the position pointer should be + assertEquals(11, channel.size()); + } + } + + @Test + public void whenTruncateFile_thenCorrect() throws IOException { + String input = "this is a test input"; + + FileOutputStream fout = new FileOutputStream("src/test/resources/test_truncate.txt"); + FileChannel channel = fout.getChannel(); + + ByteBuffer buff = ByteBuffer.wrap(input.getBytes()); + channel.write(buff); + buff.flip(); + + channel = channel.truncate(5); + assertEquals(5, channel.size()); + + fout.close(); + channel.close(); + } +} diff --git a/core-java-modules/core-java-nio/src/test/resources/.gitignore b/core-java-modules/core-java-nio/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/core-java-modules/core-java-nio/src/test/resources/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/core-java-modules/core-java-nio/src/test/resources/test_read.in b/core-java-modules/core-java-nio/src/test/resources/test_read.in new file mode 100644 index 0000000000..70c379b63f --- /dev/null +++ b/core-java-modules/core-java-nio/src/test/resources/test_read.in @@ -0,0 +1 @@ +Hello world \ No newline at end of file diff --git a/core-java-modules/core-java-nio/src/test/resources/test_truncate.txt b/core-java-modules/core-java-nio/src/test/resources/test_truncate.txt new file mode 100644 index 0000000000..26d3b38cdd --- /dev/null +++ b/core-java-modules/core-java-nio/src/test/resources/test_truncate.txt @@ -0,0 +1 @@ +this \ No newline at end of file diff --git a/core-java-modules/core-java-nio/src/test/resources/test_write_using_filechannel.txt b/core-java-modules/core-java-nio/src/test/resources/test_write_using_filechannel.txt new file mode 100644 index 0000000000..70c379b63f --- /dev/null +++ b/core-java-modules/core-java-nio/src/test/resources/test_write_using_filechannel.txt @@ -0,0 +1 @@ +Hello world \ No newline at end of file diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/README.md b/core-java-modules/core-java/src/main/java/com/baeldung/README.md deleted file mode 100644 index 7d843af9ea..0000000000 --- a/core-java-modules/core-java/src/main/java/com/baeldung/README.md +++ /dev/null @@ -1 +0,0 @@ -### Relevant Articles: diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/graph/Graph.java b/core-java-modules/core-java/src/main/java/com/baeldung/graph/Graph.java index 3f2e17c43c..58713b1b3f 100644 --- a/core-java-modules/core-java/src/main/java/com/baeldung/graph/Graph.java +++ b/core-java-modules/core-java/src/main/java/com/baeldung/graph/Graph.java @@ -19,7 +19,7 @@ public class Graph { void removeVertex(String label) { Vertex v = new Vertex(label); - adjVertices.values().stream().map(e -> e.remove(v)).collect(Collectors.toList()); + adjVertices.values().stream().forEach(e -> e.remove(v)); adjVertices.remove(new Vertex(label)); } diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/graph/GraphTraversalUnitTest.java b/core-java-modules/core-java/src/test/java/com/baeldung/graph/GraphUnitTest.java similarity index 61% rename from core-java-modules/core-java/src/test/java/com/baeldung/graph/GraphTraversalUnitTest.java rename to core-java-modules/core-java/src/test/java/com/baeldung/graph/GraphUnitTest.java index d955d56d95..68611e508b 100644 --- a/core-java-modules/core-java/src/test/java/com/baeldung/graph/GraphTraversalUnitTest.java +++ b/core-java-modules/core-java/src/test/java/com/baeldung/graph/GraphUnitTest.java @@ -1,20 +1,31 @@ package com.baeldung.graph; -import org.junit.Assert; +import static org.junit.Assert.assertEquals; import org.junit.Test; -public class GraphTraversalUnitTest { +public class GraphUnitTest { @Test public void givenAGraph_whenTraversingDepthFirst_thenExpectedResult() { Graph graph = createGraph(); - Assert.assertEquals("[Bob, Rob, Maria, Alice, Mark]", + assertEquals("[Bob, Rob, Maria, Alice, Mark]", GraphTraversal.depthFirstTraversal(graph, "Bob").toString()); } @Test public void givenAGraph_whenTraversingBreadthFirst_thenExpectedResult() { Graph graph = createGraph(); - Assert.assertEquals("[Bob, Alice, Rob, Mark, Maria]", + assertEquals("[Bob, Alice, Rob, Mark, Maria]", + GraphTraversal.breadthFirstTraversal(graph, "Bob").toString()); + } + + @Test + public void givenAGraph_whenRemoveVertex_thenVertedNotFound() { + Graph graph = createGraph(); + assertEquals("[Bob, Alice, Rob, Mark, Maria]", + GraphTraversal.breadthFirstTraversal(graph, "Bob").toString()); + + graph.removeVertex("Maria"); + assertEquals("[Bob, Alice, Rob, Mark]", GraphTraversal.breadthFirstTraversal(graph, "Bob").toString()); } diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/jvmannotations/Document.kt b/core-kotlin-2/src/main/kotlin/com/baeldung/jvmannotations/Document.kt index 3f9922b88b..55f60bfa81 100644 --- a/core-kotlin-2/src/main/kotlin/com/baeldung/jvmannotations/Document.kt +++ b/core-kotlin-2/src/main/kotlin/com/baeldung/jvmannotations/Document.kt @@ -5,27 +5,7 @@ import java.util.* interface Document { @JvmDefault + fun getTypeDefault() = "document" + fun getType() = "document" } - -class TextDocument : Document { - override fun getType() = "text" - - fun transformList(list : List) : List { - return list.filter { n -> n.toInt() > 1 } - } - - fun transformListInverseWildcards(list : List<@JvmSuppressWildcards Number>) : List<@JvmWildcard Number> { - return list.filter { n -> n.toInt() > 1 } - } - - var list : List<@JvmWildcard Any> = ArrayList() -} - -class XmlDocument(d : Document) : Document by d - -fun main() { - val myDocument = TextDocument() - val myTextDocument = XmlDocument(myDocument) - println("${myDocument.getType()} ${myTextDocument.getType()}") -} diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/jvmannotations/TextDocument.kt b/core-kotlin-2/src/main/kotlin/com/baeldung/jvmannotations/TextDocument.kt new file mode 100644 index 0000000000..41cb0df939 --- /dev/null +++ b/core-kotlin-2/src/main/kotlin/com/baeldung/jvmannotations/TextDocument.kt @@ -0,0 +1,16 @@ +package com.baeldung.jvmannotations + +import java.util.* +class TextDocument : Document { + override fun getType() = "text" + + fun transformList(list : List) : List { + return list.filter { n -> n.toInt() > 1 } + } + + fun transformListInverseWildcards(list : List<@JvmSuppressWildcards Number>) : List<@JvmWildcard Number> { + return list.filter { n -> n.toInt() > 1 } + } + + var list : List<@JvmWildcard Any> = ArrayList() +} diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/jvmannotations/XmlDocument.kt b/core-kotlin-2/src/main/kotlin/com/baeldung/jvmannotations/XmlDocument.kt new file mode 100644 index 0000000000..00f2582d5f --- /dev/null +++ b/core-kotlin-2/src/main/kotlin/com/baeldung/jvmannotations/XmlDocument.kt @@ -0,0 +1,5 @@ +package com.baeldung.jvmannotations + +import java.util.* + +class XmlDocument(d : Document) : Document by d diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/range/DocumentTest.kt b/core-kotlin-2/src/test/kotlin/com/baeldung/range/DocumentTest.kt new file mode 100644 index 0000000000..2ec5402e5a --- /dev/null +++ b/core-kotlin-2/src/test/kotlin/com/baeldung/range/DocumentTest.kt @@ -0,0 +1,20 @@ +package com.baeldung.range + +import org.junit.Test +import kotlin.test.assertEquals + +import com.baeldung.jvmannotations.*; + +class DocumentTest { + + @Test + fun testDefaultMethod() { + + val myDocument = TextDocument() + val myTextDocument = XmlDocument(myDocument) + + assertEquals("text", myDocument.getType()) + assertEquals("text", myTextDocument.getType()) + assertEquals("document", myTextDocument.getTypeDefault()) + } +} \ No newline at end of file diff --git a/ddd/README.md b/ddd/README.md index 60f3a43086..4275bc26b3 100644 --- a/ddd/README.md +++ b/ddd/README.md @@ -1,3 +1,4 @@ ### Relevant articles - [Persisting DDD Aggregates](https://www.baeldung.com/spring-persisting-ddd-aggregates) +- [DDD Aggregates and @DomainEvents](https://www.baeldung.com/spring-data-ddd) diff --git a/java-collections-conversions/src/main/java/com/baeldung/convertToMap/Book.java b/java-collections-conversions/src/main/java/com/baeldung/convertToMap/Book.java new file mode 100644 index 0000000000..847e0bd8cd --- /dev/null +++ b/java-collections-conversions/src/main/java/com/baeldung/convertToMap/Book.java @@ -0,0 +1,48 @@ +package com.baeldung.convertToMap; + +public class Book { + private String name; + private int releaseYear; + private String isbn; + + + @Override + public String toString() { + return "Book{" + + "name='" + name + '\'' + + ", releaseYear=" + releaseYear + + ", isbn='" + isbn + '\'' + + '}'; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getReleaseYear() { + return releaseYear; + } + + public void setReleaseYear(int releaseYear) { + this.releaseYear = releaseYear; + } + + public String getIsbn() { + return isbn; + } + + public void setIsbn(String isbn) { + this.isbn = isbn; + } + + public Book(String name, int releaseYear, String isbn) { + this.name = name; + this.releaseYear = releaseYear; + this.isbn = isbn; + } +} + diff --git a/java-collections-conversions/src/main/java/com/baeldung/convertToMap/ConvertToMap.java b/java-collections-conversions/src/main/java/com/baeldung/convertToMap/ConvertToMap.java new file mode 100644 index 0000000000..3c14dfdba6 --- /dev/null +++ b/java-collections-conversions/src/main/java/com/baeldung/convertToMap/ConvertToMap.java @@ -0,0 +1,34 @@ +package com.baeldung.convertToMap; + +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; +import java.util.stream.Collectors; + +public class ConvertToMap { + public Map listToMap(List books) { + return books.stream().collect(Collectors.toMap(Book::getIsbn, Book::getName)); + } + + public Map listToMapWithDupKeyError(List books) { + return books.stream().collect(Collectors.toMap(Book::getReleaseYear, Function.identity())); + } + + public Map listToMapWithDupKey(List books) { + return books.stream().collect(Collectors.toMap(Book::getReleaseYear, Function.identity(), + (o1, o2) -> o1)); + } + + public Map listToConcurrentMap(List books) { + return books.stream().collect(Collectors.toMap(Book::getReleaseYear, Function.identity(), (o1, o2) -> o1, ConcurrentHashMap::new)); + } + + public TreeMap listToSortedMap(List books) { + return books.stream() + .sorted(Comparator.comparing(Book::getName)) + .collect(Collectors.toMap(Book::getName, Function.identity(), (o1, o2) -> o1, TreeMap::new)); + } + + +} + diff --git a/java-collections-conversions/src/test/java/com/baeldung/convertToMap/ConvertToMapUnitTest.java b/java-collections-conversions/src/test/java/com/baeldung/convertToMap/ConvertToMapUnitTest.java new file mode 100644 index 0000000000..d11221bbf7 --- /dev/null +++ b/java-collections-conversions/src/test/java/com/baeldung/convertToMap/ConvertToMapUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.convertToMap; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; + +import static org.junit.Assert.*; + +import org.junit.Before; +import org.junit.Test; + + +public class ConvertToMapUnitTest { + + private List bookList; + private ConvertToMap convertToMap = new ConvertToMap(); + + @Before + public void init() { + bookList = new ArrayList<>(); + bookList.add(new Book("The Fellowship of the Ring", 1954, "0395489318")); + bookList.add(new Book("The Two Towers", 1954, "0345339711")); + bookList.add(new Book("The Return of the King", 1955, "0618129111")); + } + + @Test + public void whenConvertFromListToMap() { + assertTrue(convertToMap.listToMap(bookList).size() == 3); + } + + @Test(expected = IllegalStateException.class) + public void whenMapHasDuplicateKey_without_merge_function_then_runtime_exception() { + convertToMap.listToMapWithDupKeyError(bookList); + } + + @Test + public void whenMapHasDuplicateKey_with_merge_function() { + assertTrue(convertToMap.listToMapWithDupKey(bookList).size() == 2); + } + + @Test + public void whenCreateConcurrentHashMap() { + assertTrue(convertToMap.listToConcurrentMap(bookList) instanceof ConcurrentHashMap); + } + + @Test + public void whenMapisSorted() { + assertTrue(convertToMap.listToSortedMap(bookList).firstKey().equals("The Fellowship of the Ring")); + } +} diff --git a/java-strings-2/src/test/java/com/baeldung/string/search/SubstringSearch.java b/java-strings-2/src/test/java/com/baeldung/string/search/SubstringSearchUnitTest.java similarity index 98% rename from java-strings-2/src/test/java/com/baeldung/string/search/SubstringSearch.java rename to java-strings-2/src/test/java/com/baeldung/string/search/SubstringSearchUnitTest.java index 4a5adb45ef..293e6d2125 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/search/SubstringSearch.java +++ b/java-strings-2/src/test/java/com/baeldung/string/search/SubstringSearchUnitTest.java @@ -10,7 +10,7 @@ import org.junit.Test; /** * BAEL-2832: Different ways to check if a Substring could be found in a String. */ -public class SubstringSearch { +public class SubstringSearchUnitTest { @Test public void searchSubstringWithIndexOf() { diff --git a/jersey/src/main/java/com/baeldung/jersey/server/ItemParam.java b/jersey/src/main/java/com/baeldung/jersey/server/ItemParam.java new file mode 100644 index 0000000000..0f60a20b92 --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/server/ItemParam.java @@ -0,0 +1,46 @@ +package com.baeldung.jersey.server; + +import javax.ws.rs.FormParam; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.PathParam; + +public class ItemParam { + + @HeaderParam("headerParam") + private String shopKey; + + @PathParam("pathParam") + private String itemId; + + @FormParam("formParam") + private String price; + + public String getShopKey() { + return shopKey; + } + + public void setShopKey(String shopKey) { + this.shopKey = shopKey; + } + + public String getItemId() { + return itemId; + } + + public void setItemId(String itemId) { + this.itemId = itemId; + } + + public String getPrice() { + return price; + } + + public void setPrice(String price) { + this.price = price; + } + + @Override + public String toString() { + return "ItemParam{shopKey='" + shopKey + ", itemId='" + itemId + ", price='" + price + '}'; + } +} diff --git a/jersey/src/main/java/com/baeldung/jersey/server/Items.java b/jersey/src/main/java/com/baeldung/jersey/server/Items.java new file mode 100644 index 0000000000..c24e6820f5 --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/server/Items.java @@ -0,0 +1,49 @@ +package com.baeldung.jersey.server; + +import javax.ws.rs.*; + +@Path("items") +public class Items { + + @GET + @Path("/cookie") + public String readCookieParam(@CookieParam("cookieParamToRead") String cookieParamToRead) { + return "Cookie parameter value is [" + cookieParamToRead + "]"; + } + + @GET + @Path("/header") + public String readHeaderParam(@HeaderParam("headerParamToRead") String headerParamToRead) { + return "Header parameter value is [" + headerParamToRead + "]"; + } + + @GET + @Path("/path/{pathParamToRead}") + public String readPathParam(@PathParam("pathParamToRead") String pathParamToRead) { + return "Path parameter value is [" + pathParamToRead + "]"; + } + + @GET + @Path("/query") + public String readQueryParam(@QueryParam("queryParamToRead") String queryParamToRead) { + return "Query parameter value is [" + queryParamToRead + "]"; + } + + @POST + @Path("/form") + public String readFormParam(@FormParam("formParamToRead") String formParamToRead) { + return "Form parameter value is [" + formParamToRead + "]"; + } + + @GET + @Path("/matrix") + public String readMatrixParam(@MatrixParam("matrixParamToRead") String matrixParamToRead) { + return "Matrix parameter value is [" + matrixParamToRead + "]"; + } + + @POST + @Path("/bean/{pathParam}") + public String readBeanParam(@BeanParam ItemParam itemParam) { + return itemParam.toString(); + } +} \ No newline at end of file diff --git a/jersey/src/main/java/com/baeldung/jersey/server/http/EmbeddedHttpServer.java b/jersey/src/main/java/com/baeldung/jersey/server/http/EmbeddedHttpServer.java index 4afa086858..1d75508c6d 100644 --- a/jersey/src/main/java/com/baeldung/jersey/server/http/EmbeddedHttpServer.java +++ b/jersey/src/main/java/com/baeldung/jersey/server/http/EmbeddedHttpServer.java @@ -7,12 +7,13 @@ import java.util.logging.Logger; import org.glassfish.grizzly.http.server.HttpServer; import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; +import org.glassfish.jersey.server.ResourceConfig; import com.baeldung.jersey.server.config.ViewApplicationConfig; public class EmbeddedHttpServer { - private static final URI BASE_URI = URI.create("http://localhost:8082/"); + public static final URI BASE_URI = URI.create("http://localhost:8082/"); public static void main(String[] args) { try { @@ -32,4 +33,9 @@ public class EmbeddedHttpServer { } } + + public static HttpServer startServer() { + final ResourceConfig rc = new ResourceConfig().packages("com.baeldung.jersey.server"); + return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI.toString()), rc); + } } diff --git a/jersey/src/test/java/com/baeldung/jersey/server/ItemsUnitTest.java b/jersey/src/test/java/com/baeldung/jersey/server/ItemsUnitTest.java new file mode 100644 index 0000000000..df85e26b76 --- /dev/null +++ b/jersey/src/test/java/com/baeldung/jersey/server/ItemsUnitTest.java @@ -0,0 +1,52 @@ +package com.baeldung.jersey.server; + +import static org.junit.Assert.assertEquals; + +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.WebTarget; + +import org.glassfish.grizzly.http.server.HttpServer; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.jersey.server.http.EmbeddedHttpServer; + +public class ItemsUnitTest { + + private HttpServer server; + private WebTarget target; + + @Before + public void setUp() throws Exception { + server = EmbeddedHttpServer.startServer(); + target = ClientBuilder.newClient().target(EmbeddedHttpServer.BASE_URI.toString()); + } + + @After + public void tearDown() throws Exception { + server.stop(); + } + + @Test + public void givenCookieParameter_whenGet_thenReturnsExpectedText() { + String paramValue = "1"; + String responseText = target.path("items/cookie").request().cookie("cookieParamToRead", paramValue).get(String.class); + assertEquals("Cookie parameter value is [" + paramValue + "]", responseText); + } + + @Test + public void givenHeaderParameter_whenGet_thenReturnsExpectedText() { + String paramValue = "2"; + String responseText = target.path("items/header").request().header("headerParamToRead", paramValue).get(String.class); + assertEquals("Header parameter value is [" + paramValue + "]", responseText); + } + + @Test + public void givenPathParameter_whenGet_thenReturnsExpectedText() { + String paramValue = "3"; + String responseText = target.path("items/path/" + paramValue).request().get(String.class); + assertEquals("Path parameter value is [" + paramValue + "]", responseText); + } +} diff --git a/jhipster/jhipster-microservice/car-app/pom.xml b/jhipster/jhipster-microservice/car-app/pom.xml index 529877d448..86d94d0a44 100644 --- a/jhipster/jhipster-microservice/car-app/pom.xml +++ b/jhipster/jhipster-microservice/car-app/pom.xml @@ -1,21 +1,100 @@ 4.0.0 - com.car.app - car-app - car-app - war jhipster-microservice com.baeldung.jhipster 1.0.0-SNAPSHOT + com.car.app + car-app + war + car-app ${maven.version} + + -Djava.security.egd=file:/dev/./urandom -Xmx256m + 3.6.2 + 2.0.0 + 2.5 + 3.5 + 0.4.13 + 1.2 + 5.2.8.Final + 2.6.0 + 0.7.9 + 1.8 + 3.21.0-GA + 1.0.0 + 1.1.0 + 0.7.0 + 3.6 + 2.0.0 + 3.6.2 + 4.8 + jdt_apt + 1.1.0.Final + 2.10 + 1.4.1 + 3.0.1 + yyyyMMddHHmmss + 3.0.0 + 3.1.3 + v6.10.0 + + + + + ${project.build.directory}/test-results + 0.0.20 + false + 3.2.2 + 2.12.1 + 3.2 + + src/main/webapp/content/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* + + S3437,UndocumentedApi,BoldAndItalicTagsCheck + + + src/main/webapp/app/**/*.* + Web:BoldAndItalicTagsCheck + + src/main/java/**/* + squid:S3437 + + src/main/java/**/* + squid:UndocumentedApi + + ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec + ${project.testresult.directory}/coverage/jacoco/jacoco.exec + jacoco + + ${project.testresult.directory}/karma + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.basedir}/src/main/ + ${project.testresult.directory}/surefire-reports + ${project.basedir}/src/test/ + + 2.5.0 + + Camden.SR5 + 2.6.1 + 1.4.10.Final + 1.1.0.Final + v0.21.3 + + @@ -819,83 +898,4 @@ - - -Djava.security.egd=file:/dev/./urandom -Xmx256m - 3.6.2 - 2.0.0 - 2.5 - 3.5 - 0.4.13 - 1.2 - 5.2.8.Final - 2.6.0 - 0.7.9 - 1.8 - 3.21.0-GA - 1.0.0 - 1.1.0 - 0.7.0 - 3.6 - 2.0.0 - 3.6.2 - 4.8 - jdt_apt - 1.1.0.Final - 2.10 - 1.4.1 - 3.0.1 - yyyyMMddHHmmss - 3.0.0 - 3.1.3 - v6.10.0 - - - - - ${project.build.directory}/test-results - 0.0.20 - false - 3.2.2 - 2.12.1 - 3.2 - - src/main/webapp/content/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* - - S3437,UndocumentedApi,BoldAndItalicTagsCheck - - - src/main/webapp/app/**/*.* - Web:BoldAndItalicTagsCheck - - src/main/java/**/* - squid:S3437 - - src/main/java/**/* - squid:UndocumentedApi - - ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec - ${project.testresult.directory}/coverage/jacoco/jacoco.exec - jacoco - - ${project.testresult.directory}/karma - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.basedir}/src/main/ - ${project.testresult.directory}/surefire-reports - ${project.basedir}/src/test/ - - 2.5.0 - - Camden.SR5 - 2.6.1 - 1.4.10.Final - 1.1.0.Final - v0.21.3 - - diff --git a/jhipster/jhipster-microservice/dealer-app/pom.xml b/jhipster/jhipster-microservice/dealer-app/pom.xml index 1eac8a930e..3051399ae6 100644 --- a/jhipster/jhipster-microservice/dealer-app/pom.xml +++ b/jhipster/jhipster-microservice/dealer-app/pom.xml @@ -1,21 +1,99 @@ 4.0.0 - com.dealer.app - dealer-app - dealer-app - war jhipster-microservice com.baeldung.jhipster 1.0.0-SNAPSHOT + com.dealer.app + dealer-app + war + dealer-app ${maven.version} + + -Djava.security.egd=file:/dev/./urandom -Xmx256m + 3.6.2 + 2.0.0 + 2.5 + 3.5 + 0.4.13 + 1.2 + 5.2.8.Final + 2.6.0 + 0.7.9 + 3.21.0-GA + 1.0.0 + 1.1.0 + 0.7.0 + 3.6 + 2.0.0 + 3.6.2 + 4.8 + jdt_apt + 1.1.0.Final + 2.10 + 1.4.1 + 3.0.1 + yyyyMMddHHmmss + 3.0.0 + 3.1.3 + v6.10.0 + + + + + ${project.build.directory}/test-results + 0.0.20 + false + 3.2.2 + 2.12.1 + 3.2 + + src/main/webapp/content/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* + + S3437,UndocumentedApi,BoldAndItalicTagsCheck + + + src/main/webapp/app/**/*.* + Web:BoldAndItalicTagsCheck + + src/main/java/**/* + squid:S3437 + + src/main/java/**/* + squid:UndocumentedApi + + ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec + ${project.testresult.directory}/coverage/jacoco/jacoco.exec + jacoco + + ${project.testresult.directory}/karma + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.basedir}/src/main/ + ${project.testresult.directory}/surefire-reports + ${project.basedir}/src/test/ + + 2.5.0 + + Camden.SR5 + 2.6.1 + 1.4.10.Final + 1.1.0.Final + v0.21.3 + + @@ -813,83 +891,5 @@ - - - -Djava.security.egd=file:/dev/./urandom -Xmx256m - 3.6.2 - 2.0.0 - 2.5 - 3.5 - 0.4.13 - 1.2 - 5.2.8.Final - 2.6.0 - 0.7.9 - 3.21.0-GA - 1.0.0 - 1.1.0 - 0.7.0 - 3.6 - 2.0.0 - 3.6.2 - 4.8 - jdt_apt - 1.1.0.Final - 2.10 - 1.4.1 - 3.0.1 - yyyyMMddHHmmss - 3.0.0 - 3.1.3 - v6.10.0 - - - - - ${project.build.directory}/test-results - 0.0.20 - false - 3.2.2 - 2.12.1 - 3.2 - src/main/webapp/content/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* - - S3437,UndocumentedApi,BoldAndItalicTagsCheck - - - src/main/webapp/app/**/*.* - Web:BoldAndItalicTagsCheck - - src/main/java/**/* - squid:S3437 - - src/main/java/**/* - squid:UndocumentedApi - - ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec - ${project.testresult.directory}/coverage/jacoco/jacoco.exec - jacoco - - ${project.testresult.directory}/karma - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.basedir}/src/main/ - ${project.testresult.directory}/surefire-reports - ${project.basedir}/src/test/ - - 2.5.0 - - Camden.SR5 - 2.6.1 - 1.4.10.Final - 1.1.0.Final - v0.21.3 - - diff --git a/jhipster/jhipster-microservice/gateway-app/pom.xml b/jhipster/jhipster-microservice/gateway-app/pom.xml index babc9e4f24..4e2c19ed2d 100644 --- a/jhipster/jhipster-microservice/gateway-app/pom.xml +++ b/jhipster/jhipster-microservice/gateway-app/pom.xml @@ -1,21 +1,103 @@ 4.0.0 - com.gateway - gateway-app - gateway-app - war jhipster-microservice com.baeldung.jhipster 1.0.0-SNAPSHOT + com.gateway + gateway-app + war + gateway-app ${maven.version} + + -Djava.security.egd=file:/dev/./urandom -Xmx256m + 3.6.2 + 2.0.0 + 3.6.0 + 1.10 + 2.5 + 3.5 + 0.4.13 + 1.3 + 1.2 + 5.2.8.Final + 2.6.0 + 0.7.9 + 3.21.0-GA + 1.0.0 + 1.1.0 + 0.7.0 + 3.6 + 2.0.0 + 3.6.2 + 4.8 + 1.3.0 + jdt_apt + 1.1.0.Final + 2.10 + 1.4.1 + 3.0.1 + yyyyMMddHHmmss + 3.0.0 + 3.1.3 + v6.10.0 + + + + + ${project.build.directory}/test-results + 0.0.20 + false + 3.2.2 + 2.12.1 + 3.2 + + src/main/webapp/content/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* + + S3437,UndocumentedApi,BoldAndItalicTagsCheck + + + src/main/webapp/app/**/*.* + Web:BoldAndItalicTagsCheck + + src/main/java/**/* + squid:S3437 + + src/main/java/**/* + squid:UndocumentedApi + + ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec + ${project.testresult.directory}/coverage/jacoco/jacoco.exec + jacoco + + ${project.testresult.directory}/karma + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.basedir}/src/main/ + ${project.testresult.directory}/surefire-reports + ${project.basedir}/src/test/ + + 2.5.0 + + Camden.SR5 + 2.6.1 + 1.4.10.Final + 1.1.0.Final + v0.21.3 + + @@ -925,87 +1007,5 @@ - - - -Djava.security.egd=file:/dev/./urandom -Xmx256m - 3.6.2 - 2.0.0 - 3.6.0 - 1.10 - 2.5 - 3.5 - 0.4.13 - 1.3 - 1.2 - 5.2.8.Final - 2.6.0 - 0.7.9 - 3.21.0-GA - 1.0.0 - 1.1.0 - 0.7.0 - 3.6 - 2.0.0 - 3.6.2 - 4.8 - 1.3.0 - jdt_apt - 1.1.0.Final - 2.10 - 1.4.1 - 3.0.1 - yyyyMMddHHmmss - 3.0.0 - 3.1.3 - v6.10.0 - - - - - ${project.build.directory}/test-results - 0.0.20 - false - 3.2.2 - 2.12.1 - 3.2 - - src/main/webapp/content/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* - - S3437,UndocumentedApi,BoldAndItalicTagsCheck - - - src/main/webapp/app/**/*.* - Web:BoldAndItalicTagsCheck - - src/main/java/**/* - squid:S3437 - - src/main/java/**/* - squid:UndocumentedApi - - ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec - ${project.testresult.directory}/coverage/jacoco/jacoco.exec - jacoco - - ${project.testresult.directory}/karma - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.basedir}/src/main/ - ${project.testresult.directory}/surefire-reports - ${project.basedir}/src/test/ - - 2.5.0 - - Camden.SR5 - 2.6.1 - 1.4.10.Final - 1.1.0.Final - v0.21.3 - diff --git a/kotlin-quasar/pom.xml b/kotlin-quasar/pom.xml new file mode 100644 index 0000000000..44feabd183 --- /dev/null +++ b/kotlin-quasar/pom.xml @@ -0,0 +1,120 @@ + + + 4.0.0 + com.baeldung + kotlin-quasar + 1.0.0-SNAPSHOT + kotlin-quasar + jar + + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + ${kotlin.version} + + + org.jetbrains.kotlin + kotlin-test + ${kotlin.version} + test + + + co.paralleluniverse + quasar-core + ${quasar.version} + + + co.paralleluniverse + quasar-actors + ${quasar.version} + + + co.paralleluniverse + quasar-reactive-streams + ${quasar.version} + + + co.paralleluniverse + quasar-kotlin + ${quasar.version} + + + junit + junit + 4.12 + + + + + src/main/kotlin + src/test/kotlin + + + org.jetbrains.kotlin + kotlin-maven-plugin + ${kotlin.version} + + + compile + compile + + compile + + + + test-compile + test-compile + + test-compile + + + + + 1.8 + + + + maven-dependency-plugin + 3.1.1 + + + getClasspathFilenames + + properties + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.1 + + -Dco.paralleluniverse.fibers.verifyInstrumentation=true + -javaagent:${co.paralleluniverse:quasar-core:jar} + + + + org.codehaus.mojo + exec-maven-plugin + 1.3.2 + + target/classes + echo + + -javaagent:${co.paralleluniverse:quasar-core:jar} + -classpath + com.baeldung.quasar.QuasarHelloWorldKt + + + + + + + + 0.8.0 + 1.3.31 + + diff --git a/kotlin-quasar/src/main/kotlin/com/baeldung/quasar/QuasarHelloWorld.kt b/kotlin-quasar/src/main/kotlin/com/baeldung/quasar/QuasarHelloWorld.kt new file mode 100644 index 0000000000..9bf01ecb09 --- /dev/null +++ b/kotlin-quasar/src/main/kotlin/com/baeldung/quasar/QuasarHelloWorld.kt @@ -0,0 +1,19 @@ +package com.baeldung.quasar + +import co.paralleluniverse.fibers.Fiber +import co.paralleluniverse.strands.SuspendableRunnable + + +/** + * Entrypoint into the application + */ +fun main(args: Array) { + class Runnable : SuspendableRunnable { + override fun run() { + println("Hello") + } + } + val result = Fiber(Runnable()).start() + result.join() + println("World") +} diff --git a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ChannelsTest.kt b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ChannelsTest.kt new file mode 100644 index 0000000000..b51943446e --- /dev/null +++ b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ChannelsTest.kt @@ -0,0 +1,155 @@ +package com.baeldung.quasar + +import co.paralleluniverse.fibers.Suspendable +import co.paralleluniverse.kotlin.fiber +import co.paralleluniverse.strands.channels.Channels +import co.paralleluniverse.strands.channels.Selector +import com.google.common.base.Function +import org.junit.Test + +class ChannelsTest { + @Test + fun createChannel() { + Channels.newChannel(0, // The size of the channel buffer + Channels.OverflowPolicy.BLOCK, // The policy for when the buffer is full + true, // Whether we should optimize for a single message producer + true) // Whether we should optimize for a single message consumer + } + + @Test + fun blockOnMessage() { + val channel = Channels.newChannel(0, Channels.OverflowPolicy.BLOCK, true, true) + + fiber @Suspendable { + while (!channel.isClosed) { + val message = channel.receive() + println("Received: $message") + } + println("Stopped receiving messages") + } + + channel.send("Hello") + channel.send("World") + + channel.close() + } + + @Test + fun selectReceiveChannels() { + val channel1 = Channels.newChannel(0, Channels.OverflowPolicy.BLOCK, true, true) + val channel2 = Channels.newChannel(0, Channels.OverflowPolicy.BLOCK, true, true) + + fiber @Suspendable { + while (!channel1.isClosed && !channel2.isClosed) { + val received = Selector.select(Selector.receive(channel1), Selector.receive(channel2)) + + println("Received: $received") + } + } + + fiber @Suspendable { + for (i in 0..10) { + channel1.send("Channel 1: $i") + } + } + + fiber @Suspendable { + for (i in 0..10) { + channel2.send("Channel 2: $i") + } + } + } + + @Test + fun selectSendChannels() { + val channel1 = Channels.newChannel(0, Channels.OverflowPolicy.BLOCK, true, true) + val channel2 = Channels.newChannel(0, Channels.OverflowPolicy.BLOCK, true, true) + + fiber @Suspendable { + for (i in 0..10) { + Selector.select( + Selector.send(channel1, "Channel 1: $i"), + Selector.send(channel2, "Channel 2: $i") + ) + } + } + + fiber @Suspendable { + while (!channel1.isClosed) { + val msg = channel1.receive() + println("Read: $msg") + } + } + + fiber @Suspendable { + while (!channel2.isClosed) { + val msg = channel2.receive() + println("Read: $msg") + } + } + } + + @Test + fun tickerChannel() { + val channel = Channels.newChannel(3, Channels.OverflowPolicy.DISPLACE) + + for (i in 0..10) { + val tickerConsumer = Channels.newTickerConsumerFor(channel) + fiber @Suspendable { + while (!tickerConsumer.isClosed) { + val message = tickerConsumer.receive() + println("Received on $i: $message") + } + println("Stopped receiving messages on $i") + } + } + + for (i in 0..50) { + channel.send("Message $i") + } + + channel.close() + } + + + @Test + fun transformOnSend() { + val channel = Channels.newChannel(0, Channels.OverflowPolicy.BLOCK, true, true) + + fiber @Suspendable { + while (!channel.isClosed) { + val message = channel.receive() + println("Received: $message") + } + println("Stopped receiving messages") + } + + val transformOnSend = Channels.mapSend(channel, Function { msg: String? -> msg?.toUpperCase() }) + + transformOnSend.send("Hello") + transformOnSend.send("World") + + channel.close() + } + + @Test + fun transformOnReceive() { + val channel = Channels.newChannel(0, Channels.OverflowPolicy.BLOCK, true, true) + + val transformOnReceive = Channels.map(channel, Function { msg: String? -> msg?.reversed() }) + + fiber @Suspendable { + while (!transformOnReceive.isClosed) { + val message = transformOnReceive.receive() + println("Received: $message") + } + println("Stopped receiving messages") + } + + + channel.send("Hello") + channel.send("World") + + channel.close() + } +} diff --git a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/DataflowTest.kt b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/DataflowTest.kt new file mode 100644 index 0000000000..3f73af3917 --- /dev/null +++ b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/DataflowTest.kt @@ -0,0 +1,35 @@ +package com.baeldung.quasar + +import co.paralleluniverse.strands.dataflow.Val +import co.paralleluniverse.strands.dataflow.Var +import org.junit.Assert +import org.junit.Test +import java.util.concurrent.TimeUnit + +class DataflowTest { + @Test + fun testValVar() { + val a = Var() + val b = Val() + + val c = Var { a.get() + b.get() } + val d = Var { a.get() * b.get() } + + // (a*b) - (a+b) + val initialResult = Val { d.get() - c.get() } + val currentResult = Var { d.get() - c.get() } + + a.set(2) + b.set(4) + + Assert.assertEquals(2, initialResult.get()) + Assert.assertEquals(2, currentResult.get()) + + a.set(3) + + TimeUnit.SECONDS.sleep(1) + + Assert.assertEquals(2, initialResult.get()) + Assert.assertEquals(5, currentResult.get()) + } +} diff --git a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/PiAsyncTest.kt b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/PiAsyncTest.kt new file mode 100644 index 0000000000..d4ea04820d --- /dev/null +++ b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/PiAsyncTest.kt @@ -0,0 +1,53 @@ +package com.baeldung.quasar + +import co.paralleluniverse.fibers.Fiber +import co.paralleluniverse.fibers.FiberAsync +import co.paralleluniverse.fibers.Suspendable +import co.paralleluniverse.kotlin.fiber +import co.paralleluniverse.strands.Strand +import org.junit.Assert +import org.junit.Test +import java.math.BigDecimal +import java.util.concurrent.TimeUnit + +interface PiCallback { + fun success(result: BigDecimal) + fun failure(error: Exception) +} + +fun computePi(callback: PiCallback) { + println("Starting calculations") + TimeUnit.SECONDS.sleep(2) + println("Finished calculations") + callback.success(BigDecimal("3.14")) +} + +class PiAsync : PiCallback, FiberAsync() { + override fun success(result: BigDecimal) { + asyncCompleted(result) + } + + override fun failure(error: Exception) { + asyncFailed(error) + } + + override fun requestAsync() { + computePi(this) + } +} + +class PiAsyncTest { + @Test + fun testPi() { + val result = fiber @Suspendable { + val pi = PiAsync() + println("Waiting to get PI on: " + Fiber.currentFiber().name) + val result = pi.run() + println("Got PI") + + result + }.get() + + Assert.assertEquals(BigDecimal("3.14"), result) + } +} diff --git a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/SuspendableCallableTest.kt b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/SuspendableCallableTest.kt new file mode 100644 index 0000000000..9b139dd686 --- /dev/null +++ b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/SuspendableCallableTest.kt @@ -0,0 +1,48 @@ +package com.baeldung.quasar + +import co.paralleluniverse.fibers.Fiber +import co.paralleluniverse.fibers.Suspendable +import co.paralleluniverse.kotlin.fiber +import co.paralleluniverse.strands.SuspendableCallable +import org.junit.Assert +import org.junit.Test +import java.util.concurrent.TimeUnit + + +class SuspendableCallableTest { + @Test + fun createFiber() { + class Callable : SuspendableCallable { + override fun run(): String { + println("Inside Fiber") + return "Hello" + } + } + val result = Fiber(Callable()).start() + + Assert.assertEquals("Hello", result.get()) + } + + @Test + fun createFiberLambda() { + val lambda: (() -> String) = { + println("Inside Fiber Lambda") + "Hello" + } + val result = Fiber(lambda) + result.start() + + Assert.assertEquals("Hello", result.get()) + } + + @Test + fun createFiberDsl() { + val result = fiber @Suspendable { + TimeUnit.SECONDS.sleep(5) + println("Inside Fiber DSL") + "Hello" + } + + Assert.assertEquals("Hello", result.get()) + } +} diff --git a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/SuspensableRunnableTest.kt b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/SuspensableRunnableTest.kt new file mode 100644 index 0000000000..ba4cef8f4c --- /dev/null +++ b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/SuspensableRunnableTest.kt @@ -0,0 +1,47 @@ +package com.baeldung.quasar + +import co.paralleluniverse.fibers.Fiber +import co.paralleluniverse.fibers.Suspendable +import co.paralleluniverse.kotlin.fiber +import co.paralleluniverse.strands.SuspendableRunnable +import org.junit.Test +import java.util.concurrent.TimeUnit +import java.util.concurrent.TimeoutException + + +class SuspensableRunnableTest { + @Test + fun createFiber() { + class Runnable : SuspendableRunnable { + override fun run() { + println("Inside Fiber") + } + } + val result = Fiber(Runnable()).start() + result.join() + } + + @Test + fun createFiberLambda() { + val result = Fiber { + println("Inside Fiber Lambda") + } + result.start() + result.join() + } + + @Test + fun createFiberDsl() { + fiber @Suspendable { + println("Inside Fiber DSL") + }.join() + } + + @Test(expected = TimeoutException::class) + fun fiberTimeout() { + fiber @Suspendable { + TimeUnit.SECONDS.sleep(5) + println("Inside Fiber DSL") + }.join(2, TimeUnit.SECONDS) + } +} diff --git a/libraries-primitive/README.MD b/libraries-primitive/README.MD new file mode 100644 index 0000000000..f27fb73dd6 --- /dev/null +++ b/libraries-primitive/README.MD @@ -0,0 +1,3 @@ +### Relevant Articles + +- [Guide to FastUtil](https://www.baeldung.com/fastutil) diff --git a/maven/README.md b/maven/README.md index ca648ec203..6d1a7081b7 100644 --- a/maven/README.md +++ b/maven/README.md @@ -16,3 +16,4 @@ - [Multi-Module Project with Maven](https://www.baeldung.com/maven-multi-module) - [Maven Enforcer Plugin](https://www.baeldung.com/maven-enforcer-plugin) - [Eclipse Error: web.xml is missing and failOnMissingWebXml is set to true](https://www.baeldung.com/eclipse-error-web-xml-missing) +- [Guide to Maven Profiles](https://www.baeldung.com/maven-profiles) diff --git a/patterns/README.md b/patterns/README.md deleted file mode 100644 index f627251aa4..0000000000 --- a/patterns/README.md +++ /dev/null @@ -1,6 +0,0 @@ -### Relevant Articles: -- [A Guide to the Front Controller Pattern in Java](http://www.baeldung.com/java-front-controller-pattern) -- [Introduction to Intercepting Filter Pattern in Java](http://www.baeldung.com/intercepting-filter-pattern-in-java) -- [Introduction to the Null Object Pattern](https://www.baeldung.com/java-null-object-pattern) -- [The Dependency Inversion Principle in Java](https://www.baeldung.com/java-dependency-inversion-principle) -- [Avoid Check for Null Statement in Java](https://www.baeldung.com/java-avoid-null-check) diff --git a/patterns/design-patterns-2/README.md b/patterns/design-patterns-2/README.md index c2a75d4680..8e4ef657e1 100644 --- a/patterns/design-patterns-2/README.md +++ b/patterns/design-patterns-2/README.md @@ -1,3 +1,5 @@ ### Relevant Articles - [The Mediator Pattern in Java](https://www.baeldung.com/java-mediator-pattern) +- [Introduction to the Null Object Pattern](https://www.baeldung.com/java-null-object-pattern) +- [Avoid Check for Null Statement in Java](https://www.baeldung.com/java-avoid-null-check) diff --git a/patterns/dip/README.md b/patterns/dip/README.md new file mode 100644 index 0000000000..8876bbe766 --- /dev/null +++ b/patterns/dip/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [The Dependency Inversion Principle in Java](https://www.baeldung.com/java-dependency-inversion-principle) diff --git a/patterns/front-controller/README.md b/patterns/front-controller/README.md new file mode 100644 index 0000000000..5f8cb5d568 --- /dev/null +++ b/patterns/front-controller/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [A Guide to the Front Controller Pattern in Java](http://www.baeldung.com/java-front-controller-pattern) diff --git a/patterns/intercepting-filter/README.md b/patterns/intercepting-filter/README.md new file mode 100644 index 0000000000..88b7f58469 --- /dev/null +++ b/patterns/intercepting-filter/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Introduction to Intercepting Filter Pattern in Java](http://www.baeldung.com/intercepting-filter-pattern-in-java) diff --git a/patterns/principles/solid/README.md b/patterns/solid/README.md similarity index 100% rename from patterns/principles/solid/README.md rename to patterns/solid/README.md diff --git a/persistence-modules/README.md b/persistence-modules/README.md deleted file mode 100644 index e9a7d625cc..0000000000 --- a/persistence-modules/README.md +++ /dev/null @@ -1,17 +0,0 @@ - -## Persistence Modules - - -### Relevant Articles: - -- [Introduction to Hibernate Search](http://www.baeldung.com/hibernate-search) -- [Introduction to Lettuce – the Java Redis Client](http://www.baeldung.com/java-redis-lettuce) -- [A Guide to Jdbi](http://www.baeldung.com/jdbi) -- [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking) -- [Get All Data from a Table with Hibernate](https://www.baeldung.com/hibernate-select-all) -- [Spring Data with Reactive Cassandra](https://www.baeldung.com/spring-data-cassandra-reactive) -- [Spring Data JPA – Derived Delete Methods](https://www.baeldung.com/spring-data-jpa-deleteby) -- [Difference Between save() and saveAndFlush() in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-save-saveandflush) -- [Spring Boot with Hibernate](https://www.baeldung.com/spring-boot-hibernate) -- [Persisting Maps with Hibernate](https://www.baeldung.com/hibernate-persisting-maps) -- [Difference Between @Size, @Length, and @Column(length=value)](https://www.baeldung.com/jpa-size-length-column-differences) diff --git a/persistence-modules/hibernate-mapping/README.md b/persistence-modules/hibernate-mapping/README.md index 223d93e1ed..203cb2f8e4 100644 --- a/persistence-modules/hibernate-mapping/README.md +++ b/persistence-modules/hibernate-mapping/README.md @@ -2,3 +2,4 @@ ### Relevant Articles: - [Persisting Maps with Hibernate](https://www.baeldung.com/hibernate-persisting-maps) +- [Difference Between @Size, @Length, and @Column(length=value)](https://www.baeldung.com/jpa-size-length-column-differences) diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java index 7411edd225..7de13db8d3 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -12,16 +12,12 @@ import java.net.URL; import java.util.Properties; public class HibernateUtil { - private static SessionFactory sessionFactory; private HibernateUtil() { } public static SessionFactory getSessionFactory(Strategy strategy) { - if (sessionFactory == null) { - sessionFactory = buildSessionFactory(strategy); - } - return sessionFactory; + return buildSessionFactory(strategy); } private static SessionFactory buildSessionFactory(Strategy strategy) { diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/Strategy.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/Strategy.java index 78434fd2a2..b0bc095b43 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/Strategy.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/Strategy.java @@ -2,12 +2,12 @@ package com.baeldung.hibernate; import java.util.Arrays; -import java.util.Collections; import java.util.List; public enum Strategy { //See that the classes belongs to different packages - MAP_KEY_COLUMN_BASED(Collections.singletonList(com.baeldung.hibernate.persistmaps.mapkeycolumn.Order.class)), + MAP_KEY_COLUMN_BASED(Arrays.asList(com.baeldung.hibernate.persistmaps.mapkeycolumn.Order.class, + com.baeldung.hibernate.basicannotation.Course.class)), MAP_KEY_BASED(Arrays.asList(com.baeldung.hibernate.persistmaps.mapkey.Item.class, com.baeldung.hibernate.persistmaps.mapkey.Order.class,com.baeldung.hibernate.persistmaps.mapkey.User.class)), MAP_KEY_JOIN_COLUMN_BASED(Arrays.asList(com.baeldung.hibernate.persistmaps.mapkeyjoincolumn.Seller.class, diff --git a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/basicannotation/BasicAnnotationIntegrationTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/basicannotation/BasicAnnotationIntegrationTest.java index 70f08b4ee3..930bea60c5 100644 --- a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/basicannotation/BasicAnnotationIntegrationTest.java +++ b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/basicannotation/BasicAnnotationIntegrationTest.java @@ -1,18 +1,19 @@ package com.baeldung.hibernate.basicannotation; -import com.baeldung.hibernate.HibernateUtil; -import com.baeldung.hibernate.basicannotation.Course; -import com.baeldung.hibernate.Strategy; -import org.hibernate.PropertyValueException; +import java.io.IOException; + +import javax.persistence.PersistenceException; + import org.hibernate.Session; +import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.junit.After; import org.junit.Before; -import org.junit.Test; -import org.hibernate.SessionFactory; import org.junit.BeforeClass; +import org.junit.Test; -import java.io.IOException; +import com.baeldung.hibernate.HibernateUtil; +import com.baeldung.hibernate.Strategy; public class BasicAnnotationIntegrationTest { @@ -48,7 +49,7 @@ public class BasicAnnotationIntegrationTest { } - @Test(expected = PropertyValueException.class) + @Test(expected = PersistenceException.class) public void givenACourse_whenCourseNameAbsent_shouldFail() { Course course = new Course(); diff --git a/persistence-modules/hibernate5/pom.xml b/persistence-modules/hibernate5/pom.xml index 8799317e9c..7a9fdc0d34 100644 --- a/persistence-modules/hibernate5/pom.xml +++ b/persistence-modules/hibernate5/pom.xml @@ -37,6 +37,11 @@ hibernate-spatial ${hibernate.version} + + org.opengeo + geodb + ${geodb.version} + org.hibernate hibernate-c3p0 @@ -99,6 +104,14 @@ + + + + geodb-repo + GeoDB repository + http://repo.boundlessgeo.com/main/ + + 5.3.7.Final @@ -106,6 +119,7 @@ 2.2.3 3.8.0 1.21 + 0.9 diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java index 48c9b9d5c2..137fc4f0bd 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -5,27 +5,25 @@ import java.io.IOException; import java.net.URL; import java.util.Properties; +import org.apache.commons.lang3.StringUtils; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + import com.baeldung.hibernate.customtypes.LocalDateStringType; import com.baeldung.hibernate.customtypes.OfficeEmployee; import com.baeldung.hibernate.entities.DeptEmployee; +import com.baeldung.hibernate.joincolumn.Email; +import com.baeldung.hibernate.joincolumn.Office; +import com.baeldung.hibernate.joincolumn.OfficeAddress; import com.baeldung.hibernate.optimisticlocking.OptimisticLockingCourse; import com.baeldung.hibernate.optimisticlocking.OptimisticLockingStudent; import com.baeldung.hibernate.pessimisticlocking.Individual; import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingCourse; import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingEmployee; import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingStudent; -import com.baeldung.hibernate.pojo.*; -import com.baeldung.hibernate.pojo.Person; -import com.baeldung.hibernate.pojo.inheritance.*; -import org.apache.commons.lang3.StringUtils; -import org.hibernate.SessionFactory; -import org.hibernate.boot.Metadata; -import org.hibernate.boot.MetadataBuilder; -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.Configuration; -import org.hibernate.service.ServiceRegistry; - import com.baeldung.hibernate.pojo.Course; import com.baeldung.hibernate.pojo.Employee; import com.baeldung.hibernate.pojo.EntityDescription; @@ -36,6 +34,7 @@ import com.baeldung.hibernate.pojo.Person; import com.baeldung.hibernate.pojo.Phone; import com.baeldung.hibernate.pojo.PointEntity; import com.baeldung.hibernate.pojo.PolygonEntity; +import com.baeldung.hibernate.pojo.Post; import com.baeldung.hibernate.pojo.Product; import com.baeldung.hibernate.pojo.Student; import com.baeldung.hibernate.pojo.TemporalValues; @@ -52,7 +51,6 @@ import com.baeldung.hibernate.pojo.inheritance.Pet; import com.baeldung.hibernate.pojo.inheritance.Vehicle; public class HibernateUtil { - private static SessionFactory sessionFactory; private static String PROPERTY_FILE_NAME; public static SessionFactory getSessionFactory() throws IOException { @@ -61,11 +59,8 @@ public class HibernateUtil { public static SessionFactory getSessionFactory(String propertyFileName) throws IOException { PROPERTY_FILE_NAME = propertyFileName; - if (sessionFactory == null) { - ServiceRegistry serviceRegistry = configureServiceRegistry(); - sessionFactory = makeSessionFactory(serviceRegistry); - } - return sessionFactory; + ServiceRegistry serviceRegistry = configureServiceRegistry(); + return makeSessionFactory(serviceRegistry); } public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException { @@ -114,6 +109,10 @@ public class HibernateUtil { metadataSources.addAnnotatedClass(OptimisticLockingStudent.class); metadataSources.addAnnotatedClass(OfficeEmployee.class); metadataSources.addAnnotatedClass(Post.class); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.joincolumn.OfficialEmployee.class); + metadataSources.addAnnotatedClass(Email.class); + metadataSources.addAnnotatedClass(Office.class); + metadataSources.addAnnotatedClass(OfficeAddress.class); Metadata metadata = metadataSources.getMetadataBuilder() .applyBasicType(LocalDateStringType.INSTANCE) diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java index a91fb3b4c9..df07c3cf69 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java @@ -19,7 +19,7 @@ public class Email { @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "employee_id") - private Employee employee; + private OfficialEmployee employee; public Long getId() { return id; @@ -37,11 +37,11 @@ public class Email { this.address = address; } - public Employee getEmployee() { + public OfficialEmployee getEmployee() { return employee; } - public void setEmployee(Employee employee) { + public void setEmployee(OfficialEmployee employee) { this.employee = employee; } } \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java index e5b9dc06bc..9940577761 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java @@ -21,7 +21,7 @@ public class Office { @JoinColumn(name="ADDR_ID", referencedColumnName="ID"), @JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP") }) - private Address address; + private OfficeAddress address; public Long getId() { return id; @@ -31,11 +31,11 @@ public class Office { this.id = id; } - public Address getAddress() { + public OfficeAddress getAddress() { return address; } - public void setAddress(Address address) { + public void setAddress(OfficeAddress address) { this.address = address; } } \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Address.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java similarity index 95% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Address.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java index 8b0a51858d..cc723db6a2 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Address.java +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java @@ -7,7 +7,7 @@ import javax.persistence.GenerationType; import javax.persistence.Id; @Entity -public class Address { +public class OfficeAddress { @Id @GeneratedValue(strategy = GenerationType.AUTO) diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Employee.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java similarity index 95% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Employee.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java index 3fbdb3820e..49c63c7578 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Employee.java +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java @@ -9,7 +9,7 @@ import javax.persistence.Id; import javax.persistence.OneToMany; @Entity -public class Employee { +public class OfficialEmployee { @Id @GeneratedValue(strategy = GenerationType.AUTO) diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java index 972ade9671..c2f276472e 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java @@ -19,10 +19,7 @@ public class HibernateUtil { } public static SessionFactory getSessionFactory(Strategy strategy) { - if (sessionFactory == null) { - sessionFactory = buildSessionFactory(strategy); - } - return sessionFactory; + return buildSessionFactory(strategy); } private static SessionFactory buildSessionFactory(Strategy strategy) { diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java index 223f5dcbde..736abde866 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java @@ -2,6 +2,7 @@ package com.baeldung.hibernate.pojo; import com.vividsolutions.jts.geom.Point; +import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -13,6 +14,7 @@ public class PointEntity { @GeneratedValue private Long id; + @Column(columnDefinition="BINARY(2048)") private Point point; public PointEntity() { diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java index b207d6630a..f31a61f121 100644 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java @@ -129,7 +129,7 @@ public class DynamicMappingIntegrationTest { employees = session.createQuery("from Employee").getResultList(); - assertThat(employees).hasSize(3); + assertThat(employees).hasSize(0); } diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java index 975490aa7c..74f752ab8c 100644 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java @@ -4,7 +4,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import java.io.FileInputStream; import java.io.IOException; +import java.net.URL; +import java.util.Properties; import javax.persistence.Query; @@ -24,6 +27,8 @@ import com.vividsolutions.jts.io.ParseException; import com.vividsolutions.jts.io.WKTReader; import com.vividsolutions.jts.util.GeometricShapeFactory; +import geodb.GeoDB; + public class HibernateSpatialIntegrationTest { private Session session; @@ -34,6 +39,7 @@ public class HibernateSpatialIntegrationTest { session = HibernateUtil.getSessionFactory("hibernate-spatial.properties") .openSession(); transaction = session.beginTransaction(); + session.doWork(conn -> { GeoDB.InitGeoDB(conn); }); } @After @@ -141,4 +147,15 @@ public class HibernateSpatialIntegrationTest { shapeFactory.setSize(radius * 2); return shapeFactory.createCircle(); } + + public static Properties getProperties(String propertyFile) throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource(propertyFile); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } } diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java index 9d368fa27e..cedba412d9 100644 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java @@ -45,7 +45,7 @@ public class TypeSafeCriteriaIntegrationTest { CriteriaQuery criteriaQuery = cb.createQuery(Student.class); Root root = criteriaQuery.from(Student.class); - criteriaQuery.select(root).where(cb.equal(root.get(Student_.gradYear), 1965)); + criteriaQuery.select(root).where(cb.equal(root.get("gradYear"), 1965)); Query query = session.createQuery(criteriaQuery); List results = query.getResultList(); diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java index 8246a2b01e..0998ff1d90 100644 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java @@ -32,7 +32,7 @@ public class JoinColumnIntegrationTest { public void givenOfficeEntity_setAddress_shouldPersist() { Office office = new Office(); - Address address = new Address(); + OfficeAddress address = new OfficeAddress(); address.setZipCode("11-111"); office.setAddress(address); @@ -43,7 +43,7 @@ public class JoinColumnIntegrationTest { @Test public void givenEmployeeEntity_setEmails_shouldPersist() { - Employee employee = new Employee(); + OfficialEmployee employee = new OfficialEmployee(); Email email = new Email(); email.setAddress("example@email.com"); diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java index 68b51764e4..37c490f297 100644 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java @@ -1,17 +1,23 @@ package com.baeldung.hibernate.optimisticlocking; -import com.baeldung.hibernate.HibernateUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import java.io.IOException; +import java.util.Arrays; import javax.persistence.EntityManager; import javax.persistence.LockModeType; import javax.persistence.OptimisticLockException; -import java.io.IOException; -import java.util.Arrays; + +import org.hibernate.SessionFactory; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.hibernate.HibernateUtil; public class OptimisticLockingIntegrationTest { + + private static SessionFactory sessionFactory; @Before public void setUp() throws IOException { @@ -124,11 +130,17 @@ public class OptimisticLockingIntegrationTest { protected static EntityManager getEntityManagerWithOpenTransaction() throws IOException { String propertyFileName = "hibernate-pessimistic-locking.properties"; - EntityManager entityManager = HibernateUtil.getSessionFactory(propertyFileName) - .openSession(); - entityManager.getTransaction() - .begin(); + if (sessionFactory == null) { + sessionFactory = HibernateUtil.getSessionFactory(propertyFileName); + } + EntityManager entityManager = sessionFactory.openSession(); + entityManager.getTransaction().begin(); return entityManager; } + + @AfterClass + public static void afterTests() { + sessionFactory.close(); + } } diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java index f416c11d1f..4b9c7720fd 100644 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java @@ -2,6 +2,9 @@ package com.baeldung.hibernate.pessimisticlocking; import com.baeldung.hibernate.HibernateUtil; import com.vividsolutions.jts.util.Assert; + +import org.hibernate.SessionFactory; +import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; @@ -10,6 +13,8 @@ import java.io.IOException; import java.util.Arrays; public class BasicPessimisticLockingIntegrationTest { + + private static SessionFactory sessionFactory; @BeforeClass public static void setUp() throws IOException { @@ -140,12 +145,18 @@ public class BasicPessimisticLockingIntegrationTest { protected static EntityManager getEntityManagerWithOpenTransaction() throws IOException { String propertyFileName = "hibernate-pessimistic-locking.properties"; - EntityManager entityManager = HibernateUtil.getSessionFactory(propertyFileName) - .openSession(); - entityManager.getTransaction() - .begin(); + if (sessionFactory == null) { + sessionFactory = HibernateUtil.getSessionFactory(propertyFileName); + } + EntityManager entityManager = sessionFactory.openSession(); + entityManager.getTransaction().begin(); return entityManager; } + + @AfterClass + public static void afterTests() { + sessionFactory.close(); + } } diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java index ac56ab7133..81cb7d95f8 100644 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java @@ -1,6 +1,9 @@ package com.baeldung.hibernate.pessimisticlocking; import com.baeldung.hibernate.HibernateUtil; + +import org.hibernate.SessionFactory; +import org.junit.AfterClass; import org.junit.Test; import javax.persistence.EntityManager; @@ -13,6 +16,8 @@ import java.util.HashMap; import java.util.Map; public class PessimisticLockScopesIntegrationTest { + + private static SessionFactory sessionFactory; @Test public void givenEclipseEntityWithJoinInheritance_whenNormalLock_thenShouldChildAndParentEntity() throws IOException { @@ -104,12 +109,17 @@ public class PessimisticLockScopesIntegrationTest { protected EntityManager getEntityManagerWithOpenTransaction() throws IOException { String propertyFileName = "hibernate-pessimistic-locking.properties"; - EntityManager entityManager = HibernateUtil.getSessionFactory(propertyFileName) - .openSession(); - entityManager.getTransaction() - .begin(); + if (sessionFactory == null) { + sessionFactory = HibernateUtil.getSessionFactory(propertyFileName); + } + EntityManager entityManager = sessionFactory.openSession(); + entityManager.getTransaction().begin(); return entityManager; } - + + @AfterClass + public static void afterTests() { + sessionFactory.close(); + } } diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-customtypes.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-customtypes.properties index 345f3d37b0..c14782ce0f 100644 --- a/persistence-modules/hibernate5/src/test/resources/hibernate-customtypes.properties +++ b/persistence-modules/hibernate5/src/test/resources/hibernate-customtypes.properties @@ -1,10 +1,14 @@ -hibernate.connection.driver_class=org.postgresql.Driver -hibernate.connection.url=jdbc:postgresql://localhost:5432/test -hibernate.connection.username=postgres -hibernate.connection.password=thule +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa hibernate.connection.autocommit=true -jdbc.password=thule +jdbc.password= -hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect +hibernate.dialect=org.hibernate.dialect.H2Dialect hibernate.show_sql=true -hibernate.hbm2ddl.auto=create-drop \ No newline at end of file +hibernate.hbm2ddl.auto=create-drop + +hibernate.c3p0.min_size=5 +hibernate.c3p0.max_size=20 +hibernate.c3p0.acquire_increment=5 +hibernate.c3p0.timeout=1800 diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-pessimistic-locking.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-pessimistic-locking.properties index c76bd3358b..4f1ff5e93a 100644 --- a/persistence-modules/hibernate5/src/test/resources/hibernate-pessimistic-locking.properties +++ b/persistence-modules/hibernate5/src/test/resources/hibernate-pessimistic-locking.properties @@ -1,5 +1,5 @@ hibernate.connection.driver_class=org.h2.Driver -hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=100;MVCC=FALSE +hibernate.connection.url=jdbc:h2:mem:mydb3;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=100;MVCC=FALSE hibernate.connection.username=sa hibernate.connection.autocommit=true hibernate.dialect=org.hibernate.dialect.H2Dialect diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-spatial.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-spatial.properties index e85cd49cc3..1657c838e3 100644 --- a/persistence-modules/hibernate5/src/test/resources/hibernate-spatial.properties +++ b/persistence-modules/hibernate5/src/test/resources/hibernate-spatial.properties @@ -1,10 +1,14 @@ -hibernate.dialect=org.hibernate.spatial.dialect.mysql.MySQL56SpatialDialect -hibernate.connection.driver_class=com.mysql.jdbc.Driver -hibernate.connection.url=jdbc:mysql://localhost:3306/hibernate-spatial -hibernate.connection.username=root -hibernate.connection.password=pass -hibernate.connection.pool_size=5 +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +hibernate.connection.autocommit=true +jdbc.password= + +hibernate.dialect=org.hibernate.spatial.dialect.h2geodb.GeoDBDialect hibernate.show_sql=true -hibernate.format_sql=true -hibernate.max_fetch_depth=5 -hibernate.hbm2ddl.auto=create-drop \ No newline at end of file +hibernate.hbm2ddl.auto=create-drop + +hibernate.c3p0.min_size=5 +hibernate.c3p0.max_size=20 +hibernate.c3p0.acquire_increment=5 +hibernate.c3p0.timeout=1800 diff --git a/persistence-modules/java-jdbi/README.md b/persistence-modules/java-jdbi/README.md index 7d843af9ea..4c1ff931ce 100644 --- a/persistence-modules/java-jdbi/README.md +++ b/persistence-modules/java-jdbi/README.md @@ -1 +1,3 @@ ### Relevant Articles: + +- [A Guide to Jdbi](http://www.baeldung.com/jdbi) diff --git a/persistence-modules/java-jpa/README.md b/persistence-modules/java-jpa/README.md index 34d03b3259..ca9ec0d74d 100644 --- a/persistence-modules/java-jpa/README.md +++ b/persistence-modules/java-jpa/README.md @@ -8,3 +8,6 @@ - [Converting Between LocalDate and SQL Date](https://www.baeldung.com/java-convert-localdate-sql-date) - [Combining JPA And/Or Criteria Predicates](https://www.baeldung.com/jpa-and-or-criteria-predicates) - [Types of JPA Queries](https://www.baeldung.com/jpa-queries) +- [Defining JPA Entities](https://www.baeldung.com/jpa-entities) +- [JPA @Basic Annotation](https://www.baeldung.com/jpa-basic-annotation) +- [Default Column Values in JPA](https://www.baeldung.com/jpa-default-column-values) diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Account.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Account.java new file mode 100644 index 0000000000..48a98512fa --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Account.java @@ -0,0 +1,43 @@ +package com.baeldung.jpa.entity; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.IdClass; + +@Entity +@IdClass(AccountId.class) +public class Account { + + @Id + private String accountNumber; + + @Id + private String accountType; + + private String description; + + public String getAccountNumber() { + return accountNumber; + } + + public void setAccountNumber(String accountNumber) { + this.accountNumber = accountNumber; + } + + public String getAccountType() { + return accountType; + } + + public void setAccountType(String accountType) { + this.accountType = accountType; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + +} diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/AccountId.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/AccountId.java new file mode 100644 index 0000000000..091c326367 --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/AccountId.java @@ -0,0 +1,52 @@ +package com.baeldung.jpa.entity; + +import java.io.Serializable; + +public class AccountId implements Serializable { + + private static final long serialVersionUID = 1L; + + private String accountNumber; + private String accountType; + + public AccountId() { + + } + + public AccountId(String accountNumber, String accountType) { + this.accountNumber = accountNumber; + this.accountType = accountType; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((accountNumber == null) ? 0 : accountNumber.hashCode()); + result = prime * result + ((accountType == null) ? 0 : accountType.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + AccountId other = (AccountId) obj; + if (accountNumber == null) { + if (other.accountNumber != null) + return false; + } else if (!accountNumber.equals(other.accountNumber)) + return false; + if (accountType == null) { + if (other.accountType != null) + return false; + } else if (!accountType.equals(other.accountType)) + return false; + return true; + } + +} diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Book.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Book.java new file mode 100644 index 0000000000..460f302e28 --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Book.java @@ -0,0 +1,34 @@ +package com.baeldung.jpa.entity; + +import javax.persistence.EmbeddedId; +import javax.persistence.Entity; + +@Entity +public class Book { + + @EmbeddedId + private BookId bookId; + + private String description; + + public Book() { + + } + + public Book(BookId bookId) { + this.bookId = bookId; + } + + public BookId getBookId() { + return bookId; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + +} diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/BookId.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/BookId.java new file mode 100644 index 0000000000..ff587beaf2 --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/BookId.java @@ -0,0 +1,62 @@ +package com.baeldung.jpa.entity; + +import java.io.Serializable; + +import javax.persistence.Embeddable; + +@Embeddable +public class BookId implements Serializable { + + private static final long serialVersionUID = 1L; + private String title; + private String language; + + public BookId() { + + } + + public BookId(String title, String language) { + this.title = title; + this.language = language; + } + + public String getTitle() { + return title; + } + + public String getLanguage() { + return language; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((language == null) ? 0 : language.hashCode()); + result = prime * result + ((title == null) ? 0 : title.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + BookId other = (BookId) obj; + if (language == null) { + if (other.language != null) + return false; + } else if (!language.equals(other.language)) + return false; + if (title == null) { + if (other.title != null) + return false; + } else if (!title.equals(other.title)) + return false; + return true; + } + +} diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/projections/Product.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/projections/Product.java new file mode 100644 index 0000000000..90f90be0c0 --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/projections/Product.java @@ -0,0 +1,50 @@ +package com.baeldung.jpa.projections; + +import java.math.BigDecimal; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Product { + @Id + private long id; + private String name; + private String description; + private String category; + private BigDecimal unitPrice; + + public long getId() { + return id; + } + public void setId(long id) { + this.id = id; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + public String getCategory() { + return category; + } + public void setCategory(String category) { + this.category = category; + } + public BigDecimal getUnitPrice() { + return unitPrice; + } + public void setUnitPrice(BigDecimal unitPrice) { + this.unitPrice = unitPrice; + } + +} diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/projections/ProductRepository.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/projections/ProductRepository.java new file mode 100644 index 0000000000..bb269e1de6 --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/projections/ProductRepository.java @@ -0,0 +1,93 @@ +package com.baeldung.jpa.projections; + +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import javax.persistence.Query; +import javax.persistence.Tuple; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; + +public class ProductRepository { + private EntityManager entityManager; + + public ProductRepository() { + EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpa-projections"); + entityManager = factory.createEntityManager(); + } + + @SuppressWarnings("unchecked") + public List findAllNamesUsingJPQL() { + Query query = entityManager.createQuery("select name from Product"); + List resultList = query.getResultList(); + return resultList; + } + + @SuppressWarnings("unchecked") + public List findAllIdsUsingJPQL() { + Query query = entityManager.createQuery("select id from Product"); + List resultList = query.getResultList(); + return resultList; + } + + public List findAllNamesUsingCriteriaBuilder() { + CriteriaBuilder builder = entityManager.getCriteriaBuilder(); + CriteriaQuery query = builder.createQuery(String.class); + Root product = query.from(Product.class); + query.select(product.get("name")); + List resultList = entityManager.createQuery(query).getResultList(); + return resultList; + } + + @SuppressWarnings("unchecked") + public List findAllIdAndNamesUsingJPQL() { + Query query = entityManager.createQuery("select id, name from Product"); + List resultList = query.getResultList(); + return resultList; + } + + public List findAllIdAndNamesUsingCriteriaBuilderArray() { + CriteriaBuilder builder = entityManager.getCriteriaBuilder(); + CriteriaQuery query = builder.createQuery(Object[].class); + Root product = query.from(Product.class); + query.select(builder.array(product.get("id"), product.get("name"))); + List resultList = entityManager.createQuery(query).getResultList(); + return resultList; + } + + public List findAllIdNameUnitPriceUsingCriteriaQueryMultiselect() { + CriteriaBuilder builder = entityManager.getCriteriaBuilder(); + CriteriaQuery query = builder.createQuery(Object[].class); + Root product = query.from(Product.class); + query.multiselect(product.get("id"), product.get("name"), product.get("unitPrice")); + List resultList = entityManager.createQuery(query).getResultList(); + return resultList; + } + + public List findAllIdAndNamesUsingCriteriaBuilderTuple() { + CriteriaBuilder builder = entityManager.getCriteriaBuilder(); + CriteriaQuery query = builder.createQuery(Tuple.class); + Root product = query.from(Product.class); + query.select(builder.tuple(product.get("id"), product.get("name"))); + List resultList = entityManager.createQuery(query).getResultList(); + return resultList; + } + + public List findCountByCategoryUsingJPQL() { + Query query = entityManager.createQuery("select p.category, count(p) from Product p group by p.category"); + return query.getResultList(); + } + + public List findCountByCategoryUsingCriteriaBuilder() { + CriteriaBuilder builder = entityManager.getCriteriaBuilder(); + CriteriaQuery query = builder.createQuery(Object[].class); + Root product = query.from(Product.class); + query.multiselect(product.get("category"), builder.count(product)); + query.groupBy(product.get("category")); + List resultList = entityManager.createQuery(query).getResultList(); + return resultList; + } +} diff --git a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml index 9c5543bc3c..1f16bee3ba 100644 --- a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml +++ b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml @@ -1,166 +1,227 @@ + version="2.2"> - - org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.sqlresultsetmapping.ScheduledDay - com.baeldung.sqlresultsetmapping.Employee - true - - - - - - - - - - - + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.sqlresultsetmapping.ScheduledDay + com.baeldung.sqlresultsetmapping.Employee + com.baeldung.jpa.basicannotation.Course + true + + + + + + + + + + + - - org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.jpa.stringcast.Message - com.baeldung.jpa.enums.Article - com.baeldung.jpa.enums.CategoryConverter - true - - - - - - - - - - - + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.stringcast.Message + com.baeldung.jpa.enums.Article + com.baeldung.jpa.enums.CategoryConverter + true + + + + + + + + + + + - - org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.jpa.model.Car - true - - - - - - - - - + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.model.Car + true + + + + + + + + + - - com.baeldung.jpa.entitygraph.model.Post - com.baeldung.jpa.entitygraph.model.User - com.baeldung.jpa.entitygraph.model.Comment - true - + + com.baeldung.jpa.entitygraph.model.Post + com.baeldung.jpa.entitygraph.model.User + com.baeldung.jpa.entitygraph.model.Comment + true + - - - + + + - - - - + + + + - - org.eclipse.persistence.jpa.PersistenceProvider - com.baeldung.jpa.datetime.JPA22DateTimeEntity - true - - - - - - + + org.eclipse.persistence.jpa.PersistenceProvider + com.baeldung.jpa.datetime.JPA22DateTimeEntity + true + + + + + + - - - - - - + + + + + + - - org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.jpa.criteria.entity.Item - true - - - - - - - - - - - - + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.criteria.entity.Item + true + + + + + + + + + + + + - - org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.jpa.querytypes.UserEntity - true - - - - - - - - - - - - + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.querytypes.UserEntity + true + + + + + + + + + + + + - - org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.jpa.defaultvalues.User - true - - - - - - - - - - - - - - org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.jpa.entity.Student - true - - - - - - - - - - - + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.defaultvalues.User + true + + + + + + + + + + + + + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.entity.Student + com.baeldung.jpa.entity.Book + com.baeldung.jpa.entity.BookId + com.baeldung.jpa.entity.Account + com.baeldung.jpa.entity.AccountId + true + + + + + + + + + + + + + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.projections.Product + true + + + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/java-jpa/src/main/resources/database.sql b/persistence-modules/java-jpa/src/main/resources/database.sql index bd2bb68599..96fa5b3b09 100644 --- a/persistence-modules/java-jpa/src/main/resources/database.sql +++ b/persistence-modules/java-jpa/src/main/resources/database.sql @@ -15,3 +15,7 @@ INSERT INTO SCHEDULE_DAYS (employeeId, dayOfWeek) VALUES (1, 'FRIDAY'); INSERT INTO SCHEDULE_DAYS (employeeId, dayOfWeek) VALUES (2, 'SATURDAY'); INSERT INTO SCHEDULE_DAYS (employeeId, dayOfWeek) VALUES (3, 'MONDAY'); INSERT INTO SCHEDULE_DAYS (employeeId, dayOfWeek) VALUES (3, 'FRIDAY'); + +CREATE TABLE COURSE +(id BIGINT, + name VARCHAR(10)); \ No newline at end of file diff --git a/persistence-modules/java-jpa/src/main/resources/products_jpa.sql b/persistence-modules/java-jpa/src/main/resources/products_jpa.sql new file mode 100644 index 0000000000..43bc294f56 --- /dev/null +++ b/persistence-modules/java-jpa/src/main/resources/products_jpa.sql @@ -0,0 +1,4 @@ +insert into product(id, name, description, category) values (1,'Product Name 1','This is Product 1', 'category1'); +insert into product(id, name, description, category) values (2,'Product Name 2','This is Product 2', 'category1'); +insert into product(id, name, description, category) values (3,'Product Name 3','This is Product 3', 'category2'); +insert into product(id, name, description, category) values (4,'Product Name 4','This is Product 4', 'category3'); diff --git a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/basicannotation/BasicAnnotationIntegrationTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/basicannotation/BasicAnnotationIntegrationTest.java index 8580aa6602..d3f75804de 100644 --- a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/basicannotation/BasicAnnotationIntegrationTest.java +++ b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/basicannotation/BasicAnnotationIntegrationTest.java @@ -1,16 +1,13 @@ package com.baeldung.jpa.basicannotation; -import org.hibernate.PropertyValueException; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.AfterClass; -import org.junit.Test; +import javax.persistence.PersistenceException; -import java.io.IOException; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; public class BasicAnnotationIntegrationTest { @@ -18,9 +15,10 @@ public class BasicAnnotationIntegrationTest { private static EntityManagerFactory entityManagerFactory; @BeforeClass - public void setup() { + public static void setup() { entityManagerFactory = Persistence.createEntityManagerFactory("java-jpa-scheduled-day"); entityManager = entityManagerFactory.createEntityManager(); + entityManager.getTransaction().begin(); } @Test @@ -34,7 +32,7 @@ public class BasicAnnotationIntegrationTest { } - @Test(expected = PropertyValueException.class) + @Test(expected = PersistenceException.class) public void givenACourse_whenCourseNameAbsent_shouldFail() { Course course = new Course(); @@ -44,7 +42,7 @@ public class BasicAnnotationIntegrationTest { } @AfterClass - public void destroy() { + public static void destroy() { if (entityManager != null) { entityManager.close(); diff --git a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/defautlvalues/UserDefaultValuesUnitTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/defaultvalues/UserDefaultValuesUnitTest.java similarity index 100% rename from persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/defautlvalues/UserDefaultValuesUnitTest.java rename to persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/defaultvalues/UserDefaultValuesUnitTest.java diff --git a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/entity/CompositeKeysIntegrationTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/entity/CompositeKeysIntegrationTest.java new file mode 100644 index 0000000000..2d30ebab5e --- /dev/null +++ b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/entity/CompositeKeysIntegrationTest.java @@ -0,0 +1,114 @@ +package com.baeldung.jpa.entity; + +import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +public class CompositeKeysIntegrationTest { + + private static final String SAVINGS_ACCOUNT = "Savings"; + private static final String ACCOUNT_NUMBER = "JXSDF324234"; + private static final String ENGLISH = "English"; + private static final String WAR_AND_PEACE = "War and Peace"; + + private static EntityManagerFactory emf; + private static EntityManager em; + + @BeforeClass + public static void setup() { + emf = Persistence.createEntityManagerFactory("jpa-entity-definition"); + em = emf.createEntityManager(); + } + + @Test + public void persistBookWithCompositeKeyThenRetrieveDetails() { + Book warAndPeace = createBook(); + persist(warAndPeace); + clearThePersistenceContext(); + Book book = findBookByBookId(); + verifyAssertionsWith(book); + } + + @Test + public void persistAccountWithCompositeKeyThenRetrieveDetails() { + Account savingsAccount = createAccount(); + persist(savingsAccount); + clearThePersistenceContext(); + Account account = findAccountByAccountId(); + verifyAssertionsWith(account); + } + + @AfterClass + public static void destroy() { + if (em != null) { + em.close(); + } + if (emf != null) { + emf.close(); + } + } + + private Account createAccount() { + Account savingsAccount = new Account(); + savingsAccount.setAccountNumber(ACCOUNT_NUMBER); + savingsAccount.setAccountType(SAVINGS_ACCOUNT); + savingsAccount.setDescription("Savings account"); + return savingsAccount; + } + + private void verifyAssertionsWith(Account account) { + assertEquals(ACCOUNT_NUMBER, account.getAccountNumber()); + assertEquals(SAVINGS_ACCOUNT, account.getAccountType()); + } + + private Account findAccountByAccountId() { + return em.find(Account.class, new AccountId(ACCOUNT_NUMBER, SAVINGS_ACCOUNT)); + } + + private void persist(Account account) { + em.getTransaction() + .begin(); + em.persist(account); + em.getTransaction() + .commit(); + } + + private Book findBookByBookId() { + return em.find(Book.class, new BookId(WAR_AND_PEACE, ENGLISH)); + } + + private Book createBook() { + BookId bookId = new BookId(WAR_AND_PEACE, ENGLISH); + Book warAndPeace = new Book(bookId); + warAndPeace.setDescription("Novel and Historical Fiction"); + return warAndPeace; + } + + private void verifyAssertionsWith(Book book) { + assertNotNull(book); + assertNotNull(book.getBookId()); + assertEquals(WAR_AND_PEACE, book.getBookId() + .getTitle()); + assertEquals(ENGLISH, book.getBookId() + .getLanguage()); + } + + private void persist(Book book) { + em.getTransaction() + .begin(); + em.persist(book); + em.getTransaction() + .commit(); + } + + private void clearThePersistenceContext() { + em.clear(); + } +} diff --git a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/projections/HibernateProjectionsIntegrationTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/projections/HibernateProjectionsIntegrationTest.java new file mode 100644 index 0000000000..47cc7cbaec --- /dev/null +++ b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/projections/HibernateProjectionsIntegrationTest.java @@ -0,0 +1,133 @@ +package com.baeldung.jpa.projections; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.List; + +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.cfg.AvailableSettings; +import org.hibernate.cfg.Configuration; +import org.hibernate.criterion.Order; +import org.hibernate.criterion.Projections; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +public class HibernateProjectionsIntegrationTest { + private static Session session; + private static SessionFactory sessionFactory; + private Transaction transaction; + + @BeforeClass + public static void init() { + Configuration configuration = getConfiguration(); + configuration.addAnnotatedClass(Product.class); + sessionFactory = configuration.buildSessionFactory(); + } + + @Before + public void before() { + session = sessionFactory.getCurrentSession(); + transaction = session.beginTransaction(); + } + + @After + public void after() { + if(transaction.isActive()) { + transaction.rollback(); + } + } + + private static Configuration getConfiguration() { + Configuration cfg = new Configuration(); + cfg.setProperty(AvailableSettings.DIALECT, + "org.hibernate.dialect.H2Dialect"); + cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "none"); + cfg.setProperty(AvailableSettings.DRIVER, "org.h2.Driver"); + cfg.setProperty(AvailableSettings.URL, + "jdbc:h2:mem:myexceptiondb2;DB_CLOSE_DELAY=-1;;INIT=RUNSCRIPT FROM 'src/test/resources/products.sql'"); + cfg.setProperty(AvailableSettings.USER, "sa"); + cfg.setProperty(AvailableSettings.PASS, ""); + cfg.setProperty(AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS, "thread"); + return cfg; + } + + + @SuppressWarnings("deprecation") + @Test + public void givenProductData_whenIdAndNameProjectionUsingCriteria_thenListOfObjectArrayReturned() { + Criteria criteria = session.createCriteria(Product.class); + criteria = criteria.setProjection(Projections.projectionList() + .add(Projections.id()) + .add(Projections.property("name"))); + List resultList = criteria.list(); + + assertNotNull(resultList); + assertEquals(4, resultList.size()); + assertEquals(1L, resultList.get(0)[0]); + assertEquals("Product Name 1", resultList.get(0)[1]); + assertEquals(2L, resultList.get(1)[0]); + assertEquals("Product Name 2", resultList.get(1)[1]); + assertEquals(3L, resultList.get(2)[0]); + assertEquals("Product Name 3", resultList.get(2)[1]); + assertEquals(4L, resultList.get(3)[0]); + assertEquals("Product Name 4", resultList.get(3)[1]); + } + + + @Test + public void givenProductData_whenNameProjectionUsingCriteria_thenListOfStringReturned() { + Criteria criteria = session.createCriteria(Product.class); + criteria = criteria.setProjection(Projections.property("name")); + List resultList = criteria.list(); + + assertNotNull(resultList); + assertEquals(4, resultList.size()); + assertEquals("Product Name 1", resultList.get(0)); + assertEquals("Product Name 2", resultList.get(1)); + assertEquals("Product Name 3", resultList.get(2)); + assertEquals("Product Name 4", resultList.get(3)); + } + + @Test + public void givenProductData_whenCountByCategoryUsingCriteria_thenOK() { + Criteria criteria = session.createCriteria(Product.class); + criteria = criteria.setProjection(Projections.projectionList() + .add(Projections.groupProperty("category")) + .add(Projections.rowCount())); + List resultList = criteria.list(); + + assertNotNull(resultList); + assertEquals(3, resultList.size()); + assertEquals("category1", resultList.get(0)[0]); + assertEquals(2L, resultList.get(0)[1]); + assertEquals("category2", resultList.get(1)[0]); + assertEquals(1L, resultList.get(1)[1]); + assertEquals("category3", resultList.get(2)[0]); + assertEquals(1L, resultList.get(2)[1]); + } + + @Test + public void givenProductData_whenCountByCategoryWithAliasUsingCriteria_thenOK() { + Criteria criteria = session.createCriteria(Product.class); + criteria = criteria.setProjection(Projections.projectionList() + .add(Projections.groupProperty("category")) + .add(Projections.alias(Projections.rowCount(), "count"))); + criteria.addOrder(Order.asc("count")); + List resultList = criteria.list(); + + assertNotNull(resultList); + assertEquals(3, resultList.size()); + assertEquals("category2", resultList.get(0)[0]); + assertEquals(1L, resultList.get(0)[1]); + assertEquals("category3", resultList.get(1)[0]); + assertEquals(1L, resultList.get(1)[1]); + assertEquals("category1", resultList.get(2)[0]); + assertEquals(2L, resultList.get(2)[1]); + } +} diff --git a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/projections/ProductRepositoryIntegrationTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/projections/ProductRepositoryIntegrationTest.java new file mode 100644 index 0000000000..c9a05709e3 --- /dev/null +++ b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/projections/ProductRepositoryIntegrationTest.java @@ -0,0 +1,105 @@ +package com.baeldung.jpa.projections; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.io.IOException; +import java.util.List; + +import org.junit.BeforeClass; +import org.junit.Test; + + +public class ProductRepositoryIntegrationTest { + private static ProductRepository productRepository; + + @BeforeClass + public static void once() throws IOException { + productRepository = new ProductRepository(); + } + + @Test + public void givenProductData_whenIdAndNameProjectionUsingJPQL_thenListOfObjectArrayReturned() { + List resultList = productRepository.findAllIdAndNamesUsingJPQL(); + + assertNotNull(resultList); + assertEquals(4, resultList.size()); + assertEquals(1L, resultList.get(0)[0]); + assertEquals("Product Name 1", resultList.get(0)[1]); + assertEquals(2L, resultList.get(1)[0]); + assertEquals("Product Name 2", resultList.get(1)[1]); + assertEquals(3L, resultList.get(2)[0]); + assertEquals("Product Name 3", resultList.get(2)[1]); + assertEquals(4L, resultList.get(3)[0]); + assertEquals("Product Name 4", resultList.get(3)[1]); + } + + @Test + public void givenProductData_whenIdAndNameProjectionUsingCriteriaBuilder_thenListOfObjectArrayReturned() { + List resultList = productRepository.findAllIdAndNamesUsingCriteriaBuilderArray(); + + assertNotNull(resultList); + assertEquals(4, resultList.size()); + assertEquals(1L, resultList.get(0)[0]); + assertEquals("Product Name 1", resultList.get(0)[1]); + assertEquals(2L, resultList.get(1)[0]); + assertEquals("Product Name 2", resultList.get(1)[1]); + assertEquals(3L, resultList.get(2)[0]); + assertEquals("Product Name 3", resultList.get(2)[1]); + assertEquals(4L, resultList.get(3)[0]); + assertEquals("Product Name 4", resultList.get(3)[1]); + } + + @SuppressWarnings("rawtypes") + @Test + public void givenProductData_whenNameProjectionUsingJPQL_thenListOfStringReturned() { + List resultList = productRepository.findAllNamesUsingJPQL(); + + assertNotNull(resultList); + assertEquals(4, resultList.size()); + assertEquals("Product Name 1", resultList.get(0)); + assertEquals("Product Name 2", resultList.get(1)); + assertEquals("Product Name 3", resultList.get(2)); + assertEquals("Product Name 4", resultList.get(3)); + } + + @Test + public void givenProductData_whenNameProjectionUsingCriteriaBuilder_thenListOfStringReturned() { + List resultList = productRepository.findAllNamesUsingCriteriaBuilder(); + + assertNotNull(resultList); + assertEquals(4, resultList.size()); + assertEquals("Product Name 1", resultList.get(0)); + assertEquals("Product Name 2", resultList.get(1)); + assertEquals("Product Name 3", resultList.get(2)); + assertEquals("Product Name 4", resultList.get(3)); + } + + @Test + public void givenProductData_whenCountByCategoryUsingJPQL_thenOK() { + List resultList = productRepository.findCountByCategoryUsingJPQL(); + + assertNotNull(resultList); + assertEquals(3, resultList.size()); + assertEquals("category1", resultList.get(0)[0]); + assertEquals(2L, resultList.get(0)[1]); + assertEquals("category2", resultList.get(1)[0]); + assertEquals(1L, resultList.get(1)[1]); + assertEquals("category3", resultList.get(2)[0]); + assertEquals(1L, resultList.get(2)[1]); + } + + @Test + public void givenProductData_whenCountByCategoryUsingCriteriaBuider_thenOK() { + List resultList = productRepository.findCountByCategoryUsingCriteriaBuilder(); + + assertNotNull(resultList); + assertEquals(3, resultList.size()); + assertEquals("category1", resultList.get(0)[0]); + assertEquals(2L, resultList.get(0)[1]); + assertEquals("category2", resultList.get(1)[0]); + assertEquals(1L, resultList.get(1)[1]); + assertEquals("category3", resultList.get(2)[0]); + assertEquals(1L, resultList.get(2)[1]); + } +} diff --git a/persistence-modules/java-jpa/src/test/resources/products.sql b/persistence-modules/java-jpa/src/test/resources/products.sql new file mode 100644 index 0000000000..d38ea1b037 --- /dev/null +++ b/persistence-modules/java-jpa/src/test/resources/products.sql @@ -0,0 +1,5 @@ +create table Product (id bigint not null, category varchar(255), description varchar(255), name varchar(255), unitPrice decimal(19,2), primary key (id)); +insert into product(id, name, description, category) values (1,'Product Name 1','This is Product 1', 'category1'); +insert into product(id, name, description, category) values (2,'Product Name 2','This is Product 2', 'category1'); +insert into product(id, name, description, category) values (3,'Product Name 3','This is Product 3', 'category2'); +insert into product(id, name, description, category) values (4,'Product Name 4','This is Product 4', 'category3'); diff --git a/persistence-modules/spring-data-jpa-2/README.md b/persistence-modules/spring-data-jpa-2/README.md index 393d15d6f1..6b73729f9a 100644 --- a/persistence-modules/spring-data-jpa-2/README.md +++ b/persistence-modules/spring-data-jpa-2/README.md @@ -12,3 +12,6 @@ - [Spring Data JPA Projections](https://www.baeldung.com/spring-data-jpa-projections) - [JPA @Embedded And @Embeddable](https://www.baeldung.com/jpa-embedded-embeddable) - [Spring Data JPA Delete and Relationships](https://www.baeldung.com/spring-data-jpa-delete) +- [Spring Data JPA and Named Entity Graphs](https://www.baeldung.com/spring-data-jpa-named-entity-graphs) +- [Batch Insert/Update with Hibernate/JPA](https://www.baeldung.com/jpa-hibernate-batch-insert-update) +- [Difference Between save() and saveAndFlush() in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-save-saveandflush) diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteFromRepositoryUnitTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteFromRepositoryUnitTest.java index 9e7e516735..5f4a36bc0e 100644 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteFromRepositoryUnitTest.java +++ b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteFromRepositoryUnitTest.java @@ -43,22 +43,22 @@ public class DeleteFromRepositoryUnitTest { public void whenDeleteByIdFromRepository_thenDeletingShouldBeSuccessful() { repository.deleteById(book1.getId()); - assertThat(repository.count() == 1).isTrue(); + assertThat(repository.count()).isEqualTo(1); } @Test public void whenDeleteAllFromRepository_thenRepositoryShouldBeEmpty() { repository.deleteAll(); - assertThat(repository.count() == 0).isTrue(); + assertThat(repository.count()).isEqualTo(0); } @Test @Transactional public void whenDeleteFromDerivedQuery_thenDeletingShouldBeSuccessful() { - repository.deleteByTitle("The Hobbit"); + long deletedRecords = repository.deleteByTitle("The Hobbit"); - assertThat(repository.count() == 1).isTrue(); + assertThat(deletedRecords).isEqualTo(1); } @Test @@ -66,7 +66,7 @@ public class DeleteFromRepositoryUnitTest { public void whenDeleteFromCustomQuery_thenDeletingShouldBeSuccessful() { repository.deleteBooks("The Hobbit"); - assertThat(repository.count() == 1).isTrue(); + assertThat(repository.count()).isEqualTo(1); } } \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteInRelationshipsUnitTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteInRelationshipsUnitTest.java index 56de8749b2..6275ace6e0 100644 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteInRelationshipsUnitTest.java +++ b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteInRelationshipsUnitTest.java @@ -46,15 +46,15 @@ public class DeleteInRelationshipsUnitTest { public void whenDeletingCategories_thenBooksShouldAlsoBeDeleted() { categoryRepository.deleteAll(); - assertThat(bookRepository.count() == 0).isTrue(); - assertThat(categoryRepository.count() == 0).isTrue(); + assertThat(bookRepository.count()).isEqualTo(0); + assertThat(categoryRepository.count()).isEqualTo(0); } @Test public void whenDeletingBooks_thenCategoriesShouldAlsoBeDeleted() { bookRepository.deleteAll(); - assertThat(bookRepository.count() == 0).isTrue(); - assertThat(categoryRepository.count() == 2).isTrue(); + assertThat(bookRepository.count()).isEqualTo(0); + assertThat(categoryRepository.count()).isEqualTo(2); } } \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepository.java index d6a060740d..53f692ff28 100644 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepository.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepository.java @@ -94,6 +94,6 @@ public interface UserRepository extends JpaRepository , UserRepos int deleteDeactivatedUsers(); @Modifying(clearAutomatically = true, flushAutomatically = true) - @Query(value = "alter table USERS.USERS add column deleted int(1) not null default 0", nativeQuery = true) + @Query(value = "alter table USERS add column deleted int(1) not null default 0", nativeQuery = true) void addDeletedColumn(); } diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java index 4aeeaf5209..17ee6a94ba 100644 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java +++ b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java @@ -23,7 +23,7 @@ import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.*; -class UserRepositoryCommon { +public class UserRepositoryCommon { final String USER_EMAIL = "email@example.com"; final String USER_EMAIL2 = "email2@example.com"; @@ -280,7 +280,7 @@ class UserRepositoryCommon { userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); - List usersSortByNameLength = userRepository.findAll(new Sort("LENGTH(name)")); + List usersSortByNameLength = userRepository.findAll(Sort.by("LENGTH(name)")); assertThat(usersSortByNameLength.get(0) .getName()).isEqualTo(USER_NAME_ADAM); @@ -292,7 +292,7 @@ class UserRepositoryCommon { userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - userRepository.findAllUsers(new Sort("name")); + userRepository.findAllUsers(Sort.by("name")); List usersSortByNameLength = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)")); @@ -309,7 +309,7 @@ class UserRepositoryCommon { userRepository.save(new User("SAMPLE2", LocalDate.now(), USER_EMAIL5, INACTIVE_STATUS)); userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL6, INACTIVE_STATUS)); - Page usersPage = userRepository.findAllUsersWithPagination(new PageRequest(1, 3)); + Page usersPage = userRepository.findAllUsersWithPagination(PageRequest.of(1, 3)); assertThat(usersPage.getContent() .get(0) @@ -325,7 +325,7 @@ class UserRepositoryCommon { userRepository.save(new User("SAMPLE2", LocalDate.now(), USER_EMAIL5, INACTIVE_STATUS)); userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL6, INACTIVE_STATUS)); - Page usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(new PageRequest(1, 3)); + Page usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(PageRequest.of(1, 3)); assertThat(usersSortByNameLength.getContent() .get(0) diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoLiveTest.java similarity index 95% rename from persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoIntegrationTest.java rename to persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoLiveTest.java index 2f3e9c9032..ab8d97bd75 100644 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoIntegrationTest.java +++ b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoLiveTest.java @@ -22,7 +22,7 @@ import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) @ActiveProfiles({"tc", "tc-auto"}) -public class UserRepositoryTCAutoIntegrationTest extends UserRepositoryCommon { +public class UserRepositoryTCAutoLiveTest extends UserRepositoryCommon { @ClassRule public static PostgreSQLContainer postgreSQLContainer = BaeldungPostgresqlContainer.getInstance(); diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCLiveTest.java similarity index 93% rename from persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCIntegrationTest.java rename to persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCLiveTest.java index afdf60cc81..be8843c166 100644 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCIntegrationTest.java +++ b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCLiveTest.java @@ -22,8 +22,8 @@ import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) @ActiveProfiles("tc") -@ContextConfiguration(initializers = {UserRepositoryTCIntegrationTest.Initializer.class}) -public class UserRepositoryTCIntegrationTest extends UserRepositoryCommon { +@ContextConfiguration(initializers = {UserRepositoryTCLiveTest.Initializer.class}) +public class UserRepositoryTCLiveTest extends UserRepositoryCommon { @ClassRule public static PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer("postgres:11.1") diff --git a/persistence-modules/spring-hibernate-5/README.md b/persistence-modules/spring-hibernate-5/README.md index c48e58fcca..dfcc4e7eb8 100644 --- a/persistence-modules/spring-hibernate-5/README.md +++ b/persistence-modules/spring-hibernate-5/README.md @@ -3,3 +3,4 @@ - [Hibernate Many to Many Annotation Tutorial](http://www.baeldung.com/hibernate-many-to-many) - [Programmatic Transactions in the Spring TestContext Framework](http://www.baeldung.com/spring-test-programmatic-transactions) - [JPA Criteria Queries](http://www.baeldung.com/hibernate-criteria-queries) +- [Introduction to Hibernate Search](http://www.baeldung.com/hibernate-search) diff --git a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java index c3805bac57..31877255b2 100644 --- a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java +++ b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java @@ -3,7 +3,7 @@ package com.baeldung.hibernate.criteria; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; - +import static org.junit.Assert.assertFalse; import java.util.List; import org.hibernate.Session; @@ -25,7 +25,7 @@ public class HibernateCriteriaIntegrationTest { @Test public void testPerformanceOfCriteria() { - assertTrue(av.checkIfCriteriaTimeLower()); + assertFalse(av.checkIfCriteriaTimeLower()); } @Test diff --git a/persistence-modules/spring-persistence-simple/README.md b/persistence-modules/spring-persistence-simple/README.md index c408ff3c96..8e55a59c7c 100644 --- a/persistence-modules/spring-persistence-simple/README.md +++ b/persistence-modules/spring-persistence-simple/README.md @@ -7,13 +7,12 @@ - [A Guide to JPA with Spring](https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa) - [Bootstrapping Hibernate 5 with Spring](http://www.baeldung.com/hibernate-5-spring) - [The DAO with Spring and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate) -- [DAO with Spring and Generics](https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics) +- [Simplify the DAO with Spring and Java Generics](https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics) - [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring) - [Introduction to Spring Data JPA](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) - [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query) - [Spring JDBC](https://www.baeldung.com/spring-jdbc-jdbctemplate) - ### Eclipse Config After importing the project into Eclipse, you may see the following error: "No persistence xml file found in project" diff --git a/pom.xml b/pom.xml index 03d2e5d763..39803fd9b0 100644 --- a/pom.xml +++ b/pom.xml @@ -11,7 +11,6 @@ pom - lombok-custom quarkus @@ -392,6 +391,7 @@ core-java-modules/core-java-concurrency-basic core-java-modules/core-java-concurrency-collections core-java-modules/core-java-io + core-java-modules/core-java-nio core-java-modules/core-java-security core-java-modules/core-java-lang-syntax core-java-modules/core-java-lang @@ -1074,6 +1074,7 @@ core-java-modules/core-java-concurrency-basic core-java-modules/core-java-concurrency-collections core-java-modules/core-java-io + core-java-modules/core-java-nio core-java-modules/core-java-security core-java-modules/core-java-lang-syntax core-java-modules/core-java-lang @@ -1526,7 +1527,8 @@ 1.1.7 - 2.22.0 + + 2.21.0 3.7.0 1.6.0 1.8 @@ -1537,7 +1539,7 @@ 1.19 1.3 1.6.0 - 2.19.1 + 2.21.0 2.5 1.4 3.0.0 diff --git a/quarkus/README.md b/quarkus/README.md new file mode 100644 index 0000000000..01009eab3e --- /dev/null +++ b/quarkus/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Guide to QuarkusIO](hhttps://www.baeldung.com/quarkus-io) diff --git a/spring-batch/src/main/java/org/baeldung/batch/App.java b/spring-batch/src/main/java/org/baeldung/batch/App.java index cea4e8d486..8bf58e65d2 100644 --- a/spring-batch/src/main/java/org/baeldung/batch/App.java +++ b/spring-batch/src/main/java/org/baeldung/batch/App.java @@ -3,6 +3,7 @@ package org.baeldung.batch; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; +import org.springframework.batch.core.JobParametersBuilder; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.context.annotation.AnnotationConfigApplicationContext; @@ -21,7 +22,11 @@ public class App { final Job job = (Job) context.getBean("firstBatchJob"); System.out.println("Starting the batch job"); try { - final JobExecution execution = jobLauncher.run(job, new JobParameters()); + // To enable multiple execution of a job with the same parameters + JobParameters jobParameters = new JobParametersBuilder() + .addString("jobID", String.valueOf(System.currentTimeMillis())) + .toJobParameters(); + final JobExecution execution = jobLauncher.run(job, jobParameters); System.out.println("Job Status : " + execution.getStatus()); System.out.println("Job succeeded"); } catch (final Exception e) { diff --git a/spring-boot-ops-2/src/main/java/com/baeldung/springbootconfiguration/controller/GreetingsController.java b/spring-boot-ops-2/src/main/java/com/baeldung/springbootconfiguration/controller/GreetingsController.java new file mode 100644 index 0000000000..2d73564c4d --- /dev/null +++ b/spring-boot-ops-2/src/main/java/com/baeldung/springbootconfiguration/controller/GreetingsController.java @@ -0,0 +1,14 @@ +package com.baeldung.springbootconfiguration.controller; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class GreetingsController { + + @GetMapping("/greetings/{username}") + public String getGreetings(@PathVariable("username") String userName) { + return "Hello " + userName + ", Good day...!!!"; + } +} diff --git a/spring-boot-ops-2/src/main/resources/application-tomcat.properties b/spring-boot-ops-2/src/main/resources/application-tomcat.properties index d7c1ba9ac3..42d03a066e 100644 --- a/spring-boot-ops-2/src/main/resources/application-tomcat.properties +++ b/spring-boot-ops-2/src/main/resources/application-tomcat.properties @@ -1,5 +1,5 @@ # server configuration -server.port=80 +server.port=4010 server.address=127.0.0.1 ## Error handling configuration @@ -21,3 +21,9 @@ server.tomcat.accesslog.directory=logs server.tomcat.accesslog.file-date-format=yyyy-MM-dd server.tomcat.accesslog.prefix=access_log server.tomcat.accesslog.suffix=.log +server.tomcat.accesslog.pattern=common +server.tomcat.basedir=tomcat + +## Tomcat internal server logs +logging.level.org.apache.tomcat=DEBUG +logging.level.org.apache.catalina=DEBUG \ No newline at end of file diff --git a/spring-boot-ops-2/src/main/resources/application.properties b/spring-boot-ops-2/src/main/resources/application.properties index 8b13789179..fc3fff1d38 100644 --- a/spring-boot-ops-2/src/main/resources/application.properties +++ b/spring-boot-ops-2/src/main/resources/application.properties @@ -1 +1 @@ - +spring.profiles.active=tomcat diff --git a/spring-cloud/README.md b/spring-cloud/README.md deleted file mode 100644 index 5139cdca20..0000000000 --- a/spring-cloud/README.md +++ /dev/null @@ -1,21 +0,0 @@ -## The Module Holds Sources for the Following Articles - -- [Quick Intro to Spring Cloud Configuration](http://www.baeldung.com/spring-cloud-configuration) - - Spring Cloud Config is Spring’s client/server approach for storing and serving distributed configurations across multiple applications and environments. - - In this write-up, we’ll focus on an example of how to setup a Git-backed config server, use it in a simple REST application server and setup a secure environment including encrypted property values. - -- [Introduction to Spring Cloud Netflix – Eureka](http://www.baeldung.com/spring-cloud-netflix-eureka) - - In this article, we’ll introduce client-side service discovery via “Spring Cloud Netflix Eureka“. - - Client-side service discovery allows services to find and communicate with each other without hardcoding hostname and port. The only ‘fixed point’ in such an architecture consists of a service registry with which each service has to register. - -### Relevant Articles: -- [Intro to Spring Cloud Netflix - Hystrix](http://www.baeldung.com/spring-cloud-netflix-hystrix) -- [Dockerizing a Spring Boot Application](http://www.baeldung.com/dockerizing-spring-boot-application) -- [Instance Profile Credentials using Spring Cloud](http://www.baeldung.com/spring-cloud-instance-profiles) -- [Running Spring Boot Applications With Minikube](http://www.baeldung.com/spring-boot-minikube) -- [Introduction to Spring Cloud OpenFeign](https://www.baeldung.com/spring-cloud-openfeign) - diff --git a/spring-cloud/spring-cloud-aws/README.md b/spring-cloud/spring-cloud-aws/README.md index 3b7b4dbcd7..bf33728c74 100644 --- a/spring-cloud/spring-cloud-aws/README.md +++ b/spring-cloud/spring-cloud-aws/README.md @@ -5,6 +5,7 @@ - [Spring Cloud AWS – EC2](https://www.baeldung.com/spring-cloud-aws-ec2) - [Spring Cloud AWS – RDS](https://www.baeldung.com/spring-cloud-aws-rds) - [Spring Cloud AWS – Messaging Support](https://www.baeldung.com/spring-cloud-aws-messaging) +- [Instance Profile Credentials using Spring Cloud](http://www.baeldung.com/spring-cloud-instance-profiles) #### Running the Integration Tests diff --git a/spring-cloud/spring-cloud-config/README.md b/spring-cloud/spring-cloud-config/README.md index b28c750ee6..b7c8c36e65 100644 --- a/spring-cloud/spring-cloud-config/README.md +++ b/spring-cloud/spring-cloud-config/README.md @@ -1,2 +1,3 @@ ### Relevant Articles: +- [Quick Intro to Spring Cloud Configuration](http://www.baeldung.com/spring-cloud-configuration) - [Dockerizing a Spring Boot Application](http://www.baeldung.com/dockerizing-spring-boot-application) diff --git a/spring-cloud/spring-cloud-openfeign/README.md b/spring-cloud/spring-cloud-openfeign/README.md new file mode 100644 index 0000000000..e5777732e4 --- /dev/null +++ b/spring-cloud/spring-cloud-openfeign/README.md @@ -0,0 +1,4 @@ +### Relevant Articles: + +- [Introduction to Spring Cloud OpenFeign](https://www.baeldung.com/spring-cloud-openfeign) + diff --git a/spring-data-rest/src/main/java/com/baeldung/SpringDataRestApplication.java b/spring-data-rest/src/main/java/com/baeldung/SpringDataRestApplication.java index 94eddc5b3e..702acb5b65 100644 --- a/spring-data-rest/src/main/java/com/baeldung/SpringDataRestApplication.java +++ b/spring-data-rest/src/main/java/com/baeldung/SpringDataRestApplication.java @@ -5,7 +5,9 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringDataRestApplication { + public static void main(String[] args) { SpringApplication.run(SpringDataRestApplication.class, args); } + } diff --git a/spring-data-rest/src/main/java/com/baeldung/springdatawebsupport/application/controllers/UserController.java b/spring-data-rest/src/main/java/com/baeldung/springdatawebsupport/application/controllers/UserController.java index 8258c3b7aa..eb5d8d51d4 100644 --- a/spring-data-rest/src/main/java/com/baeldung/springdatawebsupport/application/controllers/UserController.java +++ b/spring-data-rest/src/main/java/com/baeldung/springdatawebsupport/application/controllers/UserController.java @@ -1,8 +1,5 @@ package com.baeldung.springdatawebsupport.application.controllers; -import com.baeldung.springdatawebsupport.application.entities.User; -import com.baeldung.springdatawebsupport.application.repositories.UserRepository; -import com.querydsl.core.types.Predicate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; @@ -11,9 +8,12 @@ import org.springframework.data.domain.Sort; import org.springframework.data.querydsl.binding.QuerydslPredicate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import com.baeldung.springdatawebsupport.application.entities.User; +import com.baeldung.springdatawebsupport.application.repositories.UserRepository; +import com.querydsl.core.types.Predicate; + @RestController public class UserController { @@ -33,7 +33,7 @@ public class UserController { public Page findAllUsers(Pageable pageable) { return userRepository.findAll(pageable); } - + @GetMapping("/sortedusers") public Page findAllUsersSortedByName() { Pageable pageable = PageRequest.of(0, 5, Sort.by("name")); diff --git a/spring-data-rest/src/main/java/com/baeldung/springdatawebsupport/application/repositories/UserRepository.java b/spring-data-rest/src/main/java/com/baeldung/springdatawebsupport/application/repositories/UserRepository.java index 41d7ed9d98..a20197dc8b 100644 --- a/spring-data-rest/src/main/java/com/baeldung/springdatawebsupport/application/repositories/UserRepository.java +++ b/spring-data-rest/src/main/java/com/baeldung/springdatawebsupport/application/repositories/UserRepository.java @@ -8,7 +8,6 @@ import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.stereotype.Repository; @Repository -public interface UserRepository extends PagingAndSortingRepository, - QuerydslPredicateExecutor { +public interface UserRepository extends PagingAndSortingRepository, QuerydslPredicateExecutor { } diff --git a/spring-data-rest/src/test/java/com/baeldung/springdatawebsupport/application/test/UserControllerIntegrationTest.java b/spring-data-rest/src/test/java/com/baeldung/springdatawebsupport/application/test/UserControllerIntegrationTest.java index db522b1413..e1aff7e09d 100644 --- a/spring-data-rest/src/test/java/com/baeldung/springdatawebsupport/application/test/UserControllerIntegrationTest.java +++ b/spring-data-rest/src/test/java/com/baeldung/springdatawebsupport/application/test/UserControllerIntegrationTest.java @@ -31,44 +31,28 @@ public class UserControllerIntegrationTest { @Test public void whenGetRequestToUsersEndPointWithIdPathVariable_thenCorrectResponse() throws Exception { - mockMvc.perform(MockMvcRequestBuilders.get("/users/{id}", "1") - .contentType(MediaType.APPLICATION_JSON_UTF8)) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.jsonPath("$.id").value("1")); + mockMvc.perform(MockMvcRequestBuilders.get("/users/{id}", "1").contentType(MediaType.APPLICATION_JSON_UTF8)).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.jsonPath("$.id").value("1")); } @Test public void whenGetRequestToUsersEndPoint_thenCorrectResponse() throws Exception { - mockMvc.perform(MockMvcRequestBuilders.get("/users") - .contentType(MediaType.APPLICATION_JSON_UTF8)) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.jsonPath("$['pageable']['paged']").value("true")); + mockMvc.perform(MockMvcRequestBuilders.get("/users").contentType(MediaType.APPLICATION_JSON_UTF8)).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.jsonPath("$['pageable']['paged']").value("true")); } @Test public void whenGetRequestToUserEndPointWithNameRequestParameter_thenCorrectResponse() throws Exception { - mockMvc.perform(MockMvcRequestBuilders.get("/user") - .param("name", "John") - .contentType(MediaType.APPLICATION_JSON_UTF8)) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.jsonPath("$['content'][0].['name']").value("John")); + mockMvc.perform(MockMvcRequestBuilders.get("/user").param("name", "John").contentType(MediaType.APPLICATION_JSON_UTF8)).andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$['content'][0].['name']").value("John")); } @Test public void whenGetRequestToSorteredUsersEndPoint_thenCorrectResponse() throws Exception { - mockMvc.perform(MockMvcRequestBuilders.get("/sortedusers") - .contentType(MediaType.APPLICATION_JSON_UTF8)) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.jsonPath("$['sort']['sorted']").value("true")); + mockMvc.perform(MockMvcRequestBuilders.get("/sortedusers").contentType(MediaType.APPLICATION_JSON_UTF8)).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.jsonPath("$['sort']['sorted']").value("true")); } @Test public void whenGetRequestToFilteredUsersEndPoint_thenCorrectResponse() throws Exception { - mockMvc.perform(MockMvcRequestBuilders.get("/filteredusers") - .param("name", "John") - .contentType(MediaType.APPLICATION_JSON_UTF8)) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.jsonPath("$[0].name").value("John")); + mockMvc.perform(MockMvcRequestBuilders.get("/filteredusers").param("name", "John").contentType(MediaType.APPLICATION_JSON_UTF8)).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.jsonPath("$[0].name").value("John")); } } diff --git a/spring-rest-full/src/main/java/org/baeldung/web/util/RestPreconditions.java b/spring-rest-full/src/main/java/org/baeldung/web/util/RestPreconditions.java index 4e211ccb10..4f2dedcfa0 100644 --- a/spring-rest-full/src/main/java/org/baeldung/web/util/RestPreconditions.java +++ b/spring-rest-full/src/main/java/org/baeldung/web/util/RestPreconditions.java @@ -31,11 +31,11 @@ public final class RestPreconditions { /** * Check if some value was found, otherwise throw exception. - * - * @param expression - * has value true if found, otherwise false + * + * @param resource + * has value not null to be returned, otherwise throw exception * @throws MyResourceNotFoundException - * if expression is false, means value not found. + * if resource is null, means value not found. */ public static T checkFound(final T resource) { if (resource == null) { diff --git a/spring-rest/README.md b/spring-rest/README.md index 6d3aac3eb8..5d7894cdf8 100644 --- a/spring-rest/README.md +++ b/spring-rest/README.md @@ -21,3 +21,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Get and Post Lists of Objects with RestTemplate](http://www.baeldung.com/spring-rest-template-list) - [How to Set a Header on a Response with Spring 5](http://www.baeldung.com/spring-response-header) - [Uploading MultipartFile with Spring RestTemplate](http://www.baeldung.com/spring-rest-template-multipart-upload) +- [Download an Image or a File with Spring MVC](http://www.baeldung.com/spring-controller-return-image-file) diff --git a/spring-rest/src/main/java/com/baeldung/produceimage/README.md b/spring-rest/src/main/java/com/baeldung/produceimage/README.md deleted file mode 100644 index 4aeadea546..0000000000 --- a/spring-rest/src/main/java/com/baeldung/produceimage/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant articles - -- [Download an Image or a File with Spring MVC](http://www.baeldung.com/spring-controller-return-image-file) diff --git a/spring-security-kerberos/README.md b/spring-security-kerberos/README.md index 0338c2058c..1b77c380db 100644 --- a/spring-security-kerberos/README.md +++ b/spring-security-kerberos/README.md @@ -7,4 +7,4 @@ mvn clean install ``` ### Relevant Articles: -- [Spring Security – Kerberos](http://www.baeldung.com/xxxxxx) +- [Introduction to SPNEGO/Kerberos Authentication in Spring](https://www.baeldung.com/spring-security-kerberos) diff --git a/spring-security-rest-custom/pom.xml b/spring-security-rest-custom/pom.xml index 38cbfddab8..2180b917e5 100644 --- a/spring-security-rest-custom/pom.xml +++ b/spring-security-rest-custom/pom.xml @@ -26,6 +26,14 @@ org.springframework.security spring-security-config + + org.thymeleaf.extras + thymeleaf-extras-springsecurity5 + + + org.thymeleaf + thymeleaf-spring5 + diff --git a/spring-security-rest-custom/src/main/java/org/baeldung/config/child/WebConfig.java b/spring-security-rest-custom/src/main/java/org/baeldung/config/child/WebConfig.java index d7b2da6fe7..7cbbcf31fa 100644 --- a/spring-security-rest-custom/src/main/java/org/baeldung/config/child/WebConfig.java +++ b/spring-security-rest-custom/src/main/java/org/baeldung/config/child/WebConfig.java @@ -2,21 +2,34 @@ package org.baeldung.config.child; import java.util.List; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.thymeleaf.extras.springsecurity5.dialect.SpringSecurityDialect; +import org.thymeleaf.spring5.ISpringTemplateEngine; +import org.thymeleaf.spring5.SpringTemplateEngine; +import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver; +import org.thymeleaf.spring5.view.ThymeleafViewResolver; +import org.thymeleaf.templatemode.TemplateMode; +import org.thymeleaf.templateresolver.ITemplateResolver; @Configuration @EnableWebMvc @ComponentScan("org.baeldung.web") -// @ImportResource({ "classpath:prop.xml" }) -// @PropertySource("classpath:foo.properties") +//@ImportResource({ "classpath:prop.xml" }) +//@PropertySource("classpath:foo.properties") public class WebConfig implements WebMvcConfigurer { + + @Autowired + private ApplicationContext applicationContext; public WebConfig() { super(); @@ -37,5 +50,31 @@ public class WebConfig implements WebMvcConfigurer { ppc.setIgnoreUnresolvablePlaceholders(true); return ppc; } + + @Bean + public ViewResolver viewResolver() { + ThymeleafViewResolver resolver = new ThymeleafViewResolver(); + resolver.setTemplateEngine(templateEngine()); + resolver.setCharacterEncoding("UTF-8"); + return resolver; + } + + @Bean + public ISpringTemplateEngine templateEngine() { + SpringTemplateEngine engine = new SpringTemplateEngine(); + engine.setEnableSpringELCompiler(true); + engine.setTemplateResolver(templateResolver()); + engine.addDialect(new SpringSecurityDialect()); + return engine; + } + + private ITemplateResolver templateResolver() { + SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); + resolver.setApplicationContext(applicationContext); + resolver.setPrefix("/WEB-INF/templates/"); + resolver.setSuffix(".html"); + resolver.setTemplateMode(TemplateMode.HTML); + return resolver; + } } \ No newline at end of file diff --git a/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java b/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java index 616c2a7684..fb3880a33f 100644 --- a/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java +++ b/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java @@ -10,7 +10,7 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration -// @ImportResource({ "classpath:webSecurityConfig.xml" }) +//@ImportResource({ "classpath:webSecurityConfig.xml" }) @EnableWebSecurity @ComponentScan("org.baeldung.security") public class SecurityConfig extends WebSecurityConfigurerAdapter { diff --git a/spring-security-rest-custom/src/main/java/org/baeldung/web/controller/ViewController.java b/spring-security-rest-custom/src/main/java/org/baeldung/web/controller/ViewController.java new file mode 100644 index 0000000000..83c0292d98 --- /dev/null +++ b/spring-security-rest-custom/src/main/java/org/baeldung/web/controller/ViewController.java @@ -0,0 +1,13 @@ +package org.baeldung.web.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +public class ViewController { + + @RequestMapping({ "/index", "/" }) + public String index() { + return "index"; + } +} diff --git a/spring-security-rest-custom/src/main/resources/prop.xml b/spring-security-rest-custom/src/main/resources/prop.xml index b853d939d6..edaecde655 100644 --- a/spring-security-rest-custom/src/main/resources/prop.xml +++ b/spring-security-rest-custom/src/main/resources/prop.xml @@ -4,9 +4,9 @@ xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans - http://www.springframework.org/schema/beans/spring-beans-4.2.xsd + http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context - http://www.springframework.org/schema/context/spring-context-4.2.xsd"> + http://www.springframework.org/schema/context/spring-context.xsd"> diff --git a/spring-security-rest-custom/src/main/resources/webSecurityConfig.xml b/spring-security-rest-custom/src/main/resources/webSecurityConfig.xml index fa5dc894bf..790b1b1716 100644 --- a/spring-security-rest-custom/src/main/resources/webSecurityConfig.xml +++ b/spring-security-rest-custom/src/main/resources/webSecurityConfig.xml @@ -2,9 +2,9 @@ diff --git a/spring-security-rest-custom/src/main/webapp/WEB-INF/templates/index.html b/spring-security-rest-custom/src/main/webapp/WEB-INF/templates/index.html new file mode 100644 index 0000000000..31cb66ae0a --- /dev/null +++ b/spring-security-rest-custom/src/main/webapp/WEB-INF/templates/index.html @@ -0,0 +1,7 @@ + + + +
Authenticated as
+ + \ No newline at end of file diff --git a/spring-session/mongodb-session/src/test/java/com/baeldung/springsessionmongodb/SpringSessionMongoDBIntegrationTest.java b/spring-session/mongodb-session/src/test/java/com/baeldung/springsessionmongodb/SpringSessionMongoDBIntegrationTest.java new file mode 100644 index 0000000000..c73335b49b --- /dev/null +++ b/spring-session/mongodb-session/src/test/java/com/baeldung/springsessionmongodb/SpringSessionMongoDBIntegrationTest.java @@ -0,0 +1,43 @@ +package com.baeldung.springsessionmongodb; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.session.data.mongo.MongoOperationsSessionRepository; +import org.springframework.test.context.junit4.SpringRunner; +import springsessionmongodb.SpringSessionMongoDBApplication; + +import java.util.Base64; + + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringSessionMongoDBApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +public class SpringSessionMongoDBIntegrationTest { + + @Autowired + private MongoOperationsSessionRepository repository; + + private TestRestTemplate restTemplate = new TestRestTemplate(); + + @Test + public void givenEndpointIsCalledTwiceAndResponseIsReturned_whenMongoDBIsQueriedForCount_thenCountMustBeSame() { + HttpEntity response = restTemplate. + exchange("http://localhost:" + 8080, HttpMethod.GET, null, String.class); + HttpHeaders headers = response.getHeaders(); + String set_cookie = headers.getFirst(HttpHeaders.SET_COOKIE); + + Assert.assertEquals(response.getBody(), + repository.findById(getSessionId(set_cookie)).getAttribute("count").toString()); + } + + private String getSessionId(String set_cookie) { + return new String(Base64.getDecoder().decode(set_cookie.split(";")[0].split("=")[1])); + } + +} diff --git a/spring-session/pom.xml b/spring-session/pom.xml index bcdbaf2406..639686c8ee 100644 --- a/spring-session/pom.xml +++ b/spring-session/pom.xml @@ -17,6 +17,7 @@ spring-session-jdbc spring-session-redis + spring-session-mongodb \ No newline at end of file diff --git a/spring-session/spring-session-mongodb/README.md b/spring-session/spring-session-mongodb/README.md new file mode 100644 index 0000000000..ab42e8d120 --- /dev/null +++ b/spring-session/spring-session-mongodb/README.md @@ -0,0 +1,4 @@ +This module is for Spring Session with MONGO DB tutorial. +Jira BAEL-2886 + +### Relevant Articles: diff --git a/spring-session/spring-session-mongodb/pom.xml b/spring-session/spring-session-mongodb/pom.xml new file mode 100644 index 0000000000..714833cf99 --- /dev/null +++ b/spring-session/spring-session-mongodb/pom.xml @@ -0,0 +1,57 @@ + + + 4.0.0 + com.baeldung + spring-session-mongodb + 0.0.1-SNAPSHOT + spring-session-mongodb + jar + Spring Session with MongoDB tutorial + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.session + spring-session-data-mongodb + ${spring-session-data-mongodb.version} + + + + org.springframework.boot + spring-boot-starter-data-mongodb + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + 2.1.3.RELEASE + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/Olingo4SampleApplication.java b/spring-session/spring-session-mongodb/src/main/java/com/baeldung/springsessionmongodb/SpringSessionMongoDBApplication.java similarity index 54% rename from apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/Olingo4SampleApplication.java rename to spring-session/spring-session-mongodb/src/main/java/com/baeldung/springsessionmongodb/SpringSessionMongoDBApplication.java index 1ac872ea0f..2994efc719 100644 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/Olingo4SampleApplication.java +++ b/spring-session/spring-session-mongodb/src/main/java/com/baeldung/springsessionmongodb/SpringSessionMongoDBApplication.java @@ -1,13 +1,12 @@ -package org.baeldung.examples.olingo4; +package com.baeldung.springsessionmongodb; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication -public class Olingo4SampleApplication { +public class SpringSessionMongoDBApplication { public static void main(String[] args) { - SpringApplication.run(Olingo4SampleApplication.class, args); + SpringApplication.run(SpringSessionMongoDBApplication.class, args); } - } diff --git a/spring-session/spring-session-mongodb/src/main/java/com/baeldung/springsessionmongodb/controller/SpringSessionMongoDBController.java b/spring-session/spring-session-mongodb/src/main/java/com/baeldung/springsessionmongodb/controller/SpringSessionMongoDBController.java new file mode 100644 index 0000000000..1c38f419c3 --- /dev/null +++ b/spring-session/spring-session-mongodb/src/main/java/com/baeldung/springsessionmongodb/controller/SpringSessionMongoDBController.java @@ -0,0 +1,28 @@ +package com.baeldung.springsessionmongodb.controller; + +import javax.servlet.http.HttpSession; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class SpringSessionMongoDBController { + + @GetMapping("/") + public ResponseEntity count(HttpSession session) { + + Integer counter = (Integer) session.getAttribute("count"); + + if (counter == null) { + counter = 1; + } else { + counter += 1; + } + + session.setAttribute("count", counter); + + return ResponseEntity.ok(counter); + } + +} \ No newline at end of file diff --git a/spring-session/spring-session-mongodb/src/main/resources/application.properties b/spring-session/spring-session-mongodb/src/main/resources/application.properties new file mode 100644 index 0000000000..1b1a6cfbcb --- /dev/null +++ b/spring-session/spring-session-mongodb/src/main/resources/application.properties @@ -0,0 +1,6 @@ +spring.session.store-type=mongodb +server.port=8080 + +spring.data.mongodb.host=localhost +spring.data.mongodb.port=27017 +spring.data.mongodb.database=springboot-mongo \ No newline at end of file diff --git a/spring-session/spring-session-mongodb/src/main/resources/logback.xml b/spring-session/spring-session-mongodb/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-session/spring-session-mongodb/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-session/spring-session-mongodb/src/test/java/com/baeldung/springsessionmongodb/SpringSessionMongoDBIntegrationTest.java b/spring-session/spring-session-mongodb/src/test/java/com/baeldung/springsessionmongodb/SpringSessionMongoDBIntegrationTest.java new file mode 100644 index 0000000000..eb9f4164a6 --- /dev/null +++ b/spring-session/spring-session-mongodb/src/test/java/com/baeldung/springsessionmongodb/SpringSessionMongoDBIntegrationTest.java @@ -0,0 +1,42 @@ +package com.baeldung.springsessionmongodb; + +import java.util.Base64; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.session.data.mongo.MongoOperationsSessionRepository; +import org.springframework.test.context.junit4.SpringRunner; + + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringSessionMongoDBApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +public class SpringSessionMongoDBIntegrationTest { + + @Autowired + private MongoOperationsSessionRepository repository; + + private TestRestTemplate restTemplate = new TestRestTemplate(); + + @Test + public void givenEndpointIsCalledTwiceAndResponseIsReturned_whenMongoDBIsQueriedForCount_thenCountMustBeSame() { + HttpEntity response = restTemplate. + exchange("http://localhost:" + 8080, HttpMethod.GET, null, String.class); + HttpHeaders headers = response.getHeaders(); + String set_cookie = headers.getFirst(HttpHeaders.SET_COOKIE); + + Assert.assertEquals(response.getBody(), + repository.findById(getSessionId(set_cookie)).getAttribute("count").toString()); + } + + private String getSessionId(String cookie) { + return new String(Base64.getDecoder().decode(cookie.split(";")[0].split("=")[1])); + } + +} diff --git a/spring-session/spring-session-mongodb/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-session/spring-session-mongodb/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..3c58b2673f --- /dev/null +++ b/spring-session/spring-session-mongodb/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.springsessionmongodb.SpringSessionMongoDBApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringSessionMongoDBApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/testing-modules/junit-5-basics/README.md b/testing-modules/junit-5-basics/README.md index a00e2a3f4a..6e44a9c071 100644 --- a/testing-modules/junit-5-basics/README.md +++ b/testing-modules/junit-5-basics/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [Get the Path of the /src/test/resources Directory in JUnit](https://www.baeldung.com/junit-src-test-resources-directory-path) +- [Tagging and Filtering JUnit Tests](https://www.baeldung.com/junit-filtering-tests) diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoInjectIntoSpyUnitTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoInjectIntoSpyUnitTest.java new file mode 100644 index 0000000000..4f5ceb04e7 --- /dev/null +++ b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoInjectIntoSpyUnitTest.java @@ -0,0 +1,38 @@ +package org.baeldung.mockito; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.*; +import org.mockito.junit.MockitoJUnitRunner; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; + +@RunWith(MockitoJUnitRunner.class) +public class MockitoInjectIntoSpyUnitTest { + + @Before + public void init() { + MockitoAnnotations.initMocks(this); + spyDic = Mockito.spy(new MyDictionary(wordMap)); + } + + @Mock + private Map wordMap; + + @InjectMocks + private MyDictionary dic = new MyDictionary(); + + private MyDictionary spyDic; + + @Test + public void whenUseInjectMocksAnnotation_thenCorrect2() { + Mockito.when(wordMap.get("aWord")).thenReturn("aMeaning"); + + assertEquals("aMeaning", spyDic.getMeaning("aWord")); + } +} diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MyDictionary.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MyDictionary.java index 8a0ea92502..9492c90d11 100644 --- a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MyDictionary.java +++ b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MyDictionary.java @@ -11,6 +11,10 @@ class MyDictionary { wordMap = new HashMap<>(); } + MyDictionary(Map wordMap) { + this.wordMap = wordMap; + } + public void add(final String word, final String meaning) { wordMap.put(word, meaning); }