repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
mpalourdio/SpringBootTemplate
src/test/java/com/mpalourdio/springboottemplate/controllers/BasicAuthControllerTest.java
// Path: src/test/java/com/mpalourdio/springboottemplate/AbstractTestRunner.java // @ExtendWith(SpringExtension.class) // @TestPropertySource(locations = "classpath:test.properties") // @Import({BeansFactory.class}) // public abstract class AbstractTestRunner { // // protected Task task; // protected People people; // // protected void initializeData() { // task = new Task(); // task.setTaskArchived(true); // task.setTaskName("name"); // task.setTaskDescription("description"); // task.setTaskPriority("LOW"); // task.setTaskStatus("ACTIVE"); // // people = new People() // .setName("john") // .setTask(task); // } // // protected String serializeToJson(Object object) throws JsonProcessingException { // return new ObjectMapper().writeValueAsString(object); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/properties/CredentialsProperties.java // @Getter // @AllArgsConstructor // @ConstructorBinding // @ConfigurationProperties("admin") // public class CredentialsProperties { // // private final String username; // private final String password; // }
import com.mpalourdio.springboottemplate.AbstractTestRunner; import com.mpalourdio.springboottemplate.properties.CredentialsProperties; import org.apache.commons.codec.binary.Base64; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @WebMvcTest(BasicAuthController.class) class BasicAuthControllerTest extends AbstractTestRunner { @Autowired private MockMvc mvc; @Autowired
// Path: src/test/java/com/mpalourdio/springboottemplate/AbstractTestRunner.java // @ExtendWith(SpringExtension.class) // @TestPropertySource(locations = "classpath:test.properties") // @Import({BeansFactory.class}) // public abstract class AbstractTestRunner { // // protected Task task; // protected People people; // // protected void initializeData() { // task = new Task(); // task.setTaskArchived(true); // task.setTaskName("name"); // task.setTaskDescription("description"); // task.setTaskPriority("LOW"); // task.setTaskStatus("ACTIVE"); // // people = new People() // .setName("john") // .setTask(task); // } // // protected String serializeToJson(Object object) throws JsonProcessingException { // return new ObjectMapper().writeValueAsString(object); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/properties/CredentialsProperties.java // @Getter // @AllArgsConstructor // @ConstructorBinding // @ConfigurationProperties("admin") // public class CredentialsProperties { // // private final String username; // private final String password; // } // Path: src/test/java/com/mpalourdio/springboottemplate/controllers/BasicAuthControllerTest.java import com.mpalourdio.springboottemplate.AbstractTestRunner; import com.mpalourdio.springboottemplate.properties.CredentialsProperties; import org.apache.commons.codec.binary.Base64; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @WebMvcTest(BasicAuthController.class) class BasicAuthControllerTest extends AbstractTestRunner { @Autowired private MockMvc mvc; @Autowired
private CredentialsProperties credentialsProperties;
mpalourdio/SpringBootTemplate
src/test/java/com/mpalourdio/springboottemplate/model/repositories/RepositoriesServiceTest.java
// Path: src/main/java/com/mpalourdio/springboottemplate/model/RepositoriesService.java // @Service // public class RepositoriesService { // // private final EntityManager entityManager; // private final PeopleRepository peopleRepository; // private final TaskRepository taskRepository; // // public RepositoriesService( // PeopleRepository peopleRepository, // TaskRepository taskRepository, // EntityManager entityManager) { // this.peopleRepository = peopleRepository; // this.taskRepository = taskRepository; // this.entityManager = entityManager; // } // // @Transactional // public List<People> getAllPeople() { // return peopleRepository.findAll(); // } // // @Transactional // public List<Task> getAllTasks() { // return taskRepository.findAll(); // } // // @Transactional // public People useEntityManager() { // return entityManager.getReference(People.class, 1); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/People.java // @Entity // @Table(name = "task_people") // @Getter // @Setter // @Accessors(chain = true) // public class People { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_people_people_id_seq") // @Column(name = "people_id") // private int id; // // @Column(name = "name", nullable = false) // private String name; // // @ManyToOne // @JoinColumn(name = "task_id", nullable = false) // private Task task; // }
import com.mpalourdio.springboottemplate.model.RepositoriesService; import com.mpalourdio.springboottemplate.model.entities.People; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import javax.persistence.EntityManager; import static org.junit.jupiter.api.Assertions.assertEquals;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.model.repositories; @ExtendWith(MockitoExtension.class) class RepositoriesServiceTest { @Mock private EntityManager entityManager; @Mock private PeopleRepository peopleRepository; @Mock private TaskRepository taskRepository;
// Path: src/main/java/com/mpalourdio/springboottemplate/model/RepositoriesService.java // @Service // public class RepositoriesService { // // private final EntityManager entityManager; // private final PeopleRepository peopleRepository; // private final TaskRepository taskRepository; // // public RepositoriesService( // PeopleRepository peopleRepository, // TaskRepository taskRepository, // EntityManager entityManager) { // this.peopleRepository = peopleRepository; // this.taskRepository = taskRepository; // this.entityManager = entityManager; // } // // @Transactional // public List<People> getAllPeople() { // return peopleRepository.findAll(); // } // // @Transactional // public List<Task> getAllTasks() { // return taskRepository.findAll(); // } // // @Transactional // public People useEntityManager() { // return entityManager.getReference(People.class, 1); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/People.java // @Entity // @Table(name = "task_people") // @Getter // @Setter // @Accessors(chain = true) // public class People { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_people_people_id_seq") // @Column(name = "people_id") // private int id; // // @Column(name = "name", nullable = false) // private String name; // // @ManyToOne // @JoinColumn(name = "task_id", nullable = false) // private Task task; // } // Path: src/test/java/com/mpalourdio/springboottemplate/model/repositories/RepositoriesServiceTest.java import com.mpalourdio.springboottemplate.model.RepositoriesService; import com.mpalourdio.springboottemplate.model.entities.People; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import javax.persistence.EntityManager; import static org.junit.jupiter.api.Assertions.assertEquals; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.model.repositories; @ExtendWith(MockitoExtension.class) class RepositoriesServiceTest { @Mock private EntityManager entityManager; @Mock private PeopleRepository peopleRepository; @Mock private TaskRepository taskRepository;
private RepositoriesService repositoriesService;
mpalourdio/SpringBootTemplate
src/test/java/com/mpalourdio/springboottemplate/model/repositories/RepositoriesServiceTest.java
// Path: src/main/java/com/mpalourdio/springboottemplate/model/RepositoriesService.java // @Service // public class RepositoriesService { // // private final EntityManager entityManager; // private final PeopleRepository peopleRepository; // private final TaskRepository taskRepository; // // public RepositoriesService( // PeopleRepository peopleRepository, // TaskRepository taskRepository, // EntityManager entityManager) { // this.peopleRepository = peopleRepository; // this.taskRepository = taskRepository; // this.entityManager = entityManager; // } // // @Transactional // public List<People> getAllPeople() { // return peopleRepository.findAll(); // } // // @Transactional // public List<Task> getAllTasks() { // return taskRepository.findAll(); // } // // @Transactional // public People useEntityManager() { // return entityManager.getReference(People.class, 1); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/People.java // @Entity // @Table(name = "task_people") // @Getter // @Setter // @Accessors(chain = true) // public class People { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_people_people_id_seq") // @Column(name = "people_id") // private int id; // // @Column(name = "name", nullable = false) // private String name; // // @ManyToOne // @JoinColumn(name = "task_id", nullable = false) // private Task task; // }
import com.mpalourdio.springboottemplate.model.RepositoriesService; import com.mpalourdio.springboottemplate.model.entities.People; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import javax.persistence.EntityManager; import static org.junit.jupiter.api.Assertions.assertEquals;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.model.repositories; @ExtendWith(MockitoExtension.class) class RepositoriesServiceTest { @Mock private EntityManager entityManager; @Mock private PeopleRepository peopleRepository; @Mock private TaskRepository taskRepository; private RepositoriesService repositoriesService; @BeforeEach void setUp() { repositoriesService = new RepositoriesService( peopleRepository, taskRepository, entityManager ); } @Test void testEntityManagerIsMocked() { var expectedId = 666;
// Path: src/main/java/com/mpalourdio/springboottemplate/model/RepositoriesService.java // @Service // public class RepositoriesService { // // private final EntityManager entityManager; // private final PeopleRepository peopleRepository; // private final TaskRepository taskRepository; // // public RepositoriesService( // PeopleRepository peopleRepository, // TaskRepository taskRepository, // EntityManager entityManager) { // this.peopleRepository = peopleRepository; // this.taskRepository = taskRepository; // this.entityManager = entityManager; // } // // @Transactional // public List<People> getAllPeople() { // return peopleRepository.findAll(); // } // // @Transactional // public List<Task> getAllTasks() { // return taskRepository.findAll(); // } // // @Transactional // public People useEntityManager() { // return entityManager.getReference(People.class, 1); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/People.java // @Entity // @Table(name = "task_people") // @Getter // @Setter // @Accessors(chain = true) // public class People { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_people_people_id_seq") // @Column(name = "people_id") // private int id; // // @Column(name = "name", nullable = false) // private String name; // // @ManyToOne // @JoinColumn(name = "task_id", nullable = false) // private Task task; // } // Path: src/test/java/com/mpalourdio/springboottemplate/model/repositories/RepositoriesServiceTest.java import com.mpalourdio.springboottemplate.model.RepositoriesService; import com.mpalourdio.springboottemplate.model.entities.People; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import javax.persistence.EntityManager; import static org.junit.jupiter.api.Assertions.assertEquals; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.model.repositories; @ExtendWith(MockitoExtension.class) class RepositoriesServiceTest { @Mock private EntityManager entityManager; @Mock private PeopleRepository peopleRepository; @Mock private TaskRepository taskRepository; private RepositoriesService repositoriesService; @BeforeEach void setUp() { repositoriesService = new RepositoriesService( peopleRepository, taskRepository, entityManager ); } @Test void testEntityManagerIsMocked() { var expectedId = 666;
var people = new People();
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/controllers/ForwarderController.java
// Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // }
import com.mpalourdio.springboottemplate.mediatype.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.HashMap; import java.util.Map;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @Controller @RequestMapping("/forwarder") public class ForwarderController { private static final String END_POINT = "forward:/forwarder/second"; @GetMapping("/first") public String entryPoint() { return END_POINT; }
// Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // Path: src/main/java/com/mpalourdio/springboottemplate/controllers/ForwarderController.java import com.mpalourdio.springboottemplate.mediatype.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.HashMap; import java.util.Map; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @Controller @RequestMapping("/forwarder") public class ForwarderController { private static final String END_POINT = "forward:/forwarder/second"; @GetMapping("/first") public String entryPoint() { return END_POINT; }
@GetMapping(value = "/second", produces = MediaType.APPLICATION_JSON_VALUE)
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/service/ServiceWithProperties.java
// Path: src/main/java/com/mpalourdio/springboottemplate/exception/AnotherCustomException.java // public class AnotherCustomException extends Exception { // // public AnotherCustomException(String message) { // super(message); // } // }
import com.mpalourdio.springboottemplate.exception.AnotherCustomException;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.service; public class ServiceWithProperties { private final String valueFromConfig; public ServiceWithProperties(String valueFromConfig) { this.valueFromConfig = valueFromConfig; } public String getValueFromConfig() { return valueFromConfig; }
// Path: src/main/java/com/mpalourdio/springboottemplate/exception/AnotherCustomException.java // public class AnotherCustomException extends Exception { // // public AnotherCustomException(String message) { // super(message); // } // } // Path: src/main/java/com/mpalourdio/springboottemplate/service/ServiceWithProperties.java import com.mpalourdio.springboottemplate.exception.AnotherCustomException; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.service; public class ServiceWithProperties { private final String valueFromConfig; public ServiceWithProperties(String valueFromConfig) { this.valueFromConfig = valueFromConfig; } public String getValueFromConfig() { return valueFromConfig; }
public void throwException() throws AnotherCustomException {
mpalourdio/SpringBootTemplate
src/test/java/com/mpalourdio/springboottemplate/generics/BeanFromConfigurationClassTest.java
// Path: src/test/java/com/mpalourdio/springboottemplate/AbstractTestRunner.java // @ExtendWith(SpringExtension.class) // @TestPropertySource(locations = "classpath:test.properties") // @Import({BeansFactory.class}) // public abstract class AbstractTestRunner { // // protected Task task; // protected People people; // // protected void initializeData() { // task = new Task(); // task.setTaskArchived(true); // task.setTaskName("name"); // task.setTaskDescription("description"); // task.setTaskPriority("LOW"); // task.setTaskStatus("ACTIVE"); // // people = new People() // .setName("john") // .setTask(task); // } // // protected String serializeToJson(Object object) throws JsonProcessingException { // return new ObjectMapper().writeValueAsString(object); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/Task.java // @Entity // @Table(name = "task_list") // public class Task { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_list_task_id_seq") // @Column(name = "task_id") // private int id; // // @Column(name = "task_name", nullable = false) // private String taskName; // // @Column(name = "task_description", nullable = false) // private String taskDescription; // // @Column(name = "task_priority", nullable = false) // private String taskPriority; // // @Column(name = "task_status", nullable = false) // private String taskStatus; // // @ColumnDefault("false") // @Column(name = "task_archived", nullable = false) // private Boolean taskArchived = false; // // @ColumnDefault(CurrentTimestampFunction.NAME) // @Column(name = "start_date", nullable = false) // private LocalDateTime startDate = LocalDateTime.now(); // // @OneToMany(mappedBy = "task") // private List<People> people = new ArrayList<>(); // // public String getTaskName() { // return taskName; // } // // public void setTaskName(String taskName) { // this.taskName = taskName; // } // // public String getTaskDescription() { // return taskDescription; // } // // public void setTaskDescription(String taskDescription) { // this.taskDescription = taskDescription; // } // // public String getTaskPriority() { // return taskPriority; // } // // public void setTaskPriority(String taskPriority) { // this.taskPriority = taskPriority; // } // // public String getTaskStatus() { // return taskStatus; // } // // public void setTaskStatus(String taskStatus) { // this.taskStatus = taskStatus; // } // // public Boolean isTaskArchived() { // return taskArchived; // } // // public void setTaskArchived(Boolean taskArchived) { // this.taskArchived = taskArchived; // } // // public List<People> getPeople() { // return people; // } // // public void setPeople(List<People> people) { // this.people = people; // } // // // public LocalDateTime getStartDate() { // return startDate; // } // // public void setStartDate(LocalDateTime startDate) { // this.startDate = startDate; // } // // @Override // public String toString() { // return "Task [id=" + id + ", taskName=" + taskName // + ", taskDescription=" + taskDescription + ", taskPriority=" // + taskPriority + ",taskStatus=" + taskStatus + "]"; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/properties/MyPropertyConfigHolder.java // @Getter // @AllArgsConstructor // @ConstructorBinding // @ConfigurationProperties("myproperty") // public class MyPropertyConfigHolder { // // private final String first; // private final String second; // }
import com.mpalourdio.springboottemplate.AbstractTestRunner; import com.mpalourdio.springboottemplate.model.entities.Task; import com.mpalourdio.springboottemplate.properties.MyPropertyConfigHolder; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import static org.junit.jupiter.api.Assertions.assertEquals;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.generics; @EnableConfigurationProperties(MyPropertyConfigHolder.class) class BeanFromConfigurationClassTest extends AbstractTestRunner { @Autowired
// Path: src/test/java/com/mpalourdio/springboottemplate/AbstractTestRunner.java // @ExtendWith(SpringExtension.class) // @TestPropertySource(locations = "classpath:test.properties") // @Import({BeansFactory.class}) // public abstract class AbstractTestRunner { // // protected Task task; // protected People people; // // protected void initializeData() { // task = new Task(); // task.setTaskArchived(true); // task.setTaskName("name"); // task.setTaskDescription("description"); // task.setTaskPriority("LOW"); // task.setTaskStatus("ACTIVE"); // // people = new People() // .setName("john") // .setTask(task); // } // // protected String serializeToJson(Object object) throws JsonProcessingException { // return new ObjectMapper().writeValueAsString(object); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/Task.java // @Entity // @Table(name = "task_list") // public class Task { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_list_task_id_seq") // @Column(name = "task_id") // private int id; // // @Column(name = "task_name", nullable = false) // private String taskName; // // @Column(name = "task_description", nullable = false) // private String taskDescription; // // @Column(name = "task_priority", nullable = false) // private String taskPriority; // // @Column(name = "task_status", nullable = false) // private String taskStatus; // // @ColumnDefault("false") // @Column(name = "task_archived", nullable = false) // private Boolean taskArchived = false; // // @ColumnDefault(CurrentTimestampFunction.NAME) // @Column(name = "start_date", nullable = false) // private LocalDateTime startDate = LocalDateTime.now(); // // @OneToMany(mappedBy = "task") // private List<People> people = new ArrayList<>(); // // public String getTaskName() { // return taskName; // } // // public void setTaskName(String taskName) { // this.taskName = taskName; // } // // public String getTaskDescription() { // return taskDescription; // } // // public void setTaskDescription(String taskDescription) { // this.taskDescription = taskDescription; // } // // public String getTaskPriority() { // return taskPriority; // } // // public void setTaskPriority(String taskPriority) { // this.taskPriority = taskPriority; // } // // public String getTaskStatus() { // return taskStatus; // } // // public void setTaskStatus(String taskStatus) { // this.taskStatus = taskStatus; // } // // public Boolean isTaskArchived() { // return taskArchived; // } // // public void setTaskArchived(Boolean taskArchived) { // this.taskArchived = taskArchived; // } // // public List<People> getPeople() { // return people; // } // // public void setPeople(List<People> people) { // this.people = people; // } // // // public LocalDateTime getStartDate() { // return startDate; // } // // public void setStartDate(LocalDateTime startDate) { // this.startDate = startDate; // } // // @Override // public String toString() { // return "Task [id=" + id + ", taskName=" + taskName // + ", taskDescription=" + taskDescription + ", taskPriority=" // + taskPriority + ",taskStatus=" + taskStatus + "]"; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/properties/MyPropertyConfigHolder.java // @Getter // @AllArgsConstructor // @ConstructorBinding // @ConfigurationProperties("myproperty") // public class MyPropertyConfigHolder { // // private final String first; // private final String second; // } // Path: src/test/java/com/mpalourdio/springboottemplate/generics/BeanFromConfigurationClassTest.java import com.mpalourdio.springboottemplate.AbstractTestRunner; import com.mpalourdio.springboottemplate.model.entities.Task; import com.mpalourdio.springboottemplate.properties.MyPropertyConfigHolder; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import static org.junit.jupiter.api.Assertions.assertEquals; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.generics; @EnableConfigurationProperties(MyPropertyConfigHolder.class) class BeanFromConfigurationClassTest extends AbstractTestRunner { @Autowired
private BeanFromConfigurationClass<Task> beanFromConfigurationClass;
mpalourdio/SpringBootTemplate
src/main/java/app/config/WebSecurityConfig.java
// Path: src/main/java/com/mpalourdio/springboottemplate/properties/CredentialsProperties.java // @Getter // @AllArgsConstructor // @ConstructorBinding // @ConfigurationProperties("admin") // public class CredentialsProperties { // // private final String username; // private final String password; // }
import com.mpalourdio.springboottemplate.properties.CredentialsProperties; import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.User; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.web.DefaultRedirectStrategy; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler; import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package app.config; @Configuration @EnableWebSecurity
// Path: src/main/java/com/mpalourdio/springboottemplate/properties/CredentialsProperties.java // @Getter // @AllArgsConstructor // @ConstructorBinding // @ConfigurationProperties("admin") // public class CredentialsProperties { // // private final String username; // private final String password; // } // Path: src/main/java/app/config/WebSecurityConfig.java import com.mpalourdio.springboottemplate.properties.CredentialsProperties; import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.User; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.web.DefaultRedirectStrategy; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package app.config; @Configuration @EnableWebSecurity
@EnableConfigurationProperties(CredentialsProperties.class)
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/controllers/ExceptionController.java
// Path: src/main/java/com/mpalourdio/springboottemplate/exception/CustomException.java // @ResponseStatus(code = HttpStatus.PAYLOAD_TOO_LARGE) // public class CustomException extends Exception { // // public CustomException(String message) { // super(message); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/exception/ResponseObject.java // public class ResponseObject { // // public String property; // // public ResponseObject() { // // } // }
import com.mpalourdio.springboottemplate.exception.CustomException; import com.mpalourdio.springboottemplate.exception.ResponseObject; import org.springframework.http.*; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate;
package com.mpalourdio.springboottemplate.controllers; @RestController @RequestMapping("/exception") public class ExceptionController { @GetMapping(value = "nok", produces = MediaType.APPLICATION_JSON_VALUE)
// Path: src/main/java/com/mpalourdio/springboottemplate/exception/CustomException.java // @ResponseStatus(code = HttpStatus.PAYLOAD_TOO_LARGE) // public class CustomException extends Exception { // // public CustomException(String message) { // super(message); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/exception/ResponseObject.java // public class ResponseObject { // // public String property; // // public ResponseObject() { // // } // } // Path: src/main/java/com/mpalourdio/springboottemplate/controllers/ExceptionController.java import com.mpalourdio.springboottemplate.exception.CustomException; import com.mpalourdio.springboottemplate.exception.ResponseObject; import org.springframework.http.*; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; package com.mpalourdio.springboottemplate.controllers; @RestController @RequestMapping("/exception") public class ExceptionController { @GetMapping(value = "nok", produces = MediaType.APPLICATION_JSON_VALUE)
public String throwException() throws CustomException {
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/controllers/ExceptionController.java
// Path: src/main/java/com/mpalourdio/springboottemplate/exception/CustomException.java // @ResponseStatus(code = HttpStatus.PAYLOAD_TOO_LARGE) // public class CustomException extends Exception { // // public CustomException(String message) { // super(message); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/exception/ResponseObject.java // public class ResponseObject { // // public String property; // // public ResponseObject() { // // } // }
import com.mpalourdio.springboottemplate.exception.CustomException; import com.mpalourdio.springboottemplate.exception.ResponseObject; import org.springframework.http.*; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate;
package com.mpalourdio.springboottemplate.controllers; @RestController @RequestMapping("/exception") public class ExceptionController { @GetMapping(value = "nok", produces = MediaType.APPLICATION_JSON_VALUE) public String throwException() throws CustomException { if (1 == 1) { throw new CustomException("bad"); } return "all is ok if here"; } @GetMapping(value = "ok", produces = MediaType.APPLICATION_JSON_VALUE)
// Path: src/main/java/com/mpalourdio/springboottemplate/exception/CustomException.java // @ResponseStatus(code = HttpStatus.PAYLOAD_TOO_LARGE) // public class CustomException extends Exception { // // public CustomException(String message) { // super(message); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/exception/ResponseObject.java // public class ResponseObject { // // public String property; // // public ResponseObject() { // // } // } // Path: src/main/java/com/mpalourdio/springboottemplate/controllers/ExceptionController.java import com.mpalourdio.springboottemplate.exception.CustomException; import com.mpalourdio.springboottemplate.exception.ResponseObject; import org.springframework.http.*; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; package com.mpalourdio.springboottemplate.controllers; @RestController @RequestMapping("/exception") public class ExceptionController { @GetMapping(value = "nok", produces = MediaType.APPLICATION_JSON_VALUE) public String throwException() throws CustomException { if (1 == 1) { throw new CustomException("bad"); } return "all is ok if here"; } @GetMapping(value = "ok", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseObject ok() {
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/model/repositories/PeopleRepository.java
// Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/People.java // @Entity // @Table(name = "task_people") // @Getter // @Setter // @Accessors(chain = true) // public class People { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_people_people_id_seq") // @Column(name = "people_id") // private int id; // // @Column(name = "name", nullable = false) // private String name; // // @ManyToOne // @JoinColumn(name = "task_id", nullable = false) // private Task task; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/Task.java // @Entity // @Table(name = "task_list") // public class Task { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_list_task_id_seq") // @Column(name = "task_id") // private int id; // // @Column(name = "task_name", nullable = false) // private String taskName; // // @Column(name = "task_description", nullable = false) // private String taskDescription; // // @Column(name = "task_priority", nullable = false) // private String taskPriority; // // @Column(name = "task_status", nullable = false) // private String taskStatus; // // @ColumnDefault("false") // @Column(name = "task_archived", nullable = false) // private Boolean taskArchived = false; // // @ColumnDefault(CurrentTimestampFunction.NAME) // @Column(name = "start_date", nullable = false) // private LocalDateTime startDate = LocalDateTime.now(); // // @OneToMany(mappedBy = "task") // private List<People> people = new ArrayList<>(); // // public String getTaskName() { // return taskName; // } // // public void setTaskName(String taskName) { // this.taskName = taskName; // } // // public String getTaskDescription() { // return taskDescription; // } // // public void setTaskDescription(String taskDescription) { // this.taskDescription = taskDescription; // } // // public String getTaskPriority() { // return taskPriority; // } // // public void setTaskPriority(String taskPriority) { // this.taskPriority = taskPriority; // } // // public String getTaskStatus() { // return taskStatus; // } // // public void setTaskStatus(String taskStatus) { // this.taskStatus = taskStatus; // } // // public Boolean isTaskArchived() { // return taskArchived; // } // // public void setTaskArchived(Boolean taskArchived) { // this.taskArchived = taskArchived; // } // // public List<People> getPeople() { // return people; // } // // public void setPeople(List<People> people) { // this.people = people; // } // // // public LocalDateTime getStartDate() { // return startDate; // } // // public void setStartDate(LocalDateTime startDate) { // this.startDate = startDate; // } // // @Override // public String toString() { // return "Task [id=" + id + ", taskName=" + taskName // + ", taskDescription=" + taskDescription + ", taskPriority=" // + taskPriority + ",taskStatus=" + taskStatus + "]"; // } // }
import com.mpalourdio.springboottemplate.model.entities.People; import com.mpalourdio.springboottemplate.model.entities.Task; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import java.util.List;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.model.repositories; @Repository public interface PeopleRepository extends CrudRepository<People, Integer> {
// Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/People.java // @Entity // @Table(name = "task_people") // @Getter // @Setter // @Accessors(chain = true) // public class People { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_people_people_id_seq") // @Column(name = "people_id") // private int id; // // @Column(name = "name", nullable = false) // private String name; // // @ManyToOne // @JoinColumn(name = "task_id", nullable = false) // private Task task; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/Task.java // @Entity // @Table(name = "task_list") // public class Task { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_list_task_id_seq") // @Column(name = "task_id") // private int id; // // @Column(name = "task_name", nullable = false) // private String taskName; // // @Column(name = "task_description", nullable = false) // private String taskDescription; // // @Column(name = "task_priority", nullable = false) // private String taskPriority; // // @Column(name = "task_status", nullable = false) // private String taskStatus; // // @ColumnDefault("false") // @Column(name = "task_archived", nullable = false) // private Boolean taskArchived = false; // // @ColumnDefault(CurrentTimestampFunction.NAME) // @Column(name = "start_date", nullable = false) // private LocalDateTime startDate = LocalDateTime.now(); // // @OneToMany(mappedBy = "task") // private List<People> people = new ArrayList<>(); // // public String getTaskName() { // return taskName; // } // // public void setTaskName(String taskName) { // this.taskName = taskName; // } // // public String getTaskDescription() { // return taskDescription; // } // // public void setTaskDescription(String taskDescription) { // this.taskDescription = taskDescription; // } // // public String getTaskPriority() { // return taskPriority; // } // // public void setTaskPriority(String taskPriority) { // this.taskPriority = taskPriority; // } // // public String getTaskStatus() { // return taskStatus; // } // // public void setTaskStatus(String taskStatus) { // this.taskStatus = taskStatus; // } // // public Boolean isTaskArchived() { // return taskArchived; // } // // public void setTaskArchived(Boolean taskArchived) { // this.taskArchived = taskArchived; // } // // public List<People> getPeople() { // return people; // } // // public void setPeople(List<People> people) { // this.people = people; // } // // // public LocalDateTime getStartDate() { // return startDate; // } // // public void setStartDate(LocalDateTime startDate) { // this.startDate = startDate; // } // // @Override // public String toString() { // return "Task [id=" + id + ", taskName=" + taskName // + ", taskDescription=" + taskDescription + ", taskPriority=" // + taskPriority + ",taskStatus=" + taskStatus + "]"; // } // } // Path: src/main/java/com/mpalourdio/springboottemplate/model/repositories/PeopleRepository.java import com.mpalourdio.springboottemplate.model.entities.People; import com.mpalourdio.springboottemplate.model.entities.Task; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import java.util.List; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.model.repositories; @Repository public interface PeopleRepository extends CrudRepository<People, Integer> {
List<People> findByTask(Task task);
mpalourdio/SpringBootTemplate
src/test/java/com/mpalourdio/springboottemplate/AbstractTestRunner.java
// Path: src/main/java/app/config/BeansFactory.java // @Configuration // @EnableConfigurationProperties(MyPropertyConfigHolder.class) // public class BeansFactory { // // @Bean // public BeanFromConfigurationClass<Task> beanFromConfigurationClass() { // var task = new Task(); // task.setTaskName("fromBeanConfiguration"); // return new BeanFromConfigurationClass<>(Task.class, task); // } // // @Bean // public ServiceWithConfigurationProperties serviceWithConfigurationProperties(MyPropertyConfigHolder myProperty) { // return new ServiceWithConfigurationProperties(myProperty); // } // // @Bean // public ServiceWithProperties serviceWithProperties(@Value("${admin.username}") String valueFromConfig) { // return new ServiceWithProperties(valueFromConfig); // } // // @Bean // public AsyncEvent asyncEvent() { // return new AsyncEvent(); // } // // @Bean // public AsyncLogger asyncLogger(ApplicationEventPublisher eventPublisher) { // return new AsyncLogger(eventPublisher); // } // // @Bean // public MyEventListener myEventListener() { // return new MyEventListener(); // } // // @Bean // public ABeanIWantToMockInterface aBeanIWantToMock() { // return new ABeanIWantToMock(); // } // // @Bean // public UselessBean uselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // return new UselessBean(aBeanIWantToMock); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/People.java // @Entity // @Table(name = "task_people") // @Getter // @Setter // @Accessors(chain = true) // public class People { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_people_people_id_seq") // @Column(name = "people_id") // private int id; // // @Column(name = "name", nullable = false) // private String name; // // @ManyToOne // @JoinColumn(name = "task_id", nullable = false) // private Task task; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/Task.java // @Entity // @Table(name = "task_list") // public class Task { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_list_task_id_seq") // @Column(name = "task_id") // private int id; // // @Column(name = "task_name", nullable = false) // private String taskName; // // @Column(name = "task_description", nullable = false) // private String taskDescription; // // @Column(name = "task_priority", nullable = false) // private String taskPriority; // // @Column(name = "task_status", nullable = false) // private String taskStatus; // // @ColumnDefault("false") // @Column(name = "task_archived", nullable = false) // private Boolean taskArchived = false; // // @ColumnDefault(CurrentTimestampFunction.NAME) // @Column(name = "start_date", nullable = false) // private LocalDateTime startDate = LocalDateTime.now(); // // @OneToMany(mappedBy = "task") // private List<People> people = new ArrayList<>(); // // public String getTaskName() { // return taskName; // } // // public void setTaskName(String taskName) { // this.taskName = taskName; // } // // public String getTaskDescription() { // return taskDescription; // } // // public void setTaskDescription(String taskDescription) { // this.taskDescription = taskDescription; // } // // public String getTaskPriority() { // return taskPriority; // } // // public void setTaskPriority(String taskPriority) { // this.taskPriority = taskPriority; // } // // public String getTaskStatus() { // return taskStatus; // } // // public void setTaskStatus(String taskStatus) { // this.taskStatus = taskStatus; // } // // public Boolean isTaskArchived() { // return taskArchived; // } // // public void setTaskArchived(Boolean taskArchived) { // this.taskArchived = taskArchived; // } // // public List<People> getPeople() { // return people; // } // // public void setPeople(List<People> people) { // this.people = people; // } // // // public LocalDateTime getStartDate() { // return startDate; // } // // public void setStartDate(LocalDateTime startDate) { // this.startDate = startDate; // } // // @Override // public String toString() { // return "Task [id=" + id + ", taskName=" + taskName // + ", taskDescription=" + taskDescription + ", taskPriority=" // + taskPriority + ",taskStatus=" + taskStatus + "]"; // } // }
import app.config.BeansFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.mpalourdio.springboottemplate.model.entities.People; import com.mpalourdio.springboottemplate.model.entities.Task; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.context.annotation.Import; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringExtension;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate; @ExtendWith(SpringExtension.class) @TestPropertySource(locations = "classpath:test.properties")
// Path: src/main/java/app/config/BeansFactory.java // @Configuration // @EnableConfigurationProperties(MyPropertyConfigHolder.class) // public class BeansFactory { // // @Bean // public BeanFromConfigurationClass<Task> beanFromConfigurationClass() { // var task = new Task(); // task.setTaskName("fromBeanConfiguration"); // return new BeanFromConfigurationClass<>(Task.class, task); // } // // @Bean // public ServiceWithConfigurationProperties serviceWithConfigurationProperties(MyPropertyConfigHolder myProperty) { // return new ServiceWithConfigurationProperties(myProperty); // } // // @Bean // public ServiceWithProperties serviceWithProperties(@Value("${admin.username}") String valueFromConfig) { // return new ServiceWithProperties(valueFromConfig); // } // // @Bean // public AsyncEvent asyncEvent() { // return new AsyncEvent(); // } // // @Bean // public AsyncLogger asyncLogger(ApplicationEventPublisher eventPublisher) { // return new AsyncLogger(eventPublisher); // } // // @Bean // public MyEventListener myEventListener() { // return new MyEventListener(); // } // // @Bean // public ABeanIWantToMockInterface aBeanIWantToMock() { // return new ABeanIWantToMock(); // } // // @Bean // public UselessBean uselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // return new UselessBean(aBeanIWantToMock); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/People.java // @Entity // @Table(name = "task_people") // @Getter // @Setter // @Accessors(chain = true) // public class People { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_people_people_id_seq") // @Column(name = "people_id") // private int id; // // @Column(name = "name", nullable = false) // private String name; // // @ManyToOne // @JoinColumn(name = "task_id", nullable = false) // private Task task; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/Task.java // @Entity // @Table(name = "task_list") // public class Task { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_list_task_id_seq") // @Column(name = "task_id") // private int id; // // @Column(name = "task_name", nullable = false) // private String taskName; // // @Column(name = "task_description", nullable = false) // private String taskDescription; // // @Column(name = "task_priority", nullable = false) // private String taskPriority; // // @Column(name = "task_status", nullable = false) // private String taskStatus; // // @ColumnDefault("false") // @Column(name = "task_archived", nullable = false) // private Boolean taskArchived = false; // // @ColumnDefault(CurrentTimestampFunction.NAME) // @Column(name = "start_date", nullable = false) // private LocalDateTime startDate = LocalDateTime.now(); // // @OneToMany(mappedBy = "task") // private List<People> people = new ArrayList<>(); // // public String getTaskName() { // return taskName; // } // // public void setTaskName(String taskName) { // this.taskName = taskName; // } // // public String getTaskDescription() { // return taskDescription; // } // // public void setTaskDescription(String taskDescription) { // this.taskDescription = taskDescription; // } // // public String getTaskPriority() { // return taskPriority; // } // // public void setTaskPriority(String taskPriority) { // this.taskPriority = taskPriority; // } // // public String getTaskStatus() { // return taskStatus; // } // // public void setTaskStatus(String taskStatus) { // this.taskStatus = taskStatus; // } // // public Boolean isTaskArchived() { // return taskArchived; // } // // public void setTaskArchived(Boolean taskArchived) { // this.taskArchived = taskArchived; // } // // public List<People> getPeople() { // return people; // } // // public void setPeople(List<People> people) { // this.people = people; // } // // // public LocalDateTime getStartDate() { // return startDate; // } // // public void setStartDate(LocalDateTime startDate) { // this.startDate = startDate; // } // // @Override // public String toString() { // return "Task [id=" + id + ", taskName=" + taskName // + ", taskDescription=" + taskDescription + ", taskPriority=" // + taskPriority + ",taskStatus=" + taskStatus + "]"; // } // } // Path: src/test/java/com/mpalourdio/springboottemplate/AbstractTestRunner.java import app.config.BeansFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.mpalourdio.springboottemplate.model.entities.People; import com.mpalourdio.springboottemplate.model.entities.Task; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.context.annotation.Import; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringExtension; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate; @ExtendWith(SpringExtension.class) @TestPropertySource(locations = "classpath:test.properties")
@Import({BeansFactory.class})
mpalourdio/SpringBootTemplate
src/test/java/com/mpalourdio/springboottemplate/AbstractTestRunner.java
// Path: src/main/java/app/config/BeansFactory.java // @Configuration // @EnableConfigurationProperties(MyPropertyConfigHolder.class) // public class BeansFactory { // // @Bean // public BeanFromConfigurationClass<Task> beanFromConfigurationClass() { // var task = new Task(); // task.setTaskName("fromBeanConfiguration"); // return new BeanFromConfigurationClass<>(Task.class, task); // } // // @Bean // public ServiceWithConfigurationProperties serviceWithConfigurationProperties(MyPropertyConfigHolder myProperty) { // return new ServiceWithConfigurationProperties(myProperty); // } // // @Bean // public ServiceWithProperties serviceWithProperties(@Value("${admin.username}") String valueFromConfig) { // return new ServiceWithProperties(valueFromConfig); // } // // @Bean // public AsyncEvent asyncEvent() { // return new AsyncEvent(); // } // // @Bean // public AsyncLogger asyncLogger(ApplicationEventPublisher eventPublisher) { // return new AsyncLogger(eventPublisher); // } // // @Bean // public MyEventListener myEventListener() { // return new MyEventListener(); // } // // @Bean // public ABeanIWantToMockInterface aBeanIWantToMock() { // return new ABeanIWantToMock(); // } // // @Bean // public UselessBean uselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // return new UselessBean(aBeanIWantToMock); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/People.java // @Entity // @Table(name = "task_people") // @Getter // @Setter // @Accessors(chain = true) // public class People { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_people_people_id_seq") // @Column(name = "people_id") // private int id; // // @Column(name = "name", nullable = false) // private String name; // // @ManyToOne // @JoinColumn(name = "task_id", nullable = false) // private Task task; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/Task.java // @Entity // @Table(name = "task_list") // public class Task { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_list_task_id_seq") // @Column(name = "task_id") // private int id; // // @Column(name = "task_name", nullable = false) // private String taskName; // // @Column(name = "task_description", nullable = false) // private String taskDescription; // // @Column(name = "task_priority", nullable = false) // private String taskPriority; // // @Column(name = "task_status", nullable = false) // private String taskStatus; // // @ColumnDefault("false") // @Column(name = "task_archived", nullable = false) // private Boolean taskArchived = false; // // @ColumnDefault(CurrentTimestampFunction.NAME) // @Column(name = "start_date", nullable = false) // private LocalDateTime startDate = LocalDateTime.now(); // // @OneToMany(mappedBy = "task") // private List<People> people = new ArrayList<>(); // // public String getTaskName() { // return taskName; // } // // public void setTaskName(String taskName) { // this.taskName = taskName; // } // // public String getTaskDescription() { // return taskDescription; // } // // public void setTaskDescription(String taskDescription) { // this.taskDescription = taskDescription; // } // // public String getTaskPriority() { // return taskPriority; // } // // public void setTaskPriority(String taskPriority) { // this.taskPriority = taskPriority; // } // // public String getTaskStatus() { // return taskStatus; // } // // public void setTaskStatus(String taskStatus) { // this.taskStatus = taskStatus; // } // // public Boolean isTaskArchived() { // return taskArchived; // } // // public void setTaskArchived(Boolean taskArchived) { // this.taskArchived = taskArchived; // } // // public List<People> getPeople() { // return people; // } // // public void setPeople(List<People> people) { // this.people = people; // } // // // public LocalDateTime getStartDate() { // return startDate; // } // // public void setStartDate(LocalDateTime startDate) { // this.startDate = startDate; // } // // @Override // public String toString() { // return "Task [id=" + id + ", taskName=" + taskName // + ", taskDescription=" + taskDescription + ", taskPriority=" // + taskPriority + ",taskStatus=" + taskStatus + "]"; // } // }
import app.config.BeansFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.mpalourdio.springboottemplate.model.entities.People; import com.mpalourdio.springboottemplate.model.entities.Task; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.context.annotation.Import; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringExtension;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate; @ExtendWith(SpringExtension.class) @TestPropertySource(locations = "classpath:test.properties") @Import({BeansFactory.class}) public abstract class AbstractTestRunner {
// Path: src/main/java/app/config/BeansFactory.java // @Configuration // @EnableConfigurationProperties(MyPropertyConfigHolder.class) // public class BeansFactory { // // @Bean // public BeanFromConfigurationClass<Task> beanFromConfigurationClass() { // var task = new Task(); // task.setTaskName("fromBeanConfiguration"); // return new BeanFromConfigurationClass<>(Task.class, task); // } // // @Bean // public ServiceWithConfigurationProperties serviceWithConfigurationProperties(MyPropertyConfigHolder myProperty) { // return new ServiceWithConfigurationProperties(myProperty); // } // // @Bean // public ServiceWithProperties serviceWithProperties(@Value("${admin.username}") String valueFromConfig) { // return new ServiceWithProperties(valueFromConfig); // } // // @Bean // public AsyncEvent asyncEvent() { // return new AsyncEvent(); // } // // @Bean // public AsyncLogger asyncLogger(ApplicationEventPublisher eventPublisher) { // return new AsyncLogger(eventPublisher); // } // // @Bean // public MyEventListener myEventListener() { // return new MyEventListener(); // } // // @Bean // public ABeanIWantToMockInterface aBeanIWantToMock() { // return new ABeanIWantToMock(); // } // // @Bean // public UselessBean uselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // return new UselessBean(aBeanIWantToMock); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/People.java // @Entity // @Table(name = "task_people") // @Getter // @Setter // @Accessors(chain = true) // public class People { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_people_people_id_seq") // @Column(name = "people_id") // private int id; // // @Column(name = "name", nullable = false) // private String name; // // @ManyToOne // @JoinColumn(name = "task_id", nullable = false) // private Task task; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/Task.java // @Entity // @Table(name = "task_list") // public class Task { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_list_task_id_seq") // @Column(name = "task_id") // private int id; // // @Column(name = "task_name", nullable = false) // private String taskName; // // @Column(name = "task_description", nullable = false) // private String taskDescription; // // @Column(name = "task_priority", nullable = false) // private String taskPriority; // // @Column(name = "task_status", nullable = false) // private String taskStatus; // // @ColumnDefault("false") // @Column(name = "task_archived", nullable = false) // private Boolean taskArchived = false; // // @ColumnDefault(CurrentTimestampFunction.NAME) // @Column(name = "start_date", nullable = false) // private LocalDateTime startDate = LocalDateTime.now(); // // @OneToMany(mappedBy = "task") // private List<People> people = new ArrayList<>(); // // public String getTaskName() { // return taskName; // } // // public void setTaskName(String taskName) { // this.taskName = taskName; // } // // public String getTaskDescription() { // return taskDescription; // } // // public void setTaskDescription(String taskDescription) { // this.taskDescription = taskDescription; // } // // public String getTaskPriority() { // return taskPriority; // } // // public void setTaskPriority(String taskPriority) { // this.taskPriority = taskPriority; // } // // public String getTaskStatus() { // return taskStatus; // } // // public void setTaskStatus(String taskStatus) { // this.taskStatus = taskStatus; // } // // public Boolean isTaskArchived() { // return taskArchived; // } // // public void setTaskArchived(Boolean taskArchived) { // this.taskArchived = taskArchived; // } // // public List<People> getPeople() { // return people; // } // // public void setPeople(List<People> people) { // this.people = people; // } // // // public LocalDateTime getStartDate() { // return startDate; // } // // public void setStartDate(LocalDateTime startDate) { // this.startDate = startDate; // } // // @Override // public String toString() { // return "Task [id=" + id + ", taskName=" + taskName // + ", taskDescription=" + taskDescription + ", taskPriority=" // + taskPriority + ",taskStatus=" + taskStatus + "]"; // } // } // Path: src/test/java/com/mpalourdio/springboottemplate/AbstractTestRunner.java import app.config.BeansFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.mpalourdio.springboottemplate.model.entities.People; import com.mpalourdio.springboottemplate.model.entities.Task; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.context.annotation.Import; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringExtension; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate; @ExtendWith(SpringExtension.class) @TestPropertySource(locations = "classpath:test.properties") @Import({BeansFactory.class}) public abstract class AbstractTestRunner {
protected Task task;
mpalourdio/SpringBootTemplate
src/test/java/com/mpalourdio/springboottemplate/AbstractTestRunner.java
// Path: src/main/java/app/config/BeansFactory.java // @Configuration // @EnableConfigurationProperties(MyPropertyConfigHolder.class) // public class BeansFactory { // // @Bean // public BeanFromConfigurationClass<Task> beanFromConfigurationClass() { // var task = new Task(); // task.setTaskName("fromBeanConfiguration"); // return new BeanFromConfigurationClass<>(Task.class, task); // } // // @Bean // public ServiceWithConfigurationProperties serviceWithConfigurationProperties(MyPropertyConfigHolder myProperty) { // return new ServiceWithConfigurationProperties(myProperty); // } // // @Bean // public ServiceWithProperties serviceWithProperties(@Value("${admin.username}") String valueFromConfig) { // return new ServiceWithProperties(valueFromConfig); // } // // @Bean // public AsyncEvent asyncEvent() { // return new AsyncEvent(); // } // // @Bean // public AsyncLogger asyncLogger(ApplicationEventPublisher eventPublisher) { // return new AsyncLogger(eventPublisher); // } // // @Bean // public MyEventListener myEventListener() { // return new MyEventListener(); // } // // @Bean // public ABeanIWantToMockInterface aBeanIWantToMock() { // return new ABeanIWantToMock(); // } // // @Bean // public UselessBean uselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // return new UselessBean(aBeanIWantToMock); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/People.java // @Entity // @Table(name = "task_people") // @Getter // @Setter // @Accessors(chain = true) // public class People { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_people_people_id_seq") // @Column(name = "people_id") // private int id; // // @Column(name = "name", nullable = false) // private String name; // // @ManyToOne // @JoinColumn(name = "task_id", nullable = false) // private Task task; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/Task.java // @Entity // @Table(name = "task_list") // public class Task { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_list_task_id_seq") // @Column(name = "task_id") // private int id; // // @Column(name = "task_name", nullable = false) // private String taskName; // // @Column(name = "task_description", nullable = false) // private String taskDescription; // // @Column(name = "task_priority", nullable = false) // private String taskPriority; // // @Column(name = "task_status", nullable = false) // private String taskStatus; // // @ColumnDefault("false") // @Column(name = "task_archived", nullable = false) // private Boolean taskArchived = false; // // @ColumnDefault(CurrentTimestampFunction.NAME) // @Column(name = "start_date", nullable = false) // private LocalDateTime startDate = LocalDateTime.now(); // // @OneToMany(mappedBy = "task") // private List<People> people = new ArrayList<>(); // // public String getTaskName() { // return taskName; // } // // public void setTaskName(String taskName) { // this.taskName = taskName; // } // // public String getTaskDescription() { // return taskDescription; // } // // public void setTaskDescription(String taskDescription) { // this.taskDescription = taskDescription; // } // // public String getTaskPriority() { // return taskPriority; // } // // public void setTaskPriority(String taskPriority) { // this.taskPriority = taskPriority; // } // // public String getTaskStatus() { // return taskStatus; // } // // public void setTaskStatus(String taskStatus) { // this.taskStatus = taskStatus; // } // // public Boolean isTaskArchived() { // return taskArchived; // } // // public void setTaskArchived(Boolean taskArchived) { // this.taskArchived = taskArchived; // } // // public List<People> getPeople() { // return people; // } // // public void setPeople(List<People> people) { // this.people = people; // } // // // public LocalDateTime getStartDate() { // return startDate; // } // // public void setStartDate(LocalDateTime startDate) { // this.startDate = startDate; // } // // @Override // public String toString() { // return "Task [id=" + id + ", taskName=" + taskName // + ", taskDescription=" + taskDescription + ", taskPriority=" // + taskPriority + ",taskStatus=" + taskStatus + "]"; // } // }
import app.config.BeansFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.mpalourdio.springboottemplate.model.entities.People; import com.mpalourdio.springboottemplate.model.entities.Task; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.context.annotation.Import; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringExtension;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate; @ExtendWith(SpringExtension.class) @TestPropertySource(locations = "classpath:test.properties") @Import({BeansFactory.class}) public abstract class AbstractTestRunner { protected Task task;
// Path: src/main/java/app/config/BeansFactory.java // @Configuration // @EnableConfigurationProperties(MyPropertyConfigHolder.class) // public class BeansFactory { // // @Bean // public BeanFromConfigurationClass<Task> beanFromConfigurationClass() { // var task = new Task(); // task.setTaskName("fromBeanConfiguration"); // return new BeanFromConfigurationClass<>(Task.class, task); // } // // @Bean // public ServiceWithConfigurationProperties serviceWithConfigurationProperties(MyPropertyConfigHolder myProperty) { // return new ServiceWithConfigurationProperties(myProperty); // } // // @Bean // public ServiceWithProperties serviceWithProperties(@Value("${admin.username}") String valueFromConfig) { // return new ServiceWithProperties(valueFromConfig); // } // // @Bean // public AsyncEvent asyncEvent() { // return new AsyncEvent(); // } // // @Bean // public AsyncLogger asyncLogger(ApplicationEventPublisher eventPublisher) { // return new AsyncLogger(eventPublisher); // } // // @Bean // public MyEventListener myEventListener() { // return new MyEventListener(); // } // // @Bean // public ABeanIWantToMockInterface aBeanIWantToMock() { // return new ABeanIWantToMock(); // } // // @Bean // public UselessBean uselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // return new UselessBean(aBeanIWantToMock); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/People.java // @Entity // @Table(name = "task_people") // @Getter // @Setter // @Accessors(chain = true) // public class People { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_people_people_id_seq") // @Column(name = "people_id") // private int id; // // @Column(name = "name", nullable = false) // private String name; // // @ManyToOne // @JoinColumn(name = "task_id", nullable = false) // private Task task; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/Task.java // @Entity // @Table(name = "task_list") // public class Task { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_list_task_id_seq") // @Column(name = "task_id") // private int id; // // @Column(name = "task_name", nullable = false) // private String taskName; // // @Column(name = "task_description", nullable = false) // private String taskDescription; // // @Column(name = "task_priority", nullable = false) // private String taskPriority; // // @Column(name = "task_status", nullable = false) // private String taskStatus; // // @ColumnDefault("false") // @Column(name = "task_archived", nullable = false) // private Boolean taskArchived = false; // // @ColumnDefault(CurrentTimestampFunction.NAME) // @Column(name = "start_date", nullable = false) // private LocalDateTime startDate = LocalDateTime.now(); // // @OneToMany(mappedBy = "task") // private List<People> people = new ArrayList<>(); // // public String getTaskName() { // return taskName; // } // // public void setTaskName(String taskName) { // this.taskName = taskName; // } // // public String getTaskDescription() { // return taskDescription; // } // // public void setTaskDescription(String taskDescription) { // this.taskDescription = taskDescription; // } // // public String getTaskPriority() { // return taskPriority; // } // // public void setTaskPriority(String taskPriority) { // this.taskPriority = taskPriority; // } // // public String getTaskStatus() { // return taskStatus; // } // // public void setTaskStatus(String taskStatus) { // this.taskStatus = taskStatus; // } // // public Boolean isTaskArchived() { // return taskArchived; // } // // public void setTaskArchived(Boolean taskArchived) { // this.taskArchived = taskArchived; // } // // public List<People> getPeople() { // return people; // } // // public void setPeople(List<People> people) { // this.people = people; // } // // // public LocalDateTime getStartDate() { // return startDate; // } // // public void setStartDate(LocalDateTime startDate) { // this.startDate = startDate; // } // // @Override // public String toString() { // return "Task [id=" + id + ", taskName=" + taskName // + ", taskDescription=" + taskDescription + ", taskPriority=" // + taskPriority + ",taskStatus=" + taskStatus + "]"; // } // } // Path: src/test/java/com/mpalourdio/springboottemplate/AbstractTestRunner.java import app.config.BeansFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.mpalourdio.springboottemplate.model.entities.People; import com.mpalourdio.springboottemplate.model.entities.Task; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.context.annotation.Import; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringExtension; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate; @ExtendWith(SpringExtension.class) @TestPropertySource(locations = "classpath:test.properties") @Import({BeansFactory.class}) public abstract class AbstractTestRunner { protected Task task;
protected People people;
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/model/repositories/TaskRepositoryImpl.java
// Path: src/main/java/com/mpalourdio/springboottemplate/model/Dummy.java // public class Dummy { // // public String name; // @JsonIgnore // public String desc; // // public Dummy(String name, String desc) { // this.name = name; // this.desc = desc; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/Task.java // @Entity // @Table(name = "task_list") // public class Task { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_list_task_id_seq") // @Column(name = "task_id") // private int id; // // @Column(name = "task_name", nullable = false) // private String taskName; // // @Column(name = "task_description", nullable = false) // private String taskDescription; // // @Column(name = "task_priority", nullable = false) // private String taskPriority; // // @Column(name = "task_status", nullable = false) // private String taskStatus; // // @ColumnDefault("false") // @Column(name = "task_archived", nullable = false) // private Boolean taskArchived = false; // // @ColumnDefault(CurrentTimestampFunction.NAME) // @Column(name = "start_date", nullable = false) // private LocalDateTime startDate = LocalDateTime.now(); // // @OneToMany(mappedBy = "task") // private List<People> people = new ArrayList<>(); // // public String getTaskName() { // return taskName; // } // // public void setTaskName(String taskName) { // this.taskName = taskName; // } // // public String getTaskDescription() { // return taskDescription; // } // // public void setTaskDescription(String taskDescription) { // this.taskDescription = taskDescription; // } // // public String getTaskPriority() { // return taskPriority; // } // // public void setTaskPriority(String taskPriority) { // this.taskPriority = taskPriority; // } // // public String getTaskStatus() { // return taskStatus; // } // // public void setTaskStatus(String taskStatus) { // this.taskStatus = taskStatus; // } // // public Boolean isTaskArchived() { // return taskArchived; // } // // public void setTaskArchived(Boolean taskArchived) { // this.taskArchived = taskArchived; // } // // public List<People> getPeople() { // return people; // } // // public void setPeople(List<People> people) { // this.people = people; // } // // // public LocalDateTime getStartDate() { // return startDate; // } // // public void setStartDate(LocalDateTime startDate) { // this.startDate = startDate; // } // // @Override // public String toString() { // return "Task [id=" + id + ", taskName=" + taskName // + ", taskDescription=" + taskDescription + ", taskPriority=" // + taskPriority + ",taskStatus=" + taskStatus + "]"; // } // }
import com.mpalourdio.springboottemplate.model.Dummy; import com.mpalourdio.springboottemplate.model.entities.Task; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.List;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.model.repositories; /** * This implementation MUST have the 'impl' * suffix in order to be discovered ! */ public class TaskRepositoryImpl implements CustomRepository<Task> { @PersistenceContext private EntityManager entityManager; @Override public List<Task> customFindByPriority(String priority) { return entityManager .createQuery("select e from Task e where e.taskPriority = :taskPriority", Task.class) .setParameter("taskPriority", priority) .getResultList(); } @Override
// Path: src/main/java/com/mpalourdio/springboottemplate/model/Dummy.java // public class Dummy { // // public String name; // @JsonIgnore // public String desc; // // public Dummy(String name, String desc) { // this.name = name; // this.desc = desc; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/Task.java // @Entity // @Table(name = "task_list") // public class Task { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_list_task_id_seq") // @Column(name = "task_id") // private int id; // // @Column(name = "task_name", nullable = false) // private String taskName; // // @Column(name = "task_description", nullable = false) // private String taskDescription; // // @Column(name = "task_priority", nullable = false) // private String taskPriority; // // @Column(name = "task_status", nullable = false) // private String taskStatus; // // @ColumnDefault("false") // @Column(name = "task_archived", nullable = false) // private Boolean taskArchived = false; // // @ColumnDefault(CurrentTimestampFunction.NAME) // @Column(name = "start_date", nullable = false) // private LocalDateTime startDate = LocalDateTime.now(); // // @OneToMany(mappedBy = "task") // private List<People> people = new ArrayList<>(); // // public String getTaskName() { // return taskName; // } // // public void setTaskName(String taskName) { // this.taskName = taskName; // } // // public String getTaskDescription() { // return taskDescription; // } // // public void setTaskDescription(String taskDescription) { // this.taskDescription = taskDescription; // } // // public String getTaskPriority() { // return taskPriority; // } // // public void setTaskPriority(String taskPriority) { // this.taskPriority = taskPriority; // } // // public String getTaskStatus() { // return taskStatus; // } // // public void setTaskStatus(String taskStatus) { // this.taskStatus = taskStatus; // } // // public Boolean isTaskArchived() { // return taskArchived; // } // // public void setTaskArchived(Boolean taskArchived) { // this.taskArchived = taskArchived; // } // // public List<People> getPeople() { // return people; // } // // public void setPeople(List<People> people) { // this.people = people; // } // // // public LocalDateTime getStartDate() { // return startDate; // } // // public void setStartDate(LocalDateTime startDate) { // this.startDate = startDate; // } // // @Override // public String toString() { // return "Task [id=" + id + ", taskName=" + taskName // + ", taskDescription=" + taskDescription + ", taskPriority=" // + taskPriority + ",taskStatus=" + taskStatus + "]"; // } // } // Path: src/main/java/com/mpalourdio/springboottemplate/model/repositories/TaskRepositoryImpl.java import com.mpalourdio.springboottemplate.model.Dummy; import com.mpalourdio.springboottemplate.model.entities.Task; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.List; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.model.repositories; /** * This implementation MUST have the 'impl' * suffix in order to be discovered ! */ public class TaskRepositoryImpl implements CustomRepository<Task> { @PersistenceContext private EntityManager entityManager; @Override public List<Task> customFindByPriority(String priority) { return entityManager .createQuery("select e from Task e where e.taskPriority = :taskPriority", Task.class) .setParameter("taskPriority", priority) .getResultList(); } @Override
public List<Dummy> hydrateDummyObject() {
mpalourdio/SpringBootTemplate
src/test/java/com/mpalourdio/springboottemplate/rsa/RSATextEncryptorTest.java
// Path: src/main/java/com/mpalourdio/springboottemplate/rsa/exceptions/DecryptException.java // @ResponseStatus(value = HttpStatus.BAD_REQUEST) // public class DecryptException extends RuntimeException { // // public DecryptException(String message) { // super(message); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/rsa/exceptions/EncryptException.java // @ResponseStatus(value = HttpStatus.BAD_REQUEST) // public class EncryptException extends RuntimeException { // // public EncryptException(String message) { // super(message); // } // }
import com.mpalourdio.springboottemplate.rsa.exceptions.DecryptException; import com.mpalourdio.springboottemplate.rsa.exceptions.EncryptException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.rsa; class RSATextEncryptorTest { private TextEncryptor encryptor; @BeforeEach void setUp() { encryptor = new RSATextEncryptor(); } @Test void testCanEncrypt() { var toEncrypt = "luohkufiuijlkkjfhdgfjlkmkjhgfdghoiukgfhgfdsgfhhliyjhfgdsxbcnvb,;njythdxb nbnjo_iètrgfxbcv bhyèu" + "-tyhdfcbvluohkutfiuijlkjfhdgfjlkmkjhgfdghoiukgfhgfdsgfhhliyjhfgdsxbcnvb,;njythdxb nbnjo_iètrgfxbcv bhyèu-" + "tyhdfcbvluohkutfiuifgyksryusryufdsgfhhliyjhfgdsxbcnvb,;njythdxb nbnjo_iètrgfxbcv bhyèu-" + "tyhdfcbvluohkutfiuijlkjfhdgfjlkmkjhgfdghoiukgfhgfdsgfhhliyjhfgdsxbcnvb,;njythdxb nbnjo_iètrgfxbcv bhyèu-" + "tyhdfcbvluohkutfiuijlkjfhdgfjlkmkjhgfdghoiukgfhgfdsgfhhliyjhfgdsxbcnggggggggggggggggg"; var encrypted = encryptor.encrypt(toEncrypt); var decrypted = encryptor.decrypt(encrypted); assertEquals(toEncrypt, decrypted); } @Test void testDecryptThrowsException() {
// Path: src/main/java/com/mpalourdio/springboottemplate/rsa/exceptions/DecryptException.java // @ResponseStatus(value = HttpStatus.BAD_REQUEST) // public class DecryptException extends RuntimeException { // // public DecryptException(String message) { // super(message); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/rsa/exceptions/EncryptException.java // @ResponseStatus(value = HttpStatus.BAD_REQUEST) // public class EncryptException extends RuntimeException { // // public EncryptException(String message) { // super(message); // } // } // Path: src/test/java/com/mpalourdio/springboottemplate/rsa/RSATextEncryptorTest.java import com.mpalourdio.springboottemplate.rsa.exceptions.DecryptException; import com.mpalourdio.springboottemplate.rsa.exceptions.EncryptException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.rsa; class RSATextEncryptorTest { private TextEncryptor encryptor; @BeforeEach void setUp() { encryptor = new RSATextEncryptor(); } @Test void testCanEncrypt() { var toEncrypt = "luohkufiuijlkkjfhdgfjlkmkjhgfdghoiukgfhgfdsgfhhliyjhfgdsxbcnvb,;njythdxb nbnjo_iètrgfxbcv bhyèu" + "-tyhdfcbvluohkutfiuijlkjfhdgfjlkmkjhgfdghoiukgfhgfdsgfhhliyjhfgdsxbcnvb,;njythdxb nbnjo_iètrgfxbcv bhyèu-" + "tyhdfcbvluohkutfiuifgyksryusryufdsgfhhliyjhfgdsxbcnvb,;njythdxb nbnjo_iètrgfxbcv bhyèu-" + "tyhdfcbvluohkutfiuijlkjfhdgfjlkmkjhgfdghoiukgfhgfdsgfhhliyjhfgdsxbcnvb,;njythdxb nbnjo_iètrgfxbcv bhyèu-" + "tyhdfcbvluohkutfiuijlkjfhdgfjlkmkjhgfdghoiukgfhgfdsgfhhliyjhfgdsxbcnggggggggggggggggg"; var encrypted = encryptor.encrypt(toEncrypt); var decrypted = encryptor.decrypt(encrypted); assertEquals(toEncrypt, decrypted); } @Test void testDecryptThrowsException() {
assertThrows(DecryptException.class, () -> encryptor.decrypt("toto"));
mpalourdio/SpringBootTemplate
src/test/java/com/mpalourdio/springboottemplate/rsa/RSATextEncryptorTest.java
// Path: src/main/java/com/mpalourdio/springboottemplate/rsa/exceptions/DecryptException.java // @ResponseStatus(value = HttpStatus.BAD_REQUEST) // public class DecryptException extends RuntimeException { // // public DecryptException(String message) { // super(message); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/rsa/exceptions/EncryptException.java // @ResponseStatus(value = HttpStatus.BAD_REQUEST) // public class EncryptException extends RuntimeException { // // public EncryptException(String message) { // super(message); // } // }
import com.mpalourdio.springboottemplate.rsa.exceptions.DecryptException; import com.mpalourdio.springboottemplate.rsa.exceptions.EncryptException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.rsa; class RSATextEncryptorTest { private TextEncryptor encryptor; @BeforeEach void setUp() { encryptor = new RSATextEncryptor(); } @Test void testCanEncrypt() { var toEncrypt = "luohkufiuijlkkjfhdgfjlkmkjhgfdghoiukgfhgfdsgfhhliyjhfgdsxbcnvb,;njythdxb nbnjo_iètrgfxbcv bhyèu" + "-tyhdfcbvluohkutfiuijlkjfhdgfjlkmkjhgfdghoiukgfhgfdsgfhhliyjhfgdsxbcnvb,;njythdxb nbnjo_iètrgfxbcv bhyèu-" + "tyhdfcbvluohkutfiuifgyksryusryufdsgfhhliyjhfgdsxbcnvb,;njythdxb nbnjo_iètrgfxbcv bhyèu-" + "tyhdfcbvluohkutfiuijlkjfhdgfjlkmkjhgfdghoiukgfhgfdsgfhhliyjhfgdsxbcnvb,;njythdxb nbnjo_iètrgfxbcv bhyèu-" + "tyhdfcbvluohkutfiuijlkjfhdgfjlkmkjhgfdghoiukgfhgfdsgfhhliyjhfgdsxbcnggggggggggggggggg"; var encrypted = encryptor.encrypt(toEncrypt); var decrypted = encryptor.decrypt(encrypted); assertEquals(toEncrypt, decrypted); } @Test void testDecryptThrowsException() { assertThrows(DecryptException.class, () -> encryptor.decrypt("toto")); } /** * The RSA algorithm can only encrypt data that has a maximum byte length of the RSA key length in bits * divided with eight, minus eleven padding bytes, i.e. number of maximum bytes = (key length in bits / 8) - 11. * (4096/8) - 11 = 501 bytes max; */ @Test void testEncryptThrowsException() {
// Path: src/main/java/com/mpalourdio/springboottemplate/rsa/exceptions/DecryptException.java // @ResponseStatus(value = HttpStatus.BAD_REQUEST) // public class DecryptException extends RuntimeException { // // public DecryptException(String message) { // super(message); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/rsa/exceptions/EncryptException.java // @ResponseStatus(value = HttpStatus.BAD_REQUEST) // public class EncryptException extends RuntimeException { // // public EncryptException(String message) { // super(message); // } // } // Path: src/test/java/com/mpalourdio/springboottemplate/rsa/RSATextEncryptorTest.java import com.mpalourdio.springboottemplate.rsa.exceptions.DecryptException; import com.mpalourdio.springboottemplate.rsa.exceptions.EncryptException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.rsa; class RSATextEncryptorTest { private TextEncryptor encryptor; @BeforeEach void setUp() { encryptor = new RSATextEncryptor(); } @Test void testCanEncrypt() { var toEncrypt = "luohkufiuijlkkjfhdgfjlkmkjhgfdghoiukgfhgfdsgfhhliyjhfgdsxbcnvb,;njythdxb nbnjo_iètrgfxbcv bhyèu" + "-tyhdfcbvluohkutfiuijlkjfhdgfjlkmkjhgfdghoiukgfhgfdsgfhhliyjhfgdsxbcnvb,;njythdxb nbnjo_iètrgfxbcv bhyèu-" + "tyhdfcbvluohkutfiuifgyksryusryufdsgfhhliyjhfgdsxbcnvb,;njythdxb nbnjo_iètrgfxbcv bhyèu-" + "tyhdfcbvluohkutfiuijlkjfhdgfjlkmkjhgfdghoiukgfhgfdsgfhhliyjhfgdsxbcnvb,;njythdxb nbnjo_iètrgfxbcv bhyèu-" + "tyhdfcbvluohkutfiuijlkjfhdgfjlkmkjhgfdghoiukgfhgfdsgfhhliyjhfgdsxbcnggggggggggggggggg"; var encrypted = encryptor.encrypt(toEncrypt); var decrypted = encryptor.decrypt(encrypted); assertEquals(toEncrypt, decrypted); } @Test void testDecryptThrowsException() { assertThrows(DecryptException.class, () -> encryptor.decrypt("toto")); } /** * The RSA algorithm can only encrypt data that has a maximum byte length of the RSA key length in bits * divided with eight, minus eleven padding bytes, i.e. number of maximum bytes = (key length in bits / 8) - 11. * (4096/8) - 11 = 501 bytes max; */ @Test void testEncryptThrowsException() {
assertThrows(EncryptException.class, () -> encryptor.encrypt(
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/controllers/MarvelController.java
// Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/properties/MarvelProperties.java // @Getter // @AllArgsConstructor // @ConstructorBinding // @ConfigurationProperties("marvel") // public class MarvelProperties { // // private final String privatekey; // private final String publickey; // private final String unknownProperty; // }
import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.properties.MarvelProperties; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import java.util.Arrays;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @RestController @RequestMapping("/marvel")
// Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/properties/MarvelProperties.java // @Getter // @AllArgsConstructor // @ConstructorBinding // @ConfigurationProperties("marvel") // public class MarvelProperties { // // private final String privatekey; // private final String publickey; // private final String unknownProperty; // } // Path: src/main/java/com/mpalourdio/springboottemplate/controllers/MarvelController.java import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.properties.MarvelProperties; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import java.util.Arrays; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @RestController @RequestMapping("/marvel")
@EnableConfigurationProperties(MarvelProperties.class)
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/controllers/MarvelController.java
// Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/properties/MarvelProperties.java // @Getter // @AllArgsConstructor // @ConstructorBinding // @ConfigurationProperties("marvel") // public class MarvelProperties { // // private final String privatekey; // private final String publickey; // private final String unknownProperty; // }
import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.properties.MarvelProperties; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import java.util.Arrays;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @RestController @RequestMapping("/marvel") @EnableConfigurationProperties(MarvelProperties.class) public class MarvelController { private final MarvelProperties marvelProperties; private final HttpHeaders addonHeaders = new HttpHeaders(); public MarvelController(MarvelProperties marvelProperties) { this.marvelProperties = marvelProperties; buildAddonsHeaders(marvelProperties); } private void buildAddonsHeaders(MarvelProperties marvelProperties) { var unkownProperty = marvelProperties.getUnknownProperty(); if (StringUtils.isNotBlank(unkownProperty)) { Arrays.asList(unkownProperty.split(",")).forEach(h -> { var split = h.split("="); addonHeaders.add(split[0], split[1]); }); } }
// Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/properties/MarvelProperties.java // @Getter // @AllArgsConstructor // @ConstructorBinding // @ConfigurationProperties("marvel") // public class MarvelProperties { // // private final String privatekey; // private final String publickey; // private final String unknownProperty; // } // Path: src/main/java/com/mpalourdio/springboottemplate/controllers/MarvelController.java import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.properties.MarvelProperties; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import java.util.Arrays; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @RestController @RequestMapping("/marvel") @EnableConfigurationProperties(MarvelProperties.class) public class MarvelController { private final MarvelProperties marvelProperties; private final HttpHeaders addonHeaders = new HttpHeaders(); public MarvelController(MarvelProperties marvelProperties) { this.marvelProperties = marvelProperties; buildAddonsHeaders(marvelProperties); } private void buildAddonsHeaders(MarvelProperties marvelProperties) { var unkownProperty = marvelProperties.getUnknownProperty(); if (StringUtils.isNotBlank(unkownProperty)) { Arrays.asList(unkownProperty.split(",")).forEach(h -> { var split = h.split("="); addonHeaders.add(split[0], split[1]); }); } }
@GetMapping(value = "/all", produces = MediaType.APPLICATION_JSON_VALUE)
mpalourdio/SpringBootTemplate
src/test/java/com/mpalourdio/springboottemplate/service/ServiceWithPropertiesTest.java
// Path: src/main/java/com/mpalourdio/springboottemplate/exception/AnotherCustomException.java // public class AnotherCustomException extends Exception { // // public AnotherCustomException(String message) { // super(message); // } // }
import com.mpalourdio.springboottemplate.exception.AnotherCustomException; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.service; class ServiceWithPropertiesTest { @Test void testClassPropertyIsRead() { var serviceWithProperties = new ServiceWithProperties("hey"); assertEquals("hey", serviceWithProperties.getValueFromConfig()); } @Test() void throwExceptionTest() { var serviceWithProperties = new ServiceWithProperties("hey");
// Path: src/main/java/com/mpalourdio/springboottemplate/exception/AnotherCustomException.java // public class AnotherCustomException extends Exception { // // public AnotherCustomException(String message) { // super(message); // } // } // Path: src/test/java/com/mpalourdio/springboottemplate/service/ServiceWithPropertiesTest.java import com.mpalourdio.springboottemplate.exception.AnotherCustomException; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.service; class ServiceWithPropertiesTest { @Test void testClassPropertyIsRead() { var serviceWithProperties = new ServiceWithProperties("hey"); assertEquals("hey", serviceWithProperties.getValueFromConfig()); } @Test() void throwExceptionTest() { var serviceWithProperties = new ServiceWithProperties("hey");
assertThrows(AnotherCustomException.class, serviceWithProperties::throwException);
mpalourdio/SpringBootTemplate
src/test/java/com/mpalourdio/springboottemplate/controllers/MiscControllerTest.java
// Path: src/test/java/com/mpalourdio/springboottemplate/AbstractTestRunner.java // @ExtendWith(SpringExtension.class) // @TestPropertySource(locations = "classpath:test.properties") // @Import({BeansFactory.class}) // public abstract class AbstractTestRunner { // // protected Task task; // protected People people; // // protected void initializeData() { // task = new Task(); // task.setTaskArchived(true); // task.setTaskName("name"); // task.setTaskDescription("description"); // task.setTaskPriority("LOW"); // task.setTaskStatus("ACTIVE"); // // people = new People() // .setName("john") // .setTask(task); // } // // protected String serializeToJson(Object object) throws JsonProcessingException { // return new ObjectMapper().writeValueAsString(object); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Account.java // public class Account implements AccountInterface { // // public String firstName; // public String lastName; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountDecorator.java // public class AccountDecorator implements AccountInterface { // // @JsonUnwrapped // public Account account; // public Context context; // // public AccountDecorator() { // } // // public AccountDecorator(Account account) { // this.account = account; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Context.java // public class Context { // // public String ref; // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ToSerialize.java // public class ToSerialize implements Cloneable { // // public String prop1; // public String prop2; // // @Override // public ToSerialize clone() throws CloneNotSupportedException { // return (ToSerialize) super.clone(); // } // }
import com.mpalourdio.springboottemplate.AbstractTestRunner; import com.mpalourdio.springboottemplate.json.Account; import com.mpalourdio.springboottemplate.json.AccountDecorator; import com.mpalourdio.springboottemplate.json.Context; import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.service.ToSerialize; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.servlet.MockMvc; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @SpringBootTest(webEnvironment = WebEnvironment.MOCK) @AutoConfigureMockMvc @AutoConfigureTestDatabase
// Path: src/test/java/com/mpalourdio/springboottemplate/AbstractTestRunner.java // @ExtendWith(SpringExtension.class) // @TestPropertySource(locations = "classpath:test.properties") // @Import({BeansFactory.class}) // public abstract class AbstractTestRunner { // // protected Task task; // protected People people; // // protected void initializeData() { // task = new Task(); // task.setTaskArchived(true); // task.setTaskName("name"); // task.setTaskDescription("description"); // task.setTaskPriority("LOW"); // task.setTaskStatus("ACTIVE"); // // people = new People() // .setName("john") // .setTask(task); // } // // protected String serializeToJson(Object object) throws JsonProcessingException { // return new ObjectMapper().writeValueAsString(object); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Account.java // public class Account implements AccountInterface { // // public String firstName; // public String lastName; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountDecorator.java // public class AccountDecorator implements AccountInterface { // // @JsonUnwrapped // public Account account; // public Context context; // // public AccountDecorator() { // } // // public AccountDecorator(Account account) { // this.account = account; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Context.java // public class Context { // // public String ref; // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ToSerialize.java // public class ToSerialize implements Cloneable { // // public String prop1; // public String prop2; // // @Override // public ToSerialize clone() throws CloneNotSupportedException { // return (ToSerialize) super.clone(); // } // } // Path: src/test/java/com/mpalourdio/springboottemplate/controllers/MiscControllerTest.java import com.mpalourdio.springboottemplate.AbstractTestRunner; import com.mpalourdio.springboottemplate.json.Account; import com.mpalourdio.springboottemplate.json.AccountDecorator; import com.mpalourdio.springboottemplate.json.Context; import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.service.ToSerialize; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.servlet.MockMvc; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @SpringBootTest(webEnvironment = WebEnvironment.MOCK) @AutoConfigureMockMvc @AutoConfigureTestDatabase
class MiscControllerTest extends AbstractTestRunner {
mpalourdio/SpringBootTemplate
src/test/java/com/mpalourdio/springboottemplate/controllers/MiscControllerTest.java
// Path: src/test/java/com/mpalourdio/springboottemplate/AbstractTestRunner.java // @ExtendWith(SpringExtension.class) // @TestPropertySource(locations = "classpath:test.properties") // @Import({BeansFactory.class}) // public abstract class AbstractTestRunner { // // protected Task task; // protected People people; // // protected void initializeData() { // task = new Task(); // task.setTaskArchived(true); // task.setTaskName("name"); // task.setTaskDescription("description"); // task.setTaskPriority("LOW"); // task.setTaskStatus("ACTIVE"); // // people = new People() // .setName("john") // .setTask(task); // } // // protected String serializeToJson(Object object) throws JsonProcessingException { // return new ObjectMapper().writeValueAsString(object); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Account.java // public class Account implements AccountInterface { // // public String firstName; // public String lastName; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountDecorator.java // public class AccountDecorator implements AccountInterface { // // @JsonUnwrapped // public Account account; // public Context context; // // public AccountDecorator() { // } // // public AccountDecorator(Account account) { // this.account = account; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Context.java // public class Context { // // public String ref; // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ToSerialize.java // public class ToSerialize implements Cloneable { // // public String prop1; // public String prop2; // // @Override // public ToSerialize clone() throws CloneNotSupportedException { // return (ToSerialize) super.clone(); // } // }
import com.mpalourdio.springboottemplate.AbstractTestRunner; import com.mpalourdio.springboottemplate.json.Account; import com.mpalourdio.springboottemplate.json.AccountDecorator; import com.mpalourdio.springboottemplate.json.Context; import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.service.ToSerialize; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.servlet.MockMvc; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @SpringBootTest(webEnvironment = WebEnvironment.MOCK) @AutoConfigureMockMvc @AutoConfigureTestDatabase class MiscControllerTest extends AbstractTestRunner { @Autowired private MockMvc mockMvc; @Test void testSerializationForMvcTests() throws Exception {
// Path: src/test/java/com/mpalourdio/springboottemplate/AbstractTestRunner.java // @ExtendWith(SpringExtension.class) // @TestPropertySource(locations = "classpath:test.properties") // @Import({BeansFactory.class}) // public abstract class AbstractTestRunner { // // protected Task task; // protected People people; // // protected void initializeData() { // task = new Task(); // task.setTaskArchived(true); // task.setTaskName("name"); // task.setTaskDescription("description"); // task.setTaskPriority("LOW"); // task.setTaskStatus("ACTIVE"); // // people = new People() // .setName("john") // .setTask(task); // } // // protected String serializeToJson(Object object) throws JsonProcessingException { // return new ObjectMapper().writeValueAsString(object); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Account.java // public class Account implements AccountInterface { // // public String firstName; // public String lastName; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountDecorator.java // public class AccountDecorator implements AccountInterface { // // @JsonUnwrapped // public Account account; // public Context context; // // public AccountDecorator() { // } // // public AccountDecorator(Account account) { // this.account = account; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Context.java // public class Context { // // public String ref; // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ToSerialize.java // public class ToSerialize implements Cloneable { // // public String prop1; // public String prop2; // // @Override // public ToSerialize clone() throws CloneNotSupportedException { // return (ToSerialize) super.clone(); // } // } // Path: src/test/java/com/mpalourdio/springboottemplate/controllers/MiscControllerTest.java import com.mpalourdio.springboottemplate.AbstractTestRunner; import com.mpalourdio.springboottemplate.json.Account; import com.mpalourdio.springboottemplate.json.AccountDecorator; import com.mpalourdio.springboottemplate.json.Context; import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.service.ToSerialize; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.servlet.MockMvc; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @SpringBootTest(webEnvironment = WebEnvironment.MOCK) @AutoConfigureMockMvc @AutoConfigureTestDatabase class MiscControllerTest extends AbstractTestRunner { @Autowired private MockMvc mockMvc; @Test void testSerializationForMvcTests() throws Exception {
var toSerialize = new ToSerialize();
mpalourdio/SpringBootTemplate
src/test/java/com/mpalourdio/springboottemplate/controllers/MiscControllerTest.java
// Path: src/test/java/com/mpalourdio/springboottemplate/AbstractTestRunner.java // @ExtendWith(SpringExtension.class) // @TestPropertySource(locations = "classpath:test.properties") // @Import({BeansFactory.class}) // public abstract class AbstractTestRunner { // // protected Task task; // protected People people; // // protected void initializeData() { // task = new Task(); // task.setTaskArchived(true); // task.setTaskName("name"); // task.setTaskDescription("description"); // task.setTaskPriority("LOW"); // task.setTaskStatus("ACTIVE"); // // people = new People() // .setName("john") // .setTask(task); // } // // protected String serializeToJson(Object object) throws JsonProcessingException { // return new ObjectMapper().writeValueAsString(object); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Account.java // public class Account implements AccountInterface { // // public String firstName; // public String lastName; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountDecorator.java // public class AccountDecorator implements AccountInterface { // // @JsonUnwrapped // public Account account; // public Context context; // // public AccountDecorator() { // } // // public AccountDecorator(Account account) { // this.account = account; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Context.java // public class Context { // // public String ref; // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ToSerialize.java // public class ToSerialize implements Cloneable { // // public String prop1; // public String prop2; // // @Override // public ToSerialize clone() throws CloneNotSupportedException { // return (ToSerialize) super.clone(); // } // }
import com.mpalourdio.springboottemplate.AbstractTestRunner; import com.mpalourdio.springboottemplate.json.Account; import com.mpalourdio.springboottemplate.json.AccountDecorator; import com.mpalourdio.springboottemplate.json.Context; import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.service.ToSerialize; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.servlet.MockMvc; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @SpringBootTest(webEnvironment = WebEnvironment.MOCK) @AutoConfigureMockMvc @AutoConfigureTestDatabase class MiscControllerTest extends AbstractTestRunner { @Autowired private MockMvc mockMvc; @Test void testSerializationForMvcTests() throws Exception { var toSerialize = new ToSerialize(); var input = serializeToJson(toSerialize); var output = toSerialize.clone(); output.prop1 = "prop1updated"; mockMvc.perform(post("/misc/serialization") .with(csrf())
// Path: src/test/java/com/mpalourdio/springboottemplate/AbstractTestRunner.java // @ExtendWith(SpringExtension.class) // @TestPropertySource(locations = "classpath:test.properties") // @Import({BeansFactory.class}) // public abstract class AbstractTestRunner { // // protected Task task; // protected People people; // // protected void initializeData() { // task = new Task(); // task.setTaskArchived(true); // task.setTaskName("name"); // task.setTaskDescription("description"); // task.setTaskPriority("LOW"); // task.setTaskStatus("ACTIVE"); // // people = new People() // .setName("john") // .setTask(task); // } // // protected String serializeToJson(Object object) throws JsonProcessingException { // return new ObjectMapper().writeValueAsString(object); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Account.java // public class Account implements AccountInterface { // // public String firstName; // public String lastName; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountDecorator.java // public class AccountDecorator implements AccountInterface { // // @JsonUnwrapped // public Account account; // public Context context; // // public AccountDecorator() { // } // // public AccountDecorator(Account account) { // this.account = account; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Context.java // public class Context { // // public String ref; // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ToSerialize.java // public class ToSerialize implements Cloneable { // // public String prop1; // public String prop2; // // @Override // public ToSerialize clone() throws CloneNotSupportedException { // return (ToSerialize) super.clone(); // } // } // Path: src/test/java/com/mpalourdio/springboottemplate/controllers/MiscControllerTest.java import com.mpalourdio.springboottemplate.AbstractTestRunner; import com.mpalourdio.springboottemplate.json.Account; import com.mpalourdio.springboottemplate.json.AccountDecorator; import com.mpalourdio.springboottemplate.json.Context; import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.service.ToSerialize; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.servlet.MockMvc; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @SpringBootTest(webEnvironment = WebEnvironment.MOCK) @AutoConfigureMockMvc @AutoConfigureTestDatabase class MiscControllerTest extends AbstractTestRunner { @Autowired private MockMvc mockMvc; @Test void testSerializationForMvcTests() throws Exception { var toSerialize = new ToSerialize(); var input = serializeToJson(toSerialize); var output = toSerialize.clone(); output.prop1 = "prop1updated"; mockMvc.perform(post("/misc/serialization") .with(csrf())
.contentType(MediaType.APPLICATION_JSON_VALUE)
mpalourdio/SpringBootTemplate
src/test/java/com/mpalourdio/springboottemplate/controllers/MiscControllerTest.java
// Path: src/test/java/com/mpalourdio/springboottemplate/AbstractTestRunner.java // @ExtendWith(SpringExtension.class) // @TestPropertySource(locations = "classpath:test.properties") // @Import({BeansFactory.class}) // public abstract class AbstractTestRunner { // // protected Task task; // protected People people; // // protected void initializeData() { // task = new Task(); // task.setTaskArchived(true); // task.setTaskName("name"); // task.setTaskDescription("description"); // task.setTaskPriority("LOW"); // task.setTaskStatus("ACTIVE"); // // people = new People() // .setName("john") // .setTask(task); // } // // protected String serializeToJson(Object object) throws JsonProcessingException { // return new ObjectMapper().writeValueAsString(object); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Account.java // public class Account implements AccountInterface { // // public String firstName; // public String lastName; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountDecorator.java // public class AccountDecorator implements AccountInterface { // // @JsonUnwrapped // public Account account; // public Context context; // // public AccountDecorator() { // } // // public AccountDecorator(Account account) { // this.account = account; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Context.java // public class Context { // // public String ref; // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ToSerialize.java // public class ToSerialize implements Cloneable { // // public String prop1; // public String prop2; // // @Override // public ToSerialize clone() throws CloneNotSupportedException { // return (ToSerialize) super.clone(); // } // }
import com.mpalourdio.springboottemplate.AbstractTestRunner; import com.mpalourdio.springboottemplate.json.Account; import com.mpalourdio.springboottemplate.json.AccountDecorator; import com.mpalourdio.springboottemplate.json.Context; import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.service.ToSerialize; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.servlet.MockMvc; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @SpringBootTest(webEnvironment = WebEnvironment.MOCK) @AutoConfigureMockMvc @AutoConfigureTestDatabase class MiscControllerTest extends AbstractTestRunner { @Autowired private MockMvc mockMvc; @Test void testSerializationForMvcTests() throws Exception { var toSerialize = new ToSerialize(); var input = serializeToJson(toSerialize); var output = toSerialize.clone(); output.prop1 = "prop1updated"; mockMvc.perform(post("/misc/serialization") .with(csrf()) .contentType(MediaType.APPLICATION_JSON_VALUE) .content(input)) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(content().json(serializeToJson(output), true)); } @Test void testJsonUnwrappingInAClassDecorator() throws Exception {
// Path: src/test/java/com/mpalourdio/springboottemplate/AbstractTestRunner.java // @ExtendWith(SpringExtension.class) // @TestPropertySource(locations = "classpath:test.properties") // @Import({BeansFactory.class}) // public abstract class AbstractTestRunner { // // protected Task task; // protected People people; // // protected void initializeData() { // task = new Task(); // task.setTaskArchived(true); // task.setTaskName("name"); // task.setTaskDescription("description"); // task.setTaskPriority("LOW"); // task.setTaskStatus("ACTIVE"); // // people = new People() // .setName("john") // .setTask(task); // } // // protected String serializeToJson(Object object) throws JsonProcessingException { // return new ObjectMapper().writeValueAsString(object); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Account.java // public class Account implements AccountInterface { // // public String firstName; // public String lastName; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountDecorator.java // public class AccountDecorator implements AccountInterface { // // @JsonUnwrapped // public Account account; // public Context context; // // public AccountDecorator() { // } // // public AccountDecorator(Account account) { // this.account = account; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Context.java // public class Context { // // public String ref; // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ToSerialize.java // public class ToSerialize implements Cloneable { // // public String prop1; // public String prop2; // // @Override // public ToSerialize clone() throws CloneNotSupportedException { // return (ToSerialize) super.clone(); // } // } // Path: src/test/java/com/mpalourdio/springboottemplate/controllers/MiscControllerTest.java import com.mpalourdio.springboottemplate.AbstractTestRunner; import com.mpalourdio.springboottemplate.json.Account; import com.mpalourdio.springboottemplate.json.AccountDecorator; import com.mpalourdio.springboottemplate.json.Context; import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.service.ToSerialize; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.servlet.MockMvc; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @SpringBootTest(webEnvironment = WebEnvironment.MOCK) @AutoConfigureMockMvc @AutoConfigureTestDatabase class MiscControllerTest extends AbstractTestRunner { @Autowired private MockMvc mockMvc; @Test void testSerializationForMvcTests() throws Exception { var toSerialize = new ToSerialize(); var input = serializeToJson(toSerialize); var output = toSerialize.clone(); output.prop1 = "prop1updated"; mockMvc.perform(post("/misc/serialization") .with(csrf()) .contentType(MediaType.APPLICATION_JSON_VALUE) .content(input)) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(content().json(serializeToJson(output), true)); } @Test void testJsonUnwrappingInAClassDecorator() throws Exception {
var account = new Account();
mpalourdio/SpringBootTemplate
src/test/java/com/mpalourdio/springboottemplate/controllers/MiscControllerTest.java
// Path: src/test/java/com/mpalourdio/springboottemplate/AbstractTestRunner.java // @ExtendWith(SpringExtension.class) // @TestPropertySource(locations = "classpath:test.properties") // @Import({BeansFactory.class}) // public abstract class AbstractTestRunner { // // protected Task task; // protected People people; // // protected void initializeData() { // task = new Task(); // task.setTaskArchived(true); // task.setTaskName("name"); // task.setTaskDescription("description"); // task.setTaskPriority("LOW"); // task.setTaskStatus("ACTIVE"); // // people = new People() // .setName("john") // .setTask(task); // } // // protected String serializeToJson(Object object) throws JsonProcessingException { // return new ObjectMapper().writeValueAsString(object); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Account.java // public class Account implements AccountInterface { // // public String firstName; // public String lastName; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountDecorator.java // public class AccountDecorator implements AccountInterface { // // @JsonUnwrapped // public Account account; // public Context context; // // public AccountDecorator() { // } // // public AccountDecorator(Account account) { // this.account = account; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Context.java // public class Context { // // public String ref; // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ToSerialize.java // public class ToSerialize implements Cloneable { // // public String prop1; // public String prop2; // // @Override // public ToSerialize clone() throws CloneNotSupportedException { // return (ToSerialize) super.clone(); // } // }
import com.mpalourdio.springboottemplate.AbstractTestRunner; import com.mpalourdio.springboottemplate.json.Account; import com.mpalourdio.springboottemplate.json.AccountDecorator; import com.mpalourdio.springboottemplate.json.Context; import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.service.ToSerialize; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.servlet.MockMvc; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @SpringBootTest(webEnvironment = WebEnvironment.MOCK) @AutoConfigureMockMvc @AutoConfigureTestDatabase class MiscControllerTest extends AbstractTestRunner { @Autowired private MockMvc mockMvc; @Test void testSerializationForMvcTests() throws Exception { var toSerialize = new ToSerialize(); var input = serializeToJson(toSerialize); var output = toSerialize.clone(); output.prop1 = "prop1updated"; mockMvc.perform(post("/misc/serialization") .with(csrf()) .contentType(MediaType.APPLICATION_JSON_VALUE) .content(input)) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(content().json(serializeToJson(output), true)); } @Test void testJsonUnwrappingInAClassDecorator() throws Exception { var account = new Account(); account.lastName = "lastName"; account.firstName = "firstName"; var input = serializeToJson(account);
// Path: src/test/java/com/mpalourdio/springboottemplate/AbstractTestRunner.java // @ExtendWith(SpringExtension.class) // @TestPropertySource(locations = "classpath:test.properties") // @Import({BeansFactory.class}) // public abstract class AbstractTestRunner { // // protected Task task; // protected People people; // // protected void initializeData() { // task = new Task(); // task.setTaskArchived(true); // task.setTaskName("name"); // task.setTaskDescription("description"); // task.setTaskPriority("LOW"); // task.setTaskStatus("ACTIVE"); // // people = new People() // .setName("john") // .setTask(task); // } // // protected String serializeToJson(Object object) throws JsonProcessingException { // return new ObjectMapper().writeValueAsString(object); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Account.java // public class Account implements AccountInterface { // // public String firstName; // public String lastName; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountDecorator.java // public class AccountDecorator implements AccountInterface { // // @JsonUnwrapped // public Account account; // public Context context; // // public AccountDecorator() { // } // // public AccountDecorator(Account account) { // this.account = account; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Context.java // public class Context { // // public String ref; // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ToSerialize.java // public class ToSerialize implements Cloneable { // // public String prop1; // public String prop2; // // @Override // public ToSerialize clone() throws CloneNotSupportedException { // return (ToSerialize) super.clone(); // } // } // Path: src/test/java/com/mpalourdio/springboottemplate/controllers/MiscControllerTest.java import com.mpalourdio.springboottemplate.AbstractTestRunner; import com.mpalourdio.springboottemplate.json.Account; import com.mpalourdio.springboottemplate.json.AccountDecorator; import com.mpalourdio.springboottemplate.json.Context; import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.service.ToSerialize; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.servlet.MockMvc; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @SpringBootTest(webEnvironment = WebEnvironment.MOCK) @AutoConfigureMockMvc @AutoConfigureTestDatabase class MiscControllerTest extends AbstractTestRunner { @Autowired private MockMvc mockMvc; @Test void testSerializationForMvcTests() throws Exception { var toSerialize = new ToSerialize(); var input = serializeToJson(toSerialize); var output = toSerialize.clone(); output.prop1 = "prop1updated"; mockMvc.perform(post("/misc/serialization") .with(csrf()) .contentType(MediaType.APPLICATION_JSON_VALUE) .content(input)) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(content().json(serializeToJson(output), true)); } @Test void testJsonUnwrappingInAClassDecorator() throws Exception { var account = new Account(); account.lastName = "lastName"; account.firstName = "firstName"; var input = serializeToJson(account);
var accountDecorator = new AccountDecorator(account);
mpalourdio/SpringBootTemplate
src/test/java/com/mpalourdio/springboottemplate/controllers/MiscControllerTest.java
// Path: src/test/java/com/mpalourdio/springboottemplate/AbstractTestRunner.java // @ExtendWith(SpringExtension.class) // @TestPropertySource(locations = "classpath:test.properties") // @Import({BeansFactory.class}) // public abstract class AbstractTestRunner { // // protected Task task; // protected People people; // // protected void initializeData() { // task = new Task(); // task.setTaskArchived(true); // task.setTaskName("name"); // task.setTaskDescription("description"); // task.setTaskPriority("LOW"); // task.setTaskStatus("ACTIVE"); // // people = new People() // .setName("john") // .setTask(task); // } // // protected String serializeToJson(Object object) throws JsonProcessingException { // return new ObjectMapper().writeValueAsString(object); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Account.java // public class Account implements AccountInterface { // // public String firstName; // public String lastName; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountDecorator.java // public class AccountDecorator implements AccountInterface { // // @JsonUnwrapped // public Account account; // public Context context; // // public AccountDecorator() { // } // // public AccountDecorator(Account account) { // this.account = account; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Context.java // public class Context { // // public String ref; // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ToSerialize.java // public class ToSerialize implements Cloneable { // // public String prop1; // public String prop2; // // @Override // public ToSerialize clone() throws CloneNotSupportedException { // return (ToSerialize) super.clone(); // } // }
import com.mpalourdio.springboottemplate.AbstractTestRunner; import com.mpalourdio.springboottemplate.json.Account; import com.mpalourdio.springboottemplate.json.AccountDecorator; import com.mpalourdio.springboottemplate.json.Context; import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.service.ToSerialize; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.servlet.MockMvc; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @SpringBootTest(webEnvironment = WebEnvironment.MOCK) @AutoConfigureMockMvc @AutoConfigureTestDatabase class MiscControllerTest extends AbstractTestRunner { @Autowired private MockMvc mockMvc; @Test void testSerializationForMvcTests() throws Exception { var toSerialize = new ToSerialize(); var input = serializeToJson(toSerialize); var output = toSerialize.clone(); output.prop1 = "prop1updated"; mockMvc.perform(post("/misc/serialization") .with(csrf()) .contentType(MediaType.APPLICATION_JSON_VALUE) .content(input)) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(content().json(serializeToJson(output), true)); } @Test void testJsonUnwrappingInAClassDecorator() throws Exception { var account = new Account(); account.lastName = "lastName"; account.firstName = "firstName"; var input = serializeToJson(account); var accountDecorator = new AccountDecorator(account);
// Path: src/test/java/com/mpalourdio/springboottemplate/AbstractTestRunner.java // @ExtendWith(SpringExtension.class) // @TestPropertySource(locations = "classpath:test.properties") // @Import({BeansFactory.class}) // public abstract class AbstractTestRunner { // // protected Task task; // protected People people; // // protected void initializeData() { // task = new Task(); // task.setTaskArchived(true); // task.setTaskName("name"); // task.setTaskDescription("description"); // task.setTaskPriority("LOW"); // task.setTaskStatus("ACTIVE"); // // people = new People() // .setName("john") // .setTask(task); // } // // protected String serializeToJson(Object object) throws JsonProcessingException { // return new ObjectMapper().writeValueAsString(object); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Account.java // public class Account implements AccountInterface { // // public String firstName; // public String lastName; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountDecorator.java // public class AccountDecorator implements AccountInterface { // // @JsonUnwrapped // public Account account; // public Context context; // // public AccountDecorator() { // } // // public AccountDecorator(Account account) { // this.account = account; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Context.java // public class Context { // // public String ref; // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ToSerialize.java // public class ToSerialize implements Cloneable { // // public String prop1; // public String prop2; // // @Override // public ToSerialize clone() throws CloneNotSupportedException { // return (ToSerialize) super.clone(); // } // } // Path: src/test/java/com/mpalourdio/springboottemplate/controllers/MiscControllerTest.java import com.mpalourdio.springboottemplate.AbstractTestRunner; import com.mpalourdio.springboottemplate.json.Account; import com.mpalourdio.springboottemplate.json.AccountDecorator; import com.mpalourdio.springboottemplate.json.Context; import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.service.ToSerialize; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.servlet.MockMvc; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @SpringBootTest(webEnvironment = WebEnvironment.MOCK) @AutoConfigureMockMvc @AutoConfigureTestDatabase class MiscControllerTest extends AbstractTestRunner { @Autowired private MockMvc mockMvc; @Test void testSerializationForMvcTests() throws Exception { var toSerialize = new ToSerialize(); var input = serializeToJson(toSerialize); var output = toSerialize.clone(); output.prop1 = "prop1updated"; mockMvc.perform(post("/misc/serialization") .with(csrf()) .contentType(MediaType.APPLICATION_JSON_VALUE) .content(input)) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(content().json(serializeToJson(output), true)); } @Test void testJsonUnwrappingInAClassDecorator() throws Exception { var account = new Account(); account.lastName = "lastName"; account.firstName = "firstName"; var input = serializeToJson(account); var accountDecorator = new AccountDecorator(account);
var context = new Context();
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/controllers/HomeController.java
// Path: src/main/java/com/mpalourdio/springboottemplate/model/repositories/TaskRepository.java // @Repository // public interface TaskRepository extends CrudRepository<Task, Integer>, CustomRepository<Task> { // // List<Task> findByTaskArchived(int taskArchivedFalse); // // List<Task> findByTaskStatus(String taskStatus); // // @Query("SELECT e FROM Task e where e.taskArchived = :status") // List<Task> getAllTasksByArchivedValue(@Param("status") Boolean archivedStatus); // // @Override // List<Task> findAll(); // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ServiceWithProperties.java // public class ServiceWithProperties { // // private final String valueFromConfig; // // public ServiceWithProperties(String valueFromConfig) { // this.valueFromConfig = valueFromConfig; // } // // public String getValueFromConfig() { // return valueFromConfig; // } // // public void throwException() throws AnotherCustomException { // throw new AnotherCustomException("gosh"); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/UselessBean.java // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class UselessBean { // // private String testPro = "inclass"; // // private final ABeanIWantToMockInterface aBeanIWantToMock; // // public UselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // this.aBeanIWantToMock = aBeanIWantToMock; // } // // public Boolean iWantToMockThisMethod() { // return aBeanIWantToMock.iAlwaysReturnFalse(); // } // // public String getTestPro() { // return testPro; // } // // public void setTestPro(String testPro) { // this.testPro = testPro; // } // // public void testSerialization(ToSerialize toSerialize) { // toSerialize.prop1 = "prop1updated"; // } // }
import com.mpalourdio.springboottemplate.model.repositories.TaskRepository; import com.mpalourdio.springboottemplate.service.ServiceWithProperties; import com.mpalourdio.springboottemplate.service.UselessBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.client.RestTemplate;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @Controller public class HomeController { private static final String TASK_STATUS_ACTIVE = "ACTIVE"; private static final String TASK_PRIORITY_MEDIUM = "MEDIUM"; private static final String IWANTTHISINMYVIEW = "iwantthisinmyview"; private static final String IWANTTHISINMYVIEWFROMHIBERNATE = "iwantthisinmyviewfromhibernate"; private static final String HTTPS_JSONPLACEHOLDER_TYPICODE_COM_POSTS_1 = "https://jsonplaceholder.typicode.com/posts/1"; private static final String HOME_INDEX = "home/index"; private static final String NEW_BODY = "new body";
// Path: src/main/java/com/mpalourdio/springboottemplate/model/repositories/TaskRepository.java // @Repository // public interface TaskRepository extends CrudRepository<Task, Integer>, CustomRepository<Task> { // // List<Task> findByTaskArchived(int taskArchivedFalse); // // List<Task> findByTaskStatus(String taskStatus); // // @Query("SELECT e FROM Task e where e.taskArchived = :status") // List<Task> getAllTasksByArchivedValue(@Param("status") Boolean archivedStatus); // // @Override // List<Task> findAll(); // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ServiceWithProperties.java // public class ServiceWithProperties { // // private final String valueFromConfig; // // public ServiceWithProperties(String valueFromConfig) { // this.valueFromConfig = valueFromConfig; // } // // public String getValueFromConfig() { // return valueFromConfig; // } // // public void throwException() throws AnotherCustomException { // throw new AnotherCustomException("gosh"); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/UselessBean.java // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class UselessBean { // // private String testPro = "inclass"; // // private final ABeanIWantToMockInterface aBeanIWantToMock; // // public UselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // this.aBeanIWantToMock = aBeanIWantToMock; // } // // public Boolean iWantToMockThisMethod() { // return aBeanIWantToMock.iAlwaysReturnFalse(); // } // // public String getTestPro() { // return testPro; // } // // public void setTestPro(String testPro) { // this.testPro = testPro; // } // // public void testSerialization(ToSerialize toSerialize) { // toSerialize.prop1 = "prop1updated"; // } // } // Path: src/main/java/com/mpalourdio/springboottemplate/controllers/HomeController.java import com.mpalourdio.springboottemplate.model.repositories.TaskRepository; import com.mpalourdio.springboottemplate.service.ServiceWithProperties; import com.mpalourdio.springboottemplate.service.UselessBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.client.RestTemplate; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @Controller public class HomeController { private static final String TASK_STATUS_ACTIVE = "ACTIVE"; private static final String TASK_PRIORITY_MEDIUM = "MEDIUM"; private static final String IWANTTHISINMYVIEW = "iwantthisinmyview"; private static final String IWANTTHISINMYVIEWFROMHIBERNATE = "iwantthisinmyviewfromhibernate"; private static final String HTTPS_JSONPLACEHOLDER_TYPICODE_COM_POSTS_1 = "https://jsonplaceholder.typicode.com/posts/1"; private static final String HOME_INDEX = "home/index"; private static final String NEW_BODY = "new body";
private final ServiceWithProperties serviceWithProperties;
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/controllers/HomeController.java
// Path: src/main/java/com/mpalourdio/springboottemplate/model/repositories/TaskRepository.java // @Repository // public interface TaskRepository extends CrudRepository<Task, Integer>, CustomRepository<Task> { // // List<Task> findByTaskArchived(int taskArchivedFalse); // // List<Task> findByTaskStatus(String taskStatus); // // @Query("SELECT e FROM Task e where e.taskArchived = :status") // List<Task> getAllTasksByArchivedValue(@Param("status") Boolean archivedStatus); // // @Override // List<Task> findAll(); // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ServiceWithProperties.java // public class ServiceWithProperties { // // private final String valueFromConfig; // // public ServiceWithProperties(String valueFromConfig) { // this.valueFromConfig = valueFromConfig; // } // // public String getValueFromConfig() { // return valueFromConfig; // } // // public void throwException() throws AnotherCustomException { // throw new AnotherCustomException("gosh"); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/UselessBean.java // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class UselessBean { // // private String testPro = "inclass"; // // private final ABeanIWantToMockInterface aBeanIWantToMock; // // public UselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // this.aBeanIWantToMock = aBeanIWantToMock; // } // // public Boolean iWantToMockThisMethod() { // return aBeanIWantToMock.iAlwaysReturnFalse(); // } // // public String getTestPro() { // return testPro; // } // // public void setTestPro(String testPro) { // this.testPro = testPro; // } // // public void testSerialization(ToSerialize toSerialize) { // toSerialize.prop1 = "prop1updated"; // } // }
import com.mpalourdio.springboottemplate.model.repositories.TaskRepository; import com.mpalourdio.springboottemplate.service.ServiceWithProperties; import com.mpalourdio.springboottemplate.service.UselessBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.client.RestTemplate;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @Controller public class HomeController { private static final String TASK_STATUS_ACTIVE = "ACTIVE"; private static final String TASK_PRIORITY_MEDIUM = "MEDIUM"; private static final String IWANTTHISINMYVIEW = "iwantthisinmyview"; private static final String IWANTTHISINMYVIEWFROMHIBERNATE = "iwantthisinmyviewfromhibernate"; private static final String HTTPS_JSONPLACEHOLDER_TYPICODE_COM_POSTS_1 = "https://jsonplaceholder.typicode.com/posts/1"; private static final String HOME_INDEX = "home/index"; private static final String NEW_BODY = "new body"; private final ServiceWithProperties serviceWithProperties; private final String myProperty;
// Path: src/main/java/com/mpalourdio/springboottemplate/model/repositories/TaskRepository.java // @Repository // public interface TaskRepository extends CrudRepository<Task, Integer>, CustomRepository<Task> { // // List<Task> findByTaskArchived(int taskArchivedFalse); // // List<Task> findByTaskStatus(String taskStatus); // // @Query("SELECT e FROM Task e where e.taskArchived = :status") // List<Task> getAllTasksByArchivedValue(@Param("status") Boolean archivedStatus); // // @Override // List<Task> findAll(); // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ServiceWithProperties.java // public class ServiceWithProperties { // // private final String valueFromConfig; // // public ServiceWithProperties(String valueFromConfig) { // this.valueFromConfig = valueFromConfig; // } // // public String getValueFromConfig() { // return valueFromConfig; // } // // public void throwException() throws AnotherCustomException { // throw new AnotherCustomException("gosh"); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/UselessBean.java // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class UselessBean { // // private String testPro = "inclass"; // // private final ABeanIWantToMockInterface aBeanIWantToMock; // // public UselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // this.aBeanIWantToMock = aBeanIWantToMock; // } // // public Boolean iWantToMockThisMethod() { // return aBeanIWantToMock.iAlwaysReturnFalse(); // } // // public String getTestPro() { // return testPro; // } // // public void setTestPro(String testPro) { // this.testPro = testPro; // } // // public void testSerialization(ToSerialize toSerialize) { // toSerialize.prop1 = "prop1updated"; // } // } // Path: src/main/java/com/mpalourdio/springboottemplate/controllers/HomeController.java import com.mpalourdio.springboottemplate.model.repositories.TaskRepository; import com.mpalourdio.springboottemplate.service.ServiceWithProperties; import com.mpalourdio.springboottemplate.service.UselessBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.client.RestTemplate; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @Controller public class HomeController { private static final String TASK_STATUS_ACTIVE = "ACTIVE"; private static final String TASK_PRIORITY_MEDIUM = "MEDIUM"; private static final String IWANTTHISINMYVIEW = "iwantthisinmyview"; private static final String IWANTTHISINMYVIEWFROMHIBERNATE = "iwantthisinmyviewfromhibernate"; private static final String HTTPS_JSONPLACEHOLDER_TYPICODE_COM_POSTS_1 = "https://jsonplaceholder.typicode.com/posts/1"; private static final String HOME_INDEX = "home/index"; private static final String NEW_BODY = "new body"; private final ServiceWithProperties serviceWithProperties; private final String myProperty;
private final UselessBean uselessBean;
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/controllers/HomeController.java
// Path: src/main/java/com/mpalourdio/springboottemplate/model/repositories/TaskRepository.java // @Repository // public interface TaskRepository extends CrudRepository<Task, Integer>, CustomRepository<Task> { // // List<Task> findByTaskArchived(int taskArchivedFalse); // // List<Task> findByTaskStatus(String taskStatus); // // @Query("SELECT e FROM Task e where e.taskArchived = :status") // List<Task> getAllTasksByArchivedValue(@Param("status") Boolean archivedStatus); // // @Override // List<Task> findAll(); // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ServiceWithProperties.java // public class ServiceWithProperties { // // private final String valueFromConfig; // // public ServiceWithProperties(String valueFromConfig) { // this.valueFromConfig = valueFromConfig; // } // // public String getValueFromConfig() { // return valueFromConfig; // } // // public void throwException() throws AnotherCustomException { // throw new AnotherCustomException("gosh"); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/UselessBean.java // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class UselessBean { // // private String testPro = "inclass"; // // private final ABeanIWantToMockInterface aBeanIWantToMock; // // public UselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // this.aBeanIWantToMock = aBeanIWantToMock; // } // // public Boolean iWantToMockThisMethod() { // return aBeanIWantToMock.iAlwaysReturnFalse(); // } // // public String getTestPro() { // return testPro; // } // // public void setTestPro(String testPro) { // this.testPro = testPro; // } // // public void testSerialization(ToSerialize toSerialize) { // toSerialize.prop1 = "prop1updated"; // } // }
import com.mpalourdio.springboottemplate.model.repositories.TaskRepository; import com.mpalourdio.springboottemplate.service.ServiceWithProperties; import com.mpalourdio.springboottemplate.service.UselessBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.client.RestTemplate;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @Controller public class HomeController { private static final String TASK_STATUS_ACTIVE = "ACTIVE"; private static final String TASK_PRIORITY_MEDIUM = "MEDIUM"; private static final String IWANTTHISINMYVIEW = "iwantthisinmyview"; private static final String IWANTTHISINMYVIEWFROMHIBERNATE = "iwantthisinmyviewfromhibernate"; private static final String HTTPS_JSONPLACEHOLDER_TYPICODE_COM_POSTS_1 = "https://jsonplaceholder.typicode.com/posts/1"; private static final String HOME_INDEX = "home/index"; private static final String NEW_BODY = "new body"; private final ServiceWithProperties serviceWithProperties; private final String myProperty; private final UselessBean uselessBean;
// Path: src/main/java/com/mpalourdio/springboottemplate/model/repositories/TaskRepository.java // @Repository // public interface TaskRepository extends CrudRepository<Task, Integer>, CustomRepository<Task> { // // List<Task> findByTaskArchived(int taskArchivedFalse); // // List<Task> findByTaskStatus(String taskStatus); // // @Query("SELECT e FROM Task e where e.taskArchived = :status") // List<Task> getAllTasksByArchivedValue(@Param("status") Boolean archivedStatus); // // @Override // List<Task> findAll(); // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ServiceWithProperties.java // public class ServiceWithProperties { // // private final String valueFromConfig; // // public ServiceWithProperties(String valueFromConfig) { // this.valueFromConfig = valueFromConfig; // } // // public String getValueFromConfig() { // return valueFromConfig; // } // // public void throwException() throws AnotherCustomException { // throw new AnotherCustomException("gosh"); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/UselessBean.java // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class UselessBean { // // private String testPro = "inclass"; // // private final ABeanIWantToMockInterface aBeanIWantToMock; // // public UselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // this.aBeanIWantToMock = aBeanIWantToMock; // } // // public Boolean iWantToMockThisMethod() { // return aBeanIWantToMock.iAlwaysReturnFalse(); // } // // public String getTestPro() { // return testPro; // } // // public void setTestPro(String testPro) { // this.testPro = testPro; // } // // public void testSerialization(ToSerialize toSerialize) { // toSerialize.prop1 = "prop1updated"; // } // } // Path: src/main/java/com/mpalourdio/springboottemplate/controllers/HomeController.java import com.mpalourdio.springboottemplate.model.repositories.TaskRepository; import com.mpalourdio.springboottemplate.service.ServiceWithProperties; import com.mpalourdio.springboottemplate.service.UselessBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.client.RestTemplate; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @Controller public class HomeController { private static final String TASK_STATUS_ACTIVE = "ACTIVE"; private static final String TASK_PRIORITY_MEDIUM = "MEDIUM"; private static final String IWANTTHISINMYVIEW = "iwantthisinmyview"; private static final String IWANTTHISINMYVIEWFROMHIBERNATE = "iwantthisinmyviewfromhibernate"; private static final String HTTPS_JSONPLACEHOLDER_TYPICODE_COM_POSTS_1 = "https://jsonplaceholder.typicode.com/posts/1"; private static final String HOME_INDEX = "home/index"; private static final String NEW_BODY = "new body"; private final ServiceWithProperties serviceWithProperties; private final String myProperty; private final UselessBean uselessBean;
private final TaskRepository taskRepository;
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/model/repositories/CustomRepository.java
// Path: src/main/java/com/mpalourdio/springboottemplate/model/Dummy.java // public class Dummy { // // public String name; // @JsonIgnore // public String desc; // // public Dummy(String name, String desc) { // this.name = name; // this.desc = desc; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/Task.java // @Entity // @Table(name = "task_list") // public class Task { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_list_task_id_seq") // @Column(name = "task_id") // private int id; // // @Column(name = "task_name", nullable = false) // private String taskName; // // @Column(name = "task_description", nullable = false) // private String taskDescription; // // @Column(name = "task_priority", nullable = false) // private String taskPriority; // // @Column(name = "task_status", nullable = false) // private String taskStatus; // // @ColumnDefault("false") // @Column(name = "task_archived", nullable = false) // private Boolean taskArchived = false; // // @ColumnDefault(CurrentTimestampFunction.NAME) // @Column(name = "start_date", nullable = false) // private LocalDateTime startDate = LocalDateTime.now(); // // @OneToMany(mappedBy = "task") // private List<People> people = new ArrayList<>(); // // public String getTaskName() { // return taskName; // } // // public void setTaskName(String taskName) { // this.taskName = taskName; // } // // public String getTaskDescription() { // return taskDescription; // } // // public void setTaskDescription(String taskDescription) { // this.taskDescription = taskDescription; // } // // public String getTaskPriority() { // return taskPriority; // } // // public void setTaskPriority(String taskPriority) { // this.taskPriority = taskPriority; // } // // public String getTaskStatus() { // return taskStatus; // } // // public void setTaskStatus(String taskStatus) { // this.taskStatus = taskStatus; // } // // public Boolean isTaskArchived() { // return taskArchived; // } // // public void setTaskArchived(Boolean taskArchived) { // this.taskArchived = taskArchived; // } // // public List<People> getPeople() { // return people; // } // // public void setPeople(List<People> people) { // this.people = people; // } // // // public LocalDateTime getStartDate() { // return startDate; // } // // public void setStartDate(LocalDateTime startDate) { // this.startDate = startDate; // } // // @Override // public String toString() { // return "Task [id=" + id + ", taskName=" + taskName // + ", taskDescription=" + taskDescription + ", taskPriority=" // + taskPriority + ",taskStatus=" + taskStatus + "]"; // } // }
import com.mpalourdio.springboottemplate.model.Dummy; import com.mpalourdio.springboottemplate.model.entities.Task; import java.util.List;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.model.repositories; interface CustomRepository<T> { List<T> customFindByPriority(String priority);
// Path: src/main/java/com/mpalourdio/springboottemplate/model/Dummy.java // public class Dummy { // // public String name; // @JsonIgnore // public String desc; // // public Dummy(String name, String desc) { // this.name = name; // this.desc = desc; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/Task.java // @Entity // @Table(name = "task_list") // public class Task { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_list_task_id_seq") // @Column(name = "task_id") // private int id; // // @Column(name = "task_name", nullable = false) // private String taskName; // // @Column(name = "task_description", nullable = false) // private String taskDescription; // // @Column(name = "task_priority", nullable = false) // private String taskPriority; // // @Column(name = "task_status", nullable = false) // private String taskStatus; // // @ColumnDefault("false") // @Column(name = "task_archived", nullable = false) // private Boolean taskArchived = false; // // @ColumnDefault(CurrentTimestampFunction.NAME) // @Column(name = "start_date", nullable = false) // private LocalDateTime startDate = LocalDateTime.now(); // // @OneToMany(mappedBy = "task") // private List<People> people = new ArrayList<>(); // // public String getTaskName() { // return taskName; // } // // public void setTaskName(String taskName) { // this.taskName = taskName; // } // // public String getTaskDescription() { // return taskDescription; // } // // public void setTaskDescription(String taskDescription) { // this.taskDescription = taskDescription; // } // // public String getTaskPriority() { // return taskPriority; // } // // public void setTaskPriority(String taskPriority) { // this.taskPriority = taskPriority; // } // // public String getTaskStatus() { // return taskStatus; // } // // public void setTaskStatus(String taskStatus) { // this.taskStatus = taskStatus; // } // // public Boolean isTaskArchived() { // return taskArchived; // } // // public void setTaskArchived(Boolean taskArchived) { // this.taskArchived = taskArchived; // } // // public List<People> getPeople() { // return people; // } // // public void setPeople(List<People> people) { // this.people = people; // } // // // public LocalDateTime getStartDate() { // return startDate; // } // // public void setStartDate(LocalDateTime startDate) { // this.startDate = startDate; // } // // @Override // public String toString() { // return "Task [id=" + id + ", taskName=" + taskName // + ", taskDescription=" + taskDescription + ", taskPriority=" // + taskPriority + ",taskStatus=" + taskStatus + "]"; // } // } // Path: src/main/java/com/mpalourdio/springboottemplate/model/repositories/CustomRepository.java import com.mpalourdio.springboottemplate.model.Dummy; import com.mpalourdio.springboottemplate.model.entities.Task; import java.util.List; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.model.repositories; interface CustomRepository<T> { List<T> customFindByPriority(String priority);
List<Dummy> hydrateDummyObject();
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/model/repositories/CustomRepository.java
// Path: src/main/java/com/mpalourdio/springboottemplate/model/Dummy.java // public class Dummy { // // public String name; // @JsonIgnore // public String desc; // // public Dummy(String name, String desc) { // this.name = name; // this.desc = desc; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/Task.java // @Entity // @Table(name = "task_list") // public class Task { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_list_task_id_seq") // @Column(name = "task_id") // private int id; // // @Column(name = "task_name", nullable = false) // private String taskName; // // @Column(name = "task_description", nullable = false) // private String taskDescription; // // @Column(name = "task_priority", nullable = false) // private String taskPriority; // // @Column(name = "task_status", nullable = false) // private String taskStatus; // // @ColumnDefault("false") // @Column(name = "task_archived", nullable = false) // private Boolean taskArchived = false; // // @ColumnDefault(CurrentTimestampFunction.NAME) // @Column(name = "start_date", nullable = false) // private LocalDateTime startDate = LocalDateTime.now(); // // @OneToMany(mappedBy = "task") // private List<People> people = new ArrayList<>(); // // public String getTaskName() { // return taskName; // } // // public void setTaskName(String taskName) { // this.taskName = taskName; // } // // public String getTaskDescription() { // return taskDescription; // } // // public void setTaskDescription(String taskDescription) { // this.taskDescription = taskDescription; // } // // public String getTaskPriority() { // return taskPriority; // } // // public void setTaskPriority(String taskPriority) { // this.taskPriority = taskPriority; // } // // public String getTaskStatus() { // return taskStatus; // } // // public void setTaskStatus(String taskStatus) { // this.taskStatus = taskStatus; // } // // public Boolean isTaskArchived() { // return taskArchived; // } // // public void setTaskArchived(Boolean taskArchived) { // this.taskArchived = taskArchived; // } // // public List<People> getPeople() { // return people; // } // // public void setPeople(List<People> people) { // this.people = people; // } // // // public LocalDateTime getStartDate() { // return startDate; // } // // public void setStartDate(LocalDateTime startDate) { // this.startDate = startDate; // } // // @Override // public String toString() { // return "Task [id=" + id + ", taskName=" + taskName // + ", taskDescription=" + taskDescription + ", taskPriority=" // + taskPriority + ",taskStatus=" + taskStatus + "]"; // } // }
import com.mpalourdio.springboottemplate.model.Dummy; import com.mpalourdio.springboottemplate.model.entities.Task; import java.util.List;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.model.repositories; interface CustomRepository<T> { List<T> customFindByPriority(String priority); List<Dummy> hydrateDummyObject();
// Path: src/main/java/com/mpalourdio/springboottemplate/model/Dummy.java // public class Dummy { // // public String name; // @JsonIgnore // public String desc; // // public Dummy(String name, String desc) { // this.name = name; // this.desc = desc; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/Task.java // @Entity // @Table(name = "task_list") // public class Task { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_list_task_id_seq") // @Column(name = "task_id") // private int id; // // @Column(name = "task_name", nullable = false) // private String taskName; // // @Column(name = "task_description", nullable = false) // private String taskDescription; // // @Column(name = "task_priority", nullable = false) // private String taskPriority; // // @Column(name = "task_status", nullable = false) // private String taskStatus; // // @ColumnDefault("false") // @Column(name = "task_archived", nullable = false) // private Boolean taskArchived = false; // // @ColumnDefault(CurrentTimestampFunction.NAME) // @Column(name = "start_date", nullable = false) // private LocalDateTime startDate = LocalDateTime.now(); // // @OneToMany(mappedBy = "task") // private List<People> people = new ArrayList<>(); // // public String getTaskName() { // return taskName; // } // // public void setTaskName(String taskName) { // this.taskName = taskName; // } // // public String getTaskDescription() { // return taskDescription; // } // // public void setTaskDescription(String taskDescription) { // this.taskDescription = taskDescription; // } // // public String getTaskPriority() { // return taskPriority; // } // // public void setTaskPriority(String taskPriority) { // this.taskPriority = taskPriority; // } // // public String getTaskStatus() { // return taskStatus; // } // // public void setTaskStatus(String taskStatus) { // this.taskStatus = taskStatus; // } // // public Boolean isTaskArchived() { // return taskArchived; // } // // public void setTaskArchived(Boolean taskArchived) { // this.taskArchived = taskArchived; // } // // public List<People> getPeople() { // return people; // } // // public void setPeople(List<People> people) { // this.people = people; // } // // // public LocalDateTime getStartDate() { // return startDate; // } // // public void setStartDate(LocalDateTime startDate) { // this.startDate = startDate; // } // // @Override // public String toString() { // return "Task [id=" + id + ", taskName=" + taskName // + ", taskDescription=" + taskDescription + ", taskPriority=" // + taskPriority + ",taskStatus=" + taskStatus + "]"; // } // } // Path: src/main/java/com/mpalourdio/springboottemplate/model/repositories/CustomRepository.java import com.mpalourdio.springboottemplate.model.Dummy; import com.mpalourdio.springboottemplate.model.entities.Task; import java.util.List; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.model.repositories; interface CustomRepository<T> { List<T> customFindByPriority(String priority); List<Dummy> hydrateDummyObject();
List<Task> testInvalidPath();
mpalourdio/SpringBootTemplate
src/test/java/com/mpalourdio/springboottemplate/controllers/HttpVersionedApiTest.java
// Path: src/test/java/com/mpalourdio/springboottemplate/AbstractTestRunner.java // @ExtendWith(SpringExtension.class) // @TestPropertySource(locations = "classpath:test.properties") // @Import({BeansFactory.class}) // public abstract class AbstractTestRunner { // // protected Task task; // protected People people; // // protected void initializeData() { // task = new Task(); // task.setTaskArchived(true); // task.setTaskName("name"); // task.setTaskDescription("description"); // task.setTaskPriority("LOW"); // task.setTaskStatus("ACTIVE"); // // people = new People() // .setName("john") // .setTask(task); // } // // protected String serializeToJson(Object object) throws JsonProcessingException { // return new ObjectMapper().writeValueAsString(object); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // }
import com.mpalourdio.springboottemplate.AbstractTestRunner; import com.mpalourdio.springboottemplate.mediatype.MediaType; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @WebMvcTest(HttpVersionedApiController.class) class HttpVersionedApiTest extends AbstractTestRunner {
// Path: src/test/java/com/mpalourdio/springboottemplate/AbstractTestRunner.java // @ExtendWith(SpringExtension.class) // @TestPropertySource(locations = "classpath:test.properties") // @Import({BeansFactory.class}) // public abstract class AbstractTestRunner { // // protected Task task; // protected People people; // // protected void initializeData() { // task = new Task(); // task.setTaskArchived(true); // task.setTaskName("name"); // task.setTaskDescription("description"); // task.setTaskPriority("LOW"); // task.setTaskStatus("ACTIVE"); // // people = new People() // .setName("john") // .setTask(task); // } // // protected String serializeToJson(Object object) throws JsonProcessingException { // return new ObjectMapper().writeValueAsString(object); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // Path: src/test/java/com/mpalourdio/springboottemplate/controllers/HttpVersionedApiTest.java import com.mpalourdio.springboottemplate.AbstractTestRunner; import com.mpalourdio.springboottemplate.mediatype.MediaType; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @WebMvcTest(HttpVersionedApiController.class) class HttpVersionedApiTest extends AbstractTestRunner {
private static final String HEADER_V1 = MediaType.APPLICATION_VND_API_V1_VALUE;
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/model/RepositoriesService.java
// Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/People.java // @Entity // @Table(name = "task_people") // @Getter // @Setter // @Accessors(chain = true) // public class People { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_people_people_id_seq") // @Column(name = "people_id") // private int id; // // @Column(name = "name", nullable = false) // private String name; // // @ManyToOne // @JoinColumn(name = "task_id", nullable = false) // private Task task; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/Task.java // @Entity // @Table(name = "task_list") // public class Task { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_list_task_id_seq") // @Column(name = "task_id") // private int id; // // @Column(name = "task_name", nullable = false) // private String taskName; // // @Column(name = "task_description", nullable = false) // private String taskDescription; // // @Column(name = "task_priority", nullable = false) // private String taskPriority; // // @Column(name = "task_status", nullable = false) // private String taskStatus; // // @ColumnDefault("false") // @Column(name = "task_archived", nullable = false) // private Boolean taskArchived = false; // // @ColumnDefault(CurrentTimestampFunction.NAME) // @Column(name = "start_date", nullable = false) // private LocalDateTime startDate = LocalDateTime.now(); // // @OneToMany(mappedBy = "task") // private List<People> people = new ArrayList<>(); // // public String getTaskName() { // return taskName; // } // // public void setTaskName(String taskName) { // this.taskName = taskName; // } // // public String getTaskDescription() { // return taskDescription; // } // // public void setTaskDescription(String taskDescription) { // this.taskDescription = taskDescription; // } // // public String getTaskPriority() { // return taskPriority; // } // // public void setTaskPriority(String taskPriority) { // this.taskPriority = taskPriority; // } // // public String getTaskStatus() { // return taskStatus; // } // // public void setTaskStatus(String taskStatus) { // this.taskStatus = taskStatus; // } // // public Boolean isTaskArchived() { // return taskArchived; // } // // public void setTaskArchived(Boolean taskArchived) { // this.taskArchived = taskArchived; // } // // public List<People> getPeople() { // return people; // } // // public void setPeople(List<People> people) { // this.people = people; // } // // // public LocalDateTime getStartDate() { // return startDate; // } // // public void setStartDate(LocalDateTime startDate) { // this.startDate = startDate; // } // // @Override // public String toString() { // return "Task [id=" + id + ", taskName=" + taskName // + ", taskDescription=" + taskDescription + ", taskPriority=" // + taskPriority + ",taskStatus=" + taskStatus + "]"; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/repositories/PeopleRepository.java // @Repository // public interface PeopleRepository extends CrudRepository<People, Integer> { // // List<People> findByTask(Task task); // // List<People> findByName(String name); // // @Override // List<People> findAll(); // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/repositories/TaskRepository.java // @Repository // public interface TaskRepository extends CrudRepository<Task, Integer>, CustomRepository<Task> { // // List<Task> findByTaskArchived(int taskArchivedFalse); // // List<Task> findByTaskStatus(String taskStatus); // // @Query("SELECT e FROM Task e where e.taskArchived = :status") // List<Task> getAllTasksByArchivedValue(@Param("status") Boolean archivedStatus); // // @Override // List<Task> findAll(); // }
import com.mpalourdio.springboottemplate.model.entities.People; import com.mpalourdio.springboottemplate.model.entities.Task; import com.mpalourdio.springboottemplate.model.repositories.PeopleRepository; import com.mpalourdio.springboottemplate.model.repositories.TaskRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import java.util.List;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.model; @Service public class RepositoriesService { private final EntityManager entityManager;
// Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/People.java // @Entity // @Table(name = "task_people") // @Getter // @Setter // @Accessors(chain = true) // public class People { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_people_people_id_seq") // @Column(name = "people_id") // private int id; // // @Column(name = "name", nullable = false) // private String name; // // @ManyToOne // @JoinColumn(name = "task_id", nullable = false) // private Task task; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/Task.java // @Entity // @Table(name = "task_list") // public class Task { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_list_task_id_seq") // @Column(name = "task_id") // private int id; // // @Column(name = "task_name", nullable = false) // private String taskName; // // @Column(name = "task_description", nullable = false) // private String taskDescription; // // @Column(name = "task_priority", nullable = false) // private String taskPriority; // // @Column(name = "task_status", nullable = false) // private String taskStatus; // // @ColumnDefault("false") // @Column(name = "task_archived", nullable = false) // private Boolean taskArchived = false; // // @ColumnDefault(CurrentTimestampFunction.NAME) // @Column(name = "start_date", nullable = false) // private LocalDateTime startDate = LocalDateTime.now(); // // @OneToMany(mappedBy = "task") // private List<People> people = new ArrayList<>(); // // public String getTaskName() { // return taskName; // } // // public void setTaskName(String taskName) { // this.taskName = taskName; // } // // public String getTaskDescription() { // return taskDescription; // } // // public void setTaskDescription(String taskDescription) { // this.taskDescription = taskDescription; // } // // public String getTaskPriority() { // return taskPriority; // } // // public void setTaskPriority(String taskPriority) { // this.taskPriority = taskPriority; // } // // public String getTaskStatus() { // return taskStatus; // } // // public void setTaskStatus(String taskStatus) { // this.taskStatus = taskStatus; // } // // public Boolean isTaskArchived() { // return taskArchived; // } // // public void setTaskArchived(Boolean taskArchived) { // this.taskArchived = taskArchived; // } // // public List<People> getPeople() { // return people; // } // // public void setPeople(List<People> people) { // this.people = people; // } // // // public LocalDateTime getStartDate() { // return startDate; // } // // public void setStartDate(LocalDateTime startDate) { // this.startDate = startDate; // } // // @Override // public String toString() { // return "Task [id=" + id + ", taskName=" + taskName // + ", taskDescription=" + taskDescription + ", taskPriority=" // + taskPriority + ",taskStatus=" + taskStatus + "]"; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/repositories/PeopleRepository.java // @Repository // public interface PeopleRepository extends CrudRepository<People, Integer> { // // List<People> findByTask(Task task); // // List<People> findByName(String name); // // @Override // List<People> findAll(); // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/repositories/TaskRepository.java // @Repository // public interface TaskRepository extends CrudRepository<Task, Integer>, CustomRepository<Task> { // // List<Task> findByTaskArchived(int taskArchivedFalse); // // List<Task> findByTaskStatus(String taskStatus); // // @Query("SELECT e FROM Task e where e.taskArchived = :status") // List<Task> getAllTasksByArchivedValue(@Param("status") Boolean archivedStatus); // // @Override // List<Task> findAll(); // } // Path: src/main/java/com/mpalourdio/springboottemplate/model/RepositoriesService.java import com.mpalourdio.springboottemplate.model.entities.People; import com.mpalourdio.springboottemplate.model.entities.Task; import com.mpalourdio.springboottemplate.model.repositories.PeopleRepository; import com.mpalourdio.springboottemplate.model.repositories.TaskRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import java.util.List; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.model; @Service public class RepositoriesService { private final EntityManager entityManager;
private final PeopleRepository peopleRepository;
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/model/RepositoriesService.java
// Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/People.java // @Entity // @Table(name = "task_people") // @Getter // @Setter // @Accessors(chain = true) // public class People { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_people_people_id_seq") // @Column(name = "people_id") // private int id; // // @Column(name = "name", nullable = false) // private String name; // // @ManyToOne // @JoinColumn(name = "task_id", nullable = false) // private Task task; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/Task.java // @Entity // @Table(name = "task_list") // public class Task { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_list_task_id_seq") // @Column(name = "task_id") // private int id; // // @Column(name = "task_name", nullable = false) // private String taskName; // // @Column(name = "task_description", nullable = false) // private String taskDescription; // // @Column(name = "task_priority", nullable = false) // private String taskPriority; // // @Column(name = "task_status", nullable = false) // private String taskStatus; // // @ColumnDefault("false") // @Column(name = "task_archived", nullable = false) // private Boolean taskArchived = false; // // @ColumnDefault(CurrentTimestampFunction.NAME) // @Column(name = "start_date", nullable = false) // private LocalDateTime startDate = LocalDateTime.now(); // // @OneToMany(mappedBy = "task") // private List<People> people = new ArrayList<>(); // // public String getTaskName() { // return taskName; // } // // public void setTaskName(String taskName) { // this.taskName = taskName; // } // // public String getTaskDescription() { // return taskDescription; // } // // public void setTaskDescription(String taskDescription) { // this.taskDescription = taskDescription; // } // // public String getTaskPriority() { // return taskPriority; // } // // public void setTaskPriority(String taskPriority) { // this.taskPriority = taskPriority; // } // // public String getTaskStatus() { // return taskStatus; // } // // public void setTaskStatus(String taskStatus) { // this.taskStatus = taskStatus; // } // // public Boolean isTaskArchived() { // return taskArchived; // } // // public void setTaskArchived(Boolean taskArchived) { // this.taskArchived = taskArchived; // } // // public List<People> getPeople() { // return people; // } // // public void setPeople(List<People> people) { // this.people = people; // } // // // public LocalDateTime getStartDate() { // return startDate; // } // // public void setStartDate(LocalDateTime startDate) { // this.startDate = startDate; // } // // @Override // public String toString() { // return "Task [id=" + id + ", taskName=" + taskName // + ", taskDescription=" + taskDescription + ", taskPriority=" // + taskPriority + ",taskStatus=" + taskStatus + "]"; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/repositories/PeopleRepository.java // @Repository // public interface PeopleRepository extends CrudRepository<People, Integer> { // // List<People> findByTask(Task task); // // List<People> findByName(String name); // // @Override // List<People> findAll(); // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/repositories/TaskRepository.java // @Repository // public interface TaskRepository extends CrudRepository<Task, Integer>, CustomRepository<Task> { // // List<Task> findByTaskArchived(int taskArchivedFalse); // // List<Task> findByTaskStatus(String taskStatus); // // @Query("SELECT e FROM Task e where e.taskArchived = :status") // List<Task> getAllTasksByArchivedValue(@Param("status") Boolean archivedStatus); // // @Override // List<Task> findAll(); // }
import com.mpalourdio.springboottemplate.model.entities.People; import com.mpalourdio.springboottemplate.model.entities.Task; import com.mpalourdio.springboottemplate.model.repositories.PeopleRepository; import com.mpalourdio.springboottemplate.model.repositories.TaskRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import java.util.List;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.model; @Service public class RepositoriesService { private final EntityManager entityManager; private final PeopleRepository peopleRepository;
// Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/People.java // @Entity // @Table(name = "task_people") // @Getter // @Setter // @Accessors(chain = true) // public class People { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_people_people_id_seq") // @Column(name = "people_id") // private int id; // // @Column(name = "name", nullable = false) // private String name; // // @ManyToOne // @JoinColumn(name = "task_id", nullable = false) // private Task task; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/Task.java // @Entity // @Table(name = "task_list") // public class Task { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_list_task_id_seq") // @Column(name = "task_id") // private int id; // // @Column(name = "task_name", nullable = false) // private String taskName; // // @Column(name = "task_description", nullable = false) // private String taskDescription; // // @Column(name = "task_priority", nullable = false) // private String taskPriority; // // @Column(name = "task_status", nullable = false) // private String taskStatus; // // @ColumnDefault("false") // @Column(name = "task_archived", nullable = false) // private Boolean taskArchived = false; // // @ColumnDefault(CurrentTimestampFunction.NAME) // @Column(name = "start_date", nullable = false) // private LocalDateTime startDate = LocalDateTime.now(); // // @OneToMany(mappedBy = "task") // private List<People> people = new ArrayList<>(); // // public String getTaskName() { // return taskName; // } // // public void setTaskName(String taskName) { // this.taskName = taskName; // } // // public String getTaskDescription() { // return taskDescription; // } // // public void setTaskDescription(String taskDescription) { // this.taskDescription = taskDescription; // } // // public String getTaskPriority() { // return taskPriority; // } // // public void setTaskPriority(String taskPriority) { // this.taskPriority = taskPriority; // } // // public String getTaskStatus() { // return taskStatus; // } // // public void setTaskStatus(String taskStatus) { // this.taskStatus = taskStatus; // } // // public Boolean isTaskArchived() { // return taskArchived; // } // // public void setTaskArchived(Boolean taskArchived) { // this.taskArchived = taskArchived; // } // // public List<People> getPeople() { // return people; // } // // public void setPeople(List<People> people) { // this.people = people; // } // // // public LocalDateTime getStartDate() { // return startDate; // } // // public void setStartDate(LocalDateTime startDate) { // this.startDate = startDate; // } // // @Override // public String toString() { // return "Task [id=" + id + ", taskName=" + taskName // + ", taskDescription=" + taskDescription + ", taskPriority=" // + taskPriority + ",taskStatus=" + taskStatus + "]"; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/repositories/PeopleRepository.java // @Repository // public interface PeopleRepository extends CrudRepository<People, Integer> { // // List<People> findByTask(Task task); // // List<People> findByName(String name); // // @Override // List<People> findAll(); // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/repositories/TaskRepository.java // @Repository // public interface TaskRepository extends CrudRepository<Task, Integer>, CustomRepository<Task> { // // List<Task> findByTaskArchived(int taskArchivedFalse); // // List<Task> findByTaskStatus(String taskStatus); // // @Query("SELECT e FROM Task e where e.taskArchived = :status") // List<Task> getAllTasksByArchivedValue(@Param("status") Boolean archivedStatus); // // @Override // List<Task> findAll(); // } // Path: src/main/java/com/mpalourdio/springboottemplate/model/RepositoriesService.java import com.mpalourdio.springboottemplate.model.entities.People; import com.mpalourdio.springboottemplate.model.entities.Task; import com.mpalourdio.springboottemplate.model.repositories.PeopleRepository; import com.mpalourdio.springboottemplate.model.repositories.TaskRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import java.util.List; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.model; @Service public class RepositoriesService { private final EntityManager entityManager; private final PeopleRepository peopleRepository;
private final TaskRepository taskRepository;
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/model/RepositoriesService.java
// Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/People.java // @Entity // @Table(name = "task_people") // @Getter // @Setter // @Accessors(chain = true) // public class People { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_people_people_id_seq") // @Column(name = "people_id") // private int id; // // @Column(name = "name", nullable = false) // private String name; // // @ManyToOne // @JoinColumn(name = "task_id", nullable = false) // private Task task; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/Task.java // @Entity // @Table(name = "task_list") // public class Task { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_list_task_id_seq") // @Column(name = "task_id") // private int id; // // @Column(name = "task_name", nullable = false) // private String taskName; // // @Column(name = "task_description", nullable = false) // private String taskDescription; // // @Column(name = "task_priority", nullable = false) // private String taskPriority; // // @Column(name = "task_status", nullable = false) // private String taskStatus; // // @ColumnDefault("false") // @Column(name = "task_archived", nullable = false) // private Boolean taskArchived = false; // // @ColumnDefault(CurrentTimestampFunction.NAME) // @Column(name = "start_date", nullable = false) // private LocalDateTime startDate = LocalDateTime.now(); // // @OneToMany(mappedBy = "task") // private List<People> people = new ArrayList<>(); // // public String getTaskName() { // return taskName; // } // // public void setTaskName(String taskName) { // this.taskName = taskName; // } // // public String getTaskDescription() { // return taskDescription; // } // // public void setTaskDescription(String taskDescription) { // this.taskDescription = taskDescription; // } // // public String getTaskPriority() { // return taskPriority; // } // // public void setTaskPriority(String taskPriority) { // this.taskPriority = taskPriority; // } // // public String getTaskStatus() { // return taskStatus; // } // // public void setTaskStatus(String taskStatus) { // this.taskStatus = taskStatus; // } // // public Boolean isTaskArchived() { // return taskArchived; // } // // public void setTaskArchived(Boolean taskArchived) { // this.taskArchived = taskArchived; // } // // public List<People> getPeople() { // return people; // } // // public void setPeople(List<People> people) { // this.people = people; // } // // // public LocalDateTime getStartDate() { // return startDate; // } // // public void setStartDate(LocalDateTime startDate) { // this.startDate = startDate; // } // // @Override // public String toString() { // return "Task [id=" + id + ", taskName=" + taskName // + ", taskDescription=" + taskDescription + ", taskPriority=" // + taskPriority + ",taskStatus=" + taskStatus + "]"; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/repositories/PeopleRepository.java // @Repository // public interface PeopleRepository extends CrudRepository<People, Integer> { // // List<People> findByTask(Task task); // // List<People> findByName(String name); // // @Override // List<People> findAll(); // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/repositories/TaskRepository.java // @Repository // public interface TaskRepository extends CrudRepository<Task, Integer>, CustomRepository<Task> { // // List<Task> findByTaskArchived(int taskArchivedFalse); // // List<Task> findByTaskStatus(String taskStatus); // // @Query("SELECT e FROM Task e where e.taskArchived = :status") // List<Task> getAllTasksByArchivedValue(@Param("status") Boolean archivedStatus); // // @Override // List<Task> findAll(); // }
import com.mpalourdio.springboottemplate.model.entities.People; import com.mpalourdio.springboottemplate.model.entities.Task; import com.mpalourdio.springboottemplate.model.repositories.PeopleRepository; import com.mpalourdio.springboottemplate.model.repositories.TaskRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import java.util.List;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.model; @Service public class RepositoriesService { private final EntityManager entityManager; private final PeopleRepository peopleRepository; private final TaskRepository taskRepository; public RepositoriesService( PeopleRepository peopleRepository, TaskRepository taskRepository, EntityManager entityManager) { this.peopleRepository = peopleRepository; this.taskRepository = taskRepository; this.entityManager = entityManager; } @Transactional
// Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/People.java // @Entity // @Table(name = "task_people") // @Getter // @Setter // @Accessors(chain = true) // public class People { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_people_people_id_seq") // @Column(name = "people_id") // private int id; // // @Column(name = "name", nullable = false) // private String name; // // @ManyToOne // @JoinColumn(name = "task_id", nullable = false) // private Task task; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/Task.java // @Entity // @Table(name = "task_list") // public class Task { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_list_task_id_seq") // @Column(name = "task_id") // private int id; // // @Column(name = "task_name", nullable = false) // private String taskName; // // @Column(name = "task_description", nullable = false) // private String taskDescription; // // @Column(name = "task_priority", nullable = false) // private String taskPriority; // // @Column(name = "task_status", nullable = false) // private String taskStatus; // // @ColumnDefault("false") // @Column(name = "task_archived", nullable = false) // private Boolean taskArchived = false; // // @ColumnDefault(CurrentTimestampFunction.NAME) // @Column(name = "start_date", nullable = false) // private LocalDateTime startDate = LocalDateTime.now(); // // @OneToMany(mappedBy = "task") // private List<People> people = new ArrayList<>(); // // public String getTaskName() { // return taskName; // } // // public void setTaskName(String taskName) { // this.taskName = taskName; // } // // public String getTaskDescription() { // return taskDescription; // } // // public void setTaskDescription(String taskDescription) { // this.taskDescription = taskDescription; // } // // public String getTaskPriority() { // return taskPriority; // } // // public void setTaskPriority(String taskPriority) { // this.taskPriority = taskPriority; // } // // public String getTaskStatus() { // return taskStatus; // } // // public void setTaskStatus(String taskStatus) { // this.taskStatus = taskStatus; // } // // public Boolean isTaskArchived() { // return taskArchived; // } // // public void setTaskArchived(Boolean taskArchived) { // this.taskArchived = taskArchived; // } // // public List<People> getPeople() { // return people; // } // // public void setPeople(List<People> people) { // this.people = people; // } // // // public LocalDateTime getStartDate() { // return startDate; // } // // public void setStartDate(LocalDateTime startDate) { // this.startDate = startDate; // } // // @Override // public String toString() { // return "Task [id=" + id + ", taskName=" + taskName // + ", taskDescription=" + taskDescription + ", taskPriority=" // + taskPriority + ",taskStatus=" + taskStatus + "]"; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/repositories/PeopleRepository.java // @Repository // public interface PeopleRepository extends CrudRepository<People, Integer> { // // List<People> findByTask(Task task); // // List<People> findByName(String name); // // @Override // List<People> findAll(); // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/repositories/TaskRepository.java // @Repository // public interface TaskRepository extends CrudRepository<Task, Integer>, CustomRepository<Task> { // // List<Task> findByTaskArchived(int taskArchivedFalse); // // List<Task> findByTaskStatus(String taskStatus); // // @Query("SELECT e FROM Task e where e.taskArchived = :status") // List<Task> getAllTasksByArchivedValue(@Param("status") Boolean archivedStatus); // // @Override // List<Task> findAll(); // } // Path: src/main/java/com/mpalourdio/springboottemplate/model/RepositoriesService.java import com.mpalourdio.springboottemplate.model.entities.People; import com.mpalourdio.springboottemplate.model.entities.Task; import com.mpalourdio.springboottemplate.model.repositories.PeopleRepository; import com.mpalourdio.springboottemplate.model.repositories.TaskRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import java.util.List; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.model; @Service public class RepositoriesService { private final EntityManager entityManager; private final PeopleRepository peopleRepository; private final TaskRepository taskRepository; public RepositoriesService( PeopleRepository peopleRepository, TaskRepository taskRepository, EntityManager entityManager) { this.peopleRepository = peopleRepository; this.taskRepository = taskRepository; this.entityManager = entityManager; } @Transactional
public List<People> getAllPeople() {
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/model/RepositoriesService.java
// Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/People.java // @Entity // @Table(name = "task_people") // @Getter // @Setter // @Accessors(chain = true) // public class People { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_people_people_id_seq") // @Column(name = "people_id") // private int id; // // @Column(name = "name", nullable = false) // private String name; // // @ManyToOne // @JoinColumn(name = "task_id", nullable = false) // private Task task; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/Task.java // @Entity // @Table(name = "task_list") // public class Task { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_list_task_id_seq") // @Column(name = "task_id") // private int id; // // @Column(name = "task_name", nullable = false) // private String taskName; // // @Column(name = "task_description", nullable = false) // private String taskDescription; // // @Column(name = "task_priority", nullable = false) // private String taskPriority; // // @Column(name = "task_status", nullable = false) // private String taskStatus; // // @ColumnDefault("false") // @Column(name = "task_archived", nullable = false) // private Boolean taskArchived = false; // // @ColumnDefault(CurrentTimestampFunction.NAME) // @Column(name = "start_date", nullable = false) // private LocalDateTime startDate = LocalDateTime.now(); // // @OneToMany(mappedBy = "task") // private List<People> people = new ArrayList<>(); // // public String getTaskName() { // return taskName; // } // // public void setTaskName(String taskName) { // this.taskName = taskName; // } // // public String getTaskDescription() { // return taskDescription; // } // // public void setTaskDescription(String taskDescription) { // this.taskDescription = taskDescription; // } // // public String getTaskPriority() { // return taskPriority; // } // // public void setTaskPriority(String taskPriority) { // this.taskPriority = taskPriority; // } // // public String getTaskStatus() { // return taskStatus; // } // // public void setTaskStatus(String taskStatus) { // this.taskStatus = taskStatus; // } // // public Boolean isTaskArchived() { // return taskArchived; // } // // public void setTaskArchived(Boolean taskArchived) { // this.taskArchived = taskArchived; // } // // public List<People> getPeople() { // return people; // } // // public void setPeople(List<People> people) { // this.people = people; // } // // // public LocalDateTime getStartDate() { // return startDate; // } // // public void setStartDate(LocalDateTime startDate) { // this.startDate = startDate; // } // // @Override // public String toString() { // return "Task [id=" + id + ", taskName=" + taskName // + ", taskDescription=" + taskDescription + ", taskPriority=" // + taskPriority + ",taskStatus=" + taskStatus + "]"; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/repositories/PeopleRepository.java // @Repository // public interface PeopleRepository extends CrudRepository<People, Integer> { // // List<People> findByTask(Task task); // // List<People> findByName(String name); // // @Override // List<People> findAll(); // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/repositories/TaskRepository.java // @Repository // public interface TaskRepository extends CrudRepository<Task, Integer>, CustomRepository<Task> { // // List<Task> findByTaskArchived(int taskArchivedFalse); // // List<Task> findByTaskStatus(String taskStatus); // // @Query("SELECT e FROM Task e where e.taskArchived = :status") // List<Task> getAllTasksByArchivedValue(@Param("status") Boolean archivedStatus); // // @Override // List<Task> findAll(); // }
import com.mpalourdio.springboottemplate.model.entities.People; import com.mpalourdio.springboottemplate.model.entities.Task; import com.mpalourdio.springboottemplate.model.repositories.PeopleRepository; import com.mpalourdio.springboottemplate.model.repositories.TaskRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import java.util.List;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.model; @Service public class RepositoriesService { private final EntityManager entityManager; private final PeopleRepository peopleRepository; private final TaskRepository taskRepository; public RepositoriesService( PeopleRepository peopleRepository, TaskRepository taskRepository, EntityManager entityManager) { this.peopleRepository = peopleRepository; this.taskRepository = taskRepository; this.entityManager = entityManager; } @Transactional public List<People> getAllPeople() { return peopleRepository.findAll(); } @Transactional
// Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/People.java // @Entity // @Table(name = "task_people") // @Getter // @Setter // @Accessors(chain = true) // public class People { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_people_people_id_seq") // @Column(name = "people_id") // private int id; // // @Column(name = "name", nullable = false) // private String name; // // @ManyToOne // @JoinColumn(name = "task_id", nullable = false) // private Task task; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/entities/Task.java // @Entity // @Table(name = "task_list") // public class Task { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "task_list_task_id_seq") // @Column(name = "task_id") // private int id; // // @Column(name = "task_name", nullable = false) // private String taskName; // // @Column(name = "task_description", nullable = false) // private String taskDescription; // // @Column(name = "task_priority", nullable = false) // private String taskPriority; // // @Column(name = "task_status", nullable = false) // private String taskStatus; // // @ColumnDefault("false") // @Column(name = "task_archived", nullable = false) // private Boolean taskArchived = false; // // @ColumnDefault(CurrentTimestampFunction.NAME) // @Column(name = "start_date", nullable = false) // private LocalDateTime startDate = LocalDateTime.now(); // // @OneToMany(mappedBy = "task") // private List<People> people = new ArrayList<>(); // // public String getTaskName() { // return taskName; // } // // public void setTaskName(String taskName) { // this.taskName = taskName; // } // // public String getTaskDescription() { // return taskDescription; // } // // public void setTaskDescription(String taskDescription) { // this.taskDescription = taskDescription; // } // // public String getTaskPriority() { // return taskPriority; // } // // public void setTaskPriority(String taskPriority) { // this.taskPriority = taskPriority; // } // // public String getTaskStatus() { // return taskStatus; // } // // public void setTaskStatus(String taskStatus) { // this.taskStatus = taskStatus; // } // // public Boolean isTaskArchived() { // return taskArchived; // } // // public void setTaskArchived(Boolean taskArchived) { // this.taskArchived = taskArchived; // } // // public List<People> getPeople() { // return people; // } // // public void setPeople(List<People> people) { // this.people = people; // } // // // public LocalDateTime getStartDate() { // return startDate; // } // // public void setStartDate(LocalDateTime startDate) { // this.startDate = startDate; // } // // @Override // public String toString() { // return "Task [id=" + id + ", taskName=" + taskName // + ", taskDescription=" + taskDescription + ", taskPriority=" // + taskPriority + ",taskStatus=" + taskStatus + "]"; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/repositories/PeopleRepository.java // @Repository // public interface PeopleRepository extends CrudRepository<People, Integer> { // // List<People> findByTask(Task task); // // List<People> findByName(String name); // // @Override // List<People> findAll(); // } // // Path: src/main/java/com/mpalourdio/springboottemplate/model/repositories/TaskRepository.java // @Repository // public interface TaskRepository extends CrudRepository<Task, Integer>, CustomRepository<Task> { // // List<Task> findByTaskArchived(int taskArchivedFalse); // // List<Task> findByTaskStatus(String taskStatus); // // @Query("SELECT e FROM Task e where e.taskArchived = :status") // List<Task> getAllTasksByArchivedValue(@Param("status") Boolean archivedStatus); // // @Override // List<Task> findAll(); // } // Path: src/main/java/com/mpalourdio/springboottemplate/model/RepositoriesService.java import com.mpalourdio.springboottemplate.model.entities.People; import com.mpalourdio.springboottemplate.model.entities.Task; import com.mpalourdio.springboottemplate.model.repositories.PeopleRepository; import com.mpalourdio.springboottemplate.model.repositories.TaskRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import java.util.List; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.model; @Service public class RepositoriesService { private final EntityManager entityManager; private final PeopleRepository peopleRepository; private final TaskRepository taskRepository; public RepositoriesService( PeopleRepository peopleRepository, TaskRepository taskRepository, EntityManager entityManager) { this.peopleRepository = peopleRepository; this.taskRepository = taskRepository; this.entityManager = entityManager; } @Transactional public List<People> getAllPeople() { return peopleRepository.findAll(); } @Transactional
public List<Task> getAllTasks() {
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/controllers/EventController.java
// Path: src/main/java/com/mpalourdio/springboottemplate/events/AsyncEvent.java // public class AsyncEvent { // // public void publishMeLater(String message) { // System.out.println(message); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/events/AsyncLogger.java // public class AsyncLogger { // // private final ApplicationEventPublisher eventPublisher; // // public AsyncLogger(ApplicationEventPublisher eventPublisher) { // this.eventPublisher = eventPublisher; // } // // public void write(Class ownerClass, Level logLevel, String logMessage) { // eventPublisher.publishEvent(new LogEvent(ownerClass, logLevel, logMessage)); // } // // public static void log(Class ownerClass, Level logLevel, String logMessage) { // var logger = LoggerFactory.getLogger(ownerClass); // // switch (logLevel.levelInt) { // case Level.TRACE_INT: // logger.trace(logMessage); // break; // case Level.DEBUG_INT: // logger.debug(logMessage); // break; // case Level.INFO_INT: // logger.info(logMessage); // break; // case Level.WARN_INT: // logger.warn(logMessage); // break; // case Level.ERROR_INT: // logger.error(logMessage); // break; // default: // logger.info(logMessage); // break; // } // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/events/MyEvent.java // public class MyEvent { // // private String message; // // public MyEvent(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // }
import ch.qos.logback.classic.Level; import com.mpalourdio.springboottemplate.events.AsyncEvent; import com.mpalourdio.springboottemplate.events.AsyncLogger; import com.mpalourdio.springboottemplate.events.MyEvent; import com.mpalourdio.springboottemplate.mediatype.MediaType; import org.springframework.context.ApplicationEventPublisher; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @RestController @RequestMapping("/event") public class EventController { private final ApplicationEventPublisher eventPublisher;
// Path: src/main/java/com/mpalourdio/springboottemplate/events/AsyncEvent.java // public class AsyncEvent { // // public void publishMeLater(String message) { // System.out.println(message); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/events/AsyncLogger.java // public class AsyncLogger { // // private final ApplicationEventPublisher eventPublisher; // // public AsyncLogger(ApplicationEventPublisher eventPublisher) { // this.eventPublisher = eventPublisher; // } // // public void write(Class ownerClass, Level logLevel, String logMessage) { // eventPublisher.publishEvent(new LogEvent(ownerClass, logLevel, logMessage)); // } // // public static void log(Class ownerClass, Level logLevel, String logMessage) { // var logger = LoggerFactory.getLogger(ownerClass); // // switch (logLevel.levelInt) { // case Level.TRACE_INT: // logger.trace(logMessage); // break; // case Level.DEBUG_INT: // logger.debug(logMessage); // break; // case Level.INFO_INT: // logger.info(logMessage); // break; // case Level.WARN_INT: // logger.warn(logMessage); // break; // case Level.ERROR_INT: // logger.error(logMessage); // break; // default: // logger.info(logMessage); // break; // } // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/events/MyEvent.java // public class MyEvent { // // private String message; // // public MyEvent(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // Path: src/main/java/com/mpalourdio/springboottemplate/controllers/EventController.java import ch.qos.logback.classic.Level; import com.mpalourdio.springboottemplate.events.AsyncEvent; import com.mpalourdio.springboottemplate.events.AsyncLogger; import com.mpalourdio.springboottemplate.events.MyEvent; import com.mpalourdio.springboottemplate.mediatype.MediaType; import org.springframework.context.ApplicationEventPublisher; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @RestController @RequestMapping("/event") public class EventController { private final ApplicationEventPublisher eventPublisher;
private final AsyncLogger logger;
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/controllers/EventController.java
// Path: src/main/java/com/mpalourdio/springboottemplate/events/AsyncEvent.java // public class AsyncEvent { // // public void publishMeLater(String message) { // System.out.println(message); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/events/AsyncLogger.java // public class AsyncLogger { // // private final ApplicationEventPublisher eventPublisher; // // public AsyncLogger(ApplicationEventPublisher eventPublisher) { // this.eventPublisher = eventPublisher; // } // // public void write(Class ownerClass, Level logLevel, String logMessage) { // eventPublisher.publishEvent(new LogEvent(ownerClass, logLevel, logMessage)); // } // // public static void log(Class ownerClass, Level logLevel, String logMessage) { // var logger = LoggerFactory.getLogger(ownerClass); // // switch (logLevel.levelInt) { // case Level.TRACE_INT: // logger.trace(logMessage); // break; // case Level.DEBUG_INT: // logger.debug(logMessage); // break; // case Level.INFO_INT: // logger.info(logMessage); // break; // case Level.WARN_INT: // logger.warn(logMessage); // break; // case Level.ERROR_INT: // logger.error(logMessage); // break; // default: // logger.info(logMessage); // break; // } // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/events/MyEvent.java // public class MyEvent { // // private String message; // // public MyEvent(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // }
import ch.qos.logback.classic.Level; import com.mpalourdio.springboottemplate.events.AsyncEvent; import com.mpalourdio.springboottemplate.events.AsyncLogger; import com.mpalourdio.springboottemplate.events.MyEvent; import com.mpalourdio.springboottemplate.mediatype.MediaType; import org.springframework.context.ApplicationEventPublisher; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @RestController @RequestMapping("/event") public class EventController { private final ApplicationEventPublisher eventPublisher; private final AsyncLogger logger; public EventController(ApplicationEventPublisher eventPublisher, AsyncLogger asyncLogger) { this.eventPublisher = eventPublisher; logger = asyncLogger; }
// Path: src/main/java/com/mpalourdio/springboottemplate/events/AsyncEvent.java // public class AsyncEvent { // // public void publishMeLater(String message) { // System.out.println(message); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/events/AsyncLogger.java // public class AsyncLogger { // // private final ApplicationEventPublisher eventPublisher; // // public AsyncLogger(ApplicationEventPublisher eventPublisher) { // this.eventPublisher = eventPublisher; // } // // public void write(Class ownerClass, Level logLevel, String logMessage) { // eventPublisher.publishEvent(new LogEvent(ownerClass, logLevel, logMessage)); // } // // public static void log(Class ownerClass, Level logLevel, String logMessage) { // var logger = LoggerFactory.getLogger(ownerClass); // // switch (logLevel.levelInt) { // case Level.TRACE_INT: // logger.trace(logMessage); // break; // case Level.DEBUG_INT: // logger.debug(logMessage); // break; // case Level.INFO_INT: // logger.info(logMessage); // break; // case Level.WARN_INT: // logger.warn(logMessage); // break; // case Level.ERROR_INT: // logger.error(logMessage); // break; // default: // logger.info(logMessage); // break; // } // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/events/MyEvent.java // public class MyEvent { // // private String message; // // public MyEvent(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // Path: src/main/java/com/mpalourdio/springboottemplate/controllers/EventController.java import ch.qos.logback.classic.Level; import com.mpalourdio.springboottemplate.events.AsyncEvent; import com.mpalourdio.springboottemplate.events.AsyncLogger; import com.mpalourdio.springboottemplate.events.MyEvent; import com.mpalourdio.springboottemplate.mediatype.MediaType; import org.springframework.context.ApplicationEventPublisher; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @RestController @RequestMapping("/event") public class EventController { private final ApplicationEventPublisher eventPublisher; private final AsyncLogger logger; public EventController(ApplicationEventPublisher eventPublisher, AsyncLogger asyncLogger) { this.eventPublisher = eventPublisher; logger = asyncLogger; }
@GetMapping(produces = MediaType.TEXT_PLAIN_VALUE)
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/controllers/EventController.java
// Path: src/main/java/com/mpalourdio/springboottemplate/events/AsyncEvent.java // public class AsyncEvent { // // public void publishMeLater(String message) { // System.out.println(message); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/events/AsyncLogger.java // public class AsyncLogger { // // private final ApplicationEventPublisher eventPublisher; // // public AsyncLogger(ApplicationEventPublisher eventPublisher) { // this.eventPublisher = eventPublisher; // } // // public void write(Class ownerClass, Level logLevel, String logMessage) { // eventPublisher.publishEvent(new LogEvent(ownerClass, logLevel, logMessage)); // } // // public static void log(Class ownerClass, Level logLevel, String logMessage) { // var logger = LoggerFactory.getLogger(ownerClass); // // switch (logLevel.levelInt) { // case Level.TRACE_INT: // logger.trace(logMessage); // break; // case Level.DEBUG_INT: // logger.debug(logMessage); // break; // case Level.INFO_INT: // logger.info(logMessage); // break; // case Level.WARN_INT: // logger.warn(logMessage); // break; // case Level.ERROR_INT: // logger.error(logMessage); // break; // default: // logger.info(logMessage); // break; // } // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/events/MyEvent.java // public class MyEvent { // // private String message; // // public MyEvent(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // }
import ch.qos.logback.classic.Level; import com.mpalourdio.springboottemplate.events.AsyncEvent; import com.mpalourdio.springboottemplate.events.AsyncLogger; import com.mpalourdio.springboottemplate.events.MyEvent; import com.mpalourdio.springboottemplate.mediatype.MediaType; import org.springframework.context.ApplicationEventPublisher; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @RestController @RequestMapping("/event") public class EventController { private final ApplicationEventPublisher eventPublisher; private final AsyncLogger logger; public EventController(ApplicationEventPublisher eventPublisher, AsyncLogger asyncLogger) { this.eventPublisher = eventPublisher; logger = asyncLogger; } @GetMapping(produces = MediaType.TEXT_PLAIN_VALUE) public String publishAction() {
// Path: src/main/java/com/mpalourdio/springboottemplate/events/AsyncEvent.java // public class AsyncEvent { // // public void publishMeLater(String message) { // System.out.println(message); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/events/AsyncLogger.java // public class AsyncLogger { // // private final ApplicationEventPublisher eventPublisher; // // public AsyncLogger(ApplicationEventPublisher eventPublisher) { // this.eventPublisher = eventPublisher; // } // // public void write(Class ownerClass, Level logLevel, String logMessage) { // eventPublisher.publishEvent(new LogEvent(ownerClass, logLevel, logMessage)); // } // // public static void log(Class ownerClass, Level logLevel, String logMessage) { // var logger = LoggerFactory.getLogger(ownerClass); // // switch (logLevel.levelInt) { // case Level.TRACE_INT: // logger.trace(logMessage); // break; // case Level.DEBUG_INT: // logger.debug(logMessage); // break; // case Level.INFO_INT: // logger.info(logMessage); // break; // case Level.WARN_INT: // logger.warn(logMessage); // break; // case Level.ERROR_INT: // logger.error(logMessage); // break; // default: // logger.info(logMessage); // break; // } // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/events/MyEvent.java // public class MyEvent { // // private String message; // // public MyEvent(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // Path: src/main/java/com/mpalourdio/springboottemplate/controllers/EventController.java import ch.qos.logback.classic.Level; import com.mpalourdio.springboottemplate.events.AsyncEvent; import com.mpalourdio.springboottemplate.events.AsyncLogger; import com.mpalourdio.springboottemplate.events.MyEvent; import com.mpalourdio.springboottemplate.mediatype.MediaType; import org.springframework.context.ApplicationEventPublisher; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @RestController @RequestMapping("/event") public class EventController { private final ApplicationEventPublisher eventPublisher; private final AsyncLogger logger; public EventController(ApplicationEventPublisher eventPublisher, AsyncLogger asyncLogger) { this.eventPublisher = eventPublisher; logger = asyncLogger; } @GetMapping(produces = MediaType.TEXT_PLAIN_VALUE) public String publishAction() {
var asyncEvent = new AsyncEvent();
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/controllers/EventController.java
// Path: src/main/java/com/mpalourdio/springboottemplate/events/AsyncEvent.java // public class AsyncEvent { // // public void publishMeLater(String message) { // System.out.println(message); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/events/AsyncLogger.java // public class AsyncLogger { // // private final ApplicationEventPublisher eventPublisher; // // public AsyncLogger(ApplicationEventPublisher eventPublisher) { // this.eventPublisher = eventPublisher; // } // // public void write(Class ownerClass, Level logLevel, String logMessage) { // eventPublisher.publishEvent(new LogEvent(ownerClass, logLevel, logMessage)); // } // // public static void log(Class ownerClass, Level logLevel, String logMessage) { // var logger = LoggerFactory.getLogger(ownerClass); // // switch (logLevel.levelInt) { // case Level.TRACE_INT: // logger.trace(logMessage); // break; // case Level.DEBUG_INT: // logger.debug(logMessage); // break; // case Level.INFO_INT: // logger.info(logMessage); // break; // case Level.WARN_INT: // logger.warn(logMessage); // break; // case Level.ERROR_INT: // logger.error(logMessage); // break; // default: // logger.info(logMessage); // break; // } // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/events/MyEvent.java // public class MyEvent { // // private String message; // // public MyEvent(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // }
import ch.qos.logback.classic.Level; import com.mpalourdio.springboottemplate.events.AsyncEvent; import com.mpalourdio.springboottemplate.events.AsyncLogger; import com.mpalourdio.springboottemplate.events.MyEvent; import com.mpalourdio.springboottemplate.mediatype.MediaType; import org.springframework.context.ApplicationEventPublisher; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @RestController @RequestMapping("/event") public class EventController { private final ApplicationEventPublisher eventPublisher; private final AsyncLogger logger; public EventController(ApplicationEventPublisher eventPublisher, AsyncLogger asyncLogger) { this.eventPublisher = eventPublisher; logger = asyncLogger; } @GetMapping(produces = MediaType.TEXT_PLAIN_VALUE) public String publishAction() { var asyncEvent = new AsyncEvent(); eventPublisher.publishEvent(asyncEvent);
// Path: src/main/java/com/mpalourdio/springboottemplate/events/AsyncEvent.java // public class AsyncEvent { // // public void publishMeLater(String message) { // System.out.println(message); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/events/AsyncLogger.java // public class AsyncLogger { // // private final ApplicationEventPublisher eventPublisher; // // public AsyncLogger(ApplicationEventPublisher eventPublisher) { // this.eventPublisher = eventPublisher; // } // // public void write(Class ownerClass, Level logLevel, String logMessage) { // eventPublisher.publishEvent(new LogEvent(ownerClass, logLevel, logMessage)); // } // // public static void log(Class ownerClass, Level logLevel, String logMessage) { // var logger = LoggerFactory.getLogger(ownerClass); // // switch (logLevel.levelInt) { // case Level.TRACE_INT: // logger.trace(logMessage); // break; // case Level.DEBUG_INT: // logger.debug(logMessage); // break; // case Level.INFO_INT: // logger.info(logMessage); // break; // case Level.WARN_INT: // logger.warn(logMessage); // break; // case Level.ERROR_INT: // logger.error(logMessage); // break; // default: // logger.info(logMessage); // break; // } // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/events/MyEvent.java // public class MyEvent { // // private String message; // // public MyEvent(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // Path: src/main/java/com/mpalourdio/springboottemplate/controllers/EventController.java import ch.qos.logback.classic.Level; import com.mpalourdio.springboottemplate.events.AsyncEvent; import com.mpalourdio.springboottemplate.events.AsyncLogger; import com.mpalourdio.springboottemplate.events.MyEvent; import com.mpalourdio.springboottemplate.mediatype.MediaType; import org.springframework.context.ApplicationEventPublisher; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @RestController @RequestMapping("/event") public class EventController { private final ApplicationEventPublisher eventPublisher; private final AsyncLogger logger; public EventController(ApplicationEventPublisher eventPublisher, AsyncLogger asyncLogger) { this.eventPublisher = eventPublisher; logger = asyncLogger; } @GetMapping(produces = MediaType.TEXT_PLAIN_VALUE) public String publishAction() { var asyncEvent = new AsyncEvent(); eventPublisher.publishEvent(asyncEvent);
var event = new MyEvent("\uD83D\uDE0A");
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/controllers/MiscController.java
// Path: src/main/java/com/mpalourdio/springboottemplate/json/Account.java // public class Account implements AccountInterface { // // public String firstName; // public String lastName; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountDecorator.java // public class AccountDecorator implements AccountInterface { // // @JsonUnwrapped // public Account account; // public Context context; // // public AccountDecorator() { // } // // public AccountDecorator(Account account) { // this.account = account; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountInterface.java // public interface AccountInterface { // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Context.java // public class Context { // // public String ref; // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/properties/CredentialsProperties.java // @Getter // @AllArgsConstructor // @ConstructorBinding // @ConfigurationProperties("admin") // public class CredentialsProperties { // // private final String username; // private final String password; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ToSerialize.java // public class ToSerialize implements Cloneable { // // public String prop1; // public String prop2; // // @Override // public ToSerialize clone() throws CloneNotSupportedException { // return (ToSerialize) super.clone(); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/UselessBean.java // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class UselessBean { // // private String testPro = "inclass"; // // private final ABeanIWantToMockInterface aBeanIWantToMock; // // public UselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // this.aBeanIWantToMock = aBeanIWantToMock; // } // // public Boolean iWantToMockThisMethod() { // return aBeanIWantToMock.iAlwaysReturnFalse(); // } // // public String getTestPro() { // return testPro; // } // // public void setTestPro(String testPro) { // this.testPro = testPro; // } // // public void testSerialization(ToSerialize toSerialize) { // toSerialize.prop1 = "prop1updated"; // } // }
import com.mpalourdio.springboottemplate.json.Account; import com.mpalourdio.springboottemplate.json.AccountDecorator; import com.mpalourdio.springboottemplate.json.AccountInterface; import com.mpalourdio.springboottemplate.json.Context; import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.properties.CredentialsProperties; import com.mpalourdio.springboottemplate.service.ToSerialize; import com.mpalourdio.springboottemplate.service.UselessBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @RequestMapping("/misc") @RestController public class MiscController { private final String serverPort; private final String[] propertiesList;
// Path: src/main/java/com/mpalourdio/springboottemplate/json/Account.java // public class Account implements AccountInterface { // // public String firstName; // public String lastName; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountDecorator.java // public class AccountDecorator implements AccountInterface { // // @JsonUnwrapped // public Account account; // public Context context; // // public AccountDecorator() { // } // // public AccountDecorator(Account account) { // this.account = account; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountInterface.java // public interface AccountInterface { // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Context.java // public class Context { // // public String ref; // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/properties/CredentialsProperties.java // @Getter // @AllArgsConstructor // @ConstructorBinding // @ConfigurationProperties("admin") // public class CredentialsProperties { // // private final String username; // private final String password; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ToSerialize.java // public class ToSerialize implements Cloneable { // // public String prop1; // public String prop2; // // @Override // public ToSerialize clone() throws CloneNotSupportedException { // return (ToSerialize) super.clone(); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/UselessBean.java // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class UselessBean { // // private String testPro = "inclass"; // // private final ABeanIWantToMockInterface aBeanIWantToMock; // // public UselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // this.aBeanIWantToMock = aBeanIWantToMock; // } // // public Boolean iWantToMockThisMethod() { // return aBeanIWantToMock.iAlwaysReturnFalse(); // } // // public String getTestPro() { // return testPro; // } // // public void setTestPro(String testPro) { // this.testPro = testPro; // } // // public void testSerialization(ToSerialize toSerialize) { // toSerialize.prop1 = "prop1updated"; // } // } // Path: src/main/java/com/mpalourdio/springboottemplate/controllers/MiscController.java import com.mpalourdio.springboottemplate.json.Account; import com.mpalourdio.springboottemplate.json.AccountDecorator; import com.mpalourdio.springboottemplate.json.AccountInterface; import com.mpalourdio.springboottemplate.json.Context; import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.properties.CredentialsProperties; import com.mpalourdio.springboottemplate.service.ToSerialize; import com.mpalourdio.springboottemplate.service.UselessBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @RequestMapping("/misc") @RestController public class MiscController { private final String serverPort; private final String[] propertiesList;
private final CredentialsProperties credentialsProperties;
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/controllers/MiscController.java
// Path: src/main/java/com/mpalourdio/springboottemplate/json/Account.java // public class Account implements AccountInterface { // // public String firstName; // public String lastName; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountDecorator.java // public class AccountDecorator implements AccountInterface { // // @JsonUnwrapped // public Account account; // public Context context; // // public AccountDecorator() { // } // // public AccountDecorator(Account account) { // this.account = account; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountInterface.java // public interface AccountInterface { // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Context.java // public class Context { // // public String ref; // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/properties/CredentialsProperties.java // @Getter // @AllArgsConstructor // @ConstructorBinding // @ConfigurationProperties("admin") // public class CredentialsProperties { // // private final String username; // private final String password; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ToSerialize.java // public class ToSerialize implements Cloneable { // // public String prop1; // public String prop2; // // @Override // public ToSerialize clone() throws CloneNotSupportedException { // return (ToSerialize) super.clone(); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/UselessBean.java // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class UselessBean { // // private String testPro = "inclass"; // // private final ABeanIWantToMockInterface aBeanIWantToMock; // // public UselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // this.aBeanIWantToMock = aBeanIWantToMock; // } // // public Boolean iWantToMockThisMethod() { // return aBeanIWantToMock.iAlwaysReturnFalse(); // } // // public String getTestPro() { // return testPro; // } // // public void setTestPro(String testPro) { // this.testPro = testPro; // } // // public void testSerialization(ToSerialize toSerialize) { // toSerialize.prop1 = "prop1updated"; // } // }
import com.mpalourdio.springboottemplate.json.Account; import com.mpalourdio.springboottemplate.json.AccountDecorator; import com.mpalourdio.springboottemplate.json.AccountInterface; import com.mpalourdio.springboottemplate.json.Context; import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.properties.CredentialsProperties; import com.mpalourdio.springboottemplate.service.ToSerialize; import com.mpalourdio.springboottemplate.service.UselessBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @RequestMapping("/misc") @RestController public class MiscController { private final String serverPort; private final String[] propertiesList; private final CredentialsProperties credentialsProperties;
// Path: src/main/java/com/mpalourdio/springboottemplate/json/Account.java // public class Account implements AccountInterface { // // public String firstName; // public String lastName; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountDecorator.java // public class AccountDecorator implements AccountInterface { // // @JsonUnwrapped // public Account account; // public Context context; // // public AccountDecorator() { // } // // public AccountDecorator(Account account) { // this.account = account; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountInterface.java // public interface AccountInterface { // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Context.java // public class Context { // // public String ref; // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/properties/CredentialsProperties.java // @Getter // @AllArgsConstructor // @ConstructorBinding // @ConfigurationProperties("admin") // public class CredentialsProperties { // // private final String username; // private final String password; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ToSerialize.java // public class ToSerialize implements Cloneable { // // public String prop1; // public String prop2; // // @Override // public ToSerialize clone() throws CloneNotSupportedException { // return (ToSerialize) super.clone(); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/UselessBean.java // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class UselessBean { // // private String testPro = "inclass"; // // private final ABeanIWantToMockInterface aBeanIWantToMock; // // public UselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // this.aBeanIWantToMock = aBeanIWantToMock; // } // // public Boolean iWantToMockThisMethod() { // return aBeanIWantToMock.iAlwaysReturnFalse(); // } // // public String getTestPro() { // return testPro; // } // // public void setTestPro(String testPro) { // this.testPro = testPro; // } // // public void testSerialization(ToSerialize toSerialize) { // toSerialize.prop1 = "prop1updated"; // } // } // Path: src/main/java/com/mpalourdio/springboottemplate/controllers/MiscController.java import com.mpalourdio.springboottemplate.json.Account; import com.mpalourdio.springboottemplate.json.AccountDecorator; import com.mpalourdio.springboottemplate.json.AccountInterface; import com.mpalourdio.springboottemplate.json.Context; import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.properties.CredentialsProperties; import com.mpalourdio.springboottemplate.service.ToSerialize; import com.mpalourdio.springboottemplate.service.UselessBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @RequestMapping("/misc") @RestController public class MiscController { private final String serverPort; private final String[] propertiesList; private final CredentialsProperties credentialsProperties;
private final UselessBean uselessBean;
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/controllers/MiscController.java
// Path: src/main/java/com/mpalourdio/springboottemplate/json/Account.java // public class Account implements AccountInterface { // // public String firstName; // public String lastName; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountDecorator.java // public class AccountDecorator implements AccountInterface { // // @JsonUnwrapped // public Account account; // public Context context; // // public AccountDecorator() { // } // // public AccountDecorator(Account account) { // this.account = account; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountInterface.java // public interface AccountInterface { // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Context.java // public class Context { // // public String ref; // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/properties/CredentialsProperties.java // @Getter // @AllArgsConstructor // @ConstructorBinding // @ConfigurationProperties("admin") // public class CredentialsProperties { // // private final String username; // private final String password; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ToSerialize.java // public class ToSerialize implements Cloneable { // // public String prop1; // public String prop2; // // @Override // public ToSerialize clone() throws CloneNotSupportedException { // return (ToSerialize) super.clone(); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/UselessBean.java // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class UselessBean { // // private String testPro = "inclass"; // // private final ABeanIWantToMockInterface aBeanIWantToMock; // // public UselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // this.aBeanIWantToMock = aBeanIWantToMock; // } // // public Boolean iWantToMockThisMethod() { // return aBeanIWantToMock.iAlwaysReturnFalse(); // } // // public String getTestPro() { // return testPro; // } // // public void setTestPro(String testPro) { // this.testPro = testPro; // } // // public void testSerialization(ToSerialize toSerialize) { // toSerialize.prop1 = "prop1updated"; // } // }
import com.mpalourdio.springboottemplate.json.Account; import com.mpalourdio.springboottemplate.json.AccountDecorator; import com.mpalourdio.springboottemplate.json.AccountInterface; import com.mpalourdio.springboottemplate.json.Context; import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.properties.CredentialsProperties; import com.mpalourdio.springboottemplate.service.ToSerialize; import com.mpalourdio.springboottemplate.service.UselessBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @RequestMapping("/misc") @RestController public class MiscController { private final String serverPort; private final String[] propertiesList; private final CredentialsProperties credentialsProperties; private final UselessBean uselessBean; public MiscController( @Value("${server.port}") String serverPort, @Value("${list}") String[] propertiesList, CredentialsProperties credentialsProperties, UselessBean uselessBean ) { this.serverPort = serverPort; this.propertiesList = propertiesList; this.credentialsProperties = credentialsProperties; this.uselessBean = uselessBean; } @GetMapping("/basicauth") public String restTemplateWithBasicAuth() { var rt = new RestTemplateBuilder() .basicAuthentication(credentialsProperties.getUsername(), credentialsProperties.getPassword()).build(); return rt.getForObject("http://localhost:" + serverPort + "/basicauth", String.class); }
// Path: src/main/java/com/mpalourdio/springboottemplate/json/Account.java // public class Account implements AccountInterface { // // public String firstName; // public String lastName; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountDecorator.java // public class AccountDecorator implements AccountInterface { // // @JsonUnwrapped // public Account account; // public Context context; // // public AccountDecorator() { // } // // public AccountDecorator(Account account) { // this.account = account; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountInterface.java // public interface AccountInterface { // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Context.java // public class Context { // // public String ref; // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/properties/CredentialsProperties.java // @Getter // @AllArgsConstructor // @ConstructorBinding // @ConfigurationProperties("admin") // public class CredentialsProperties { // // private final String username; // private final String password; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ToSerialize.java // public class ToSerialize implements Cloneable { // // public String prop1; // public String prop2; // // @Override // public ToSerialize clone() throws CloneNotSupportedException { // return (ToSerialize) super.clone(); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/UselessBean.java // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class UselessBean { // // private String testPro = "inclass"; // // private final ABeanIWantToMockInterface aBeanIWantToMock; // // public UselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // this.aBeanIWantToMock = aBeanIWantToMock; // } // // public Boolean iWantToMockThisMethod() { // return aBeanIWantToMock.iAlwaysReturnFalse(); // } // // public String getTestPro() { // return testPro; // } // // public void setTestPro(String testPro) { // this.testPro = testPro; // } // // public void testSerialization(ToSerialize toSerialize) { // toSerialize.prop1 = "prop1updated"; // } // } // Path: src/main/java/com/mpalourdio/springboottemplate/controllers/MiscController.java import com.mpalourdio.springboottemplate.json.Account; import com.mpalourdio.springboottemplate.json.AccountDecorator; import com.mpalourdio.springboottemplate.json.AccountInterface; import com.mpalourdio.springboottemplate.json.Context; import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.properties.CredentialsProperties; import com.mpalourdio.springboottemplate.service.ToSerialize; import com.mpalourdio.springboottemplate.service.UselessBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @RequestMapping("/misc") @RestController public class MiscController { private final String serverPort; private final String[] propertiesList; private final CredentialsProperties credentialsProperties; private final UselessBean uselessBean; public MiscController( @Value("${server.port}") String serverPort, @Value("${list}") String[] propertiesList, CredentialsProperties credentialsProperties, UselessBean uselessBean ) { this.serverPort = serverPort; this.propertiesList = propertiesList; this.credentialsProperties = credentialsProperties; this.uselessBean = uselessBean; } @GetMapping("/basicauth") public String restTemplateWithBasicAuth() { var rt = new RestTemplateBuilder() .basicAuthentication(credentialsProperties.getUsername(), credentialsProperties.getPassword()).build(); return rt.getForObject("http://localhost:" + serverPort + "/basicauth", String.class); }
@PostMapping(value = "/serialization", produces = MediaType.APPLICATION_JSON_VALUE)
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/controllers/MiscController.java
// Path: src/main/java/com/mpalourdio/springboottemplate/json/Account.java // public class Account implements AccountInterface { // // public String firstName; // public String lastName; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountDecorator.java // public class AccountDecorator implements AccountInterface { // // @JsonUnwrapped // public Account account; // public Context context; // // public AccountDecorator() { // } // // public AccountDecorator(Account account) { // this.account = account; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountInterface.java // public interface AccountInterface { // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Context.java // public class Context { // // public String ref; // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/properties/CredentialsProperties.java // @Getter // @AllArgsConstructor // @ConstructorBinding // @ConfigurationProperties("admin") // public class CredentialsProperties { // // private final String username; // private final String password; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ToSerialize.java // public class ToSerialize implements Cloneable { // // public String prop1; // public String prop2; // // @Override // public ToSerialize clone() throws CloneNotSupportedException { // return (ToSerialize) super.clone(); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/UselessBean.java // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class UselessBean { // // private String testPro = "inclass"; // // private final ABeanIWantToMockInterface aBeanIWantToMock; // // public UselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // this.aBeanIWantToMock = aBeanIWantToMock; // } // // public Boolean iWantToMockThisMethod() { // return aBeanIWantToMock.iAlwaysReturnFalse(); // } // // public String getTestPro() { // return testPro; // } // // public void setTestPro(String testPro) { // this.testPro = testPro; // } // // public void testSerialization(ToSerialize toSerialize) { // toSerialize.prop1 = "prop1updated"; // } // }
import com.mpalourdio.springboottemplate.json.Account; import com.mpalourdio.springboottemplate.json.AccountDecorator; import com.mpalourdio.springboottemplate.json.AccountInterface; import com.mpalourdio.springboottemplate.json.Context; import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.properties.CredentialsProperties; import com.mpalourdio.springboottemplate.service.ToSerialize; import com.mpalourdio.springboottemplate.service.UselessBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @RequestMapping("/misc") @RestController public class MiscController { private final String serverPort; private final String[] propertiesList; private final CredentialsProperties credentialsProperties; private final UselessBean uselessBean; public MiscController( @Value("${server.port}") String serverPort, @Value("${list}") String[] propertiesList, CredentialsProperties credentialsProperties, UselessBean uselessBean ) { this.serverPort = serverPort; this.propertiesList = propertiesList; this.credentialsProperties = credentialsProperties; this.uselessBean = uselessBean; } @GetMapping("/basicauth") public String restTemplateWithBasicAuth() { var rt = new RestTemplateBuilder() .basicAuthentication(credentialsProperties.getUsername(), credentialsProperties.getPassword()).build(); return rt.getForObject("http://localhost:" + serverPort + "/basicauth", String.class); } @PostMapping(value = "/serialization", produces = MediaType.APPLICATION_JSON_VALUE)
// Path: src/main/java/com/mpalourdio/springboottemplate/json/Account.java // public class Account implements AccountInterface { // // public String firstName; // public String lastName; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountDecorator.java // public class AccountDecorator implements AccountInterface { // // @JsonUnwrapped // public Account account; // public Context context; // // public AccountDecorator() { // } // // public AccountDecorator(Account account) { // this.account = account; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountInterface.java // public interface AccountInterface { // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Context.java // public class Context { // // public String ref; // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/properties/CredentialsProperties.java // @Getter // @AllArgsConstructor // @ConstructorBinding // @ConfigurationProperties("admin") // public class CredentialsProperties { // // private final String username; // private final String password; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ToSerialize.java // public class ToSerialize implements Cloneable { // // public String prop1; // public String prop2; // // @Override // public ToSerialize clone() throws CloneNotSupportedException { // return (ToSerialize) super.clone(); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/UselessBean.java // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class UselessBean { // // private String testPro = "inclass"; // // private final ABeanIWantToMockInterface aBeanIWantToMock; // // public UselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // this.aBeanIWantToMock = aBeanIWantToMock; // } // // public Boolean iWantToMockThisMethod() { // return aBeanIWantToMock.iAlwaysReturnFalse(); // } // // public String getTestPro() { // return testPro; // } // // public void setTestPro(String testPro) { // this.testPro = testPro; // } // // public void testSerialization(ToSerialize toSerialize) { // toSerialize.prop1 = "prop1updated"; // } // } // Path: src/main/java/com/mpalourdio/springboottemplate/controllers/MiscController.java import com.mpalourdio.springboottemplate.json.Account; import com.mpalourdio.springboottemplate.json.AccountDecorator; import com.mpalourdio.springboottemplate.json.AccountInterface; import com.mpalourdio.springboottemplate.json.Context; import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.properties.CredentialsProperties; import com.mpalourdio.springboottemplate.service.ToSerialize; import com.mpalourdio.springboottemplate.service.UselessBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @RequestMapping("/misc") @RestController public class MiscController { private final String serverPort; private final String[] propertiesList; private final CredentialsProperties credentialsProperties; private final UselessBean uselessBean; public MiscController( @Value("${server.port}") String serverPort, @Value("${list}") String[] propertiesList, CredentialsProperties credentialsProperties, UselessBean uselessBean ) { this.serverPort = serverPort; this.propertiesList = propertiesList; this.credentialsProperties = credentialsProperties; this.uselessBean = uselessBean; } @GetMapping("/basicauth") public String restTemplateWithBasicAuth() { var rt = new RestTemplateBuilder() .basicAuthentication(credentialsProperties.getUsername(), credentialsProperties.getPassword()).build(); return rt.getForObject("http://localhost:" + serverPort + "/basicauth", String.class); } @PostMapping(value = "/serialization", produces = MediaType.APPLICATION_JSON_VALUE)
public ToSerialize testSerialization(@RequestBody ToSerialize toSerialize) {
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/controllers/MiscController.java
// Path: src/main/java/com/mpalourdio/springboottemplate/json/Account.java // public class Account implements AccountInterface { // // public String firstName; // public String lastName; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountDecorator.java // public class AccountDecorator implements AccountInterface { // // @JsonUnwrapped // public Account account; // public Context context; // // public AccountDecorator() { // } // // public AccountDecorator(Account account) { // this.account = account; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountInterface.java // public interface AccountInterface { // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Context.java // public class Context { // // public String ref; // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/properties/CredentialsProperties.java // @Getter // @AllArgsConstructor // @ConstructorBinding // @ConfigurationProperties("admin") // public class CredentialsProperties { // // private final String username; // private final String password; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ToSerialize.java // public class ToSerialize implements Cloneable { // // public String prop1; // public String prop2; // // @Override // public ToSerialize clone() throws CloneNotSupportedException { // return (ToSerialize) super.clone(); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/UselessBean.java // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class UselessBean { // // private String testPro = "inclass"; // // private final ABeanIWantToMockInterface aBeanIWantToMock; // // public UselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // this.aBeanIWantToMock = aBeanIWantToMock; // } // // public Boolean iWantToMockThisMethod() { // return aBeanIWantToMock.iAlwaysReturnFalse(); // } // // public String getTestPro() { // return testPro; // } // // public void setTestPro(String testPro) { // this.testPro = testPro; // } // // public void testSerialization(ToSerialize toSerialize) { // toSerialize.prop1 = "prop1updated"; // } // }
import com.mpalourdio.springboottemplate.json.Account; import com.mpalourdio.springboottemplate.json.AccountDecorator; import com.mpalourdio.springboottemplate.json.AccountInterface; import com.mpalourdio.springboottemplate.json.Context; import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.properties.CredentialsProperties; import com.mpalourdio.springboottemplate.service.ToSerialize; import com.mpalourdio.springboottemplate.service.UselessBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors;
private final CredentialsProperties credentialsProperties; private final UselessBean uselessBean; public MiscController( @Value("${server.port}") String serverPort, @Value("${list}") String[] propertiesList, CredentialsProperties credentialsProperties, UselessBean uselessBean ) { this.serverPort = serverPort; this.propertiesList = propertiesList; this.credentialsProperties = credentialsProperties; this.uselessBean = uselessBean; } @GetMapping("/basicauth") public String restTemplateWithBasicAuth() { var rt = new RestTemplateBuilder() .basicAuthentication(credentialsProperties.getUsername(), credentialsProperties.getPassword()).build(); return rt.getForObject("http://localhost:" + serverPort + "/basicauth", String.class); } @PostMapping(value = "/serialization", produces = MediaType.APPLICATION_JSON_VALUE) public ToSerialize testSerialization(@RequestBody ToSerialize toSerialize) { uselessBean.testSerialization(toSerialize); return toSerialize; } @PostMapping(value = "/jsonunwrapped", produces = MediaType.APPLICATION_JSON_VALUE)
// Path: src/main/java/com/mpalourdio/springboottemplate/json/Account.java // public class Account implements AccountInterface { // // public String firstName; // public String lastName; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountDecorator.java // public class AccountDecorator implements AccountInterface { // // @JsonUnwrapped // public Account account; // public Context context; // // public AccountDecorator() { // } // // public AccountDecorator(Account account) { // this.account = account; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountInterface.java // public interface AccountInterface { // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Context.java // public class Context { // // public String ref; // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/properties/CredentialsProperties.java // @Getter // @AllArgsConstructor // @ConstructorBinding // @ConfigurationProperties("admin") // public class CredentialsProperties { // // private final String username; // private final String password; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ToSerialize.java // public class ToSerialize implements Cloneable { // // public String prop1; // public String prop2; // // @Override // public ToSerialize clone() throws CloneNotSupportedException { // return (ToSerialize) super.clone(); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/UselessBean.java // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class UselessBean { // // private String testPro = "inclass"; // // private final ABeanIWantToMockInterface aBeanIWantToMock; // // public UselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // this.aBeanIWantToMock = aBeanIWantToMock; // } // // public Boolean iWantToMockThisMethod() { // return aBeanIWantToMock.iAlwaysReturnFalse(); // } // // public String getTestPro() { // return testPro; // } // // public void setTestPro(String testPro) { // this.testPro = testPro; // } // // public void testSerialization(ToSerialize toSerialize) { // toSerialize.prop1 = "prop1updated"; // } // } // Path: src/main/java/com/mpalourdio/springboottemplate/controllers/MiscController.java import com.mpalourdio.springboottemplate.json.Account; import com.mpalourdio.springboottemplate.json.AccountDecorator; import com.mpalourdio.springboottemplate.json.AccountInterface; import com.mpalourdio.springboottemplate.json.Context; import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.properties.CredentialsProperties; import com.mpalourdio.springboottemplate.service.ToSerialize; import com.mpalourdio.springboottemplate.service.UselessBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; private final CredentialsProperties credentialsProperties; private final UselessBean uselessBean; public MiscController( @Value("${server.port}") String serverPort, @Value("${list}") String[] propertiesList, CredentialsProperties credentialsProperties, UselessBean uselessBean ) { this.serverPort = serverPort; this.propertiesList = propertiesList; this.credentialsProperties = credentialsProperties; this.uselessBean = uselessBean; } @GetMapping("/basicauth") public String restTemplateWithBasicAuth() { var rt = new RestTemplateBuilder() .basicAuthentication(credentialsProperties.getUsername(), credentialsProperties.getPassword()).build(); return rt.getForObject("http://localhost:" + serverPort + "/basicauth", String.class); } @PostMapping(value = "/serialization", produces = MediaType.APPLICATION_JSON_VALUE) public ToSerialize testSerialization(@RequestBody ToSerialize toSerialize) { uselessBean.testSerialization(toSerialize); return toSerialize; } @PostMapping(value = "/jsonunwrapped", produces = MediaType.APPLICATION_JSON_VALUE)
public AccountInterface jsonUnwrapped(@RequestBody Account account) {
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/controllers/MiscController.java
// Path: src/main/java/com/mpalourdio/springboottemplate/json/Account.java // public class Account implements AccountInterface { // // public String firstName; // public String lastName; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountDecorator.java // public class AccountDecorator implements AccountInterface { // // @JsonUnwrapped // public Account account; // public Context context; // // public AccountDecorator() { // } // // public AccountDecorator(Account account) { // this.account = account; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountInterface.java // public interface AccountInterface { // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Context.java // public class Context { // // public String ref; // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/properties/CredentialsProperties.java // @Getter // @AllArgsConstructor // @ConstructorBinding // @ConfigurationProperties("admin") // public class CredentialsProperties { // // private final String username; // private final String password; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ToSerialize.java // public class ToSerialize implements Cloneable { // // public String prop1; // public String prop2; // // @Override // public ToSerialize clone() throws CloneNotSupportedException { // return (ToSerialize) super.clone(); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/UselessBean.java // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class UselessBean { // // private String testPro = "inclass"; // // private final ABeanIWantToMockInterface aBeanIWantToMock; // // public UselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // this.aBeanIWantToMock = aBeanIWantToMock; // } // // public Boolean iWantToMockThisMethod() { // return aBeanIWantToMock.iAlwaysReturnFalse(); // } // // public String getTestPro() { // return testPro; // } // // public void setTestPro(String testPro) { // this.testPro = testPro; // } // // public void testSerialization(ToSerialize toSerialize) { // toSerialize.prop1 = "prop1updated"; // } // }
import com.mpalourdio.springboottemplate.json.Account; import com.mpalourdio.springboottemplate.json.AccountDecorator; import com.mpalourdio.springboottemplate.json.AccountInterface; import com.mpalourdio.springboottemplate.json.Context; import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.properties.CredentialsProperties; import com.mpalourdio.springboottemplate.service.ToSerialize; import com.mpalourdio.springboottemplate.service.UselessBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors;
private final CredentialsProperties credentialsProperties; private final UselessBean uselessBean; public MiscController( @Value("${server.port}") String serverPort, @Value("${list}") String[] propertiesList, CredentialsProperties credentialsProperties, UselessBean uselessBean ) { this.serverPort = serverPort; this.propertiesList = propertiesList; this.credentialsProperties = credentialsProperties; this.uselessBean = uselessBean; } @GetMapping("/basicauth") public String restTemplateWithBasicAuth() { var rt = new RestTemplateBuilder() .basicAuthentication(credentialsProperties.getUsername(), credentialsProperties.getPassword()).build(); return rt.getForObject("http://localhost:" + serverPort + "/basicauth", String.class); } @PostMapping(value = "/serialization", produces = MediaType.APPLICATION_JSON_VALUE) public ToSerialize testSerialization(@RequestBody ToSerialize toSerialize) { uselessBean.testSerialization(toSerialize); return toSerialize; } @PostMapping(value = "/jsonunwrapped", produces = MediaType.APPLICATION_JSON_VALUE)
// Path: src/main/java/com/mpalourdio/springboottemplate/json/Account.java // public class Account implements AccountInterface { // // public String firstName; // public String lastName; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountDecorator.java // public class AccountDecorator implements AccountInterface { // // @JsonUnwrapped // public Account account; // public Context context; // // public AccountDecorator() { // } // // public AccountDecorator(Account account) { // this.account = account; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountInterface.java // public interface AccountInterface { // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Context.java // public class Context { // // public String ref; // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/properties/CredentialsProperties.java // @Getter // @AllArgsConstructor // @ConstructorBinding // @ConfigurationProperties("admin") // public class CredentialsProperties { // // private final String username; // private final String password; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ToSerialize.java // public class ToSerialize implements Cloneable { // // public String prop1; // public String prop2; // // @Override // public ToSerialize clone() throws CloneNotSupportedException { // return (ToSerialize) super.clone(); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/UselessBean.java // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class UselessBean { // // private String testPro = "inclass"; // // private final ABeanIWantToMockInterface aBeanIWantToMock; // // public UselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // this.aBeanIWantToMock = aBeanIWantToMock; // } // // public Boolean iWantToMockThisMethod() { // return aBeanIWantToMock.iAlwaysReturnFalse(); // } // // public String getTestPro() { // return testPro; // } // // public void setTestPro(String testPro) { // this.testPro = testPro; // } // // public void testSerialization(ToSerialize toSerialize) { // toSerialize.prop1 = "prop1updated"; // } // } // Path: src/main/java/com/mpalourdio/springboottemplate/controllers/MiscController.java import com.mpalourdio.springboottemplate.json.Account; import com.mpalourdio.springboottemplate.json.AccountDecorator; import com.mpalourdio.springboottemplate.json.AccountInterface; import com.mpalourdio.springboottemplate.json.Context; import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.properties.CredentialsProperties; import com.mpalourdio.springboottemplate.service.ToSerialize; import com.mpalourdio.springboottemplate.service.UselessBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; private final CredentialsProperties credentialsProperties; private final UselessBean uselessBean; public MiscController( @Value("${server.port}") String serverPort, @Value("${list}") String[] propertiesList, CredentialsProperties credentialsProperties, UselessBean uselessBean ) { this.serverPort = serverPort; this.propertiesList = propertiesList; this.credentialsProperties = credentialsProperties; this.uselessBean = uselessBean; } @GetMapping("/basicauth") public String restTemplateWithBasicAuth() { var rt = new RestTemplateBuilder() .basicAuthentication(credentialsProperties.getUsername(), credentialsProperties.getPassword()).build(); return rt.getForObject("http://localhost:" + serverPort + "/basicauth", String.class); } @PostMapping(value = "/serialization", produces = MediaType.APPLICATION_JSON_VALUE) public ToSerialize testSerialization(@RequestBody ToSerialize toSerialize) { uselessBean.testSerialization(toSerialize); return toSerialize; } @PostMapping(value = "/jsonunwrapped", produces = MediaType.APPLICATION_JSON_VALUE)
public AccountInterface jsonUnwrapped(@RequestBody Account account) {
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/controllers/MiscController.java
// Path: src/main/java/com/mpalourdio/springboottemplate/json/Account.java // public class Account implements AccountInterface { // // public String firstName; // public String lastName; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountDecorator.java // public class AccountDecorator implements AccountInterface { // // @JsonUnwrapped // public Account account; // public Context context; // // public AccountDecorator() { // } // // public AccountDecorator(Account account) { // this.account = account; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountInterface.java // public interface AccountInterface { // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Context.java // public class Context { // // public String ref; // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/properties/CredentialsProperties.java // @Getter // @AllArgsConstructor // @ConstructorBinding // @ConfigurationProperties("admin") // public class CredentialsProperties { // // private final String username; // private final String password; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ToSerialize.java // public class ToSerialize implements Cloneable { // // public String prop1; // public String prop2; // // @Override // public ToSerialize clone() throws CloneNotSupportedException { // return (ToSerialize) super.clone(); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/UselessBean.java // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class UselessBean { // // private String testPro = "inclass"; // // private final ABeanIWantToMockInterface aBeanIWantToMock; // // public UselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // this.aBeanIWantToMock = aBeanIWantToMock; // } // // public Boolean iWantToMockThisMethod() { // return aBeanIWantToMock.iAlwaysReturnFalse(); // } // // public String getTestPro() { // return testPro; // } // // public void setTestPro(String testPro) { // this.testPro = testPro; // } // // public void testSerialization(ToSerialize toSerialize) { // toSerialize.prop1 = "prop1updated"; // } // }
import com.mpalourdio.springboottemplate.json.Account; import com.mpalourdio.springboottemplate.json.AccountDecorator; import com.mpalourdio.springboottemplate.json.AccountInterface; import com.mpalourdio.springboottemplate.json.Context; import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.properties.CredentialsProperties; import com.mpalourdio.springboottemplate.service.ToSerialize; import com.mpalourdio.springboottemplate.service.UselessBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors;
public MiscController( @Value("${server.port}") String serverPort, @Value("${list}") String[] propertiesList, CredentialsProperties credentialsProperties, UselessBean uselessBean ) { this.serverPort = serverPort; this.propertiesList = propertiesList; this.credentialsProperties = credentialsProperties; this.uselessBean = uselessBean; } @GetMapping("/basicauth") public String restTemplateWithBasicAuth() { var rt = new RestTemplateBuilder() .basicAuthentication(credentialsProperties.getUsername(), credentialsProperties.getPassword()).build(); return rt.getForObject("http://localhost:" + serverPort + "/basicauth", String.class); } @PostMapping(value = "/serialization", produces = MediaType.APPLICATION_JSON_VALUE) public ToSerialize testSerialization(@RequestBody ToSerialize toSerialize) { uselessBean.testSerialization(toSerialize); return toSerialize; } @PostMapping(value = "/jsonunwrapped", produces = MediaType.APPLICATION_JSON_VALUE) public AccountInterface jsonUnwrapped(@RequestBody Account account) {
// Path: src/main/java/com/mpalourdio/springboottemplate/json/Account.java // public class Account implements AccountInterface { // // public String firstName; // public String lastName; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountDecorator.java // public class AccountDecorator implements AccountInterface { // // @JsonUnwrapped // public Account account; // public Context context; // // public AccountDecorator() { // } // // public AccountDecorator(Account account) { // this.account = account; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountInterface.java // public interface AccountInterface { // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Context.java // public class Context { // // public String ref; // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/properties/CredentialsProperties.java // @Getter // @AllArgsConstructor // @ConstructorBinding // @ConfigurationProperties("admin") // public class CredentialsProperties { // // private final String username; // private final String password; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ToSerialize.java // public class ToSerialize implements Cloneable { // // public String prop1; // public String prop2; // // @Override // public ToSerialize clone() throws CloneNotSupportedException { // return (ToSerialize) super.clone(); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/UselessBean.java // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class UselessBean { // // private String testPro = "inclass"; // // private final ABeanIWantToMockInterface aBeanIWantToMock; // // public UselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // this.aBeanIWantToMock = aBeanIWantToMock; // } // // public Boolean iWantToMockThisMethod() { // return aBeanIWantToMock.iAlwaysReturnFalse(); // } // // public String getTestPro() { // return testPro; // } // // public void setTestPro(String testPro) { // this.testPro = testPro; // } // // public void testSerialization(ToSerialize toSerialize) { // toSerialize.prop1 = "prop1updated"; // } // } // Path: src/main/java/com/mpalourdio/springboottemplate/controllers/MiscController.java import com.mpalourdio.springboottemplate.json.Account; import com.mpalourdio.springboottemplate.json.AccountDecorator; import com.mpalourdio.springboottemplate.json.AccountInterface; import com.mpalourdio.springboottemplate.json.Context; import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.properties.CredentialsProperties; import com.mpalourdio.springboottemplate.service.ToSerialize; import com.mpalourdio.springboottemplate.service.UselessBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public MiscController( @Value("${server.port}") String serverPort, @Value("${list}") String[] propertiesList, CredentialsProperties credentialsProperties, UselessBean uselessBean ) { this.serverPort = serverPort; this.propertiesList = propertiesList; this.credentialsProperties = credentialsProperties; this.uselessBean = uselessBean; } @GetMapping("/basicauth") public String restTemplateWithBasicAuth() { var rt = new RestTemplateBuilder() .basicAuthentication(credentialsProperties.getUsername(), credentialsProperties.getPassword()).build(); return rt.getForObject("http://localhost:" + serverPort + "/basicauth", String.class); } @PostMapping(value = "/serialization", produces = MediaType.APPLICATION_JSON_VALUE) public ToSerialize testSerialization(@RequestBody ToSerialize toSerialize) { uselessBean.testSerialization(toSerialize); return toSerialize; } @PostMapping(value = "/jsonunwrapped", produces = MediaType.APPLICATION_JSON_VALUE) public AccountInterface jsonUnwrapped(@RequestBody Account account) {
var accountDecorator = new AccountDecorator(account);
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/controllers/MiscController.java
// Path: src/main/java/com/mpalourdio/springboottemplate/json/Account.java // public class Account implements AccountInterface { // // public String firstName; // public String lastName; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountDecorator.java // public class AccountDecorator implements AccountInterface { // // @JsonUnwrapped // public Account account; // public Context context; // // public AccountDecorator() { // } // // public AccountDecorator(Account account) { // this.account = account; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountInterface.java // public interface AccountInterface { // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Context.java // public class Context { // // public String ref; // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/properties/CredentialsProperties.java // @Getter // @AllArgsConstructor // @ConstructorBinding // @ConfigurationProperties("admin") // public class CredentialsProperties { // // private final String username; // private final String password; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ToSerialize.java // public class ToSerialize implements Cloneable { // // public String prop1; // public String prop2; // // @Override // public ToSerialize clone() throws CloneNotSupportedException { // return (ToSerialize) super.clone(); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/UselessBean.java // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class UselessBean { // // private String testPro = "inclass"; // // private final ABeanIWantToMockInterface aBeanIWantToMock; // // public UselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // this.aBeanIWantToMock = aBeanIWantToMock; // } // // public Boolean iWantToMockThisMethod() { // return aBeanIWantToMock.iAlwaysReturnFalse(); // } // // public String getTestPro() { // return testPro; // } // // public void setTestPro(String testPro) { // this.testPro = testPro; // } // // public void testSerialization(ToSerialize toSerialize) { // toSerialize.prop1 = "prop1updated"; // } // }
import com.mpalourdio.springboottemplate.json.Account; import com.mpalourdio.springboottemplate.json.AccountDecorator; import com.mpalourdio.springboottemplate.json.AccountInterface; import com.mpalourdio.springboottemplate.json.Context; import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.properties.CredentialsProperties; import com.mpalourdio.springboottemplate.service.ToSerialize; import com.mpalourdio.springboottemplate.service.UselessBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors;
public MiscController( @Value("${server.port}") String serverPort, @Value("${list}") String[] propertiesList, CredentialsProperties credentialsProperties, UselessBean uselessBean ) { this.serverPort = serverPort; this.propertiesList = propertiesList; this.credentialsProperties = credentialsProperties; this.uselessBean = uselessBean; } @GetMapping("/basicauth") public String restTemplateWithBasicAuth() { var rt = new RestTemplateBuilder() .basicAuthentication(credentialsProperties.getUsername(), credentialsProperties.getPassword()).build(); return rt.getForObject("http://localhost:" + serverPort + "/basicauth", String.class); } @PostMapping(value = "/serialization", produces = MediaType.APPLICATION_JSON_VALUE) public ToSerialize testSerialization(@RequestBody ToSerialize toSerialize) { uselessBean.testSerialization(toSerialize); return toSerialize; } @PostMapping(value = "/jsonunwrapped", produces = MediaType.APPLICATION_JSON_VALUE) public AccountInterface jsonUnwrapped(@RequestBody Account account) { var accountDecorator = new AccountDecorator(account);
// Path: src/main/java/com/mpalourdio/springboottemplate/json/Account.java // public class Account implements AccountInterface { // // public String firstName; // public String lastName; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountDecorator.java // public class AccountDecorator implements AccountInterface { // // @JsonUnwrapped // public Account account; // public Context context; // // public AccountDecorator() { // } // // public AccountDecorator(Account account) { // this.account = account; // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/AccountInterface.java // public interface AccountInterface { // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/json/Context.java // public class Context { // // public String ref; // // } // // Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/properties/CredentialsProperties.java // @Getter // @AllArgsConstructor // @ConstructorBinding // @ConfigurationProperties("admin") // public class CredentialsProperties { // // private final String username; // private final String password; // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/ToSerialize.java // public class ToSerialize implements Cloneable { // // public String prop1; // public String prop2; // // @Override // public ToSerialize clone() throws CloneNotSupportedException { // return (ToSerialize) super.clone(); // } // } // // Path: src/main/java/com/mpalourdio/springboottemplate/service/UselessBean.java // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class UselessBean { // // private String testPro = "inclass"; // // private final ABeanIWantToMockInterface aBeanIWantToMock; // // public UselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // this.aBeanIWantToMock = aBeanIWantToMock; // } // // public Boolean iWantToMockThisMethod() { // return aBeanIWantToMock.iAlwaysReturnFalse(); // } // // public String getTestPro() { // return testPro; // } // // public void setTestPro(String testPro) { // this.testPro = testPro; // } // // public void testSerialization(ToSerialize toSerialize) { // toSerialize.prop1 = "prop1updated"; // } // } // Path: src/main/java/com/mpalourdio/springboottemplate/controllers/MiscController.java import com.mpalourdio.springboottemplate.json.Account; import com.mpalourdio.springboottemplate.json.AccountDecorator; import com.mpalourdio.springboottemplate.json.AccountInterface; import com.mpalourdio.springboottemplate.json.Context; import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.properties.CredentialsProperties; import com.mpalourdio.springboottemplate.service.ToSerialize; import com.mpalourdio.springboottemplate.service.UselessBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public MiscController( @Value("${server.port}") String serverPort, @Value("${list}") String[] propertiesList, CredentialsProperties credentialsProperties, UselessBean uselessBean ) { this.serverPort = serverPort; this.propertiesList = propertiesList; this.credentialsProperties = credentialsProperties; this.uselessBean = uselessBean; } @GetMapping("/basicauth") public String restTemplateWithBasicAuth() { var rt = new RestTemplateBuilder() .basicAuthentication(credentialsProperties.getUsername(), credentialsProperties.getPassword()).build(); return rt.getForObject("http://localhost:" + serverPort + "/basicauth", String.class); } @PostMapping(value = "/serialization", produces = MediaType.APPLICATION_JSON_VALUE) public ToSerialize testSerialization(@RequestBody ToSerialize toSerialize) { uselessBean.testSerialization(toSerialize); return toSerialize; } @PostMapping(value = "/jsonunwrapped", produces = MediaType.APPLICATION_JSON_VALUE) public AccountInterface jsonUnwrapped(@RequestBody Account account) { var accountDecorator = new AccountDecorator(account);
var context = new Context();
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/SpringBootTemplateApplication.java
// Path: src/main/java/app/config/BeansFactory.java // @Configuration // @EnableConfigurationProperties(MyPropertyConfigHolder.class) // public class BeansFactory { // // @Bean // public BeanFromConfigurationClass<Task> beanFromConfigurationClass() { // var task = new Task(); // task.setTaskName("fromBeanConfiguration"); // return new BeanFromConfigurationClass<>(Task.class, task); // } // // @Bean // public ServiceWithConfigurationProperties serviceWithConfigurationProperties(MyPropertyConfigHolder myProperty) { // return new ServiceWithConfigurationProperties(myProperty); // } // // @Bean // public ServiceWithProperties serviceWithProperties(@Value("${admin.username}") String valueFromConfig) { // return new ServiceWithProperties(valueFromConfig); // } // // @Bean // public AsyncEvent asyncEvent() { // return new AsyncEvent(); // } // // @Bean // public AsyncLogger asyncLogger(ApplicationEventPublisher eventPublisher) { // return new AsyncLogger(eventPublisher); // } // // @Bean // public MyEventListener myEventListener() { // return new MyEventListener(); // } // // @Bean // public ABeanIWantToMockInterface aBeanIWantToMock() { // return new ABeanIWantToMock(); // } // // @Bean // public UselessBean uselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // return new UselessBean(aBeanIWantToMock); // } // } // // Path: src/main/java/app/config/WebSecurityConfig.java // @Configuration // @EnableWebSecurity // @EnableConfigurationProperties(CredentialsProperties.class) // public class WebSecurityConfig extends WebSecurityConfigurerAdapter { // // private static final String BASIC_AUTH_ENDPOINT = "/basicauth"; // private static final String ADMIN_ROLE = "ADMIN"; // private static final String ACTUATOR_ROLE = "ACTUATOR"; // // private final CredentialsProperties credentialsProperties; // // public WebSecurityConfig(CredentialsProperties credentialsProperties) { // this.credentialsProperties = credentialsProperties; // } // // @Override // protected void configure(HttpSecurity http) throws Exception { // //We disable csrf protection for actuator endpoints so we can post with curl // //ex : the refresh endpoint // http.csrf().ignoringRequestMatchers(EndpointRequest.toAnyEndpoint()); // // http.logout() // .logoutSuccessUrl("/") // .invalidateHttpSession(true) // .clearAuthentication(true) // .logoutSuccessHandler(logoutHandler()) // .logoutRequestMatcher(new AntPathRequestMatcher("/logout")); // // http.authorizeRequests() // .antMatchers(BASIC_AUTH_ENDPOINT) // .hasRole(ADMIN_ROLE) // .requestMatchers(EndpointRequest.toAnyEndpoint()) // .hasRole(ACTUATOR_ROLE) // .and() // .httpBasic(); // } // // @Bean // public InMemoryUserDetailsManager inMemoryUserDetailsManager() { // return new InMemoryUserDetailsManager( // User.withDefaultPasswordEncoder() // .username(credentialsProperties.getUsername()) // .password(credentialsProperties.getPassword()) // .roles(ADMIN_ROLE, ACTUATOR_ROLE) // .build() // ); // } // // private LogoutSuccessHandler logoutHandler() { // var logoutSuccessHandler = new SimpleUrlLogoutSuccessHandler(); // var redirectStrategy = new DefaultRedirectStrategy(); // // redirectStrategy.setContextRelative(false); // logoutSuccessHandler.setRedirectStrategy(redirectStrategy); // // return logoutSuccessHandler; // } // }
import app.config.BeansFactory; import app.config.WebSecurityConfig; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.PropertySource; import java.util.Arrays;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate; @SpringBootApplication @PropertySource(value = { "file:properties/global.properties", "file:properties/local.properties" }, ignoreResourceNotFound = true) @Import({
// Path: src/main/java/app/config/BeansFactory.java // @Configuration // @EnableConfigurationProperties(MyPropertyConfigHolder.class) // public class BeansFactory { // // @Bean // public BeanFromConfigurationClass<Task> beanFromConfigurationClass() { // var task = new Task(); // task.setTaskName("fromBeanConfiguration"); // return new BeanFromConfigurationClass<>(Task.class, task); // } // // @Bean // public ServiceWithConfigurationProperties serviceWithConfigurationProperties(MyPropertyConfigHolder myProperty) { // return new ServiceWithConfigurationProperties(myProperty); // } // // @Bean // public ServiceWithProperties serviceWithProperties(@Value("${admin.username}") String valueFromConfig) { // return new ServiceWithProperties(valueFromConfig); // } // // @Bean // public AsyncEvent asyncEvent() { // return new AsyncEvent(); // } // // @Bean // public AsyncLogger asyncLogger(ApplicationEventPublisher eventPublisher) { // return new AsyncLogger(eventPublisher); // } // // @Bean // public MyEventListener myEventListener() { // return new MyEventListener(); // } // // @Bean // public ABeanIWantToMockInterface aBeanIWantToMock() { // return new ABeanIWantToMock(); // } // // @Bean // public UselessBean uselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // return new UselessBean(aBeanIWantToMock); // } // } // // Path: src/main/java/app/config/WebSecurityConfig.java // @Configuration // @EnableWebSecurity // @EnableConfigurationProperties(CredentialsProperties.class) // public class WebSecurityConfig extends WebSecurityConfigurerAdapter { // // private static final String BASIC_AUTH_ENDPOINT = "/basicauth"; // private static final String ADMIN_ROLE = "ADMIN"; // private static final String ACTUATOR_ROLE = "ACTUATOR"; // // private final CredentialsProperties credentialsProperties; // // public WebSecurityConfig(CredentialsProperties credentialsProperties) { // this.credentialsProperties = credentialsProperties; // } // // @Override // protected void configure(HttpSecurity http) throws Exception { // //We disable csrf protection for actuator endpoints so we can post with curl // //ex : the refresh endpoint // http.csrf().ignoringRequestMatchers(EndpointRequest.toAnyEndpoint()); // // http.logout() // .logoutSuccessUrl("/") // .invalidateHttpSession(true) // .clearAuthentication(true) // .logoutSuccessHandler(logoutHandler()) // .logoutRequestMatcher(new AntPathRequestMatcher("/logout")); // // http.authorizeRequests() // .antMatchers(BASIC_AUTH_ENDPOINT) // .hasRole(ADMIN_ROLE) // .requestMatchers(EndpointRequest.toAnyEndpoint()) // .hasRole(ACTUATOR_ROLE) // .and() // .httpBasic(); // } // // @Bean // public InMemoryUserDetailsManager inMemoryUserDetailsManager() { // return new InMemoryUserDetailsManager( // User.withDefaultPasswordEncoder() // .username(credentialsProperties.getUsername()) // .password(credentialsProperties.getPassword()) // .roles(ADMIN_ROLE, ACTUATOR_ROLE) // .build() // ); // } // // private LogoutSuccessHandler logoutHandler() { // var logoutSuccessHandler = new SimpleUrlLogoutSuccessHandler(); // var redirectStrategy = new DefaultRedirectStrategy(); // // redirectStrategy.setContextRelative(false); // logoutSuccessHandler.setRedirectStrategy(redirectStrategy); // // return logoutSuccessHandler; // } // } // Path: src/main/java/com/mpalourdio/springboottemplate/SpringBootTemplateApplication.java import app.config.BeansFactory; import app.config.WebSecurityConfig; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.PropertySource; import java.util.Arrays; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate; @SpringBootApplication @PropertySource(value = { "file:properties/global.properties", "file:properties/local.properties" }, ignoreResourceNotFound = true) @Import({
WebSecurityConfig.class,
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/SpringBootTemplateApplication.java
// Path: src/main/java/app/config/BeansFactory.java // @Configuration // @EnableConfigurationProperties(MyPropertyConfigHolder.class) // public class BeansFactory { // // @Bean // public BeanFromConfigurationClass<Task> beanFromConfigurationClass() { // var task = new Task(); // task.setTaskName("fromBeanConfiguration"); // return new BeanFromConfigurationClass<>(Task.class, task); // } // // @Bean // public ServiceWithConfigurationProperties serviceWithConfigurationProperties(MyPropertyConfigHolder myProperty) { // return new ServiceWithConfigurationProperties(myProperty); // } // // @Bean // public ServiceWithProperties serviceWithProperties(@Value("${admin.username}") String valueFromConfig) { // return new ServiceWithProperties(valueFromConfig); // } // // @Bean // public AsyncEvent asyncEvent() { // return new AsyncEvent(); // } // // @Bean // public AsyncLogger asyncLogger(ApplicationEventPublisher eventPublisher) { // return new AsyncLogger(eventPublisher); // } // // @Bean // public MyEventListener myEventListener() { // return new MyEventListener(); // } // // @Bean // public ABeanIWantToMockInterface aBeanIWantToMock() { // return new ABeanIWantToMock(); // } // // @Bean // public UselessBean uselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // return new UselessBean(aBeanIWantToMock); // } // } // // Path: src/main/java/app/config/WebSecurityConfig.java // @Configuration // @EnableWebSecurity // @EnableConfigurationProperties(CredentialsProperties.class) // public class WebSecurityConfig extends WebSecurityConfigurerAdapter { // // private static final String BASIC_AUTH_ENDPOINT = "/basicauth"; // private static final String ADMIN_ROLE = "ADMIN"; // private static final String ACTUATOR_ROLE = "ACTUATOR"; // // private final CredentialsProperties credentialsProperties; // // public WebSecurityConfig(CredentialsProperties credentialsProperties) { // this.credentialsProperties = credentialsProperties; // } // // @Override // protected void configure(HttpSecurity http) throws Exception { // //We disable csrf protection for actuator endpoints so we can post with curl // //ex : the refresh endpoint // http.csrf().ignoringRequestMatchers(EndpointRequest.toAnyEndpoint()); // // http.logout() // .logoutSuccessUrl("/") // .invalidateHttpSession(true) // .clearAuthentication(true) // .logoutSuccessHandler(logoutHandler()) // .logoutRequestMatcher(new AntPathRequestMatcher("/logout")); // // http.authorizeRequests() // .antMatchers(BASIC_AUTH_ENDPOINT) // .hasRole(ADMIN_ROLE) // .requestMatchers(EndpointRequest.toAnyEndpoint()) // .hasRole(ACTUATOR_ROLE) // .and() // .httpBasic(); // } // // @Bean // public InMemoryUserDetailsManager inMemoryUserDetailsManager() { // return new InMemoryUserDetailsManager( // User.withDefaultPasswordEncoder() // .username(credentialsProperties.getUsername()) // .password(credentialsProperties.getPassword()) // .roles(ADMIN_ROLE, ACTUATOR_ROLE) // .build() // ); // } // // private LogoutSuccessHandler logoutHandler() { // var logoutSuccessHandler = new SimpleUrlLogoutSuccessHandler(); // var redirectStrategy = new DefaultRedirectStrategy(); // // redirectStrategy.setContextRelative(false); // logoutSuccessHandler.setRedirectStrategy(redirectStrategy); // // return logoutSuccessHandler; // } // }
import app.config.BeansFactory; import app.config.WebSecurityConfig; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.PropertySource; import java.util.Arrays;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate; @SpringBootApplication @PropertySource(value = { "file:properties/global.properties", "file:properties/local.properties" }, ignoreResourceNotFound = true) @Import({ WebSecurityConfig.class,
// Path: src/main/java/app/config/BeansFactory.java // @Configuration // @EnableConfigurationProperties(MyPropertyConfigHolder.class) // public class BeansFactory { // // @Bean // public BeanFromConfigurationClass<Task> beanFromConfigurationClass() { // var task = new Task(); // task.setTaskName("fromBeanConfiguration"); // return new BeanFromConfigurationClass<>(Task.class, task); // } // // @Bean // public ServiceWithConfigurationProperties serviceWithConfigurationProperties(MyPropertyConfigHolder myProperty) { // return new ServiceWithConfigurationProperties(myProperty); // } // // @Bean // public ServiceWithProperties serviceWithProperties(@Value("${admin.username}") String valueFromConfig) { // return new ServiceWithProperties(valueFromConfig); // } // // @Bean // public AsyncEvent asyncEvent() { // return new AsyncEvent(); // } // // @Bean // public AsyncLogger asyncLogger(ApplicationEventPublisher eventPublisher) { // return new AsyncLogger(eventPublisher); // } // // @Bean // public MyEventListener myEventListener() { // return new MyEventListener(); // } // // @Bean // public ABeanIWantToMockInterface aBeanIWantToMock() { // return new ABeanIWantToMock(); // } // // @Bean // public UselessBean uselessBean(ABeanIWantToMockInterface aBeanIWantToMock) { // return new UselessBean(aBeanIWantToMock); // } // } // // Path: src/main/java/app/config/WebSecurityConfig.java // @Configuration // @EnableWebSecurity // @EnableConfigurationProperties(CredentialsProperties.class) // public class WebSecurityConfig extends WebSecurityConfigurerAdapter { // // private static final String BASIC_AUTH_ENDPOINT = "/basicauth"; // private static final String ADMIN_ROLE = "ADMIN"; // private static final String ACTUATOR_ROLE = "ACTUATOR"; // // private final CredentialsProperties credentialsProperties; // // public WebSecurityConfig(CredentialsProperties credentialsProperties) { // this.credentialsProperties = credentialsProperties; // } // // @Override // protected void configure(HttpSecurity http) throws Exception { // //We disable csrf protection for actuator endpoints so we can post with curl // //ex : the refresh endpoint // http.csrf().ignoringRequestMatchers(EndpointRequest.toAnyEndpoint()); // // http.logout() // .logoutSuccessUrl("/") // .invalidateHttpSession(true) // .clearAuthentication(true) // .logoutSuccessHandler(logoutHandler()) // .logoutRequestMatcher(new AntPathRequestMatcher("/logout")); // // http.authorizeRequests() // .antMatchers(BASIC_AUTH_ENDPOINT) // .hasRole(ADMIN_ROLE) // .requestMatchers(EndpointRequest.toAnyEndpoint()) // .hasRole(ACTUATOR_ROLE) // .and() // .httpBasic(); // } // // @Bean // public InMemoryUserDetailsManager inMemoryUserDetailsManager() { // return new InMemoryUserDetailsManager( // User.withDefaultPasswordEncoder() // .username(credentialsProperties.getUsername()) // .password(credentialsProperties.getPassword()) // .roles(ADMIN_ROLE, ACTUATOR_ROLE) // .build() // ); // } // // private LogoutSuccessHandler logoutHandler() { // var logoutSuccessHandler = new SimpleUrlLogoutSuccessHandler(); // var redirectStrategy = new DefaultRedirectStrategy(); // // redirectStrategy.setContextRelative(false); // logoutSuccessHandler.setRedirectStrategy(redirectStrategy); // // return logoutSuccessHandler; // } // } // Path: src/main/java/com/mpalourdio/springboottemplate/SpringBootTemplateApplication.java import app.config.BeansFactory; import app.config.WebSecurityConfig; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.PropertySource; import java.util.Arrays; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate; @SpringBootApplication @PropertySource(value = { "file:properties/global.properties", "file:properties/local.properties" }, ignoreResourceNotFound = true) @Import({ WebSecurityConfig.class,
BeansFactory.class,
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/controllers/HttpVersionedApiController.java
// Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // }
import com.mpalourdio.springboottemplate.mediatype.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Collections; import java.util.List;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; /** * Running a GET request here with ACCEPT header = application/vnd.api.v1+json;q=0.9, application/json * will receive response from processV2. * * The same thing will happen if no ACCEPT header is specified * * @link https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html * @link http://allegro.tech/2015/01/Content-headers-or-how-to-version-api.html */ @RestController @RequestMapping("/http") public class HttpVersionedApiController {
// Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // Path: src/main/java/com/mpalourdio/springboottemplate/controllers/HttpVersionedApiController.java import com.mpalourdio.springboottemplate.mediatype.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Collections; import java.util.List; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; /** * Running a GET request here with ACCEPT header = application/vnd.api.v1+json;q=0.9, application/json * will receive response from processV2. * * The same thing will happen if no ACCEPT header is specified * * @link https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html * @link http://allegro.tech/2015/01/Content-headers-or-how-to-version-api.html */ @RestController @RequestMapping("/http") public class HttpVersionedApiController {
@GetMapping(value = "/test", produces = MediaType.APPLICATION_VND_API_V1_VALUE)
mpalourdio/SpringBootTemplate
src/test/java/com/mpalourdio/springboottemplate/controllers/EventControllerTest.java
// Path: src/test/java/com/mpalourdio/springboottemplate/AbstractTestRunner.java // @ExtendWith(SpringExtension.class) // @TestPropertySource(locations = "classpath:test.properties") // @Import({BeansFactory.class}) // public abstract class AbstractTestRunner { // // protected Task task; // protected People people; // // protected void initializeData() { // task = new Task(); // task.setTaskArchived(true); // task.setTaskName("name"); // task.setTaskDescription("description"); // task.setTaskPriority("LOW"); // task.setTaskStatus("ACTIVE"); // // people = new People() // .setName("john") // .setTask(task); // } // // protected String serializeToJson(Object object) throws JsonProcessingException { // return new ObjectMapper().writeValueAsString(object); // } // }
import com.mpalourdio.springboottemplate.AbstractTestRunner; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @SpringBootTest(webEnvironment = WebEnvironment.MOCK) @AutoConfigureMockMvc @AutoConfigureTestDatabase
// Path: src/test/java/com/mpalourdio/springboottemplate/AbstractTestRunner.java // @ExtendWith(SpringExtension.class) // @TestPropertySource(locations = "classpath:test.properties") // @Import({BeansFactory.class}) // public abstract class AbstractTestRunner { // // protected Task task; // protected People people; // // protected void initializeData() { // task = new Task(); // task.setTaskArchived(true); // task.setTaskName("name"); // task.setTaskDescription("description"); // task.setTaskPriority("LOW"); // task.setTaskStatus("ACTIVE"); // // people = new People() // .setName("john") // .setTask(task); // } // // protected String serializeToJson(Object object) throws JsonProcessingException { // return new ObjectMapper().writeValueAsString(object); // } // } // Path: src/test/java/com/mpalourdio/springboottemplate/controllers/EventControllerTest.java import com.mpalourdio.springboottemplate.AbstractTestRunner; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @SpringBootTest(webEnvironment = WebEnvironment.MOCK) @AutoConfigureMockMvc @AutoConfigureTestDatabase
class EventControllerTest extends AbstractTestRunner {
mpalourdio/SpringBootTemplate
src/test/java/com/mpalourdio/springboottemplate/controllers/HomeControllerTest.java
// Path: src/test/java/com/mpalourdio/springboottemplate/AbstractTestRunner.java // @ExtendWith(SpringExtension.class) // @TestPropertySource(locations = "classpath:test.properties") // @Import({BeansFactory.class}) // public abstract class AbstractTestRunner { // // protected Task task; // protected People people; // // protected void initializeData() { // task = new Task(); // task.setTaskArchived(true); // task.setTaskName("name"); // task.setTaskDescription("description"); // task.setTaskPriority("LOW"); // task.setTaskStatus("ACTIVE"); // // people = new People() // .setName("john") // .setTask(task); // } // // protected String serializeToJson(Object object) throws JsonProcessingException { // return new ObjectMapper().writeValueAsString(object); // } // }
import com.google.gson.Gson; import com.mpalourdio.springboottemplate.AbstractTestRunner; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @SpringBootTest @AutoConfigureMockMvc @AutoConfigureTestDatabase
// Path: src/test/java/com/mpalourdio/springboottemplate/AbstractTestRunner.java // @ExtendWith(SpringExtension.class) // @TestPropertySource(locations = "classpath:test.properties") // @Import({BeansFactory.class}) // public abstract class AbstractTestRunner { // // protected Task task; // protected People people; // // protected void initializeData() { // task = new Task(); // task.setTaskArchived(true); // task.setTaskName("name"); // task.setTaskDescription("description"); // task.setTaskPriority("LOW"); // task.setTaskStatus("ACTIVE"); // // people = new People() // .setName("john") // .setTask(task); // } // // protected String serializeToJson(Object object) throws JsonProcessingException { // return new ObjectMapper().writeValueAsString(object); // } // } // Path: src/test/java/com/mpalourdio/springboottemplate/controllers/HomeControllerTest.java import com.google.gson.Gson; import com.mpalourdio.springboottemplate.AbstractTestRunner; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @SpringBootTest @AutoConfigureMockMvc @AutoConfigureTestDatabase
class HomeControllerTest extends AbstractTestRunner {
mpalourdio/SpringBootTemplate
src/test/java/com/mpalourdio/springboottemplate/service/EnumableTest.java
// Path: src/main/java/com/mpalourdio/springboottemplate/model/MyEnum.java // @JsonFormat(shape = JsonFormat.Shape.OBJECT) // public enum MyEnum { // // TOTO("tata"); // // private final String value; // // MyEnum(String value) { // this.value = value; // } // // @JsonValue // public String getValue() { // return value; // } // }
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.mpalourdio.springboottemplate.model.MyEnum; import org.junit.jupiter.api.Test; import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertEquals;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.service; class EnumableTest { @Test void testCanSerializeWithEnums() throws JsonProcessingException { var enumable = new Enumable();
// Path: src/main/java/com/mpalourdio/springboottemplate/model/MyEnum.java // @JsonFormat(shape = JsonFormat.Shape.OBJECT) // public enum MyEnum { // // TOTO("tata"); // // private final String value; // // MyEnum(String value) { // this.value = value; // } // // @JsonValue // public String getValue() { // return value; // } // } // Path: src/test/java/com/mpalourdio/springboottemplate/service/EnumableTest.java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.mpalourdio.springboottemplate.model.MyEnum; import org.junit.jupiter.api.Test; import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertEquals; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.service; class EnumableTest { @Test void testCanSerializeWithEnums() throws JsonProcessingException { var enumable = new Enumable();
enumable.myEnum = MyEnum.TOTO;
mpalourdio/SpringBootTemplate
src/main/java/com/mpalourdio/springboottemplate/controllers/BasicAuthController.java
// Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // }
import com.mpalourdio.springboottemplate.mediatype.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController;
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @RestController public class BasicAuthController {
// Path: src/main/java/com/mpalourdio/springboottemplate/mediatype/MediaType.java // public final class MediaType extends org.springframework.http.MediaType { // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V1; // public static final String APPLICATION_VND_API_V1_VALUE = "application/vnd.api.v1+json;charset=UTF-8"; // // public static final org.springframework.http.MediaType APPLICATION_VND_API_V2; // public static final String APPLICATION_VND_API_V2_VALUE = "application/vnd.api.v2+json;charset=UTF-8"; // // private MediaType(String type) { // super(type); // } // // static { // var applicationType = "application"; // APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, "vnd.api.v1+json", StandardCharsets.UTF_8); // APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, "vnd.api.v2+json", StandardCharsets.UTF_8); // } // } // Path: src/main/java/com/mpalourdio/springboottemplate/controllers/BasicAuthController.java import com.mpalourdio.springboottemplate.mediatype.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; /* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.controllers; @RestController public class BasicAuthController {
@GetMapping(value = "/basicauth", produces = MediaType.APPLICATION_JSON_VALUE)
irccloud/android
src/com/irccloud/android/BackgroundTaskWorker.java
// Path: src/com/irccloud/android/data/IRCCloudDatabase.java // @Database(entities = {RecentConversation.class, BackgroundTask.class, LogExport.class, Notification.class, Notification_LastSeenEID.class, Notification_ServerNick.class, Avatar.class}, version = IRCCloudDatabase.VERSION, exportSchema = false) // public abstract class IRCCloudDatabase extends RoomDatabase { // public static final String NAME = "irccloud"; // public static final int VERSION = 13; // // public abstract RecentConversationsList.RecentConversationsDao RecentConversationsDao(); // public abstract BackgroundTaskWorker.BackgroundTasksDao BackgroundTasksDao(); // public abstract LogExportsList.LogExportsDao LogExportsDao(); // public abstract NotificationsList.NotificationsDao NotificationsDao(); // public abstract AvatarsList.AvatarsDao AvatarsDao(); // // private static IRCCloudDatabase sInstance; // public static IRCCloudDatabase getInstance() { // if (sInstance == null) { // synchronized (IRCCloudDatabase.class) { // if (sInstance == null) { // sInstance = Room.databaseBuilder(IRCCloudApplication.getInstance().getApplicationContext(), IRCCloudDatabase.class, NAME) // .fallbackToDestructiveMigrationFrom(12) // .fallbackToDestructiveMigration() // .fallbackToDestructiveMigrationOnDowngrade() // .allowMainThreadQueries() // .build(); // } // } // } // return sInstance; // } // } // // Path: src/com/irccloud/android/data/model/BackgroundTask.java // @Entity // public class BackgroundTask { // @Ignore // public static final int TYPE_FCM_REGISTER = 1; // @Ignore // public static final int TYPE_FCM_UNREGISTER = 2; // // @PrimaryKey // @NonNull // private String tag; // // private int type; // // private String session; // // private String data; // // public String getTag() { // return tag; // } // // public void setTag(String tag) { // this.tag = tag; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // public String getSession() { // return session; // } // // public void setSession(String session) { // this.session = session; // } // // public String getData() { // return data; // } // // public void setData(String data) { // this.data = data; // } // }
import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Looper; import android.util.Log; import androidx.annotation.NonNull; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.OnConflictStrategy; import androidx.room.Query; import androidx.room.Update; import androidx.work.Constraints; import androidx.work.Data; import androidx.work.ExistingWorkPolicy; import androidx.work.ListenableWorker; import androidx.work.NetworkType; import androidx.work.OneTimeWorkRequest; import androidx.work.WorkManager; import androidx.work.Worker; import androidx.work.WorkerParameters; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.messaging.FirebaseMessaging; import com.irccloud.android.data.IRCCloudDatabase; import com.irccloud.android.data.model.BackgroundTask; import org.json.JSONObject; import java.util.List;
/* * Copyright (c) 2015 IRCCloud, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.irccloud.android; public class BackgroundTaskWorker extends Worker { @Dao public interface BackgroundTasksDao { @Query("SELECT * FROM BackgroundTask")
// Path: src/com/irccloud/android/data/IRCCloudDatabase.java // @Database(entities = {RecentConversation.class, BackgroundTask.class, LogExport.class, Notification.class, Notification_LastSeenEID.class, Notification_ServerNick.class, Avatar.class}, version = IRCCloudDatabase.VERSION, exportSchema = false) // public abstract class IRCCloudDatabase extends RoomDatabase { // public static final String NAME = "irccloud"; // public static final int VERSION = 13; // // public abstract RecentConversationsList.RecentConversationsDao RecentConversationsDao(); // public abstract BackgroundTaskWorker.BackgroundTasksDao BackgroundTasksDao(); // public abstract LogExportsList.LogExportsDao LogExportsDao(); // public abstract NotificationsList.NotificationsDao NotificationsDao(); // public abstract AvatarsList.AvatarsDao AvatarsDao(); // // private static IRCCloudDatabase sInstance; // public static IRCCloudDatabase getInstance() { // if (sInstance == null) { // synchronized (IRCCloudDatabase.class) { // if (sInstance == null) { // sInstance = Room.databaseBuilder(IRCCloudApplication.getInstance().getApplicationContext(), IRCCloudDatabase.class, NAME) // .fallbackToDestructiveMigrationFrom(12) // .fallbackToDestructiveMigration() // .fallbackToDestructiveMigrationOnDowngrade() // .allowMainThreadQueries() // .build(); // } // } // } // return sInstance; // } // } // // Path: src/com/irccloud/android/data/model/BackgroundTask.java // @Entity // public class BackgroundTask { // @Ignore // public static final int TYPE_FCM_REGISTER = 1; // @Ignore // public static final int TYPE_FCM_UNREGISTER = 2; // // @PrimaryKey // @NonNull // private String tag; // // private int type; // // private String session; // // private String data; // // public String getTag() { // return tag; // } // // public void setTag(String tag) { // this.tag = tag; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // public String getSession() { // return session; // } // // public void setSession(String session) { // this.session = session; // } // // public String getData() { // return data; // } // // public void setData(String data) { // this.data = data; // } // } // Path: src/com/irccloud/android/BackgroundTaskWorker.java import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Looper; import android.util.Log; import androidx.annotation.NonNull; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.OnConflictStrategy; import androidx.room.Query; import androidx.room.Update; import androidx.work.Constraints; import androidx.work.Data; import androidx.work.ExistingWorkPolicy; import androidx.work.ListenableWorker; import androidx.work.NetworkType; import androidx.work.OneTimeWorkRequest; import androidx.work.WorkManager; import androidx.work.Worker; import androidx.work.WorkerParameters; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.messaging.FirebaseMessaging; import com.irccloud.android.data.IRCCloudDatabase; import com.irccloud.android.data.model.BackgroundTask; import org.json.JSONObject; import java.util.List; /* * Copyright (c) 2015 IRCCloud, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.irccloud.android; public class BackgroundTaskWorker extends Worker { @Dao public interface BackgroundTasksDao { @Query("SELECT * FROM BackgroundTask")
List<BackgroundTask> getBackgroundTasks();
irccloud/android
src/com/irccloud/android/BackgroundTaskWorker.java
// Path: src/com/irccloud/android/data/IRCCloudDatabase.java // @Database(entities = {RecentConversation.class, BackgroundTask.class, LogExport.class, Notification.class, Notification_LastSeenEID.class, Notification_ServerNick.class, Avatar.class}, version = IRCCloudDatabase.VERSION, exportSchema = false) // public abstract class IRCCloudDatabase extends RoomDatabase { // public static final String NAME = "irccloud"; // public static final int VERSION = 13; // // public abstract RecentConversationsList.RecentConversationsDao RecentConversationsDao(); // public abstract BackgroundTaskWorker.BackgroundTasksDao BackgroundTasksDao(); // public abstract LogExportsList.LogExportsDao LogExportsDao(); // public abstract NotificationsList.NotificationsDao NotificationsDao(); // public abstract AvatarsList.AvatarsDao AvatarsDao(); // // private static IRCCloudDatabase sInstance; // public static IRCCloudDatabase getInstance() { // if (sInstance == null) { // synchronized (IRCCloudDatabase.class) { // if (sInstance == null) { // sInstance = Room.databaseBuilder(IRCCloudApplication.getInstance().getApplicationContext(), IRCCloudDatabase.class, NAME) // .fallbackToDestructiveMigrationFrom(12) // .fallbackToDestructiveMigration() // .fallbackToDestructiveMigrationOnDowngrade() // .allowMainThreadQueries() // .build(); // } // } // } // return sInstance; // } // } // // Path: src/com/irccloud/android/data/model/BackgroundTask.java // @Entity // public class BackgroundTask { // @Ignore // public static final int TYPE_FCM_REGISTER = 1; // @Ignore // public static final int TYPE_FCM_UNREGISTER = 2; // // @PrimaryKey // @NonNull // private String tag; // // private int type; // // private String session; // // private String data; // // public String getTag() { // return tag; // } // // public void setTag(String tag) { // this.tag = tag; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // public String getSession() { // return session; // } // // public void setSession(String session) { // this.session = session; // } // // public String getData() { // return data; // } // // public void setData(String data) { // this.data = data; // } // }
import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Looper; import android.util.Log; import androidx.annotation.NonNull; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.OnConflictStrategy; import androidx.room.Query; import androidx.room.Update; import androidx.work.Constraints; import androidx.work.Data; import androidx.work.ExistingWorkPolicy; import androidx.work.ListenableWorker; import androidx.work.NetworkType; import androidx.work.OneTimeWorkRequest; import androidx.work.WorkManager; import androidx.work.Worker; import androidx.work.WorkerParameters; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.messaging.FirebaseMessaging; import com.irccloud.android.data.IRCCloudDatabase; import com.irccloud.android.data.model.BackgroundTask; import org.json.JSONObject; import java.util.List;
/* * Copyright (c) 2015 IRCCloud, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.irccloud.android; public class BackgroundTaskWorker extends Worker { @Dao public interface BackgroundTasksDao { @Query("SELECT * FROM BackgroundTask") List<BackgroundTask> getBackgroundTasks(); @Query("SELECT * FROM BackgroundTask WHERE type = :type") List<BackgroundTask> getBackgroundTasks(int type); @Query("SELECT * FROM BackgroundTask WHERE type = :type AND data = :data") List<BackgroundTask> getBackgroundTasks(int type, String data); @Query("SELECT * FROM BackgroundTask WHERE tag = :tag LIMIT 1") BackgroundTask getBackgroundTask(String tag); @Insert(onConflict = OnConflictStrategy.REPLACE) void insert(BackgroundTask backgroundTask); @Update void update(BackgroundTask backgroundTask); @Delete void delete(BackgroundTask backgroundTask); } public BackgroundTaskWorker(@NonNull Context appContext, @NonNull WorkerParameters params) { super(appContext, params); } public static void registerGCM(String token) {
// Path: src/com/irccloud/android/data/IRCCloudDatabase.java // @Database(entities = {RecentConversation.class, BackgroundTask.class, LogExport.class, Notification.class, Notification_LastSeenEID.class, Notification_ServerNick.class, Avatar.class}, version = IRCCloudDatabase.VERSION, exportSchema = false) // public abstract class IRCCloudDatabase extends RoomDatabase { // public static final String NAME = "irccloud"; // public static final int VERSION = 13; // // public abstract RecentConversationsList.RecentConversationsDao RecentConversationsDao(); // public abstract BackgroundTaskWorker.BackgroundTasksDao BackgroundTasksDao(); // public abstract LogExportsList.LogExportsDao LogExportsDao(); // public abstract NotificationsList.NotificationsDao NotificationsDao(); // public abstract AvatarsList.AvatarsDao AvatarsDao(); // // private static IRCCloudDatabase sInstance; // public static IRCCloudDatabase getInstance() { // if (sInstance == null) { // synchronized (IRCCloudDatabase.class) { // if (sInstance == null) { // sInstance = Room.databaseBuilder(IRCCloudApplication.getInstance().getApplicationContext(), IRCCloudDatabase.class, NAME) // .fallbackToDestructiveMigrationFrom(12) // .fallbackToDestructiveMigration() // .fallbackToDestructiveMigrationOnDowngrade() // .allowMainThreadQueries() // .build(); // } // } // } // return sInstance; // } // } // // Path: src/com/irccloud/android/data/model/BackgroundTask.java // @Entity // public class BackgroundTask { // @Ignore // public static final int TYPE_FCM_REGISTER = 1; // @Ignore // public static final int TYPE_FCM_UNREGISTER = 2; // // @PrimaryKey // @NonNull // private String tag; // // private int type; // // private String session; // // private String data; // // public String getTag() { // return tag; // } // // public void setTag(String tag) { // this.tag = tag; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // public String getSession() { // return session; // } // // public void setSession(String session) { // this.session = session; // } // // public String getData() { // return data; // } // // public void setData(String data) { // this.data = data; // } // } // Path: src/com/irccloud/android/BackgroundTaskWorker.java import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Looper; import android.util.Log; import androidx.annotation.NonNull; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.OnConflictStrategy; import androidx.room.Query; import androidx.room.Update; import androidx.work.Constraints; import androidx.work.Data; import androidx.work.ExistingWorkPolicy; import androidx.work.ListenableWorker; import androidx.work.NetworkType; import androidx.work.OneTimeWorkRequest; import androidx.work.WorkManager; import androidx.work.Worker; import androidx.work.WorkerParameters; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.messaging.FirebaseMessaging; import com.irccloud.android.data.IRCCloudDatabase; import com.irccloud.android.data.model.BackgroundTask; import org.json.JSONObject; import java.util.List; /* * Copyright (c) 2015 IRCCloud, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.irccloud.android; public class BackgroundTaskWorker extends Worker { @Dao public interface BackgroundTasksDao { @Query("SELECT * FROM BackgroundTask") List<BackgroundTask> getBackgroundTasks(); @Query("SELECT * FROM BackgroundTask WHERE type = :type") List<BackgroundTask> getBackgroundTasks(int type); @Query("SELECT * FROM BackgroundTask WHERE type = :type AND data = :data") List<BackgroundTask> getBackgroundTasks(int type, String data); @Query("SELECT * FROM BackgroundTask WHERE tag = :tag LIMIT 1") BackgroundTask getBackgroundTask(String tag); @Insert(onConflict = OnConflictStrategy.REPLACE) void insert(BackgroundTask backgroundTask); @Update void update(BackgroundTask backgroundTask); @Delete void delete(BackgroundTask backgroundTask); } public BackgroundTaskWorker(@NonNull Context appContext, @NonNull WorkerParameters params) { super(appContext, params); } public static void registerGCM(String token) {
List<BackgroundTask> tasks = IRCCloudDatabase.getInstance().BackgroundTasksDao().getBackgroundTasks(BackgroundTask.TYPE_FCM_REGISTER);
irccloud/android
src/com/irccloud/android/data/collection/UsersList.java
// Path: src/com/irccloud/android/AlphanumComparator.java // public class AlphanumComparator implements Comparator<CharSequence> { // // /** // * The collator used for comparison of the alpha part // */ // private final Collator collator; // // /** // * Create comparator using platform default collator. // * (equivalent to using Collator.getInstance()) // */ // public AlphanumComparator() { // this(Collator.getInstance()); // } // // /** // * Create comparator using specified collator // */ // public AlphanumComparator(final Collator collator) { // if (collator == null) // throw new IllegalArgumentException("collator must not be null"); // this.collator = collator; // } // // /** // * Ideally this would be generalized to Character.isDigit(), but I have // * no knowledge about arabic language and other digits, so I treat // * them as characters... // */ // private static boolean isDigit(final int character) { // // code between ASCII '0' and '9'? // return character >= 48 && character <= 57; // } // // /** // * Get subsequence of only characters or only digits, but not mixed // */ // private static CharSequence getChunk(final CharSequence charSeq, final int start) { // int index = start; // final int length = charSeq.length(); // final boolean mode = isDigit(charSeq.charAt(index++)); // while (index < length) { // if (isDigit(charSeq.charAt(index)) != mode) // break; // ++index; // } // return charSeq.subSequence(start, index); // } // // /** // * Implements Comparator<CharSequence>.compare // */ // public int compare(final CharSequence charSeq1, final CharSequence charSeq2) { // final int length1 = charSeq1.length(); // final int length2 = charSeq2.length(); // int index1 = 0; // int index2 = 0; // int result = 0; // while (result == 0 && index1 < length1 && index2 < length2) { // final CharSequence chunk1 = getChunk(charSeq1, index1); // index1 += chunk1.length(); // // final CharSequence chunk2 = getChunk(charSeq2, index2); // index2 += chunk2.length(); // // if (isDigit(chunk1.charAt(0)) && isDigit(chunk2.charAt(0))) { // final int clen1 = chunk1.length(); // final int clen2 = chunk2.length(); // // count and skip leading zeros // int zeros1 = 0; // while (zeros1 < clen1 && chunk1.charAt(zeros1) == '0') // ++zeros1; // // count and skip leading zeros // int zeros2 = 0; // while (zeros2 < clen2 && chunk2.charAt(zeros2) == '0') // ++zeros2; // // the longer run of non-zero digits is greater // result = (clen1 - zeros1) - (clen2 - zeros2); // // if the length is the same, the first differing digit decides // // which one is deemed greater. // int subi1 = zeros1; // int subi2 = zeros2; // while (result == 0 && subi1 < clen1 && subi2 < clen2) { // result = chunk1.charAt(subi1++) - chunk2.charAt(subi2++); // } // // if still no difference, the longer zeros-prefix is greater // if (result == 0) // result = subi1 - subi2; // } else { // // in case we are working with Strings, toString() doesn't create // // any objects (String.toString() returns the same string itself). // result = collator.compare(chunk1.toString(), chunk2.toString()); // } // } // // if there was no difference at all, let the longer one be the greater one // if (result == 0) // result = length1 - length2; // // limit result to (-1, 0, or 1) // return Integer.signum(result); // } // } // // Path: src/com/irccloud/android/data/model/User.java // public class User { // //@Unique(unique = false, uniqueGroups = 1) // public int cid; // // //@Unique(unique = false, uniqueGroups = 1) // public int bid; // // //@Unique(unique = false, uniqueGroups = 1) // public String nick; // // public String old_nick = null; // // public String nick_lowercase; // // public String hostmask; // // public String mode; // // public int away; // // public String away_msg; // // public String ircserver; // // public String display_name; // // public int joined; // // public long last_mention = -1; // public long last_message = -1; // // public String getDisplayName() { // if(display_name != null && display_name.length() > 0) // return display_name; // else // return nick; // } // // public String toString() { // return "{cid: " + cid + ", bid: " + bid + ", nick: " + nick + ", hostmask: " + hostmask + "}"; // } // }
import android.annotation.SuppressLint; import com.irccloud.android.AlphanumComparator; import com.irccloud.android.data.model.User; import java.text.Collator; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.TreeMap;
/* * Copyright (c) 2015 IRCCloud, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.irccloud.android.data.collection; @SuppressLint("UseSparseArrays") public class UsersList {
// Path: src/com/irccloud/android/AlphanumComparator.java // public class AlphanumComparator implements Comparator<CharSequence> { // // /** // * The collator used for comparison of the alpha part // */ // private final Collator collator; // // /** // * Create comparator using platform default collator. // * (equivalent to using Collator.getInstance()) // */ // public AlphanumComparator() { // this(Collator.getInstance()); // } // // /** // * Create comparator using specified collator // */ // public AlphanumComparator(final Collator collator) { // if (collator == null) // throw new IllegalArgumentException("collator must not be null"); // this.collator = collator; // } // // /** // * Ideally this would be generalized to Character.isDigit(), but I have // * no knowledge about arabic language and other digits, so I treat // * them as characters... // */ // private static boolean isDigit(final int character) { // // code between ASCII '0' and '9'? // return character >= 48 && character <= 57; // } // // /** // * Get subsequence of only characters or only digits, but not mixed // */ // private static CharSequence getChunk(final CharSequence charSeq, final int start) { // int index = start; // final int length = charSeq.length(); // final boolean mode = isDigit(charSeq.charAt(index++)); // while (index < length) { // if (isDigit(charSeq.charAt(index)) != mode) // break; // ++index; // } // return charSeq.subSequence(start, index); // } // // /** // * Implements Comparator<CharSequence>.compare // */ // public int compare(final CharSequence charSeq1, final CharSequence charSeq2) { // final int length1 = charSeq1.length(); // final int length2 = charSeq2.length(); // int index1 = 0; // int index2 = 0; // int result = 0; // while (result == 0 && index1 < length1 && index2 < length2) { // final CharSequence chunk1 = getChunk(charSeq1, index1); // index1 += chunk1.length(); // // final CharSequence chunk2 = getChunk(charSeq2, index2); // index2 += chunk2.length(); // // if (isDigit(chunk1.charAt(0)) && isDigit(chunk2.charAt(0))) { // final int clen1 = chunk1.length(); // final int clen2 = chunk2.length(); // // count and skip leading zeros // int zeros1 = 0; // while (zeros1 < clen1 && chunk1.charAt(zeros1) == '0') // ++zeros1; // // count and skip leading zeros // int zeros2 = 0; // while (zeros2 < clen2 && chunk2.charAt(zeros2) == '0') // ++zeros2; // // the longer run of non-zero digits is greater // result = (clen1 - zeros1) - (clen2 - zeros2); // // if the length is the same, the first differing digit decides // // which one is deemed greater. // int subi1 = zeros1; // int subi2 = zeros2; // while (result == 0 && subi1 < clen1 && subi2 < clen2) { // result = chunk1.charAt(subi1++) - chunk2.charAt(subi2++); // } // // if still no difference, the longer zeros-prefix is greater // if (result == 0) // result = subi1 - subi2; // } else { // // in case we are working with Strings, toString() doesn't create // // any objects (String.toString() returns the same string itself). // result = collator.compare(chunk1.toString(), chunk2.toString()); // } // } // // if there was no difference at all, let the longer one be the greater one // if (result == 0) // result = length1 - length2; // // limit result to (-1, 0, or 1) // return Integer.signum(result); // } // } // // Path: src/com/irccloud/android/data/model/User.java // public class User { // //@Unique(unique = false, uniqueGroups = 1) // public int cid; // // //@Unique(unique = false, uniqueGroups = 1) // public int bid; // // //@Unique(unique = false, uniqueGroups = 1) // public String nick; // // public String old_nick = null; // // public String nick_lowercase; // // public String hostmask; // // public String mode; // // public int away; // // public String away_msg; // // public String ircserver; // // public String display_name; // // public int joined; // // public long last_mention = -1; // public long last_message = -1; // // public String getDisplayName() { // if(display_name != null && display_name.length() > 0) // return display_name; // else // return nick; // } // // public String toString() { // return "{cid: " + cid + ", bid: " + bid + ", nick: " + nick + ", hostmask: " + hostmask + "}"; // } // } // Path: src/com/irccloud/android/data/collection/UsersList.java import android.annotation.SuppressLint; import com.irccloud.android.AlphanumComparator; import com.irccloud.android.data.model.User; import java.text.Collator; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.TreeMap; /* * Copyright (c) 2015 IRCCloud, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.irccloud.android.data.collection; @SuppressLint("UseSparseArrays") public class UsersList {
private final HashMap<Integer, TreeMap<String, User>> users;
tielei/AsyncProgrammingDemos
AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/multitask/multilevelcaching/diskcache/mock/MockImageDiskCache.java
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/AsyncCallback.java // public interface AsyncCallback <D> { // void onResult(D data); // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/multitask/multilevelcaching/diskcache/ImageDiskCache.java // public interface ImageDiskCache { // /** // * 异步获取缓存的Bitmap对象. // * @param key // * @param callback 用于返回缓存的Bitmap对象 // */ // void getImage(String key, AsyncCallback<Bitmap> callback); // /** // * 保存Bitmap对象到缓存中. // * @param key // * @param bitmap 要保存的Bitmap对象 // * @param callback 用于返回当前保存操作的结果是成功还是失败. // */ // void putImage(String key, Bitmap bitmap, AsyncCallback<Boolean> callback); // }
import android.graphics.Bitmap; import android.os.Handler; import android.os.Looper; import com.zhangtielei.demos.async.programming.common.AsyncCallback; import com.zhangtielei.demos.async.programming.multitask.multilevelcaching.diskcache.ImageDiskCache; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit;
/* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.multitask.multilevelcaching.diskcache.mock; /** * Created by Tielei Zhang on 16/5/17. */ public class MockImageDiskCache implements ImageDiskCache { private ExecutorService executorService = Executors.newCachedThreadPool(); private Handler mainHandler = new Handler(Looper.getMainLooper()); private Random rand = new Random(); @Override
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/AsyncCallback.java // public interface AsyncCallback <D> { // void onResult(D data); // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/multitask/multilevelcaching/diskcache/ImageDiskCache.java // public interface ImageDiskCache { // /** // * 异步获取缓存的Bitmap对象. // * @param key // * @param callback 用于返回缓存的Bitmap对象 // */ // void getImage(String key, AsyncCallback<Bitmap> callback); // /** // * 保存Bitmap对象到缓存中. // * @param key // * @param bitmap 要保存的Bitmap对象 // * @param callback 用于返回当前保存操作的结果是成功还是失败. // */ // void putImage(String key, Bitmap bitmap, AsyncCallback<Boolean> callback); // } // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/multitask/multilevelcaching/diskcache/mock/MockImageDiskCache.java import android.graphics.Bitmap; import android.os.Handler; import android.os.Looper; import com.zhangtielei.demos.async.programming.common.AsyncCallback; import com.zhangtielei.demos.async.programming.multitask.multilevelcaching.diskcache.ImageDiskCache; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.multitask.multilevelcaching.diskcache.mock; /** * Created by Tielei Zhang on 16/5/17. */ public class MockImageDiskCache implements ImageDiskCache { private ExecutorService executorService = Executors.newCachedThreadPool(); private Handler mainHandler = new Handler(Looper.getMainLooper()); private Random rand = new Random(); @Override
public void getImage(String key, final AsyncCallback<Bitmap> callback) {
tielei/AsyncProgrammingDemos
AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/multitask/pagecaching/localcache/mock/MockLocalDataCache.java
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/AsyncCallback.java // public interface AsyncCallback <D> { // void onResult(D data); // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/multitask/pagecaching/localcache/LocalDataCache.java // public interface LocalDataCache { // /** // * 异步获取本地缓存的HttpResponse对象. // * @param key // * @param callback 用于返回缓存对象 // */ // void getCachingData(String key, AsyncCallback<HttpResponse> callback); // // /** // * 保存HttpResponse对象到缓存中. // * @param key // * @param data 要保存的HttpResponse对象 // * @param callback 用于返回当前保存操作的结果是成功还是失败. // */ // void putCachingData(String key, HttpResponse data, AsyncCallback<Boolean> callback); // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/multitask/pagecaching/model/HttpResponse.java // public class HttpResponse { // }
import android.os.Handler; import android.os.Looper; import com.zhangtielei.demos.async.programming.common.AsyncCallback; import com.zhangtielei.demos.async.programming.multitask.pagecaching.localcache.LocalDataCache; import com.zhangtielei.demos.async.programming.multitask.pagecaching.model.HttpResponse; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit;
/* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.multitask.pagecaching.localcache.mock; /** * Created by Tielei Zhang on 16/5/17. * 本地页面Cache的一个假的实现. */ public class MockLocalDataCache implements LocalDataCache { private ExecutorService executorService = Executors.newCachedThreadPool(); private Handler mainHandler = new Handler(Looper.getMainLooper()); private Random rand = new Random(); @Override
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/AsyncCallback.java // public interface AsyncCallback <D> { // void onResult(D data); // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/multitask/pagecaching/localcache/LocalDataCache.java // public interface LocalDataCache { // /** // * 异步获取本地缓存的HttpResponse对象. // * @param key // * @param callback 用于返回缓存对象 // */ // void getCachingData(String key, AsyncCallback<HttpResponse> callback); // // /** // * 保存HttpResponse对象到缓存中. // * @param key // * @param data 要保存的HttpResponse对象 // * @param callback 用于返回当前保存操作的结果是成功还是失败. // */ // void putCachingData(String key, HttpResponse data, AsyncCallback<Boolean> callback); // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/multitask/pagecaching/model/HttpResponse.java // public class HttpResponse { // } // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/multitask/pagecaching/localcache/mock/MockLocalDataCache.java import android.os.Handler; import android.os.Looper; import com.zhangtielei.demos.async.programming.common.AsyncCallback; import com.zhangtielei.demos.async.programming.multitask.pagecaching.localcache.LocalDataCache; import com.zhangtielei.demos.async.programming.multitask.pagecaching.model.HttpResponse; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.multitask.pagecaching.localcache.mock; /** * Created by Tielei Zhang on 16/5/17. * 本地页面Cache的一个假的实现. */ public class MockLocalDataCache implements LocalDataCache { private ExecutorService executorService = Executors.newCachedThreadPool(); private Handler mainHandler = new Handler(Looper.getMainLooper()); private Random rand = new Random(); @Override
public void getCachingData(String key, final AsyncCallback<HttpResponse> callback) {
tielei/AsyncProgrammingDemos
AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/multitask/pagecaching/localcache/mock/MockLocalDataCache.java
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/AsyncCallback.java // public interface AsyncCallback <D> { // void onResult(D data); // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/multitask/pagecaching/localcache/LocalDataCache.java // public interface LocalDataCache { // /** // * 异步获取本地缓存的HttpResponse对象. // * @param key // * @param callback 用于返回缓存对象 // */ // void getCachingData(String key, AsyncCallback<HttpResponse> callback); // // /** // * 保存HttpResponse对象到缓存中. // * @param key // * @param data 要保存的HttpResponse对象 // * @param callback 用于返回当前保存操作的结果是成功还是失败. // */ // void putCachingData(String key, HttpResponse data, AsyncCallback<Boolean> callback); // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/multitask/pagecaching/model/HttpResponse.java // public class HttpResponse { // }
import android.os.Handler; import android.os.Looper; import com.zhangtielei.demos.async.programming.common.AsyncCallback; import com.zhangtielei.demos.async.programming.multitask.pagecaching.localcache.LocalDataCache; import com.zhangtielei.demos.async.programming.multitask.pagecaching.model.HttpResponse; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit;
/* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.multitask.pagecaching.localcache.mock; /** * Created by Tielei Zhang on 16/5/17. * 本地页面Cache的一个假的实现. */ public class MockLocalDataCache implements LocalDataCache { private ExecutorService executorService = Executors.newCachedThreadPool(); private Handler mainHandler = new Handler(Looper.getMainLooper()); private Random rand = new Random(); @Override
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/AsyncCallback.java // public interface AsyncCallback <D> { // void onResult(D data); // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/multitask/pagecaching/localcache/LocalDataCache.java // public interface LocalDataCache { // /** // * 异步获取本地缓存的HttpResponse对象. // * @param key // * @param callback 用于返回缓存对象 // */ // void getCachingData(String key, AsyncCallback<HttpResponse> callback); // // /** // * 保存HttpResponse对象到缓存中. // * @param key // * @param data 要保存的HttpResponse对象 // * @param callback 用于返回当前保存操作的结果是成功还是失败. // */ // void putCachingData(String key, HttpResponse data, AsyncCallback<Boolean> callback); // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/multitask/pagecaching/model/HttpResponse.java // public class HttpResponse { // } // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/multitask/pagecaching/localcache/mock/MockLocalDataCache.java import android.os.Handler; import android.os.Looper; import com.zhangtielei.demos.async.programming.common.AsyncCallback; import com.zhangtielei.demos.async.programming.multitask.pagecaching.localcache.LocalDataCache; import com.zhangtielei.demos.async.programming.multitask.pagecaching.model.HttpResponse; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.multitask.pagecaching.localcache.mock; /** * Created by Tielei Zhang on 16/5/17. * 本地页面Cache的一个假的实现. */ public class MockLocalDataCache implements LocalDataCache { private ExecutorService executorService = Executors.newCachedThreadPool(); private Handler mainHandler = new Handler(Looper.getMainLooper()); private Random rand = new Random(); @Override
public void getCachingData(String key, final AsyncCallback<HttpResponse> callback) {
tielei/AsyncProgrammingDemos
AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/queueing/v1/TaskQueueDemoActivity.java
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // }
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import java.util.Random; import java.util.concurrent.TimeUnit;
/* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.queueing.v1; /** * 演示基于TSQ的任务队列的运行情况. */ public class TaskQueueDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView; private TaskQueue taskQueue; private static long taskIdCounter; private Random rand1 = new Random(); private Random rand2 = new Random(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_display); description = (TextView) findViewById(R.id.description); logTextView = (TextView) findViewById(R.id.log_display); description.setText(R.string.queueing_demo1_description); taskQueue = new TSQBasedTaskQueue(); taskQueue.setListener(new TaskQueue.TaskQueueListener() { @Override public void taskComplete(Task task) {
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // } // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/queueing/v1/TaskQueueDemoActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import java.util.Random; import java.util.concurrent.TimeUnit; /* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.queueing.v1; /** * 演示基于TSQ的任务队列的运行情况. */ public class TaskQueueDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView; private TaskQueue taskQueue; private static long taskIdCounter; private Random rand1 = new Random(); private Random rand2 = new Random(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_display); description = (TextView) findViewById(R.id.description); logTextView = (TextView) findViewById(R.id.log_display); description.setText(R.string.queueing_demo1_description); taskQueue = new TSQBasedTaskQueue(); taskQueue.setListener(new TaskQueue.TaskQueueListener() { @Override public void taskComplete(Task task) {
TextLogUtil.println(logTextView, "Task (" + task.getTaskId() + ") complete");
tielei/AsyncProgrammingDemos
AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/queueing/v3/TaskQueueDemoActivity.java
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/queueing/v3/mock/MockAsyncTask.java // public class MockAsyncTask implements Task<Void> { // private static long taskIdCounter; // // private String taskId; // // private ExecutorService executorService = Executors.newCachedThreadPool(); // private Random rand1 = new Random(); // private Random rand2 = new Random(); // // public MockAsyncTask() { // taskId = String.valueOf(++taskIdCounter); // } // // @Override // public String getTaskId() { // return taskId; // } // // @Override // public Observable<Void> start() { // return Observable.create(new Observable.OnSubscribe<Void>() { // @Override // public void call(Subscriber<? super Void> subscriber) { // //任务随机执行0~3秒 // try { // TimeUnit.MILLISECONDS.sleep(rand1.nextInt(3000)); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // //模拟失败情况: 以80%的概率失败 // Exception error = null; // if (rand2.nextInt(10) < 8) { // error = new RuntimeException("runtime error..."); // } // // if (error == null) { // //当前异步任务没有返回数据, 不用调用onNext // subscriber.onCompleted(); // } // else { // subscriber.onError(error); // } // // } // }).subscribeOn(Schedulers.from(executorService)) // .observeOn(AndroidSchedulers.mainThread()); // } // // // }
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import com.zhangtielei.demos.async.programming.queueing.v3.mock.MockAsyncTask; import rx.Observable; import rx.Subscriber; import rx.Subscription; import java.util.ArrayList; import java.util.List;
/* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.queueing.v3; /** * 演示基于RxJava的任务队列的运行情况. */ public class TaskQueueDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView; private TaskQueue taskQueue; private List<Subscription> subscriptionList = new ArrayList<Subscription>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_display); description = (TextView) findViewById(R.id.description); logTextView = (TextView) findViewById(R.id.log_display); description.setText(R.string.queueing_demo3_description); taskQueue = new RxJavaBasedTaskQueue(); /** * 启动5个任务 */ for (int i = 0; i < 5; i++) {
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/queueing/v3/mock/MockAsyncTask.java // public class MockAsyncTask implements Task<Void> { // private static long taskIdCounter; // // private String taskId; // // private ExecutorService executorService = Executors.newCachedThreadPool(); // private Random rand1 = new Random(); // private Random rand2 = new Random(); // // public MockAsyncTask() { // taskId = String.valueOf(++taskIdCounter); // } // // @Override // public String getTaskId() { // return taskId; // } // // @Override // public Observable<Void> start() { // return Observable.create(new Observable.OnSubscribe<Void>() { // @Override // public void call(Subscriber<? super Void> subscriber) { // //任务随机执行0~3秒 // try { // TimeUnit.MILLISECONDS.sleep(rand1.nextInt(3000)); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // //模拟失败情况: 以80%的概率失败 // Exception error = null; // if (rand2.nextInt(10) < 8) { // error = new RuntimeException("runtime error..."); // } // // if (error == null) { // //当前异步任务没有返回数据, 不用调用onNext // subscriber.onCompleted(); // } // else { // subscriber.onError(error); // } // // } // }).subscribeOn(Schedulers.from(executorService)) // .observeOn(AndroidSchedulers.mainThread()); // } // // // } // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/queueing/v3/TaskQueueDemoActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import com.zhangtielei.demos.async.programming.queueing.v3.mock.MockAsyncTask; import rx.Observable; import rx.Subscriber; import rx.Subscription; import java.util.ArrayList; import java.util.List; /* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.queueing.v3; /** * 演示基于RxJava的任务队列的运行情况. */ public class TaskQueueDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView; private TaskQueue taskQueue; private List<Subscription> subscriptionList = new ArrayList<Subscription>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_display); description = (TextView) findViewById(R.id.description); logTextView = (TextView) findViewById(R.id.log_display); description.setText(R.string.queueing_demo3_description); taskQueue = new RxJavaBasedTaskQueue(); /** * 启动5个任务 */ for (int i = 0; i < 5; i++) {
final MockAsyncTask task = new MockAsyncTask();
tielei/AsyncProgrammingDemos
AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/queueing/v3/TaskQueueDemoActivity.java
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/queueing/v3/mock/MockAsyncTask.java // public class MockAsyncTask implements Task<Void> { // private static long taskIdCounter; // // private String taskId; // // private ExecutorService executorService = Executors.newCachedThreadPool(); // private Random rand1 = new Random(); // private Random rand2 = new Random(); // // public MockAsyncTask() { // taskId = String.valueOf(++taskIdCounter); // } // // @Override // public String getTaskId() { // return taskId; // } // // @Override // public Observable<Void> start() { // return Observable.create(new Observable.OnSubscribe<Void>() { // @Override // public void call(Subscriber<? super Void> subscriber) { // //任务随机执行0~3秒 // try { // TimeUnit.MILLISECONDS.sleep(rand1.nextInt(3000)); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // //模拟失败情况: 以80%的概率失败 // Exception error = null; // if (rand2.nextInt(10) < 8) { // error = new RuntimeException("runtime error..."); // } // // if (error == null) { // //当前异步任务没有返回数据, 不用调用onNext // subscriber.onCompleted(); // } // else { // subscriber.onError(error); // } // // } // }).subscribeOn(Schedulers.from(executorService)) // .observeOn(AndroidSchedulers.mainThread()); // } // // // }
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import com.zhangtielei.demos.async.programming.queueing.v3.mock.MockAsyncTask; import rx.Observable; import rx.Subscriber; import rx.Subscription; import java.util.ArrayList; import java.util.List;
/* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.queueing.v3; /** * 演示基于RxJava的任务队列的运行情况. */ public class TaskQueueDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView; private TaskQueue taskQueue; private List<Subscription> subscriptionList = new ArrayList<Subscription>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_display); description = (TextView) findViewById(R.id.description); logTextView = (TextView) findViewById(R.id.log_display); description.setText(R.string.queueing_demo3_description); taskQueue = new RxJavaBasedTaskQueue(); /** * 启动5个任务 */ for (int i = 0; i < 5; i++) { final MockAsyncTask task = new MockAsyncTask();
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/queueing/v3/mock/MockAsyncTask.java // public class MockAsyncTask implements Task<Void> { // private static long taskIdCounter; // // private String taskId; // // private ExecutorService executorService = Executors.newCachedThreadPool(); // private Random rand1 = new Random(); // private Random rand2 = new Random(); // // public MockAsyncTask() { // taskId = String.valueOf(++taskIdCounter); // } // // @Override // public String getTaskId() { // return taskId; // } // // @Override // public Observable<Void> start() { // return Observable.create(new Observable.OnSubscribe<Void>() { // @Override // public void call(Subscriber<? super Void> subscriber) { // //任务随机执行0~3秒 // try { // TimeUnit.MILLISECONDS.sleep(rand1.nextInt(3000)); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // //模拟失败情况: 以80%的概率失败 // Exception error = null; // if (rand2.nextInt(10) < 8) { // error = new RuntimeException("runtime error..."); // } // // if (error == null) { // //当前异步任务没有返回数据, 不用调用onNext // subscriber.onCompleted(); // } // else { // subscriber.onError(error); // } // // } // }).subscribeOn(Schedulers.from(executorService)) // .observeOn(AndroidSchedulers.mainThread()); // } // // // } // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/queueing/v3/TaskQueueDemoActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import com.zhangtielei.demos.async.programming.queueing.v3.mock.MockAsyncTask; import rx.Observable; import rx.Subscriber; import rx.Subscription; import java.util.ArrayList; import java.util.List; /* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.queueing.v3; /** * 演示基于RxJava的任务队列的运行情况. */ public class TaskQueueDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView; private TaskQueue taskQueue; private List<Subscription> subscriptionList = new ArrayList<Subscription>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_display); description = (TextView) findViewById(R.id.description); logTextView = (TextView) findViewById(R.id.log_display); description.setText(R.string.queueing_demo3_description); taskQueue = new RxJavaBasedTaskQueue(); /** * 启动5个任务 */ for (int i = 0; i < 5; i++) { final MockAsyncTask task = new MockAsyncTask();
TextLogUtil.println(logTextView, "Add task (" + task.getTaskId() + ") to queue");
tielei/AsyncProgrammingDemos
AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/introduction/servicebinding/ServiceBindingDemoActivity.java
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/introduction/servicebinding/service/SomeService.java // public class SomeService extends Service { // private static final String TAG = "SomeService"; // // public SomeService() { // } // // /** // * 用于OnBind返回的Binder实例 // */ // private ServiceBinder binder = new ServiceBinder(); // private List<ServiceListener> listeners = new ArrayList<ServiceListener>(); // // private Random random = new Random(); // // @Override // public IBinder onBind(Intent intent) { // // Return the communication channel to the service. // return binder; // } // // public void addListener(ServiceListener listener) { // if (!listeners.contains(listener)) { // listeners.add(listener); // } // } // // public void removeListener(ServiceListener listener) { // listeners.remove(listener); // } // // /** // * 与此Service通信的Binder类 // */ // public class ServiceBinder extends Binder { // public SomeService getService() { // return SomeService.this; // } // } // // /** // * 此Service对外界的回调接口定义. // */ // public interface ServiceListener { // void callback(); // } // // }
import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import com.zhangtielei.demos.async.programming.introduction.servicebinding.service.SomeService;
/* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.introduction.servicebinding; /** * 用于演示最普通的Service绑定和解绑. */ public class ServiceBindingDemoActivity extends AppCompatActivity implements SomeService.ServiceListener { /** * 对于Service的引用 */ private SomeService someService; /** * 指示本Activity是否处于running状态:执行过onResume就变为running状态。 */ private boolean running; private TextView description; private TextView logTextView; private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { //解除Activity与Service的引用和监听关系 //... if (someService != null) { someService.removeListener(ServiceBindingDemoActivity.this); someService = null; }
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/introduction/servicebinding/service/SomeService.java // public class SomeService extends Service { // private static final String TAG = "SomeService"; // // public SomeService() { // } // // /** // * 用于OnBind返回的Binder实例 // */ // private ServiceBinder binder = new ServiceBinder(); // private List<ServiceListener> listeners = new ArrayList<ServiceListener>(); // // private Random random = new Random(); // // @Override // public IBinder onBind(Intent intent) { // // Return the communication channel to the service. // return binder; // } // // public void addListener(ServiceListener listener) { // if (!listeners.contains(listener)) { // listeners.add(listener); // } // } // // public void removeListener(ServiceListener listener) { // listeners.remove(listener); // } // // /** // * 与此Service通信的Binder类 // */ // public class ServiceBinder extends Binder { // public SomeService getService() { // return SomeService.this; // } // } // // /** // * 此Service对外界的回调接口定义. // */ // public interface ServiceListener { // void callback(); // } // // } // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/introduction/servicebinding/ServiceBindingDemoActivity.java import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import com.zhangtielei.demos.async.programming.introduction.servicebinding.service.SomeService; /* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.introduction.servicebinding; /** * 用于演示最普通的Service绑定和解绑. */ public class ServiceBindingDemoActivity extends AppCompatActivity implements SomeService.ServiceListener { /** * 对于Service的引用 */ private SomeService someService; /** * 指示本Activity是否处于running状态:执行过onResume就变为running状态。 */ private boolean running; private TextView description; private TextView logTextView; private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { //解除Activity与Service的引用和监听关系 //... if (someService != null) { someService.removeListener(ServiceBindingDemoActivity.this); someService = null; }
TextLogUtil.println(logTextView, "disconnected to SomeService...");
tielei/AsyncProgrammingDemos
AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/v3/EmojiDownloadDemoActivity.java
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiDownloader.java // public interface EmojiDownloader { // /** // * 开始下载指定的表情包 // * @param emojiPackage // */ // void startDownloadEmoji(EmojiPackage emojiPackage); // // /** // * 设置监听器. // * @param listener // */ // void setEmojiDownloadListener(EmojiDownloadListener listener); // // /** // * 这里定义回调相关的接口. 不是我们要讨论的重点. // * 这里的定义用于完整演示. // */ // // interface EmojiDownloadListener { // /** // * 表情包下载成功回调. // * @param emojiPackage // */ // void emojiDownloadSuccess(EmojiPackage emojiPackage); // // /** // * 表情包下载失败回调. // * @param emojiPackage // * @param errorCode 为简单起见, 这里的值复用{@link com.zhangtielei.demos.async.programming.callback.download.v3.DownloadListener}中的错误码定义. // * @param errorMessage // */ // void emojiDownloadFailed(EmojiPackage emojiPackage, int errorCode, String errorMessage); // // /** // * 表情包下载进度回调. 每次下载完一个图片文件后回调一次. // * @param emojiPackage // * @param downloadEmojiUrl 当前刚下载完的图片文件URL // */ // void emojiDownloadProgress(EmojiPackage emojiPackage, String downloadEmojiUrl); // } // // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiPackage.java // public class EmojiPackage { // /** // * 表情包ID // */ // public long emojiId; // /** // * 表情包图片列表 // */ // public List<String> emojiUrls; // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // }
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiDownloader; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiPackage; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import java.util.ArrayList;
/* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.callback.emoji.v3; /** * 通过为每一个异步任务创建一个接口实例的方式来传递上下文的表情包下载演示页面. */ public class EmojiDownloadDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView;
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiDownloader.java // public interface EmojiDownloader { // /** // * 开始下载指定的表情包 // * @param emojiPackage // */ // void startDownloadEmoji(EmojiPackage emojiPackage); // // /** // * 设置监听器. // * @param listener // */ // void setEmojiDownloadListener(EmojiDownloadListener listener); // // /** // * 这里定义回调相关的接口. 不是我们要讨论的重点. // * 这里的定义用于完整演示. // */ // // interface EmojiDownloadListener { // /** // * 表情包下载成功回调. // * @param emojiPackage // */ // void emojiDownloadSuccess(EmojiPackage emojiPackage); // // /** // * 表情包下载失败回调. // * @param emojiPackage // * @param errorCode 为简单起见, 这里的值复用{@link com.zhangtielei.demos.async.programming.callback.download.v3.DownloadListener}中的错误码定义. // * @param errorMessage // */ // void emojiDownloadFailed(EmojiPackage emojiPackage, int errorCode, String errorMessage); // // /** // * 表情包下载进度回调. 每次下载完一个图片文件后回调一次. // * @param emojiPackage // * @param downloadEmojiUrl 当前刚下载完的图片文件URL // */ // void emojiDownloadProgress(EmojiPackage emojiPackage, String downloadEmojiUrl); // } // // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiPackage.java // public class EmojiPackage { // /** // * 表情包ID // */ // public long emojiId; // /** // * 表情包图片列表 // */ // public List<String> emojiUrls; // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // } // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/v3/EmojiDownloadDemoActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiDownloader; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiPackage; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import java.util.ArrayList; /* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.callback.emoji.v3; /** * 通过为每一个异步任务创建一个接口实例的方式来传递上下文的表情包下载演示页面. */ public class EmojiDownloadDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView;
private EmojiDownloader emojiDownloader;
tielei/AsyncProgrammingDemos
AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/v3/EmojiDownloadDemoActivity.java
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiDownloader.java // public interface EmojiDownloader { // /** // * 开始下载指定的表情包 // * @param emojiPackage // */ // void startDownloadEmoji(EmojiPackage emojiPackage); // // /** // * 设置监听器. // * @param listener // */ // void setEmojiDownloadListener(EmojiDownloadListener listener); // // /** // * 这里定义回调相关的接口. 不是我们要讨论的重点. // * 这里的定义用于完整演示. // */ // // interface EmojiDownloadListener { // /** // * 表情包下载成功回调. // * @param emojiPackage // */ // void emojiDownloadSuccess(EmojiPackage emojiPackage); // // /** // * 表情包下载失败回调. // * @param emojiPackage // * @param errorCode 为简单起见, 这里的值复用{@link com.zhangtielei.demos.async.programming.callback.download.v3.DownloadListener}中的错误码定义. // * @param errorMessage // */ // void emojiDownloadFailed(EmojiPackage emojiPackage, int errorCode, String errorMessage); // // /** // * 表情包下载进度回调. 每次下载完一个图片文件后回调一次. // * @param emojiPackage // * @param downloadEmojiUrl 当前刚下载完的图片文件URL // */ // void emojiDownloadProgress(EmojiPackage emojiPackage, String downloadEmojiUrl); // } // // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiPackage.java // public class EmojiPackage { // /** // * 表情包ID // */ // public long emojiId; // /** // * 表情包图片列表 // */ // public List<String> emojiUrls; // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // }
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiDownloader; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiPackage; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import java.util.ArrayList;
/* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.callback.emoji.v3; /** * 通过为每一个异步任务创建一个接口实例的方式来传递上下文的表情包下载演示页面. */ public class EmojiDownloadDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView; private EmojiDownloader emojiDownloader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_display); description = (TextView) findViewById(R.id.description); logTextView = (TextView) findViewById(R.id.log_display); description.setText(R.string.emoji_download_demo3_description); emojiDownloader = new MyEmojiDownloader(); emojiDownloader.setEmojiDownloadListener(new EmojiDownloader.EmojiDownloadListener() { @Override
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiDownloader.java // public interface EmojiDownloader { // /** // * 开始下载指定的表情包 // * @param emojiPackage // */ // void startDownloadEmoji(EmojiPackage emojiPackage); // // /** // * 设置监听器. // * @param listener // */ // void setEmojiDownloadListener(EmojiDownloadListener listener); // // /** // * 这里定义回调相关的接口. 不是我们要讨论的重点. // * 这里的定义用于完整演示. // */ // // interface EmojiDownloadListener { // /** // * 表情包下载成功回调. // * @param emojiPackage // */ // void emojiDownloadSuccess(EmojiPackage emojiPackage); // // /** // * 表情包下载失败回调. // * @param emojiPackage // * @param errorCode 为简单起见, 这里的值复用{@link com.zhangtielei.demos.async.programming.callback.download.v3.DownloadListener}中的错误码定义. // * @param errorMessage // */ // void emojiDownloadFailed(EmojiPackage emojiPackage, int errorCode, String errorMessage); // // /** // * 表情包下载进度回调. 每次下载完一个图片文件后回调一次. // * @param emojiPackage // * @param downloadEmojiUrl 当前刚下载完的图片文件URL // */ // void emojiDownloadProgress(EmojiPackage emojiPackage, String downloadEmojiUrl); // } // // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiPackage.java // public class EmojiPackage { // /** // * 表情包ID // */ // public long emojiId; // /** // * 表情包图片列表 // */ // public List<String> emojiUrls; // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // } // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/v3/EmojiDownloadDemoActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiDownloader; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiPackage; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import java.util.ArrayList; /* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.callback.emoji.v3; /** * 通过为每一个异步任务创建一个接口实例的方式来传递上下文的表情包下载演示页面. */ public class EmojiDownloadDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView; private EmojiDownloader emojiDownloader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_display); description = (TextView) findViewById(R.id.description); logTextView = (TextView) findViewById(R.id.log_display); description.setText(R.string.emoji_download_demo3_description); emojiDownloader = new MyEmojiDownloader(); emojiDownloader.setEmojiDownloadListener(new EmojiDownloader.EmojiDownloadListener() { @Override
public void emojiDownloadSuccess(EmojiPackage emojiPackage) {
tielei/AsyncProgrammingDemos
AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/v3/EmojiDownloadDemoActivity.java
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiDownloader.java // public interface EmojiDownloader { // /** // * 开始下载指定的表情包 // * @param emojiPackage // */ // void startDownloadEmoji(EmojiPackage emojiPackage); // // /** // * 设置监听器. // * @param listener // */ // void setEmojiDownloadListener(EmojiDownloadListener listener); // // /** // * 这里定义回调相关的接口. 不是我们要讨论的重点. // * 这里的定义用于完整演示. // */ // // interface EmojiDownloadListener { // /** // * 表情包下载成功回调. // * @param emojiPackage // */ // void emojiDownloadSuccess(EmojiPackage emojiPackage); // // /** // * 表情包下载失败回调. // * @param emojiPackage // * @param errorCode 为简单起见, 这里的值复用{@link com.zhangtielei.demos.async.programming.callback.download.v3.DownloadListener}中的错误码定义. // * @param errorMessage // */ // void emojiDownloadFailed(EmojiPackage emojiPackage, int errorCode, String errorMessage); // // /** // * 表情包下载进度回调. 每次下载完一个图片文件后回调一次. // * @param emojiPackage // * @param downloadEmojiUrl 当前刚下载完的图片文件URL // */ // void emojiDownloadProgress(EmojiPackage emojiPackage, String downloadEmojiUrl); // } // // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiPackage.java // public class EmojiPackage { // /** // * 表情包ID // */ // public long emojiId; // /** // * 表情包图片列表 // */ // public List<String> emojiUrls; // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // }
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiDownloader; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiPackage; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import java.util.ArrayList;
/* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.callback.emoji.v3; /** * 通过为每一个异步任务创建一个接口实例的方式来传递上下文的表情包下载演示页面. */ public class EmojiDownloadDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView; private EmojiDownloader emojiDownloader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_display); description = (TextView) findViewById(R.id.description); logTextView = (TextView) findViewById(R.id.log_display); description.setText(R.string.emoji_download_demo3_description); emojiDownloader = new MyEmojiDownloader(); emojiDownloader.setEmojiDownloadListener(new EmojiDownloader.EmojiDownloadListener() { @Override public void emojiDownloadSuccess(EmojiPackage emojiPackage) {
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiDownloader.java // public interface EmojiDownloader { // /** // * 开始下载指定的表情包 // * @param emojiPackage // */ // void startDownloadEmoji(EmojiPackage emojiPackage); // // /** // * 设置监听器. // * @param listener // */ // void setEmojiDownloadListener(EmojiDownloadListener listener); // // /** // * 这里定义回调相关的接口. 不是我们要讨论的重点. // * 这里的定义用于完整演示. // */ // // interface EmojiDownloadListener { // /** // * 表情包下载成功回调. // * @param emojiPackage // */ // void emojiDownloadSuccess(EmojiPackage emojiPackage); // // /** // * 表情包下载失败回调. // * @param emojiPackage // * @param errorCode 为简单起见, 这里的值复用{@link com.zhangtielei.demos.async.programming.callback.download.v3.DownloadListener}中的错误码定义. // * @param errorMessage // */ // void emojiDownloadFailed(EmojiPackage emojiPackage, int errorCode, String errorMessage); // // /** // * 表情包下载进度回调. 每次下载完一个图片文件后回调一次. // * @param emojiPackage // * @param downloadEmojiUrl 当前刚下载完的图片文件URL // */ // void emojiDownloadProgress(EmojiPackage emojiPackage, String downloadEmojiUrl); // } // // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiPackage.java // public class EmojiPackage { // /** // * 表情包ID // */ // public long emojiId; // /** // * 表情包图片列表 // */ // public List<String> emojiUrls; // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // } // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/v3/EmojiDownloadDemoActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiDownloader; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiPackage; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import java.util.ArrayList; /* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.callback.emoji.v3; /** * 通过为每一个异步任务创建一个接口实例的方式来传递上下文的表情包下载演示页面. */ public class EmojiDownloadDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView; private EmojiDownloader emojiDownloader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_display); description = (TextView) findViewById(R.id.description); logTextView = (TextView) findViewById(R.id.log_display); description.setText(R.string.emoji_download_demo3_description); emojiDownloader = new MyEmojiDownloader(); emojiDownloader.setEmojiDownloadListener(new EmojiDownloader.EmojiDownloadListener() { @Override public void emojiDownloadSuccess(EmojiPackage emojiPackage) {
TextLogUtil.println(logTextView, "emoji package (emojiId: " + emojiPackage.emojiId + ") downloaded success!");
tielei/AsyncProgrammingDemos
AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/queueing/QueueingDemoListActivity.java
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/queueing/v1/TaskQueueDemoActivity.java // public class TaskQueueDemoActivity extends AppCompatActivity { // private TextView description; // private TextView logTextView; // // private TaskQueue taskQueue; // // private static long taskIdCounter; // private Random rand1 = new Random(); // private Random rand2 = new Random(); // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_log_display); // // description = (TextView) findViewById(R.id.description); // logTextView = (TextView) findViewById(R.id.log_display); // // description.setText(R.string.queueing_demo1_description); // // taskQueue = new TSQBasedTaskQueue(); // taskQueue.setListener(new TaskQueue.TaskQueueListener() { // @Override // public void taskComplete(Task task) { // TextLogUtil.println(logTextView, "Task (" + task.getTaskId() + ") complete"); // } // // @Override // public void taskFailed(Task task, Throwable cause) { // TextLogUtil.println(logTextView, "Task (" + task.getTaskId() + ") failed, error message: " + cause.getMessage()); // } // }); // // /** // * 启动5个任务 // */ // for (int i = 0; i < 5; i++) { // Task task = new Task() { // private String taskId = String.valueOf(++taskIdCounter); // // @Override // public void run() { // //任务随机执行0~3秒 // try { // TimeUnit.MILLISECONDS.sleep(rand1.nextInt(3000)); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // //模拟失败情况: 以80%的概率失败 // if (rand2.nextInt(10) < 8) { // throw new RuntimeException("runtime error..."); // } // } // // @Override // public String getTaskId() { // return taskId; // } // }; // TextLogUtil.println(logTextView, "Add task (" + task.getTaskId() + ") to queue"); // taskQueue.addTask(task); // } // // } // // @Override // protected void onDestroy() { // taskQueue.setListener(null); // taskQueue.destroy(); // // super.onDestroy(); // } // // }
import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListAdapter; import android.widget.ListView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.queueing.v1.TaskQueueDemoActivity;
/* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.queueing; public class QueueingDemoListActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_item_list); ListView listView = (ListView) findViewById(R.id.item_list); Resources resources = getResources(); String[] textList = new String[] { resources.getString(R.string.queueing_demo_1), resources.getString(R.string.queueing_demo_2), resources.getString(R.string.queueing_demo_3), }; ListAdapter listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, textList); listView.setAdapter(listAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { switch (position) { case 0: {
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/queueing/v1/TaskQueueDemoActivity.java // public class TaskQueueDemoActivity extends AppCompatActivity { // private TextView description; // private TextView logTextView; // // private TaskQueue taskQueue; // // private static long taskIdCounter; // private Random rand1 = new Random(); // private Random rand2 = new Random(); // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_log_display); // // description = (TextView) findViewById(R.id.description); // logTextView = (TextView) findViewById(R.id.log_display); // // description.setText(R.string.queueing_demo1_description); // // taskQueue = new TSQBasedTaskQueue(); // taskQueue.setListener(new TaskQueue.TaskQueueListener() { // @Override // public void taskComplete(Task task) { // TextLogUtil.println(logTextView, "Task (" + task.getTaskId() + ") complete"); // } // // @Override // public void taskFailed(Task task, Throwable cause) { // TextLogUtil.println(logTextView, "Task (" + task.getTaskId() + ") failed, error message: " + cause.getMessage()); // } // }); // // /** // * 启动5个任务 // */ // for (int i = 0; i < 5; i++) { // Task task = new Task() { // private String taskId = String.valueOf(++taskIdCounter); // // @Override // public void run() { // //任务随机执行0~3秒 // try { // TimeUnit.MILLISECONDS.sleep(rand1.nextInt(3000)); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // //模拟失败情况: 以80%的概率失败 // if (rand2.nextInt(10) < 8) { // throw new RuntimeException("runtime error..."); // } // } // // @Override // public String getTaskId() { // return taskId; // } // }; // TextLogUtil.println(logTextView, "Add task (" + task.getTaskId() + ") to queue"); // taskQueue.addTask(task); // } // // } // // @Override // protected void onDestroy() { // taskQueue.setListener(null); // taskQueue.destroy(); // // super.onDestroy(); // } // // } // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/queueing/QueueingDemoListActivity.java import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListAdapter; import android.widget.ListView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.queueing.v1.TaskQueueDemoActivity; /* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.queueing; public class QueueingDemoListActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_item_list); ListView listView = (ListView) findViewById(R.id.item_list); Resources resources = getResources(); String[] textList = new String[] { resources.getString(R.string.queueing_demo_1), resources.getString(R.string.queueing_demo_2), resources.getString(R.string.queueing_demo_3), }; ListAdapter listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, textList); listView.setAdapter(listAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { switch (position) { case 0: {
Intent intent = new Intent(QueueingDemoListActivity.this, TaskQueueDemoActivity.class);
tielei/AsyncProgrammingDemos
AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/v1/EmojiDownloadDemoActivity.java
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiDownloader.java // public interface EmojiDownloader { // /** // * 开始下载指定的表情包 // * @param emojiPackage // */ // void startDownloadEmoji(EmojiPackage emojiPackage); // // /** // * 设置监听器. // * @param listener // */ // void setEmojiDownloadListener(EmojiDownloadListener listener); // // /** // * 这里定义回调相关的接口. 不是我们要讨论的重点. // * 这里的定义用于完整演示. // */ // // interface EmojiDownloadListener { // /** // * 表情包下载成功回调. // * @param emojiPackage // */ // void emojiDownloadSuccess(EmojiPackage emojiPackage); // // /** // * 表情包下载失败回调. // * @param emojiPackage // * @param errorCode 为简单起见, 这里的值复用{@link com.zhangtielei.demos.async.programming.callback.download.v3.DownloadListener}中的错误码定义. // * @param errorMessage // */ // void emojiDownloadFailed(EmojiPackage emojiPackage, int errorCode, String errorMessage); // // /** // * 表情包下载进度回调. 每次下载完一个图片文件后回调一次. // * @param emojiPackage // * @param downloadEmojiUrl 当前刚下载完的图片文件URL // */ // void emojiDownloadProgress(EmojiPackage emojiPackage, String downloadEmojiUrl); // } // // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiPackage.java // public class EmojiPackage { // /** // * 表情包ID // */ // public long emojiId; // /** // * 表情包图片列表 // */ // public List<String> emojiUrls; // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // }
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiDownloader; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiPackage; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import java.util.ArrayList;
/* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.callback.emoji.v1; /** * 通过全局保存一份上下文来实现表情包下载的演示页面. */ public class EmojiDownloadDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView;
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiDownloader.java // public interface EmojiDownloader { // /** // * 开始下载指定的表情包 // * @param emojiPackage // */ // void startDownloadEmoji(EmojiPackage emojiPackage); // // /** // * 设置监听器. // * @param listener // */ // void setEmojiDownloadListener(EmojiDownloadListener listener); // // /** // * 这里定义回调相关的接口. 不是我们要讨论的重点. // * 这里的定义用于完整演示. // */ // // interface EmojiDownloadListener { // /** // * 表情包下载成功回调. // * @param emojiPackage // */ // void emojiDownloadSuccess(EmojiPackage emojiPackage); // // /** // * 表情包下载失败回调. // * @param emojiPackage // * @param errorCode 为简单起见, 这里的值复用{@link com.zhangtielei.demos.async.programming.callback.download.v3.DownloadListener}中的错误码定义. // * @param errorMessage // */ // void emojiDownloadFailed(EmojiPackage emojiPackage, int errorCode, String errorMessage); // // /** // * 表情包下载进度回调. 每次下载完一个图片文件后回调一次. // * @param emojiPackage // * @param downloadEmojiUrl 当前刚下载完的图片文件URL // */ // void emojiDownloadProgress(EmojiPackage emojiPackage, String downloadEmojiUrl); // } // // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiPackage.java // public class EmojiPackage { // /** // * 表情包ID // */ // public long emojiId; // /** // * 表情包图片列表 // */ // public List<String> emojiUrls; // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // } // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/v1/EmojiDownloadDemoActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiDownloader; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiPackage; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import java.util.ArrayList; /* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.callback.emoji.v1; /** * 通过全局保存一份上下文来实现表情包下载的演示页面. */ public class EmojiDownloadDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView;
private EmojiDownloader emojiDownloader;
tielei/AsyncProgrammingDemos
AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/v1/EmojiDownloadDemoActivity.java
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiDownloader.java // public interface EmojiDownloader { // /** // * 开始下载指定的表情包 // * @param emojiPackage // */ // void startDownloadEmoji(EmojiPackage emojiPackage); // // /** // * 设置监听器. // * @param listener // */ // void setEmojiDownloadListener(EmojiDownloadListener listener); // // /** // * 这里定义回调相关的接口. 不是我们要讨论的重点. // * 这里的定义用于完整演示. // */ // // interface EmojiDownloadListener { // /** // * 表情包下载成功回调. // * @param emojiPackage // */ // void emojiDownloadSuccess(EmojiPackage emojiPackage); // // /** // * 表情包下载失败回调. // * @param emojiPackage // * @param errorCode 为简单起见, 这里的值复用{@link com.zhangtielei.demos.async.programming.callback.download.v3.DownloadListener}中的错误码定义. // * @param errorMessage // */ // void emojiDownloadFailed(EmojiPackage emojiPackage, int errorCode, String errorMessage); // // /** // * 表情包下载进度回调. 每次下载完一个图片文件后回调一次. // * @param emojiPackage // * @param downloadEmojiUrl 当前刚下载完的图片文件URL // */ // void emojiDownloadProgress(EmojiPackage emojiPackage, String downloadEmojiUrl); // } // // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiPackage.java // public class EmojiPackage { // /** // * 表情包ID // */ // public long emojiId; // /** // * 表情包图片列表 // */ // public List<String> emojiUrls; // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // }
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiDownloader; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiPackage; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import java.util.ArrayList;
/* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.callback.emoji.v1; /** * 通过全局保存一份上下文来实现表情包下载的演示页面. */ public class EmojiDownloadDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView; private EmojiDownloader emojiDownloader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_display); description = (TextView) findViewById(R.id.description); logTextView = (TextView) findViewById(R.id.log_display); description.setText(R.string.emoji_download_demo1_description); emojiDownloader = new MyEmojiDownloader(); emojiDownloader.setEmojiDownloadListener(new EmojiDownloader.EmojiDownloadListener() { @Override
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiDownloader.java // public interface EmojiDownloader { // /** // * 开始下载指定的表情包 // * @param emojiPackage // */ // void startDownloadEmoji(EmojiPackage emojiPackage); // // /** // * 设置监听器. // * @param listener // */ // void setEmojiDownloadListener(EmojiDownloadListener listener); // // /** // * 这里定义回调相关的接口. 不是我们要讨论的重点. // * 这里的定义用于完整演示. // */ // // interface EmojiDownloadListener { // /** // * 表情包下载成功回调. // * @param emojiPackage // */ // void emojiDownloadSuccess(EmojiPackage emojiPackage); // // /** // * 表情包下载失败回调. // * @param emojiPackage // * @param errorCode 为简单起见, 这里的值复用{@link com.zhangtielei.demos.async.programming.callback.download.v3.DownloadListener}中的错误码定义. // * @param errorMessage // */ // void emojiDownloadFailed(EmojiPackage emojiPackage, int errorCode, String errorMessage); // // /** // * 表情包下载进度回调. 每次下载完一个图片文件后回调一次. // * @param emojiPackage // * @param downloadEmojiUrl 当前刚下载完的图片文件URL // */ // void emojiDownloadProgress(EmojiPackage emojiPackage, String downloadEmojiUrl); // } // // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiPackage.java // public class EmojiPackage { // /** // * 表情包ID // */ // public long emojiId; // /** // * 表情包图片列表 // */ // public List<String> emojiUrls; // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // } // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/v1/EmojiDownloadDemoActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiDownloader; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiPackage; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import java.util.ArrayList; /* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.callback.emoji.v1; /** * 通过全局保存一份上下文来实现表情包下载的演示页面. */ public class EmojiDownloadDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView; private EmojiDownloader emojiDownloader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_display); description = (TextView) findViewById(R.id.description); logTextView = (TextView) findViewById(R.id.log_display); description.setText(R.string.emoji_download_demo1_description); emojiDownloader = new MyEmojiDownloader(); emojiDownloader.setEmojiDownloadListener(new EmojiDownloader.EmojiDownloadListener() { @Override
public void emojiDownloadSuccess(EmojiPackage emojiPackage) {
tielei/AsyncProgrammingDemos
AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/v1/EmojiDownloadDemoActivity.java
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiDownloader.java // public interface EmojiDownloader { // /** // * 开始下载指定的表情包 // * @param emojiPackage // */ // void startDownloadEmoji(EmojiPackage emojiPackage); // // /** // * 设置监听器. // * @param listener // */ // void setEmojiDownloadListener(EmojiDownloadListener listener); // // /** // * 这里定义回调相关的接口. 不是我们要讨论的重点. // * 这里的定义用于完整演示. // */ // // interface EmojiDownloadListener { // /** // * 表情包下载成功回调. // * @param emojiPackage // */ // void emojiDownloadSuccess(EmojiPackage emojiPackage); // // /** // * 表情包下载失败回调. // * @param emojiPackage // * @param errorCode 为简单起见, 这里的值复用{@link com.zhangtielei.demos.async.programming.callback.download.v3.DownloadListener}中的错误码定义. // * @param errorMessage // */ // void emojiDownloadFailed(EmojiPackage emojiPackage, int errorCode, String errorMessage); // // /** // * 表情包下载进度回调. 每次下载完一个图片文件后回调一次. // * @param emojiPackage // * @param downloadEmojiUrl 当前刚下载完的图片文件URL // */ // void emojiDownloadProgress(EmojiPackage emojiPackage, String downloadEmojiUrl); // } // // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiPackage.java // public class EmojiPackage { // /** // * 表情包ID // */ // public long emojiId; // /** // * 表情包图片列表 // */ // public List<String> emojiUrls; // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // }
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiDownloader; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiPackage; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import java.util.ArrayList;
/* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.callback.emoji.v1; /** * 通过全局保存一份上下文来实现表情包下载的演示页面. */ public class EmojiDownloadDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView; private EmojiDownloader emojiDownloader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_display); description = (TextView) findViewById(R.id.description); logTextView = (TextView) findViewById(R.id.log_display); description.setText(R.string.emoji_download_demo1_description); emojiDownloader = new MyEmojiDownloader(); emojiDownloader.setEmojiDownloadListener(new EmojiDownloader.EmojiDownloadListener() { @Override public void emojiDownloadSuccess(EmojiPackage emojiPackage) {
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiDownloader.java // public interface EmojiDownloader { // /** // * 开始下载指定的表情包 // * @param emojiPackage // */ // void startDownloadEmoji(EmojiPackage emojiPackage); // // /** // * 设置监听器. // * @param listener // */ // void setEmojiDownloadListener(EmojiDownloadListener listener); // // /** // * 这里定义回调相关的接口. 不是我们要讨论的重点. // * 这里的定义用于完整演示. // */ // // interface EmojiDownloadListener { // /** // * 表情包下载成功回调. // * @param emojiPackage // */ // void emojiDownloadSuccess(EmojiPackage emojiPackage); // // /** // * 表情包下载失败回调. // * @param emojiPackage // * @param errorCode 为简单起见, 这里的值复用{@link com.zhangtielei.demos.async.programming.callback.download.v3.DownloadListener}中的错误码定义. // * @param errorMessage // */ // void emojiDownloadFailed(EmojiPackage emojiPackage, int errorCode, String errorMessage); // // /** // * 表情包下载进度回调. 每次下载完一个图片文件后回调一次. // * @param emojiPackage // * @param downloadEmojiUrl 当前刚下载完的图片文件URL // */ // void emojiDownloadProgress(EmojiPackage emojiPackage, String downloadEmojiUrl); // } // // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiPackage.java // public class EmojiPackage { // /** // * 表情包ID // */ // public long emojiId; // /** // * 表情包图片列表 // */ // public List<String> emojiUrls; // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // } // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/v1/EmojiDownloadDemoActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiDownloader; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiPackage; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import java.util.ArrayList; /* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.callback.emoji.v1; /** * 通过全局保存一份上下文来实现表情包下载的演示页面. */ public class EmojiDownloadDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView; private EmojiDownloader emojiDownloader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_display); description = (TextView) findViewById(R.id.description); logTextView = (TextView) findViewById(R.id.log_display); description.setText(R.string.emoji_download_demo1_description); emojiDownloader = new MyEmojiDownloader(); emojiDownloader.setEmojiDownloadListener(new EmojiDownloader.EmojiDownloadListener() { @Override public void emojiDownloadSuccess(EmojiPackage emojiPackage) {
TextLogUtil.println(logTextView, "emoji package (emojiId: " + emojiPackage.emojiId + ") downloaded success!");
tielei/AsyncProgrammingDemos
AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/queueing/v2/TaskQueueDemoActivity.java
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/queueing/v2/mock/MockAsyncTask.java // public class MockAsyncTask implements Task { // private static long taskIdCounter; // // private String taskId; // private TaskListener listener; // // private ExecutorService executorService = Executors.newCachedThreadPool(); // private Handler mainHandler = new Handler(Looper.getMainLooper()); // private Random rand1 = new Random(); // private Random rand2 = new Random(); // // public MockAsyncTask() { // taskId = String.valueOf(++taskIdCounter); // } // // @Override // public String getTaskId() { // return taskId; // } // // @Override // public void start() { // executorService.execute(new Runnable() { // @Override // public void run() { // //任务随机执行0~3秒 // try { // TimeUnit.MILLISECONDS.sleep(rand1.nextInt(3000)); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // //模拟失败情况: 以80%的概率失败 // Exception error = null; // if (rand2.nextInt(10) < 8) { // error = new RuntimeException("runtime error..."); // } // // final Exception finalError = error; // mainHandler.post(new Runnable() { // @Override // public void run() { // if (listener != null) { // try { // if (finalError == null) { // listener.taskComplete(MockAsyncTask.this); // } // else { // listener.taskFailed(MockAsyncTask.this, finalError); // } // } // catch (Throwable e) { // e.printStackTrace(); // } // } // } // }); // // } // }); // } // // @Override // public void setListener(TaskListener listener) { // this.listener = listener; // } // }
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import com.zhangtielei.demos.async.programming.queueing.v2.mock.MockAsyncTask;
/* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.queueing.v2; /** * 演示基于"异步+Callback"的任务队列的运行情况. */ public class TaskQueueDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView; private TaskQueue taskQueue; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_display); description = (TextView) findViewById(R.id.description); logTextView = (TextView) findViewById(R.id.log_display); description.setText(R.string.queueing_demo2_description); taskQueue = new CallbackBasedTaskQueue(); taskQueue.setListener(new TaskQueue.TaskQueueListener() { @Override public void taskComplete(Task task) {
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/queueing/v2/mock/MockAsyncTask.java // public class MockAsyncTask implements Task { // private static long taskIdCounter; // // private String taskId; // private TaskListener listener; // // private ExecutorService executorService = Executors.newCachedThreadPool(); // private Handler mainHandler = new Handler(Looper.getMainLooper()); // private Random rand1 = new Random(); // private Random rand2 = new Random(); // // public MockAsyncTask() { // taskId = String.valueOf(++taskIdCounter); // } // // @Override // public String getTaskId() { // return taskId; // } // // @Override // public void start() { // executorService.execute(new Runnable() { // @Override // public void run() { // //任务随机执行0~3秒 // try { // TimeUnit.MILLISECONDS.sleep(rand1.nextInt(3000)); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // //模拟失败情况: 以80%的概率失败 // Exception error = null; // if (rand2.nextInt(10) < 8) { // error = new RuntimeException("runtime error..."); // } // // final Exception finalError = error; // mainHandler.post(new Runnable() { // @Override // public void run() { // if (listener != null) { // try { // if (finalError == null) { // listener.taskComplete(MockAsyncTask.this); // } // else { // listener.taskFailed(MockAsyncTask.this, finalError); // } // } // catch (Throwable e) { // e.printStackTrace(); // } // } // } // }); // // } // }); // } // // @Override // public void setListener(TaskListener listener) { // this.listener = listener; // } // } // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/queueing/v2/TaskQueueDemoActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import com.zhangtielei.demos.async.programming.queueing.v2.mock.MockAsyncTask; /* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.queueing.v2; /** * 演示基于"异步+Callback"的任务队列的运行情况. */ public class TaskQueueDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView; private TaskQueue taskQueue; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_display); description = (TextView) findViewById(R.id.description); logTextView = (TextView) findViewById(R.id.log_display); description.setText(R.string.queueing_demo2_description); taskQueue = new CallbackBasedTaskQueue(); taskQueue.setListener(new TaskQueue.TaskQueueListener() { @Override public void taskComplete(Task task) {
TextLogUtil.println(logTextView, "Task (" + task.getTaskId() + ") complete");
tielei/AsyncProgrammingDemos
AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/queueing/v2/TaskQueueDemoActivity.java
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/queueing/v2/mock/MockAsyncTask.java // public class MockAsyncTask implements Task { // private static long taskIdCounter; // // private String taskId; // private TaskListener listener; // // private ExecutorService executorService = Executors.newCachedThreadPool(); // private Handler mainHandler = new Handler(Looper.getMainLooper()); // private Random rand1 = new Random(); // private Random rand2 = new Random(); // // public MockAsyncTask() { // taskId = String.valueOf(++taskIdCounter); // } // // @Override // public String getTaskId() { // return taskId; // } // // @Override // public void start() { // executorService.execute(new Runnable() { // @Override // public void run() { // //任务随机执行0~3秒 // try { // TimeUnit.MILLISECONDS.sleep(rand1.nextInt(3000)); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // //模拟失败情况: 以80%的概率失败 // Exception error = null; // if (rand2.nextInt(10) < 8) { // error = new RuntimeException("runtime error..."); // } // // final Exception finalError = error; // mainHandler.post(new Runnable() { // @Override // public void run() { // if (listener != null) { // try { // if (finalError == null) { // listener.taskComplete(MockAsyncTask.this); // } // else { // listener.taskFailed(MockAsyncTask.this, finalError); // } // } // catch (Throwable e) { // e.printStackTrace(); // } // } // } // }); // // } // }); // } // // @Override // public void setListener(TaskListener listener) { // this.listener = listener; // } // }
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import com.zhangtielei.demos.async.programming.queueing.v2.mock.MockAsyncTask;
/* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.queueing.v2; /** * 演示基于"异步+Callback"的任务队列的运行情况. */ public class TaskQueueDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView; private TaskQueue taskQueue; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_display); description = (TextView) findViewById(R.id.description); logTextView = (TextView) findViewById(R.id.log_display); description.setText(R.string.queueing_demo2_description); taskQueue = new CallbackBasedTaskQueue(); taskQueue.setListener(new TaskQueue.TaskQueueListener() { @Override public void taskComplete(Task task) { TextLogUtil.println(logTextView, "Task (" + task.getTaskId() + ") complete"); } @Override public void taskFailed(Task task, Throwable cause) { TextLogUtil.println(logTextView, "Task (" + task.getTaskId() + ") failed, error message: " + cause.getMessage()); } }); /** * 启动5个任务 */ for (int i = 0; i < 5; i++) {
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/queueing/v2/mock/MockAsyncTask.java // public class MockAsyncTask implements Task { // private static long taskIdCounter; // // private String taskId; // private TaskListener listener; // // private ExecutorService executorService = Executors.newCachedThreadPool(); // private Handler mainHandler = new Handler(Looper.getMainLooper()); // private Random rand1 = new Random(); // private Random rand2 = new Random(); // // public MockAsyncTask() { // taskId = String.valueOf(++taskIdCounter); // } // // @Override // public String getTaskId() { // return taskId; // } // // @Override // public void start() { // executorService.execute(new Runnable() { // @Override // public void run() { // //任务随机执行0~3秒 // try { // TimeUnit.MILLISECONDS.sleep(rand1.nextInt(3000)); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // //模拟失败情况: 以80%的概率失败 // Exception error = null; // if (rand2.nextInt(10) < 8) { // error = new RuntimeException("runtime error..."); // } // // final Exception finalError = error; // mainHandler.post(new Runnable() { // @Override // public void run() { // if (listener != null) { // try { // if (finalError == null) { // listener.taskComplete(MockAsyncTask.this); // } // else { // listener.taskFailed(MockAsyncTask.this, finalError); // } // } // catch (Throwable e) { // e.printStackTrace(); // } // } // } // }); // // } // }); // } // // @Override // public void setListener(TaskListener listener) { // this.listener = listener; // } // } // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/queueing/v2/TaskQueueDemoActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import com.zhangtielei.demos.async.programming.queueing.v2.mock.MockAsyncTask; /* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.queueing.v2; /** * 演示基于"异步+Callback"的任务队列的运行情况. */ public class TaskQueueDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView; private TaskQueue taskQueue; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_display); description = (TextView) findViewById(R.id.description); logTextView = (TextView) findViewById(R.id.log_display); description.setText(R.string.queueing_demo2_description); taskQueue = new CallbackBasedTaskQueue(); taskQueue.setListener(new TaskQueue.TaskQueueListener() { @Override public void taskComplete(Task task) { TextLogUtil.println(logTextView, "Task (" + task.getTaskId() + ") complete"); } @Override public void taskFailed(Task task, Throwable cause) { TextLogUtil.println(logTextView, "Task (" + task.getTaskId() + ") failed, error message: " + cause.getMessage()); } }); /** * 启动5个任务 */ for (int i = 0; i < 5; i++) {
Task task = new MockAsyncTask();
tielei/AsyncProgrammingDemos
AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/v4/EmojiDownloadDemoActivity.java
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiDownloader.java // public interface EmojiDownloader { // /** // * 开始下载指定的表情包 // * @param emojiPackage // */ // void startDownloadEmoji(EmojiPackage emojiPackage); // // /** // * 设置监听器. // * @param listener // */ // void setEmojiDownloadListener(EmojiDownloadListener listener); // // /** // * 这里定义回调相关的接口. 不是我们要讨论的重点. // * 这里的定义用于完整演示. // */ // // interface EmojiDownloadListener { // /** // * 表情包下载成功回调. // * @param emojiPackage // */ // void emojiDownloadSuccess(EmojiPackage emojiPackage); // // /** // * 表情包下载失败回调. // * @param emojiPackage // * @param errorCode 为简单起见, 这里的值复用{@link com.zhangtielei.demos.async.programming.callback.download.v3.DownloadListener}中的错误码定义. // * @param errorMessage // */ // void emojiDownloadFailed(EmojiPackage emojiPackage, int errorCode, String errorMessage); // // /** // * 表情包下载进度回调. 每次下载完一个图片文件后回调一次. // * @param emojiPackage // * @param downloadEmojiUrl 当前刚下载完的图片文件URL // */ // void emojiDownloadProgress(EmojiPackage emojiPackage, String downloadEmojiUrl); // } // // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiPackage.java // public class EmojiPackage { // /** // * 表情包ID // */ // public long emojiId; // /** // * 表情包图片列表 // */ // public List<String> emojiUrls; // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // }
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiDownloader; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiPackage; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import java.util.ArrayList;
/* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.callback.emoji.v4; /** * 利用支持上下文传递的异步接口来实现表情包下载的演示页面. */ public class EmojiDownloadDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView;
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiDownloader.java // public interface EmojiDownloader { // /** // * 开始下载指定的表情包 // * @param emojiPackage // */ // void startDownloadEmoji(EmojiPackage emojiPackage); // // /** // * 设置监听器. // * @param listener // */ // void setEmojiDownloadListener(EmojiDownloadListener listener); // // /** // * 这里定义回调相关的接口. 不是我们要讨论的重点. // * 这里的定义用于完整演示. // */ // // interface EmojiDownloadListener { // /** // * 表情包下载成功回调. // * @param emojiPackage // */ // void emojiDownloadSuccess(EmojiPackage emojiPackage); // // /** // * 表情包下载失败回调. // * @param emojiPackage // * @param errorCode 为简单起见, 这里的值复用{@link com.zhangtielei.demos.async.programming.callback.download.v3.DownloadListener}中的错误码定义. // * @param errorMessage // */ // void emojiDownloadFailed(EmojiPackage emojiPackage, int errorCode, String errorMessage); // // /** // * 表情包下载进度回调. 每次下载完一个图片文件后回调一次. // * @param emojiPackage // * @param downloadEmojiUrl 当前刚下载完的图片文件URL // */ // void emojiDownloadProgress(EmojiPackage emojiPackage, String downloadEmojiUrl); // } // // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiPackage.java // public class EmojiPackage { // /** // * 表情包ID // */ // public long emojiId; // /** // * 表情包图片列表 // */ // public List<String> emojiUrls; // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // } // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/v4/EmojiDownloadDemoActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiDownloader; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiPackage; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import java.util.ArrayList; /* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.callback.emoji.v4; /** * 利用支持上下文传递的异步接口来实现表情包下载的演示页面. */ public class EmojiDownloadDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView;
private EmojiDownloader emojiDownloader;
tielei/AsyncProgrammingDemos
AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/v4/EmojiDownloadDemoActivity.java
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiDownloader.java // public interface EmojiDownloader { // /** // * 开始下载指定的表情包 // * @param emojiPackage // */ // void startDownloadEmoji(EmojiPackage emojiPackage); // // /** // * 设置监听器. // * @param listener // */ // void setEmojiDownloadListener(EmojiDownloadListener listener); // // /** // * 这里定义回调相关的接口. 不是我们要讨论的重点. // * 这里的定义用于完整演示. // */ // // interface EmojiDownloadListener { // /** // * 表情包下载成功回调. // * @param emojiPackage // */ // void emojiDownloadSuccess(EmojiPackage emojiPackage); // // /** // * 表情包下载失败回调. // * @param emojiPackage // * @param errorCode 为简单起见, 这里的值复用{@link com.zhangtielei.demos.async.programming.callback.download.v3.DownloadListener}中的错误码定义. // * @param errorMessage // */ // void emojiDownloadFailed(EmojiPackage emojiPackage, int errorCode, String errorMessage); // // /** // * 表情包下载进度回调. 每次下载完一个图片文件后回调一次. // * @param emojiPackage // * @param downloadEmojiUrl 当前刚下载完的图片文件URL // */ // void emojiDownloadProgress(EmojiPackage emojiPackage, String downloadEmojiUrl); // } // // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiPackage.java // public class EmojiPackage { // /** // * 表情包ID // */ // public long emojiId; // /** // * 表情包图片列表 // */ // public List<String> emojiUrls; // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // }
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiDownloader; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiPackage; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import java.util.ArrayList;
/* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.callback.emoji.v4; /** * 利用支持上下文传递的异步接口来实现表情包下载的演示页面. */ public class EmojiDownloadDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView; private EmojiDownloader emojiDownloader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_display); description = (TextView) findViewById(R.id.description); logTextView = (TextView) findViewById(R.id.log_display); description.setText(R.string.emoji_download_demo4_description); emojiDownloader = new MyEmojiDownloader(); emojiDownloader.setEmojiDownloadListener(new EmojiDownloader.EmojiDownloadListener() { @Override
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiDownloader.java // public interface EmojiDownloader { // /** // * 开始下载指定的表情包 // * @param emojiPackage // */ // void startDownloadEmoji(EmojiPackage emojiPackage); // // /** // * 设置监听器. // * @param listener // */ // void setEmojiDownloadListener(EmojiDownloadListener listener); // // /** // * 这里定义回调相关的接口. 不是我们要讨论的重点. // * 这里的定义用于完整演示. // */ // // interface EmojiDownloadListener { // /** // * 表情包下载成功回调. // * @param emojiPackage // */ // void emojiDownloadSuccess(EmojiPackage emojiPackage); // // /** // * 表情包下载失败回调. // * @param emojiPackage // * @param errorCode 为简单起见, 这里的值复用{@link com.zhangtielei.demos.async.programming.callback.download.v3.DownloadListener}中的错误码定义. // * @param errorMessage // */ // void emojiDownloadFailed(EmojiPackage emojiPackage, int errorCode, String errorMessage); // // /** // * 表情包下载进度回调. 每次下载完一个图片文件后回调一次. // * @param emojiPackage // * @param downloadEmojiUrl 当前刚下载完的图片文件URL // */ // void emojiDownloadProgress(EmojiPackage emojiPackage, String downloadEmojiUrl); // } // // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiPackage.java // public class EmojiPackage { // /** // * 表情包ID // */ // public long emojiId; // /** // * 表情包图片列表 // */ // public List<String> emojiUrls; // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // } // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/v4/EmojiDownloadDemoActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiDownloader; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiPackage; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import java.util.ArrayList; /* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.callback.emoji.v4; /** * 利用支持上下文传递的异步接口来实现表情包下载的演示页面. */ public class EmojiDownloadDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView; private EmojiDownloader emojiDownloader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_display); description = (TextView) findViewById(R.id.description); logTextView = (TextView) findViewById(R.id.log_display); description.setText(R.string.emoji_download_demo4_description); emojiDownloader = new MyEmojiDownloader(); emojiDownloader.setEmojiDownloadListener(new EmojiDownloader.EmojiDownloadListener() { @Override
public void emojiDownloadSuccess(EmojiPackage emojiPackage) {
tielei/AsyncProgrammingDemos
AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/v4/EmojiDownloadDemoActivity.java
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiDownloader.java // public interface EmojiDownloader { // /** // * 开始下载指定的表情包 // * @param emojiPackage // */ // void startDownloadEmoji(EmojiPackage emojiPackage); // // /** // * 设置监听器. // * @param listener // */ // void setEmojiDownloadListener(EmojiDownloadListener listener); // // /** // * 这里定义回调相关的接口. 不是我们要讨论的重点. // * 这里的定义用于完整演示. // */ // // interface EmojiDownloadListener { // /** // * 表情包下载成功回调. // * @param emojiPackage // */ // void emojiDownloadSuccess(EmojiPackage emojiPackage); // // /** // * 表情包下载失败回调. // * @param emojiPackage // * @param errorCode 为简单起见, 这里的值复用{@link com.zhangtielei.demos.async.programming.callback.download.v3.DownloadListener}中的错误码定义. // * @param errorMessage // */ // void emojiDownloadFailed(EmojiPackage emojiPackage, int errorCode, String errorMessage); // // /** // * 表情包下载进度回调. 每次下载完一个图片文件后回调一次. // * @param emojiPackage // * @param downloadEmojiUrl 当前刚下载完的图片文件URL // */ // void emojiDownloadProgress(EmojiPackage emojiPackage, String downloadEmojiUrl); // } // // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiPackage.java // public class EmojiPackage { // /** // * 表情包ID // */ // public long emojiId; // /** // * 表情包图片列表 // */ // public List<String> emojiUrls; // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // }
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiDownloader; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiPackage; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import java.util.ArrayList;
/* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.callback.emoji.v4; /** * 利用支持上下文传递的异步接口来实现表情包下载的演示页面. */ public class EmojiDownloadDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView; private EmojiDownloader emojiDownloader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_display); description = (TextView) findViewById(R.id.description); logTextView = (TextView) findViewById(R.id.log_display); description.setText(R.string.emoji_download_demo4_description); emojiDownloader = new MyEmojiDownloader(); emojiDownloader.setEmojiDownloadListener(new EmojiDownloader.EmojiDownloadListener() { @Override public void emojiDownloadSuccess(EmojiPackage emojiPackage) {
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiDownloader.java // public interface EmojiDownloader { // /** // * 开始下载指定的表情包 // * @param emojiPackage // */ // void startDownloadEmoji(EmojiPackage emojiPackage); // // /** // * 设置监听器. // * @param listener // */ // void setEmojiDownloadListener(EmojiDownloadListener listener); // // /** // * 这里定义回调相关的接口. 不是我们要讨论的重点. // * 这里的定义用于完整演示. // */ // // interface EmojiDownloadListener { // /** // * 表情包下载成功回调. // * @param emojiPackage // */ // void emojiDownloadSuccess(EmojiPackage emojiPackage); // // /** // * 表情包下载失败回调. // * @param emojiPackage // * @param errorCode 为简单起见, 这里的值复用{@link com.zhangtielei.demos.async.programming.callback.download.v3.DownloadListener}中的错误码定义. // * @param errorMessage // */ // void emojiDownloadFailed(EmojiPackage emojiPackage, int errorCode, String errorMessage); // // /** // * 表情包下载进度回调. 每次下载完一个图片文件后回调一次. // * @param emojiPackage // * @param downloadEmojiUrl 当前刚下载完的图片文件URL // */ // void emojiDownloadProgress(EmojiPackage emojiPackage, String downloadEmojiUrl); // } // // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiPackage.java // public class EmojiPackage { // /** // * 表情包ID // */ // public long emojiId; // /** // * 表情包图片列表 // */ // public List<String> emojiUrls; // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // } // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/v4/EmojiDownloadDemoActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiDownloader; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiPackage; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import java.util.ArrayList; /* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.callback.emoji.v4; /** * 利用支持上下文传递的异步接口来实现表情包下载的演示页面. */ public class EmojiDownloadDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView; private EmojiDownloader emojiDownloader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_display); description = (TextView) findViewById(R.id.description); logTextView = (TextView) findViewById(R.id.log_display); description.setText(R.string.emoji_download_demo4_description); emojiDownloader = new MyEmojiDownloader(); emojiDownloader.setEmojiDownloadListener(new EmojiDownloader.EmojiDownloadListener() { @Override public void emojiDownloadSuccess(EmojiPackage emojiPackage) {
TextLogUtil.println(logTextView, "emoji package (emojiId: " + emojiPackage.emojiId + ") downloaded success!");
tielei/AsyncProgrammingDemos
AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiDownloadDemoListActivity.java
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/v1/EmojiDownloadDemoActivity.java // public class EmojiDownloadDemoActivity extends AppCompatActivity { // private TextView description; // private TextView logTextView; // // private EmojiDownloader emojiDownloader; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_log_display); // // description = (TextView) findViewById(R.id.description); // logTextView = (TextView) findViewById(R.id.log_display); // // description.setText(R.string.emoji_download_demo1_description); // // emojiDownloader = new MyEmojiDownloader(); // emojiDownloader.setEmojiDownloadListener(new EmojiDownloader.EmojiDownloadListener() { // @Override // public void emojiDownloadSuccess(EmojiPackage emojiPackage) { // TextLogUtil.println(logTextView, "emoji package (emojiId: " + emojiPackage.emojiId + ") downloaded success!"); // } // // @Override // public void emojiDownloadFailed(EmojiPackage emojiPackage, int errorCode, String errorMessage) { // TextLogUtil.println(logTextView, "emoji package (emojiId: " + emojiPackage.emojiId + ") downloaded failed! errorCode: " + errorCode + ", errorMessage: " + errorMessage); // } // // @Override // public void emojiDownloadProgress(EmojiPackage emojiPackage, String downloadEmojiUrl) { // TextLogUtil.println(logTextView, "progress: " + downloadEmojiUrl + " downloaded..."); // } // }); // // //构造要下载的表情包 // EmojiPackage emojiPackage = new EmojiPackage(); // emojiPackage.emojiId = 1001; // emojiPackage.emojiUrls = new ArrayList<String>(); // emojiPackage.emojiUrls.add("http://zhangtielei.com/demourls/1.png"); // emojiPackage.emojiUrls.add("http://zhangtielei.com/demourls/2.png"); // emojiPackage.emojiUrls.add("http://zhangtielei.com/demourls/3.png"); // emojiPackage.emojiUrls.add("http://zhangtielei.com/demourls/4.png"); // emojiPackage.emojiUrls.add("http://zhangtielei.com/demourls/5.png"); // // TextLogUtil.println(logTextView, "Start downloading emoji package (emojiId: " + emojiPackage.emojiId + ") with " + emojiPackage.emojiUrls.size() + " URLs"); // emojiDownloader.startDownloadEmoji(emojiPackage); // } // // }
import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListAdapter; import android.widget.ListView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.callback.emoji.v1.EmojiDownloadDemoActivity;
/* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.callback.emoji; /** * 表情包下载演示程序入口列表 */ public class EmojiDownloadDemoListActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_item_list); ListView listView = (ListView) findViewById(R.id.item_list); Resources resources = getResources(); String[] textList = new String[] { resources.getString(R.string.emoji_download_demo_1), resources.getString(R.string.emoji_download_demo_2), resources.getString(R.string.emoji_download_demo_3), resources.getString(R.string.emoji_download_demo_4), }; ListAdapter listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, textList); listView.setAdapter(listAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { switch (position) { case 0: {
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/v1/EmojiDownloadDemoActivity.java // public class EmojiDownloadDemoActivity extends AppCompatActivity { // private TextView description; // private TextView logTextView; // // private EmojiDownloader emojiDownloader; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_log_display); // // description = (TextView) findViewById(R.id.description); // logTextView = (TextView) findViewById(R.id.log_display); // // description.setText(R.string.emoji_download_demo1_description); // // emojiDownloader = new MyEmojiDownloader(); // emojiDownloader.setEmojiDownloadListener(new EmojiDownloader.EmojiDownloadListener() { // @Override // public void emojiDownloadSuccess(EmojiPackage emojiPackage) { // TextLogUtil.println(logTextView, "emoji package (emojiId: " + emojiPackage.emojiId + ") downloaded success!"); // } // // @Override // public void emojiDownloadFailed(EmojiPackage emojiPackage, int errorCode, String errorMessage) { // TextLogUtil.println(logTextView, "emoji package (emojiId: " + emojiPackage.emojiId + ") downloaded failed! errorCode: " + errorCode + ", errorMessage: " + errorMessage); // } // // @Override // public void emojiDownloadProgress(EmojiPackage emojiPackage, String downloadEmojiUrl) { // TextLogUtil.println(logTextView, "progress: " + downloadEmojiUrl + " downloaded..."); // } // }); // // //构造要下载的表情包 // EmojiPackage emojiPackage = new EmojiPackage(); // emojiPackage.emojiId = 1001; // emojiPackage.emojiUrls = new ArrayList<String>(); // emojiPackage.emojiUrls.add("http://zhangtielei.com/demourls/1.png"); // emojiPackage.emojiUrls.add("http://zhangtielei.com/demourls/2.png"); // emojiPackage.emojiUrls.add("http://zhangtielei.com/demourls/3.png"); // emojiPackage.emojiUrls.add("http://zhangtielei.com/demourls/4.png"); // emojiPackage.emojiUrls.add("http://zhangtielei.com/demourls/5.png"); // // TextLogUtil.println(logTextView, "Start downloading emoji package (emojiId: " + emojiPackage.emojiId + ") with " + emojiPackage.emojiUrls.size() + " URLs"); // emojiDownloader.startDownloadEmoji(emojiPackage); // } // // } // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiDownloadDemoListActivity.java import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListAdapter; import android.widget.ListView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.callback.emoji.v1.EmojiDownloadDemoActivity; /* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.callback.emoji; /** * 表情包下载演示程序入口列表 */ public class EmojiDownloadDemoListActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_item_list); ListView listView = (ListView) findViewById(R.id.item_list); Resources resources = getResources(); String[] textList = new String[] { resources.getString(R.string.emoji_download_demo_1), resources.getString(R.string.emoji_download_demo_2), resources.getString(R.string.emoji_download_demo_3), resources.getString(R.string.emoji_download_demo_4), }; ListAdapter listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, textList); listView.setAdapter(listAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { switch (position) { case 0: {
Intent intent = new Intent(EmojiDownloadDemoListActivity.this, EmojiDownloadDemoActivity.class);
tielei/AsyncProgrammingDemos
AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/v2/EmojiDownloadDemoActivity.java
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiDownloader.java // public interface EmojiDownloader { // /** // * 开始下载指定的表情包 // * @param emojiPackage // */ // void startDownloadEmoji(EmojiPackage emojiPackage); // // /** // * 设置监听器. // * @param listener // */ // void setEmojiDownloadListener(EmojiDownloadListener listener); // // /** // * 这里定义回调相关的接口. 不是我们要讨论的重点. // * 这里的定义用于完整演示. // */ // // interface EmojiDownloadListener { // /** // * 表情包下载成功回调. // * @param emojiPackage // */ // void emojiDownloadSuccess(EmojiPackage emojiPackage); // // /** // * 表情包下载失败回调. // * @param emojiPackage // * @param errorCode 为简单起见, 这里的值复用{@link com.zhangtielei.demos.async.programming.callback.download.v3.DownloadListener}中的错误码定义. // * @param errorMessage // */ // void emojiDownloadFailed(EmojiPackage emojiPackage, int errorCode, String errorMessage); // // /** // * 表情包下载进度回调. 每次下载完一个图片文件后回调一次. // * @param emojiPackage // * @param downloadEmojiUrl 当前刚下载完的图片文件URL // */ // void emojiDownloadProgress(EmojiPackage emojiPackage, String downloadEmojiUrl); // } // // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiPackage.java // public class EmojiPackage { // /** // * 表情包ID // */ // public long emojiId; // /** // * 表情包图片列表 // */ // public List<String> emojiUrls; // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // }
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiDownloader; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiPackage; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import java.util.ArrayList;
/* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.callback.emoji.v2; /** * 通过用映射关系来保存上下文来实现表情包下载的演示页面. */ public class EmojiDownloadDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView;
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiDownloader.java // public interface EmojiDownloader { // /** // * 开始下载指定的表情包 // * @param emojiPackage // */ // void startDownloadEmoji(EmojiPackage emojiPackage); // // /** // * 设置监听器. // * @param listener // */ // void setEmojiDownloadListener(EmojiDownloadListener listener); // // /** // * 这里定义回调相关的接口. 不是我们要讨论的重点. // * 这里的定义用于完整演示. // */ // // interface EmojiDownloadListener { // /** // * 表情包下载成功回调. // * @param emojiPackage // */ // void emojiDownloadSuccess(EmojiPackage emojiPackage); // // /** // * 表情包下载失败回调. // * @param emojiPackage // * @param errorCode 为简单起见, 这里的值复用{@link com.zhangtielei.demos.async.programming.callback.download.v3.DownloadListener}中的错误码定义. // * @param errorMessage // */ // void emojiDownloadFailed(EmojiPackage emojiPackage, int errorCode, String errorMessage); // // /** // * 表情包下载进度回调. 每次下载完一个图片文件后回调一次. // * @param emojiPackage // * @param downloadEmojiUrl 当前刚下载完的图片文件URL // */ // void emojiDownloadProgress(EmojiPackage emojiPackage, String downloadEmojiUrl); // } // // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiPackage.java // public class EmojiPackage { // /** // * 表情包ID // */ // public long emojiId; // /** // * 表情包图片列表 // */ // public List<String> emojiUrls; // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // } // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/v2/EmojiDownloadDemoActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiDownloader; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiPackage; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import java.util.ArrayList; /* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.callback.emoji.v2; /** * 通过用映射关系来保存上下文来实现表情包下载的演示页面. */ public class EmojiDownloadDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView;
private EmojiDownloader emojiDownloader;
tielei/AsyncProgrammingDemos
AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/v2/EmojiDownloadDemoActivity.java
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiDownloader.java // public interface EmojiDownloader { // /** // * 开始下载指定的表情包 // * @param emojiPackage // */ // void startDownloadEmoji(EmojiPackage emojiPackage); // // /** // * 设置监听器. // * @param listener // */ // void setEmojiDownloadListener(EmojiDownloadListener listener); // // /** // * 这里定义回调相关的接口. 不是我们要讨论的重点. // * 这里的定义用于完整演示. // */ // // interface EmojiDownloadListener { // /** // * 表情包下载成功回调. // * @param emojiPackage // */ // void emojiDownloadSuccess(EmojiPackage emojiPackage); // // /** // * 表情包下载失败回调. // * @param emojiPackage // * @param errorCode 为简单起见, 这里的值复用{@link com.zhangtielei.demos.async.programming.callback.download.v3.DownloadListener}中的错误码定义. // * @param errorMessage // */ // void emojiDownloadFailed(EmojiPackage emojiPackage, int errorCode, String errorMessage); // // /** // * 表情包下载进度回调. 每次下载完一个图片文件后回调一次. // * @param emojiPackage // * @param downloadEmojiUrl 当前刚下载完的图片文件URL // */ // void emojiDownloadProgress(EmojiPackage emojiPackage, String downloadEmojiUrl); // } // // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiPackage.java // public class EmojiPackage { // /** // * 表情包ID // */ // public long emojiId; // /** // * 表情包图片列表 // */ // public List<String> emojiUrls; // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // }
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiDownloader; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiPackage; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import java.util.ArrayList;
/* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.callback.emoji.v2; /** * 通过用映射关系来保存上下文来实现表情包下载的演示页面. */ public class EmojiDownloadDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView; private EmojiDownloader emojiDownloader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_display); description = (TextView) findViewById(R.id.description); logTextView = (TextView) findViewById(R.id.log_display); description.setText(R.string.emoji_download_demo2_description); emojiDownloader = new MyEmojiDownloader(); emojiDownloader.setEmojiDownloadListener(new EmojiDownloader.EmojiDownloadListener() { @Override
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiDownloader.java // public interface EmojiDownloader { // /** // * 开始下载指定的表情包 // * @param emojiPackage // */ // void startDownloadEmoji(EmojiPackage emojiPackage); // // /** // * 设置监听器. // * @param listener // */ // void setEmojiDownloadListener(EmojiDownloadListener listener); // // /** // * 这里定义回调相关的接口. 不是我们要讨论的重点. // * 这里的定义用于完整演示. // */ // // interface EmojiDownloadListener { // /** // * 表情包下载成功回调. // * @param emojiPackage // */ // void emojiDownloadSuccess(EmojiPackage emojiPackage); // // /** // * 表情包下载失败回调. // * @param emojiPackage // * @param errorCode 为简单起见, 这里的值复用{@link com.zhangtielei.demos.async.programming.callback.download.v3.DownloadListener}中的错误码定义. // * @param errorMessage // */ // void emojiDownloadFailed(EmojiPackage emojiPackage, int errorCode, String errorMessage); // // /** // * 表情包下载进度回调. 每次下载完一个图片文件后回调一次. // * @param emojiPackage // * @param downloadEmojiUrl 当前刚下载完的图片文件URL // */ // void emojiDownloadProgress(EmojiPackage emojiPackage, String downloadEmojiUrl); // } // // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiPackage.java // public class EmojiPackage { // /** // * 表情包ID // */ // public long emojiId; // /** // * 表情包图片列表 // */ // public List<String> emojiUrls; // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // } // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/v2/EmojiDownloadDemoActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiDownloader; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiPackage; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import java.util.ArrayList; /* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.callback.emoji.v2; /** * 通过用映射关系来保存上下文来实现表情包下载的演示页面. */ public class EmojiDownloadDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView; private EmojiDownloader emojiDownloader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_display); description = (TextView) findViewById(R.id.description); logTextView = (TextView) findViewById(R.id.log_display); description.setText(R.string.emoji_download_demo2_description); emojiDownloader = new MyEmojiDownloader(); emojiDownloader.setEmojiDownloadListener(new EmojiDownloader.EmojiDownloadListener() { @Override
public void emojiDownloadSuccess(EmojiPackage emojiPackage) {
tielei/AsyncProgrammingDemos
AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/v2/EmojiDownloadDemoActivity.java
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiDownloader.java // public interface EmojiDownloader { // /** // * 开始下载指定的表情包 // * @param emojiPackage // */ // void startDownloadEmoji(EmojiPackage emojiPackage); // // /** // * 设置监听器. // * @param listener // */ // void setEmojiDownloadListener(EmojiDownloadListener listener); // // /** // * 这里定义回调相关的接口. 不是我们要讨论的重点. // * 这里的定义用于完整演示. // */ // // interface EmojiDownloadListener { // /** // * 表情包下载成功回调. // * @param emojiPackage // */ // void emojiDownloadSuccess(EmojiPackage emojiPackage); // // /** // * 表情包下载失败回调. // * @param emojiPackage // * @param errorCode 为简单起见, 这里的值复用{@link com.zhangtielei.demos.async.programming.callback.download.v3.DownloadListener}中的错误码定义. // * @param errorMessage // */ // void emojiDownloadFailed(EmojiPackage emojiPackage, int errorCode, String errorMessage); // // /** // * 表情包下载进度回调. 每次下载完一个图片文件后回调一次. // * @param emojiPackage // * @param downloadEmojiUrl 当前刚下载完的图片文件URL // */ // void emojiDownloadProgress(EmojiPackage emojiPackage, String downloadEmojiUrl); // } // // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiPackage.java // public class EmojiPackage { // /** // * 表情包ID // */ // public long emojiId; // /** // * 表情包图片列表 // */ // public List<String> emojiUrls; // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // }
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiDownloader; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiPackage; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import java.util.ArrayList;
/* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.callback.emoji.v2; /** * 通过用映射关系来保存上下文来实现表情包下载的演示页面. */ public class EmojiDownloadDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView; private EmojiDownloader emojiDownloader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_display); description = (TextView) findViewById(R.id.description); logTextView = (TextView) findViewById(R.id.log_display); description.setText(R.string.emoji_download_demo2_description); emojiDownloader = new MyEmojiDownloader(); emojiDownloader.setEmojiDownloadListener(new EmojiDownloader.EmojiDownloadListener() { @Override public void emojiDownloadSuccess(EmojiPackage emojiPackage) {
// Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiDownloader.java // public interface EmojiDownloader { // /** // * 开始下载指定的表情包 // * @param emojiPackage // */ // void startDownloadEmoji(EmojiPackage emojiPackage); // // /** // * 设置监听器. // * @param listener // */ // void setEmojiDownloadListener(EmojiDownloadListener listener); // // /** // * 这里定义回调相关的接口. 不是我们要讨论的重点. // * 这里的定义用于完整演示. // */ // // interface EmojiDownloadListener { // /** // * 表情包下载成功回调. // * @param emojiPackage // */ // void emojiDownloadSuccess(EmojiPackage emojiPackage); // // /** // * 表情包下载失败回调. // * @param emojiPackage // * @param errorCode 为简单起见, 这里的值复用{@link com.zhangtielei.demos.async.programming.callback.download.v3.DownloadListener}中的错误码定义. // * @param errorMessage // */ // void emojiDownloadFailed(EmojiPackage emojiPackage, int errorCode, String errorMessage); // // /** // * 表情包下载进度回调. 每次下载完一个图片文件后回调一次. // * @param emojiPackage // * @param downloadEmojiUrl 当前刚下载完的图片文件URL // */ // void emojiDownloadProgress(EmojiPackage emojiPackage, String downloadEmojiUrl); // } // // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/EmojiPackage.java // public class EmojiPackage { // /** // * 表情包ID // */ // public long emojiId; // /** // * 表情包图片列表 // */ // public List<String> emojiUrls; // } // // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/common/utils/TextLogUtil.java // public class TextLogUtil { // /** // * 在一个TextView上追加一行日志. // * @param logTextView // * @param log // */ // public static void println(TextView logTextView, CharSequence log) { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); // String timestamp = sdf.format(new Date()); // // CharSequence newText = timestamp + ": " + log; // CharSequence oldText = logTextView.getText(); // if (oldText == null || oldText.length() <= 0) { // logTextView.setText(newText); // } // else { // logTextView.setText(oldText + "\n" + newText); // } // } // } // Path: AndroidDemos/app/src/main/java/com/zhangtielei/demos/async/programming/callback/emoji/v2/EmojiDownloadDemoActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.zhangtielei.demos.async.programming.R; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiDownloader; import com.zhangtielei.demos.async.programming.callback.emoji.EmojiPackage; import com.zhangtielei.demos.async.programming.common.utils.TextLogUtil; import java.util.ArrayList; /* * Copyright (C) 2016 Tielei Zhang (zhangtielei.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhangtielei.demos.async.programming.callback.emoji.v2; /** * 通过用映射关系来保存上下文来实现表情包下载的演示页面. */ public class EmojiDownloadDemoActivity extends AppCompatActivity { private TextView description; private TextView logTextView; private EmojiDownloader emojiDownloader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_display); description = (TextView) findViewById(R.id.description); logTextView = (TextView) findViewById(R.id.log_display); description.setText(R.string.emoji_download_demo2_description); emojiDownloader = new MyEmojiDownloader(); emojiDownloader.setEmojiDownloadListener(new EmojiDownloader.EmojiDownloadListener() { @Override public void emojiDownloadSuccess(EmojiPackage emojiPackage) {
TextLogUtil.println(logTextView, "emoji package (emojiId: " + emojiPackage.emojiId + ") downloaded success!");
evsinev/docker-network-veth
server/src/main/java/io/pne/veth/server/handlers/service/impl/NetworkServiceImpl.java
// Path: server/src/main/java/io/pne/veth/server/handlers/dao/IEndpointDao.java // public interface IEndpointDao { // // void addEndpoint(TEndpoint aEndpoint); // // TEndpoint findEndPoint(String aEndpointId); // // void removeEndpoint(String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/INetworkDao.java // public interface INetworkDao { // // void addNetwork(TNetwork aNetwork); // // TNetwork findNetwork(String aNetworkId); // // void removeNetwork(String aNetworkId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TEndpoint.java // public class TEndpoint { // // public final String id; // public final String ipAddress; // public final String macAddress; // public final String device; // // public TEndpoint(String id, String ipAddress, String macAddress, String aDevice) { // this.id = id; // this.ipAddress = ipAddress; // this.macAddress = macAddress; // device = aDevice; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TNetwork.java // public class TNetwork { // // public final String id; // public final String gateway; // public final String pool; // public final String interfaceSuffix; // // public TNetwork(String id, String gateway, String pool, String aSuffix) { // this.id = id; // this.gateway = gateway; // this.pool = pool; // interfaceSuffix = aSuffix; // } // // @Override // public String toString() { // return "TNetwork{" + // "id='" + id + '\'' + // ", gateway='" + gateway + '\'' + // ", pool='" + pool + '\'' + // ", interfaceSuffix='" + interfaceSuffix + '\'' + // '}'; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/ICommandService.java // public interface ICommandService { // // String executeCommand(ShellCommand aCommand) throws IOException, InterruptedException; // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/INetworkService.java // public interface INetworkService { // // String getNetworkGateway(String aNetwork, String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/model/ShellCommand.java // public class ShellCommand { // // public final String[] arguments; // // private ShellCommand(String[] aArguments) { // arguments = aArguments; // } // // public String getCommand() { // StringBuilder sb = new StringBuilder(); // sb.append(arguments[0]); // for(int i=1; i<arguments.length; i++) { // sb.append(' '); // sb.append(arguments[i]); // } // return sb.toString(); // } // // public static class Builder { // private final List<String> arguments; // // public Builder(String aCommandName) { // arguments = new ArrayList<>(); // arguments.add(aCommandName); // } // // public Builder add(String aArgument) { // arguments.add(aArgument); // return this; // } // // public ShellCommand build() { // return new ShellCommand(arguments.toArray(new String[arguments.size()])); // } // } // // @Override // public String toString() { // return "ShellCommand{" + // "arguments=" + Arrays.toString(arguments) + // '}'; // } // }
import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; import io.pne.veth.server.handlers.dao.IEndpointDao; import io.pne.veth.server.handlers.dao.INetworkDao; import io.pne.veth.server.handlers.dao.TEndpoint; import io.pne.veth.server.handlers.dao.TNetwork; import io.pne.veth.server.handlers.service.ICommandService; import io.pne.veth.server.handlers.service.INetworkService; import io.pne.veth.server.handlers.service.model.ShellCommand; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.StringTokenizer;
package io.pne.veth.server.handlers.service.impl; public class NetworkServiceImpl implements INetworkService { private static final Logger LOG = LoggerFactory.getLogger(NetworkServiceImpl.class);
// Path: server/src/main/java/io/pne/veth/server/handlers/dao/IEndpointDao.java // public interface IEndpointDao { // // void addEndpoint(TEndpoint aEndpoint); // // TEndpoint findEndPoint(String aEndpointId); // // void removeEndpoint(String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/INetworkDao.java // public interface INetworkDao { // // void addNetwork(TNetwork aNetwork); // // TNetwork findNetwork(String aNetworkId); // // void removeNetwork(String aNetworkId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TEndpoint.java // public class TEndpoint { // // public final String id; // public final String ipAddress; // public final String macAddress; // public final String device; // // public TEndpoint(String id, String ipAddress, String macAddress, String aDevice) { // this.id = id; // this.ipAddress = ipAddress; // this.macAddress = macAddress; // device = aDevice; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TNetwork.java // public class TNetwork { // // public final String id; // public final String gateway; // public final String pool; // public final String interfaceSuffix; // // public TNetwork(String id, String gateway, String pool, String aSuffix) { // this.id = id; // this.gateway = gateway; // this.pool = pool; // interfaceSuffix = aSuffix; // } // // @Override // public String toString() { // return "TNetwork{" + // "id='" + id + '\'' + // ", gateway='" + gateway + '\'' + // ", pool='" + pool + '\'' + // ", interfaceSuffix='" + interfaceSuffix + '\'' + // '}'; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/ICommandService.java // public interface ICommandService { // // String executeCommand(ShellCommand aCommand) throws IOException, InterruptedException; // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/INetworkService.java // public interface INetworkService { // // String getNetworkGateway(String aNetwork, String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/model/ShellCommand.java // public class ShellCommand { // // public final String[] arguments; // // private ShellCommand(String[] aArguments) { // arguments = aArguments; // } // // public String getCommand() { // StringBuilder sb = new StringBuilder(); // sb.append(arguments[0]); // for(int i=1; i<arguments.length; i++) { // sb.append(' '); // sb.append(arguments[i]); // } // return sb.toString(); // } // // public static class Builder { // private final List<String> arguments; // // public Builder(String aCommandName) { // arguments = new ArrayList<>(); // arguments.add(aCommandName); // } // // public Builder add(String aArgument) { // arguments.add(aArgument); // return this; // } // // public ShellCommand build() { // return new ShellCommand(arguments.toArray(new String[arguments.size()])); // } // } // // @Override // public String toString() { // return "ShellCommand{" + // "arguments=" + Arrays.toString(arguments) + // '}'; // } // } // Path: server/src/main/java/io/pne/veth/server/handlers/service/impl/NetworkServiceImpl.java import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; import io.pne.veth.server.handlers.dao.IEndpointDao; import io.pne.veth.server.handlers.dao.INetworkDao; import io.pne.veth.server.handlers.dao.TEndpoint; import io.pne.veth.server.handlers.dao.TNetwork; import io.pne.veth.server.handlers.service.ICommandService; import io.pne.veth.server.handlers.service.INetworkService; import io.pne.veth.server.handlers.service.model.ShellCommand; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.StringTokenizer; package io.pne.veth.server.handlers.service.impl; public class NetworkServiceImpl implements INetworkService { private static final Logger LOG = LoggerFactory.getLogger(NetworkServiceImpl.class);
private final INetworkDao networkDao;
evsinev/docker-network-veth
server/src/main/java/io/pne/veth/server/handlers/service/impl/NetworkServiceImpl.java
// Path: server/src/main/java/io/pne/veth/server/handlers/dao/IEndpointDao.java // public interface IEndpointDao { // // void addEndpoint(TEndpoint aEndpoint); // // TEndpoint findEndPoint(String aEndpointId); // // void removeEndpoint(String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/INetworkDao.java // public interface INetworkDao { // // void addNetwork(TNetwork aNetwork); // // TNetwork findNetwork(String aNetworkId); // // void removeNetwork(String aNetworkId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TEndpoint.java // public class TEndpoint { // // public final String id; // public final String ipAddress; // public final String macAddress; // public final String device; // // public TEndpoint(String id, String ipAddress, String macAddress, String aDevice) { // this.id = id; // this.ipAddress = ipAddress; // this.macAddress = macAddress; // device = aDevice; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TNetwork.java // public class TNetwork { // // public final String id; // public final String gateway; // public final String pool; // public final String interfaceSuffix; // // public TNetwork(String id, String gateway, String pool, String aSuffix) { // this.id = id; // this.gateway = gateway; // this.pool = pool; // interfaceSuffix = aSuffix; // } // // @Override // public String toString() { // return "TNetwork{" + // "id='" + id + '\'' + // ", gateway='" + gateway + '\'' + // ", pool='" + pool + '\'' + // ", interfaceSuffix='" + interfaceSuffix + '\'' + // '}'; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/ICommandService.java // public interface ICommandService { // // String executeCommand(ShellCommand aCommand) throws IOException, InterruptedException; // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/INetworkService.java // public interface INetworkService { // // String getNetworkGateway(String aNetwork, String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/model/ShellCommand.java // public class ShellCommand { // // public final String[] arguments; // // private ShellCommand(String[] aArguments) { // arguments = aArguments; // } // // public String getCommand() { // StringBuilder sb = new StringBuilder(); // sb.append(arguments[0]); // for(int i=1; i<arguments.length; i++) { // sb.append(' '); // sb.append(arguments[i]); // } // return sb.toString(); // } // // public static class Builder { // private final List<String> arguments; // // public Builder(String aCommandName) { // arguments = new ArrayList<>(); // arguments.add(aCommandName); // } // // public Builder add(String aArgument) { // arguments.add(aArgument); // return this; // } // // public ShellCommand build() { // return new ShellCommand(arguments.toArray(new String[arguments.size()])); // } // } // // @Override // public String toString() { // return "ShellCommand{" + // "arguments=" + Arrays.toString(arguments) + // '}'; // } // }
import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; import io.pne.veth.server.handlers.dao.IEndpointDao; import io.pne.veth.server.handlers.dao.INetworkDao; import io.pne.veth.server.handlers.dao.TEndpoint; import io.pne.veth.server.handlers.dao.TNetwork; import io.pne.veth.server.handlers.service.ICommandService; import io.pne.veth.server.handlers.service.INetworkService; import io.pne.veth.server.handlers.service.model.ShellCommand; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.StringTokenizer;
package io.pne.veth.server.handlers.service.impl; public class NetworkServiceImpl implements INetworkService { private static final Logger LOG = LoggerFactory.getLogger(NetworkServiceImpl.class); private final INetworkDao networkDao;
// Path: server/src/main/java/io/pne/veth/server/handlers/dao/IEndpointDao.java // public interface IEndpointDao { // // void addEndpoint(TEndpoint aEndpoint); // // TEndpoint findEndPoint(String aEndpointId); // // void removeEndpoint(String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/INetworkDao.java // public interface INetworkDao { // // void addNetwork(TNetwork aNetwork); // // TNetwork findNetwork(String aNetworkId); // // void removeNetwork(String aNetworkId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TEndpoint.java // public class TEndpoint { // // public final String id; // public final String ipAddress; // public final String macAddress; // public final String device; // // public TEndpoint(String id, String ipAddress, String macAddress, String aDevice) { // this.id = id; // this.ipAddress = ipAddress; // this.macAddress = macAddress; // device = aDevice; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TNetwork.java // public class TNetwork { // // public final String id; // public final String gateway; // public final String pool; // public final String interfaceSuffix; // // public TNetwork(String id, String gateway, String pool, String aSuffix) { // this.id = id; // this.gateway = gateway; // this.pool = pool; // interfaceSuffix = aSuffix; // } // // @Override // public String toString() { // return "TNetwork{" + // "id='" + id + '\'' + // ", gateway='" + gateway + '\'' + // ", pool='" + pool + '\'' + // ", interfaceSuffix='" + interfaceSuffix + '\'' + // '}'; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/ICommandService.java // public interface ICommandService { // // String executeCommand(ShellCommand aCommand) throws IOException, InterruptedException; // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/INetworkService.java // public interface INetworkService { // // String getNetworkGateway(String aNetwork, String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/model/ShellCommand.java // public class ShellCommand { // // public final String[] arguments; // // private ShellCommand(String[] aArguments) { // arguments = aArguments; // } // // public String getCommand() { // StringBuilder sb = new StringBuilder(); // sb.append(arguments[0]); // for(int i=1; i<arguments.length; i++) { // sb.append(' '); // sb.append(arguments[i]); // } // return sb.toString(); // } // // public static class Builder { // private final List<String> arguments; // // public Builder(String aCommandName) { // arguments = new ArrayList<>(); // arguments.add(aCommandName); // } // // public Builder add(String aArgument) { // arguments.add(aArgument); // return this; // } // // public ShellCommand build() { // return new ShellCommand(arguments.toArray(new String[arguments.size()])); // } // } // // @Override // public String toString() { // return "ShellCommand{" + // "arguments=" + Arrays.toString(arguments) + // '}'; // } // } // Path: server/src/main/java/io/pne/veth/server/handlers/service/impl/NetworkServiceImpl.java import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; import io.pne.veth.server.handlers.dao.IEndpointDao; import io.pne.veth.server.handlers.dao.INetworkDao; import io.pne.veth.server.handlers.dao.TEndpoint; import io.pne.veth.server.handlers.dao.TNetwork; import io.pne.veth.server.handlers.service.ICommandService; import io.pne.veth.server.handlers.service.INetworkService; import io.pne.veth.server.handlers.service.model.ShellCommand; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.StringTokenizer; package io.pne.veth.server.handlers.service.impl; public class NetworkServiceImpl implements INetworkService { private static final Logger LOG = LoggerFactory.getLogger(NetworkServiceImpl.class); private final INetworkDao networkDao;
private final IEndpointDao endpointDao;
evsinev/docker-network-veth
server/src/main/java/io/pne/veth/server/handlers/service/impl/NetworkServiceImpl.java
// Path: server/src/main/java/io/pne/veth/server/handlers/dao/IEndpointDao.java // public interface IEndpointDao { // // void addEndpoint(TEndpoint aEndpoint); // // TEndpoint findEndPoint(String aEndpointId); // // void removeEndpoint(String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/INetworkDao.java // public interface INetworkDao { // // void addNetwork(TNetwork aNetwork); // // TNetwork findNetwork(String aNetworkId); // // void removeNetwork(String aNetworkId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TEndpoint.java // public class TEndpoint { // // public final String id; // public final String ipAddress; // public final String macAddress; // public final String device; // // public TEndpoint(String id, String ipAddress, String macAddress, String aDevice) { // this.id = id; // this.ipAddress = ipAddress; // this.macAddress = macAddress; // device = aDevice; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TNetwork.java // public class TNetwork { // // public final String id; // public final String gateway; // public final String pool; // public final String interfaceSuffix; // // public TNetwork(String id, String gateway, String pool, String aSuffix) { // this.id = id; // this.gateway = gateway; // this.pool = pool; // interfaceSuffix = aSuffix; // } // // @Override // public String toString() { // return "TNetwork{" + // "id='" + id + '\'' + // ", gateway='" + gateway + '\'' + // ", pool='" + pool + '\'' + // ", interfaceSuffix='" + interfaceSuffix + '\'' + // '}'; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/ICommandService.java // public interface ICommandService { // // String executeCommand(ShellCommand aCommand) throws IOException, InterruptedException; // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/INetworkService.java // public interface INetworkService { // // String getNetworkGateway(String aNetwork, String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/model/ShellCommand.java // public class ShellCommand { // // public final String[] arguments; // // private ShellCommand(String[] aArguments) { // arguments = aArguments; // } // // public String getCommand() { // StringBuilder sb = new StringBuilder(); // sb.append(arguments[0]); // for(int i=1; i<arguments.length; i++) { // sb.append(' '); // sb.append(arguments[i]); // } // return sb.toString(); // } // // public static class Builder { // private final List<String> arguments; // // public Builder(String aCommandName) { // arguments = new ArrayList<>(); // arguments.add(aCommandName); // } // // public Builder add(String aArgument) { // arguments.add(aArgument); // return this; // } // // public ShellCommand build() { // return new ShellCommand(arguments.toArray(new String[arguments.size()])); // } // } // // @Override // public String toString() { // return "ShellCommand{" + // "arguments=" + Arrays.toString(arguments) + // '}'; // } // }
import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; import io.pne.veth.server.handlers.dao.IEndpointDao; import io.pne.veth.server.handlers.dao.INetworkDao; import io.pne.veth.server.handlers.dao.TEndpoint; import io.pne.veth.server.handlers.dao.TNetwork; import io.pne.veth.server.handlers.service.ICommandService; import io.pne.veth.server.handlers.service.INetworkService; import io.pne.veth.server.handlers.service.model.ShellCommand; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.StringTokenizer;
package io.pne.veth.server.handlers.service.impl; public class NetworkServiceImpl implements INetworkService { private static final Logger LOG = LoggerFactory.getLogger(NetworkServiceImpl.class); private final INetworkDao networkDao; private final IEndpointDao endpointDao; private final Gson gson;
// Path: server/src/main/java/io/pne/veth/server/handlers/dao/IEndpointDao.java // public interface IEndpointDao { // // void addEndpoint(TEndpoint aEndpoint); // // TEndpoint findEndPoint(String aEndpointId); // // void removeEndpoint(String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/INetworkDao.java // public interface INetworkDao { // // void addNetwork(TNetwork aNetwork); // // TNetwork findNetwork(String aNetworkId); // // void removeNetwork(String aNetworkId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TEndpoint.java // public class TEndpoint { // // public final String id; // public final String ipAddress; // public final String macAddress; // public final String device; // // public TEndpoint(String id, String ipAddress, String macAddress, String aDevice) { // this.id = id; // this.ipAddress = ipAddress; // this.macAddress = macAddress; // device = aDevice; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TNetwork.java // public class TNetwork { // // public final String id; // public final String gateway; // public final String pool; // public final String interfaceSuffix; // // public TNetwork(String id, String gateway, String pool, String aSuffix) { // this.id = id; // this.gateway = gateway; // this.pool = pool; // interfaceSuffix = aSuffix; // } // // @Override // public String toString() { // return "TNetwork{" + // "id='" + id + '\'' + // ", gateway='" + gateway + '\'' + // ", pool='" + pool + '\'' + // ", interfaceSuffix='" + interfaceSuffix + '\'' + // '}'; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/ICommandService.java // public interface ICommandService { // // String executeCommand(ShellCommand aCommand) throws IOException, InterruptedException; // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/INetworkService.java // public interface INetworkService { // // String getNetworkGateway(String aNetwork, String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/model/ShellCommand.java // public class ShellCommand { // // public final String[] arguments; // // private ShellCommand(String[] aArguments) { // arguments = aArguments; // } // // public String getCommand() { // StringBuilder sb = new StringBuilder(); // sb.append(arguments[0]); // for(int i=1; i<arguments.length; i++) { // sb.append(' '); // sb.append(arguments[i]); // } // return sb.toString(); // } // // public static class Builder { // private final List<String> arguments; // // public Builder(String aCommandName) { // arguments = new ArrayList<>(); // arguments.add(aCommandName); // } // // public Builder add(String aArgument) { // arguments.add(aArgument); // return this; // } // // public ShellCommand build() { // return new ShellCommand(arguments.toArray(new String[arguments.size()])); // } // } // // @Override // public String toString() { // return "ShellCommand{" + // "arguments=" + Arrays.toString(arguments) + // '}'; // } // } // Path: server/src/main/java/io/pne/veth/server/handlers/service/impl/NetworkServiceImpl.java import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; import io.pne.veth.server.handlers.dao.IEndpointDao; import io.pne.veth.server.handlers.dao.INetworkDao; import io.pne.veth.server.handlers.dao.TEndpoint; import io.pne.veth.server.handlers.dao.TNetwork; import io.pne.veth.server.handlers.service.ICommandService; import io.pne.veth.server.handlers.service.INetworkService; import io.pne.veth.server.handlers.service.model.ShellCommand; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.StringTokenizer; package io.pne.veth.server.handlers.service.impl; public class NetworkServiceImpl implements INetworkService { private static final Logger LOG = LoggerFactory.getLogger(NetworkServiceImpl.class); private final INetworkDao networkDao; private final IEndpointDao endpointDao; private final Gson gson;
private final ICommandService commandService;
evsinev/docker-network-veth
server/src/main/java/io/pne/veth/server/handlers/service/impl/NetworkServiceImpl.java
// Path: server/src/main/java/io/pne/veth/server/handlers/dao/IEndpointDao.java // public interface IEndpointDao { // // void addEndpoint(TEndpoint aEndpoint); // // TEndpoint findEndPoint(String aEndpointId); // // void removeEndpoint(String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/INetworkDao.java // public interface INetworkDao { // // void addNetwork(TNetwork aNetwork); // // TNetwork findNetwork(String aNetworkId); // // void removeNetwork(String aNetworkId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TEndpoint.java // public class TEndpoint { // // public final String id; // public final String ipAddress; // public final String macAddress; // public final String device; // // public TEndpoint(String id, String ipAddress, String macAddress, String aDevice) { // this.id = id; // this.ipAddress = ipAddress; // this.macAddress = macAddress; // device = aDevice; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TNetwork.java // public class TNetwork { // // public final String id; // public final String gateway; // public final String pool; // public final String interfaceSuffix; // // public TNetwork(String id, String gateway, String pool, String aSuffix) { // this.id = id; // this.gateway = gateway; // this.pool = pool; // interfaceSuffix = aSuffix; // } // // @Override // public String toString() { // return "TNetwork{" + // "id='" + id + '\'' + // ", gateway='" + gateway + '\'' + // ", pool='" + pool + '\'' + // ", interfaceSuffix='" + interfaceSuffix + '\'' + // '}'; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/ICommandService.java // public interface ICommandService { // // String executeCommand(ShellCommand aCommand) throws IOException, InterruptedException; // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/INetworkService.java // public interface INetworkService { // // String getNetworkGateway(String aNetwork, String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/model/ShellCommand.java // public class ShellCommand { // // public final String[] arguments; // // private ShellCommand(String[] aArguments) { // arguments = aArguments; // } // // public String getCommand() { // StringBuilder sb = new StringBuilder(); // sb.append(arguments[0]); // for(int i=1; i<arguments.length; i++) { // sb.append(' '); // sb.append(arguments[i]); // } // return sb.toString(); // } // // public static class Builder { // private final List<String> arguments; // // public Builder(String aCommandName) { // arguments = new ArrayList<>(); // arguments.add(aCommandName); // } // // public Builder add(String aArgument) { // arguments.add(aArgument); // return this; // } // // public ShellCommand build() { // return new ShellCommand(arguments.toArray(new String[arguments.size()])); // } // } // // @Override // public String toString() { // return "ShellCommand{" + // "arguments=" + Arrays.toString(arguments) + // '}'; // } // }
import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; import io.pne.veth.server.handlers.dao.IEndpointDao; import io.pne.veth.server.handlers.dao.INetworkDao; import io.pne.veth.server.handlers.dao.TEndpoint; import io.pne.veth.server.handlers.dao.TNetwork; import io.pne.veth.server.handlers.service.ICommandService; import io.pne.veth.server.handlers.service.INetworkService; import io.pne.veth.server.handlers.service.model.ShellCommand; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.StringTokenizer;
package io.pne.veth.server.handlers.service.impl; public class NetworkServiceImpl implements INetworkService { private static final Logger LOG = LoggerFactory.getLogger(NetworkServiceImpl.class); private final INetworkDao networkDao; private final IEndpointDao endpointDao; private final Gson gson; private final ICommandService commandService; public NetworkServiceImpl(INetworkDao networkDao, IEndpointDao endpointDao, Gson gson, ICommandService shellService) { this.networkDao = networkDao; this.endpointDao = endpointDao; this.gson = gson; this.commandService = shellService; } @Override public String getNetworkGateway(String aNetworkId, String aEndpointId) {
// Path: server/src/main/java/io/pne/veth/server/handlers/dao/IEndpointDao.java // public interface IEndpointDao { // // void addEndpoint(TEndpoint aEndpoint); // // TEndpoint findEndPoint(String aEndpointId); // // void removeEndpoint(String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/INetworkDao.java // public interface INetworkDao { // // void addNetwork(TNetwork aNetwork); // // TNetwork findNetwork(String aNetworkId); // // void removeNetwork(String aNetworkId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TEndpoint.java // public class TEndpoint { // // public final String id; // public final String ipAddress; // public final String macAddress; // public final String device; // // public TEndpoint(String id, String ipAddress, String macAddress, String aDevice) { // this.id = id; // this.ipAddress = ipAddress; // this.macAddress = macAddress; // device = aDevice; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TNetwork.java // public class TNetwork { // // public final String id; // public final String gateway; // public final String pool; // public final String interfaceSuffix; // // public TNetwork(String id, String gateway, String pool, String aSuffix) { // this.id = id; // this.gateway = gateway; // this.pool = pool; // interfaceSuffix = aSuffix; // } // // @Override // public String toString() { // return "TNetwork{" + // "id='" + id + '\'' + // ", gateway='" + gateway + '\'' + // ", pool='" + pool + '\'' + // ", interfaceSuffix='" + interfaceSuffix + '\'' + // '}'; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/ICommandService.java // public interface ICommandService { // // String executeCommand(ShellCommand aCommand) throws IOException, InterruptedException; // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/INetworkService.java // public interface INetworkService { // // String getNetworkGateway(String aNetwork, String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/model/ShellCommand.java // public class ShellCommand { // // public final String[] arguments; // // private ShellCommand(String[] aArguments) { // arguments = aArguments; // } // // public String getCommand() { // StringBuilder sb = new StringBuilder(); // sb.append(arguments[0]); // for(int i=1; i<arguments.length; i++) { // sb.append(' '); // sb.append(arguments[i]); // } // return sb.toString(); // } // // public static class Builder { // private final List<String> arguments; // // public Builder(String aCommandName) { // arguments = new ArrayList<>(); // arguments.add(aCommandName); // } // // public Builder add(String aArgument) { // arguments.add(aArgument); // return this; // } // // public ShellCommand build() { // return new ShellCommand(arguments.toArray(new String[arguments.size()])); // } // } // // @Override // public String toString() { // return "ShellCommand{" + // "arguments=" + Arrays.toString(arguments) + // '}'; // } // } // Path: server/src/main/java/io/pne/veth/server/handlers/service/impl/NetworkServiceImpl.java import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; import io.pne.veth.server.handlers.dao.IEndpointDao; import io.pne.veth.server.handlers.dao.INetworkDao; import io.pne.veth.server.handlers.dao.TEndpoint; import io.pne.veth.server.handlers.dao.TNetwork; import io.pne.veth.server.handlers.service.ICommandService; import io.pne.veth.server.handlers.service.INetworkService; import io.pne.veth.server.handlers.service.model.ShellCommand; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.StringTokenizer; package io.pne.veth.server.handlers.service.impl; public class NetworkServiceImpl implements INetworkService { private static final Logger LOG = LoggerFactory.getLogger(NetworkServiceImpl.class); private final INetworkDao networkDao; private final IEndpointDao endpointDao; private final Gson gson; private final ICommandService commandService; public NetworkServiceImpl(INetworkDao networkDao, IEndpointDao endpointDao, Gson gson, ICommandService shellService) { this.networkDao = networkDao; this.endpointDao = endpointDao; this.gson = gson; this.commandService = shellService; } @Override public String getNetworkGateway(String aNetworkId, String aEndpointId) {
TNetwork network = networkDao.findNetwork(aNetworkId);
evsinev/docker-network-veth
server/src/main/java/io/pne/veth/server/handlers/service/impl/NetworkServiceImpl.java
// Path: server/src/main/java/io/pne/veth/server/handlers/dao/IEndpointDao.java // public interface IEndpointDao { // // void addEndpoint(TEndpoint aEndpoint); // // TEndpoint findEndPoint(String aEndpointId); // // void removeEndpoint(String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/INetworkDao.java // public interface INetworkDao { // // void addNetwork(TNetwork aNetwork); // // TNetwork findNetwork(String aNetworkId); // // void removeNetwork(String aNetworkId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TEndpoint.java // public class TEndpoint { // // public final String id; // public final String ipAddress; // public final String macAddress; // public final String device; // // public TEndpoint(String id, String ipAddress, String macAddress, String aDevice) { // this.id = id; // this.ipAddress = ipAddress; // this.macAddress = macAddress; // device = aDevice; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TNetwork.java // public class TNetwork { // // public final String id; // public final String gateway; // public final String pool; // public final String interfaceSuffix; // // public TNetwork(String id, String gateway, String pool, String aSuffix) { // this.id = id; // this.gateway = gateway; // this.pool = pool; // interfaceSuffix = aSuffix; // } // // @Override // public String toString() { // return "TNetwork{" + // "id='" + id + '\'' + // ", gateway='" + gateway + '\'' + // ", pool='" + pool + '\'' + // ", interfaceSuffix='" + interfaceSuffix + '\'' + // '}'; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/ICommandService.java // public interface ICommandService { // // String executeCommand(ShellCommand aCommand) throws IOException, InterruptedException; // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/INetworkService.java // public interface INetworkService { // // String getNetworkGateway(String aNetwork, String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/model/ShellCommand.java // public class ShellCommand { // // public final String[] arguments; // // private ShellCommand(String[] aArguments) { // arguments = aArguments; // } // // public String getCommand() { // StringBuilder sb = new StringBuilder(); // sb.append(arguments[0]); // for(int i=1; i<arguments.length; i++) { // sb.append(' '); // sb.append(arguments[i]); // } // return sb.toString(); // } // // public static class Builder { // private final List<String> arguments; // // public Builder(String aCommandName) { // arguments = new ArrayList<>(); // arguments.add(aCommandName); // } // // public Builder add(String aArgument) { // arguments.add(aArgument); // return this; // } // // public ShellCommand build() { // return new ShellCommand(arguments.toArray(new String[arguments.size()])); // } // } // // @Override // public String toString() { // return "ShellCommand{" + // "arguments=" + Arrays.toString(arguments) + // '}'; // } // }
import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; import io.pne.veth.server.handlers.dao.IEndpointDao; import io.pne.veth.server.handlers.dao.INetworkDao; import io.pne.veth.server.handlers.dao.TEndpoint; import io.pne.veth.server.handlers.dao.TNetwork; import io.pne.veth.server.handlers.service.ICommandService; import io.pne.veth.server.handlers.service.INetworkService; import io.pne.veth.server.handlers.service.model.ShellCommand; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.StringTokenizer;
package io.pne.veth.server.handlers.service.impl; public class NetworkServiceImpl implements INetworkService { private static final Logger LOG = LoggerFactory.getLogger(NetworkServiceImpl.class); private final INetworkDao networkDao; private final IEndpointDao endpointDao; private final Gson gson; private final ICommandService commandService; public NetworkServiceImpl(INetworkDao networkDao, IEndpointDao endpointDao, Gson gson, ICommandService shellService) { this.networkDao = networkDao; this.endpointDao = endpointDao; this.gson = gson; this.commandService = shellService; } @Override public String getNetworkGateway(String aNetworkId, String aEndpointId) { TNetwork network = networkDao.findNetwork(aNetworkId); if(network == null) { network = findNetworkInDocker(aNetworkId); if(network != null) { networkDao.addNetwork(network); } } if(network != null) { return network.gateway; } final String gateway = createGatewayFromEndpoint(aEndpointId); LOG.warn("Got the gateway [{}] from the endpoint info", gateway); return gateway; } private String createGatewayFromEndpoint(String aEndpointId) {
// Path: server/src/main/java/io/pne/veth/server/handlers/dao/IEndpointDao.java // public interface IEndpointDao { // // void addEndpoint(TEndpoint aEndpoint); // // TEndpoint findEndPoint(String aEndpointId); // // void removeEndpoint(String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/INetworkDao.java // public interface INetworkDao { // // void addNetwork(TNetwork aNetwork); // // TNetwork findNetwork(String aNetworkId); // // void removeNetwork(String aNetworkId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TEndpoint.java // public class TEndpoint { // // public final String id; // public final String ipAddress; // public final String macAddress; // public final String device; // // public TEndpoint(String id, String ipAddress, String macAddress, String aDevice) { // this.id = id; // this.ipAddress = ipAddress; // this.macAddress = macAddress; // device = aDevice; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TNetwork.java // public class TNetwork { // // public final String id; // public final String gateway; // public final String pool; // public final String interfaceSuffix; // // public TNetwork(String id, String gateway, String pool, String aSuffix) { // this.id = id; // this.gateway = gateway; // this.pool = pool; // interfaceSuffix = aSuffix; // } // // @Override // public String toString() { // return "TNetwork{" + // "id='" + id + '\'' + // ", gateway='" + gateway + '\'' + // ", pool='" + pool + '\'' + // ", interfaceSuffix='" + interfaceSuffix + '\'' + // '}'; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/ICommandService.java // public interface ICommandService { // // String executeCommand(ShellCommand aCommand) throws IOException, InterruptedException; // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/INetworkService.java // public interface INetworkService { // // String getNetworkGateway(String aNetwork, String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/model/ShellCommand.java // public class ShellCommand { // // public final String[] arguments; // // private ShellCommand(String[] aArguments) { // arguments = aArguments; // } // // public String getCommand() { // StringBuilder sb = new StringBuilder(); // sb.append(arguments[0]); // for(int i=1; i<arguments.length; i++) { // sb.append(' '); // sb.append(arguments[i]); // } // return sb.toString(); // } // // public static class Builder { // private final List<String> arguments; // // public Builder(String aCommandName) { // arguments = new ArrayList<>(); // arguments.add(aCommandName); // } // // public Builder add(String aArgument) { // arguments.add(aArgument); // return this; // } // // public ShellCommand build() { // return new ShellCommand(arguments.toArray(new String[arguments.size()])); // } // } // // @Override // public String toString() { // return "ShellCommand{" + // "arguments=" + Arrays.toString(arguments) + // '}'; // } // } // Path: server/src/main/java/io/pne/veth/server/handlers/service/impl/NetworkServiceImpl.java import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; import io.pne.veth.server.handlers.dao.IEndpointDao; import io.pne.veth.server.handlers.dao.INetworkDao; import io.pne.veth.server.handlers.dao.TEndpoint; import io.pne.veth.server.handlers.dao.TNetwork; import io.pne.veth.server.handlers.service.ICommandService; import io.pne.veth.server.handlers.service.INetworkService; import io.pne.veth.server.handlers.service.model.ShellCommand; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.StringTokenizer; package io.pne.veth.server.handlers.service.impl; public class NetworkServiceImpl implements INetworkService { private static final Logger LOG = LoggerFactory.getLogger(NetworkServiceImpl.class); private final INetworkDao networkDao; private final IEndpointDao endpointDao; private final Gson gson; private final ICommandService commandService; public NetworkServiceImpl(INetworkDao networkDao, IEndpointDao endpointDao, Gson gson, ICommandService shellService) { this.networkDao = networkDao; this.endpointDao = endpointDao; this.gson = gson; this.commandService = shellService; } @Override public String getNetworkGateway(String aNetworkId, String aEndpointId) { TNetwork network = networkDao.findNetwork(aNetworkId); if(network == null) { network = findNetworkInDocker(aNetworkId); if(network != null) { networkDao.addNetwork(network); } } if(network != null) { return network.gateway; } final String gateway = createGatewayFromEndpoint(aEndpointId); LOG.warn("Got the gateway [{}] from the endpoint info", gateway); return gateway; } private String createGatewayFromEndpoint(String aEndpointId) {
TEndpoint endpoint = endpointDao.findEndPoint(aEndpointId);
evsinev/docker-network-veth
server/src/main/java/io/pne/veth/server/handlers/service/impl/NetworkServiceImpl.java
// Path: server/src/main/java/io/pne/veth/server/handlers/dao/IEndpointDao.java // public interface IEndpointDao { // // void addEndpoint(TEndpoint aEndpoint); // // TEndpoint findEndPoint(String aEndpointId); // // void removeEndpoint(String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/INetworkDao.java // public interface INetworkDao { // // void addNetwork(TNetwork aNetwork); // // TNetwork findNetwork(String aNetworkId); // // void removeNetwork(String aNetworkId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TEndpoint.java // public class TEndpoint { // // public final String id; // public final String ipAddress; // public final String macAddress; // public final String device; // // public TEndpoint(String id, String ipAddress, String macAddress, String aDevice) { // this.id = id; // this.ipAddress = ipAddress; // this.macAddress = macAddress; // device = aDevice; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TNetwork.java // public class TNetwork { // // public final String id; // public final String gateway; // public final String pool; // public final String interfaceSuffix; // // public TNetwork(String id, String gateway, String pool, String aSuffix) { // this.id = id; // this.gateway = gateway; // this.pool = pool; // interfaceSuffix = aSuffix; // } // // @Override // public String toString() { // return "TNetwork{" + // "id='" + id + '\'' + // ", gateway='" + gateway + '\'' + // ", pool='" + pool + '\'' + // ", interfaceSuffix='" + interfaceSuffix + '\'' + // '}'; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/ICommandService.java // public interface ICommandService { // // String executeCommand(ShellCommand aCommand) throws IOException, InterruptedException; // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/INetworkService.java // public interface INetworkService { // // String getNetworkGateway(String aNetwork, String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/model/ShellCommand.java // public class ShellCommand { // // public final String[] arguments; // // private ShellCommand(String[] aArguments) { // arguments = aArguments; // } // // public String getCommand() { // StringBuilder sb = new StringBuilder(); // sb.append(arguments[0]); // for(int i=1; i<arguments.length; i++) { // sb.append(' '); // sb.append(arguments[i]); // } // return sb.toString(); // } // // public static class Builder { // private final List<String> arguments; // // public Builder(String aCommandName) { // arguments = new ArrayList<>(); // arguments.add(aCommandName); // } // // public Builder add(String aArgument) { // arguments.add(aArgument); // return this; // } // // public ShellCommand build() { // return new ShellCommand(arguments.toArray(new String[arguments.size()])); // } // } // // @Override // public String toString() { // return "ShellCommand{" + // "arguments=" + Arrays.toString(arguments) + // '}'; // } // }
import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; import io.pne.veth.server.handlers.dao.IEndpointDao; import io.pne.veth.server.handlers.dao.INetworkDao; import io.pne.veth.server.handlers.dao.TEndpoint; import io.pne.veth.server.handlers.dao.TNetwork; import io.pne.veth.server.handlers.service.ICommandService; import io.pne.veth.server.handlers.service.INetworkService; import io.pne.veth.server.handlers.service.model.ShellCommand; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.StringTokenizer;
} @Override public String getNetworkGateway(String aNetworkId, String aEndpointId) { TNetwork network = networkDao.findNetwork(aNetworkId); if(network == null) { network = findNetworkInDocker(aNetworkId); if(network != null) { networkDao.addNetwork(network); } } if(network != null) { return network.gateway; } final String gateway = createGatewayFromEndpoint(aEndpointId); LOG.warn("Got the gateway [{}] from the endpoint info", gateway); return gateway; } private String createGatewayFromEndpoint(String aEndpointId) { TEndpoint endpoint = endpointDao.findEndPoint(aEndpointId); String address = endpoint.ipAddress; int pos = address.lastIndexOf('.'); return address.substring(0, pos ) + ".1"; } private TNetwork findNetworkInDocker(String aNetworkId) { // command: docker network inspect dns-1-network
// Path: server/src/main/java/io/pne/veth/server/handlers/dao/IEndpointDao.java // public interface IEndpointDao { // // void addEndpoint(TEndpoint aEndpoint); // // TEndpoint findEndPoint(String aEndpointId); // // void removeEndpoint(String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/INetworkDao.java // public interface INetworkDao { // // void addNetwork(TNetwork aNetwork); // // TNetwork findNetwork(String aNetworkId); // // void removeNetwork(String aNetworkId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TEndpoint.java // public class TEndpoint { // // public final String id; // public final String ipAddress; // public final String macAddress; // public final String device; // // public TEndpoint(String id, String ipAddress, String macAddress, String aDevice) { // this.id = id; // this.ipAddress = ipAddress; // this.macAddress = macAddress; // device = aDevice; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TNetwork.java // public class TNetwork { // // public final String id; // public final String gateway; // public final String pool; // public final String interfaceSuffix; // // public TNetwork(String id, String gateway, String pool, String aSuffix) { // this.id = id; // this.gateway = gateway; // this.pool = pool; // interfaceSuffix = aSuffix; // } // // @Override // public String toString() { // return "TNetwork{" + // "id='" + id + '\'' + // ", gateway='" + gateway + '\'' + // ", pool='" + pool + '\'' + // ", interfaceSuffix='" + interfaceSuffix + '\'' + // '}'; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/ICommandService.java // public interface ICommandService { // // String executeCommand(ShellCommand aCommand) throws IOException, InterruptedException; // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/INetworkService.java // public interface INetworkService { // // String getNetworkGateway(String aNetwork, String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/model/ShellCommand.java // public class ShellCommand { // // public final String[] arguments; // // private ShellCommand(String[] aArguments) { // arguments = aArguments; // } // // public String getCommand() { // StringBuilder sb = new StringBuilder(); // sb.append(arguments[0]); // for(int i=1; i<arguments.length; i++) { // sb.append(' '); // sb.append(arguments[i]); // } // return sb.toString(); // } // // public static class Builder { // private final List<String> arguments; // // public Builder(String aCommandName) { // arguments = new ArrayList<>(); // arguments.add(aCommandName); // } // // public Builder add(String aArgument) { // arguments.add(aArgument); // return this; // } // // public ShellCommand build() { // return new ShellCommand(arguments.toArray(new String[arguments.size()])); // } // } // // @Override // public String toString() { // return "ShellCommand{" + // "arguments=" + Arrays.toString(arguments) + // '}'; // } // } // Path: server/src/main/java/io/pne/veth/server/handlers/service/impl/NetworkServiceImpl.java import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; import io.pne.veth.server.handlers.dao.IEndpointDao; import io.pne.veth.server.handlers.dao.INetworkDao; import io.pne.veth.server.handlers.dao.TEndpoint; import io.pne.veth.server.handlers.dao.TNetwork; import io.pne.veth.server.handlers.service.ICommandService; import io.pne.veth.server.handlers.service.INetworkService; import io.pne.veth.server.handlers.service.model.ShellCommand; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.StringTokenizer; } @Override public String getNetworkGateway(String aNetworkId, String aEndpointId) { TNetwork network = networkDao.findNetwork(aNetworkId); if(network == null) { network = findNetworkInDocker(aNetworkId); if(network != null) { networkDao.addNetwork(network); } } if(network != null) { return network.gateway; } final String gateway = createGatewayFromEndpoint(aEndpointId); LOG.warn("Got the gateway [{}] from the endpoint info", gateway); return gateway; } private String createGatewayFromEndpoint(String aEndpointId) { TEndpoint endpoint = endpointDao.findEndPoint(aEndpointId); String address = endpoint.ipAddress; int pos = address.lastIndexOf('.'); return address.substring(0, pos ) + ".1"; } private TNetwork findNetworkInDocker(String aNetworkId) { // command: docker network inspect dns-1-network
ShellCommand command = new ShellCommand.Builder("docker")
evsinev/docker-network-veth
server/src/main/java/io/pne/veth/server/handlers/service/impl/CommandServiceSsh.java
// Path: server/src/main/java/io/pne/veth/server/handlers/service/ICommandService.java // public interface ICommandService { // // String executeCommand(ShellCommand aCommand) throws IOException, InterruptedException; // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/model/ShellCommand.java // public class ShellCommand { // // public final String[] arguments; // // private ShellCommand(String[] aArguments) { // arguments = aArguments; // } // // public String getCommand() { // StringBuilder sb = new StringBuilder(); // sb.append(arguments[0]); // for(int i=1; i<arguments.length; i++) { // sb.append(' '); // sb.append(arguments[i]); // } // return sb.toString(); // } // // public static class Builder { // private final List<String> arguments; // // public Builder(String aCommandName) { // arguments = new ArrayList<>(); // arguments.add(aCommandName); // } // // public Builder add(String aArgument) { // arguments.add(aArgument); // return this; // } // // public ShellCommand build() { // return new ShellCommand(arguments.toArray(new String[arguments.size()])); // } // } // // @Override // public String toString() { // return "ShellCommand{" + // "arguments=" + Arrays.toString(arguments) + // '}'; // } // }
import io.pne.veth.server.handlers.service.ICommandService; import io.pne.veth.server.handlers.service.model.ShellCommand; import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.common.IOUtils; import net.schmizz.sshj.connection.channel.direct.Session; import java.io.IOException; import java.util.concurrent.TimeUnit;
package io.pne.veth.server.handlers.service.impl; public class CommandServiceSsh implements ICommandService { @Override
// Path: server/src/main/java/io/pne/veth/server/handlers/service/ICommandService.java // public interface ICommandService { // // String executeCommand(ShellCommand aCommand) throws IOException, InterruptedException; // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/model/ShellCommand.java // public class ShellCommand { // // public final String[] arguments; // // private ShellCommand(String[] aArguments) { // arguments = aArguments; // } // // public String getCommand() { // StringBuilder sb = new StringBuilder(); // sb.append(arguments[0]); // for(int i=1; i<arguments.length; i++) { // sb.append(' '); // sb.append(arguments[i]); // } // return sb.toString(); // } // // public static class Builder { // private final List<String> arguments; // // public Builder(String aCommandName) { // arguments = new ArrayList<>(); // arguments.add(aCommandName); // } // // public Builder add(String aArgument) { // arguments.add(aArgument); // return this; // } // // public ShellCommand build() { // return new ShellCommand(arguments.toArray(new String[arguments.size()])); // } // } // // @Override // public String toString() { // return "ShellCommand{" + // "arguments=" + Arrays.toString(arguments) + // '}'; // } // } // Path: server/src/main/java/io/pne/veth/server/handlers/service/impl/CommandServiceSsh.java import io.pne.veth.server.handlers.service.ICommandService; import io.pne.veth.server.handlers.service.model.ShellCommand; import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.common.IOUtils; import net.schmizz.sshj.connection.channel.direct.Session; import java.io.IOException; import java.util.concurrent.TimeUnit; package io.pne.veth.server.handlers.service.impl; public class CommandServiceSsh implements ICommandService { @Override
public String executeCommand(ShellCommand aCommand) throws IOException {
evsinev/docker-network-veth
server/src/main/java/io/pne/veth/server/handlers/DispatchHandler.java
// Path: server/src/main/java/io/pne/veth/server/http/IHttpRequestListener.java // public interface IHttpRequestListener { // // FullHttpResponse createResponse(FullHttpRequest aRequest); // // } // // Path: server/src/main/java/io/pne/veth/server/utils/Strings.java // public static String padRight(String aText, int aLength) { // StringBuilder sb = new StringBuilder(aLength); // sb.append(aText); // while(sb.length() < aLength) { // sb.append(' '); // } // return sb.toString(); // }
import com.google.gson.Gson; import io.netty.buffer.ByteBufUtil; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.util.AsciiString; import io.pne.veth.server.http.IHttpRequestListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH; import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; import static io.pne.veth.server.utils.Strings.padRight;
} public static class Builder { private final HashMap<String, IHttpRequestListener> listeners = new HashMap<>(); private Gson gson; @SuppressWarnings("unused") public Builder add(String aPath, IHttpRequestListener aListener) { listeners.put(aPath, aListener); return this; } public <I, O> Builder add(String aPath, IJsonHandler<I, O> aHandler) { listeners.put(aPath, new JsonHandler<>(gson, aHandler)); return this; } public DispatchHandler build() { LOG.info("Dispatch URL:"); int keyMax = 50; int requestMax = 35; int responseMax = 40; for (Map.Entry<String, IHttpRequestListener> entry : listeners.entrySet()) { final IHttpRequestListener listener = entry.getValue(); if(listener instanceof JsonHandler) { JsonHandler jsonListener = (JsonHandler) listener;
// Path: server/src/main/java/io/pne/veth/server/http/IHttpRequestListener.java // public interface IHttpRequestListener { // // FullHttpResponse createResponse(FullHttpRequest aRequest); // // } // // Path: server/src/main/java/io/pne/veth/server/utils/Strings.java // public static String padRight(String aText, int aLength) { // StringBuilder sb = new StringBuilder(aLength); // sb.append(aText); // while(sb.length() < aLength) { // sb.append(' '); // } // return sb.toString(); // } // Path: server/src/main/java/io/pne/veth/server/handlers/DispatchHandler.java import com.google.gson.Gson; import io.netty.buffer.ByteBufUtil; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.util.AsciiString; import io.pne.veth.server.http.IHttpRequestListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH; import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; import static io.pne.veth.server.utils.Strings.padRight; } public static class Builder { private final HashMap<String, IHttpRequestListener> listeners = new HashMap<>(); private Gson gson; @SuppressWarnings("unused") public Builder add(String aPath, IHttpRequestListener aListener) { listeners.put(aPath, aListener); return this; } public <I, O> Builder add(String aPath, IJsonHandler<I, O> aHandler) { listeners.put(aPath, new JsonHandler<>(gson, aHandler)); return this; } public DispatchHandler build() { LOG.info("Dispatch URL:"); int keyMax = 50; int requestMax = 35; int responseMax = 40; for (Map.Entry<String, IHttpRequestListener> entry : listeners.entrySet()) { final IHttpRequestListener listener = entry.getValue(); if(listener instanceof JsonHandler) { JsonHandler jsonListener = (JsonHandler) listener;
LOG.info(" {} - {} - {}", padRight(entry.getKey(), keyMax), padRight(jsonListener.getRequestClass().getSimpleName(), requestMax), padRight(jsonListener.getHandlerClass().getSimpleName(), responseMax));
evsinev/docker-network-veth
server/src/main/java/io/pne/veth/server/handlers/location/networkdriver/EndpointOperInfoHandler.java
// Path: server/src/main/java/io/pne/veth/server/handlers/IJsonHandler.java // public interface IJsonHandler<I,O> { // // O handle(I aRequest); // // Class<I> getRequestClass(); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/IEndpointDao.java // public interface IEndpointDao { // // void addEndpoint(TEndpoint aEndpoint); // // TEndpoint findEndPoint(String aEndpointId); // // void removeEndpoint(String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TEndpoint.java // public class TEndpoint { // // public final String id; // public final String ipAddress; // public final String macAddress; // public final String device; // // public TEndpoint(String id, String ipAddress, String macAddress, String aDevice) { // this.id = id; // this.ipAddress = ipAddress; // this.macAddress = macAddress; // device = aDevice; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/model/InfoRequest.java // public class InfoRequest { // // @SerializedName("NetworkID") public String networkID; // @SerializedName("EndpointID") public String endpointId; // // @Override // public String toString() { // return "InfoRequest{" + // "networkID='" + networkID + '\'' + // ", endpointId='" + endpointId + '\'' + // '}'; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/model/InfoResponse.java // public class InfoResponse { // // @SerializedName("Value") public Map<String, String> value; // // }
import io.pne.veth.server.handlers.IJsonHandler; import io.pne.veth.server.handlers.dao.IEndpointDao; import io.pne.veth.server.handlers.dao.TEndpoint; import io.pne.veth.server.handlers.model.InfoRequest; import io.pne.veth.server.handlers.model.InfoResponse; import java.util.HashMap;
package io.pne.veth.server.handlers.location.networkdriver; public class EndpointOperInfoHandler implements IJsonHandler<InfoRequest, InfoResponse> { private final IEndpointDao endpointDao; public EndpointOperInfoHandler(IEndpointDao endpointDao) { this.endpointDao = endpointDao; } @Override public InfoResponse handle(InfoRequest aRequest) { /* "Value": { "hostNic.Addr": "192.168.3.2/24", "hostNic.HardwareAddr": "62:7b:0b:7d:54:8d", "hostNic.Name": "dns-1.c", "id": "dc90c4902a7a43cf897f91c094252f038c2e24c507083c81bb7a2ec2b7f79543", "srcName": "dns-1.c" } */
// Path: server/src/main/java/io/pne/veth/server/handlers/IJsonHandler.java // public interface IJsonHandler<I,O> { // // O handle(I aRequest); // // Class<I> getRequestClass(); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/IEndpointDao.java // public interface IEndpointDao { // // void addEndpoint(TEndpoint aEndpoint); // // TEndpoint findEndPoint(String aEndpointId); // // void removeEndpoint(String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TEndpoint.java // public class TEndpoint { // // public final String id; // public final String ipAddress; // public final String macAddress; // public final String device; // // public TEndpoint(String id, String ipAddress, String macAddress, String aDevice) { // this.id = id; // this.ipAddress = ipAddress; // this.macAddress = macAddress; // device = aDevice; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/model/InfoRequest.java // public class InfoRequest { // // @SerializedName("NetworkID") public String networkID; // @SerializedName("EndpointID") public String endpointId; // // @Override // public String toString() { // return "InfoRequest{" + // "networkID='" + networkID + '\'' + // ", endpointId='" + endpointId + '\'' + // '}'; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/model/InfoResponse.java // public class InfoResponse { // // @SerializedName("Value") public Map<String, String> value; // // } // Path: server/src/main/java/io/pne/veth/server/handlers/location/networkdriver/EndpointOperInfoHandler.java import io.pne.veth.server.handlers.IJsonHandler; import io.pne.veth.server.handlers.dao.IEndpointDao; import io.pne.veth.server.handlers.dao.TEndpoint; import io.pne.veth.server.handlers.model.InfoRequest; import io.pne.veth.server.handlers.model.InfoResponse; import java.util.HashMap; package io.pne.veth.server.handlers.location.networkdriver; public class EndpointOperInfoHandler implements IJsonHandler<InfoRequest, InfoResponse> { private final IEndpointDao endpointDao; public EndpointOperInfoHandler(IEndpointDao endpointDao) { this.endpointDao = endpointDao; } @Override public InfoResponse handle(InfoRequest aRequest) { /* "Value": { "hostNic.Addr": "192.168.3.2/24", "hostNic.HardwareAddr": "62:7b:0b:7d:54:8d", "hostNic.Name": "dns-1.c", "id": "dc90c4902a7a43cf897f91c094252f038c2e24c507083c81bb7a2ec2b7f79543", "srcName": "dns-1.c" } */
TEndpoint endpoint = endpointDao.findEndPoint(aRequest.endpointId);
evsinev/docker-network-veth
server/src/main/java/io/pne/veth/server/handlers/location/networkdriver/GetCapabilitiesHandler.java
// Path: server/src/main/java/io/pne/veth/server/handlers/IJsonHandler.java // public interface IJsonHandler<I,O> { // // O handle(I aRequest); // // Class<I> getRequestClass(); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/model/CapabilitiesResponse.java // public class CapabilitiesResponse { // public final CapabilityScope scope; // // public CapabilitiesResponse(CapabilityScope scope) { // this.scope = scope; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/model/CapabilityScope.java // public enum CapabilityScope { // // global, local // }
import io.pne.veth.server.handlers.IJsonHandler; import io.pne.veth.server.handlers.model.CapabilitiesResponse; import io.pne.veth.server.handlers.model.CapabilityScope;
package io.pne.veth.server.handlers.location.networkdriver; public class GetCapabilitiesHandler implements IJsonHandler<Void, CapabilitiesResponse> { @Override public CapabilitiesResponse handle(Void aRequest) {
// Path: server/src/main/java/io/pne/veth/server/handlers/IJsonHandler.java // public interface IJsonHandler<I,O> { // // O handle(I aRequest); // // Class<I> getRequestClass(); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/model/CapabilitiesResponse.java // public class CapabilitiesResponse { // public final CapabilityScope scope; // // public CapabilitiesResponse(CapabilityScope scope) { // this.scope = scope; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/model/CapabilityScope.java // public enum CapabilityScope { // // global, local // } // Path: server/src/main/java/io/pne/veth/server/handlers/location/networkdriver/GetCapabilitiesHandler.java import io.pne.veth.server.handlers.IJsonHandler; import io.pne.veth.server.handlers.model.CapabilitiesResponse; import io.pne.veth.server.handlers.model.CapabilityScope; package io.pne.veth.server.handlers.location.networkdriver; public class GetCapabilitiesHandler implements IJsonHandler<Void, CapabilitiesResponse> { @Override public CapabilitiesResponse handle(Void aRequest) {
return new CapabilitiesResponse(CapabilityScope.local);
evsinev/docker-network-veth
server/src/main/java/io/pne/veth/server/handlers/location/networkdriver/CreateEndPointHandler.java
// Path: server/src/main/java/io/pne/veth/server/handlers/IJsonHandler.java // public interface IJsonHandler<I,O> { // // O handle(I aRequest); // // Class<I> getRequestClass(); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/IEndpointDao.java // public interface IEndpointDao { // // void addEndpoint(TEndpoint aEndpoint); // // TEndpoint findEndPoint(String aEndpointId); // // void removeEndpoint(String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TEndpoint.java // public class TEndpoint { // // public final String id; // public final String ipAddress; // public final String macAddress; // public final String device; // // public TEndpoint(String id, String ipAddress, String macAddress, String aDevice) { // this.id = id; // this.ipAddress = ipAddress; // this.macAddress = macAddress; // device = aDevice; // } // }
import io.pne.veth.server.handlers.IJsonHandler; import io.pne.veth.server.handlers.dao.IEndpointDao; import io.pne.veth.server.handlers.dao.TEndpoint; import io.pne.veth.server.handlers.model.*;
package io.pne.veth.server.handlers.location.networkdriver; public class CreateEndPointHandler implements IJsonHandler<CreateEndpointRequest, CreateEndpointResponse> { final IEndpointDao endpointDao; public CreateEndPointHandler(IEndpointDao endpointDao) { this.endpointDao = endpointDao; } @Override public CreateEndpointResponse handle(CreateEndpointRequest aRequest) { /* "Interface": { "Address" : "", "AddressIPv6": "", "MacAddress" : "" } */ final EndpointInterface iface = aRequest.endpointInterface; if(iface == null) { throw new IllegalStateException("No section 'Interface': "+aRequest); }
// Path: server/src/main/java/io/pne/veth/server/handlers/IJsonHandler.java // public interface IJsonHandler<I,O> { // // O handle(I aRequest); // // Class<I> getRequestClass(); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/IEndpointDao.java // public interface IEndpointDao { // // void addEndpoint(TEndpoint aEndpoint); // // TEndpoint findEndPoint(String aEndpointId); // // void removeEndpoint(String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TEndpoint.java // public class TEndpoint { // // public final String id; // public final String ipAddress; // public final String macAddress; // public final String device; // // public TEndpoint(String id, String ipAddress, String macAddress, String aDevice) { // this.id = id; // this.ipAddress = ipAddress; // this.macAddress = macAddress; // device = aDevice; // } // } // Path: server/src/main/java/io/pne/veth/server/handlers/location/networkdriver/CreateEndPointHandler.java import io.pne.veth.server.handlers.IJsonHandler; import io.pne.veth.server.handlers.dao.IEndpointDao; import io.pne.veth.server.handlers.dao.TEndpoint; import io.pne.veth.server.handlers.model.*; package io.pne.veth.server.handlers.location.networkdriver; public class CreateEndPointHandler implements IJsonHandler<CreateEndpointRequest, CreateEndpointResponse> { final IEndpointDao endpointDao; public CreateEndPointHandler(IEndpointDao endpointDao) { this.endpointDao = endpointDao; } @Override public CreateEndpointResponse handle(CreateEndpointRequest aRequest) { /* "Interface": { "Address" : "", "AddressIPv6": "", "MacAddress" : "" } */ final EndpointInterface iface = aRequest.endpointInterface; if(iface == null) { throw new IllegalStateException("No section 'Interface': "+aRequest); }
endpointDao.addEndpoint(new TEndpoint(
evsinev/docker-network-veth
server/src/main/java/io/pne/veth/server/handlers/location/networkdriver/CreateNetworkHandler.java
// Path: server/src/main/java/io/pne/veth/server/handlers/IJsonHandler.java // public interface IJsonHandler<I,O> { // // O handle(I aRequest); // // Class<I> getRequestClass(); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/INetworkDao.java // public interface INetworkDao { // // void addNetwork(TNetwork aNetwork); // // TNetwork findNetwork(String aNetworkId); // // void removeNetwork(String aNetworkId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TNetwork.java // public class TNetwork { // // public final String id; // public final String gateway; // public final String pool; // public final String interfaceSuffix; // // public TNetwork(String id, String gateway, String pool, String aSuffix) { // this.id = id; // this.gateway = gateway; // this.pool = pool; // interfaceSuffix = aSuffix; // } // // @Override // public String toString() { // return "TNetwork{" + // "id='" + id + '\'' + // ", gateway='" + gateway + '\'' + // ", pool='" + pool + '\'' + // ", interfaceSuffix='" + interfaceSuffix + '\'' + // '}'; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/model/CreateNetworkRequest.java // public class CreateNetworkRequest { // // @SerializedName("NetworkID") public String networkID; // @SerializedName("Options") public Map<String, Object> options; // @SerializedName("IPv4Data") public IPAMData[] ipv4Data; // @SerializedName("IPv6Data") public IPAMData[] ipv6Data; // // // @Override // public String toString() { // return "CreateNetworkRequest{" + // "NetworkID='" + networkID + '\'' + // ", Options=" + options + // ", IPv4Data=" + Arrays.toString(ipv4Data) + // ", IPv6Data=" + Arrays.toString(ipv6Data) + // '}'; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/model/SuccessResponse.java // public class SuccessResponse { // // public static final SuccessResponse SUCCESS = new SuccessResponse(); // }
import io.pne.veth.server.handlers.IJsonHandler; import io.pne.veth.server.handlers.dao.INetworkDao; import io.pne.veth.server.handlers.dao.TNetwork; import io.pne.veth.server.handlers.model.CreateNetworkRequest; import io.pne.veth.server.handlers.model.SuccessResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map;
package io.pne.veth.server.handlers.location.networkdriver; public class CreateNetworkHandler implements IJsonHandler<CreateNetworkRequest, SuccessResponse> { private static final Logger LOG = LoggerFactory.getLogger(CreateNetworkHandler.class);
// Path: server/src/main/java/io/pne/veth/server/handlers/IJsonHandler.java // public interface IJsonHandler<I,O> { // // O handle(I aRequest); // // Class<I> getRequestClass(); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/INetworkDao.java // public interface INetworkDao { // // void addNetwork(TNetwork aNetwork); // // TNetwork findNetwork(String aNetworkId); // // void removeNetwork(String aNetworkId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TNetwork.java // public class TNetwork { // // public final String id; // public final String gateway; // public final String pool; // public final String interfaceSuffix; // // public TNetwork(String id, String gateway, String pool, String aSuffix) { // this.id = id; // this.gateway = gateway; // this.pool = pool; // interfaceSuffix = aSuffix; // } // // @Override // public String toString() { // return "TNetwork{" + // "id='" + id + '\'' + // ", gateway='" + gateway + '\'' + // ", pool='" + pool + '\'' + // ", interfaceSuffix='" + interfaceSuffix + '\'' + // '}'; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/model/CreateNetworkRequest.java // public class CreateNetworkRequest { // // @SerializedName("NetworkID") public String networkID; // @SerializedName("Options") public Map<String, Object> options; // @SerializedName("IPv4Data") public IPAMData[] ipv4Data; // @SerializedName("IPv6Data") public IPAMData[] ipv6Data; // // // @Override // public String toString() { // return "CreateNetworkRequest{" + // "NetworkID='" + networkID + '\'' + // ", Options=" + options + // ", IPv4Data=" + Arrays.toString(ipv4Data) + // ", IPv6Data=" + Arrays.toString(ipv6Data) + // '}'; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/model/SuccessResponse.java // public class SuccessResponse { // // public static final SuccessResponse SUCCESS = new SuccessResponse(); // } // Path: server/src/main/java/io/pne/veth/server/handlers/location/networkdriver/CreateNetworkHandler.java import io.pne.veth.server.handlers.IJsonHandler; import io.pne.veth.server.handlers.dao.INetworkDao; import io.pne.veth.server.handlers.dao.TNetwork; import io.pne.veth.server.handlers.model.CreateNetworkRequest; import io.pne.veth.server.handlers.model.SuccessResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; package io.pne.veth.server.handlers.location.networkdriver; public class CreateNetworkHandler implements IJsonHandler<CreateNetworkRequest, SuccessResponse> { private static final Logger LOG = LoggerFactory.getLogger(CreateNetworkHandler.class);
private final INetworkDao networkDao;
evsinev/docker-network-veth
server/src/main/java/io/pne/veth/server/handlers/location/networkdriver/CreateNetworkHandler.java
// Path: server/src/main/java/io/pne/veth/server/handlers/IJsonHandler.java // public interface IJsonHandler<I,O> { // // O handle(I aRequest); // // Class<I> getRequestClass(); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/INetworkDao.java // public interface INetworkDao { // // void addNetwork(TNetwork aNetwork); // // TNetwork findNetwork(String aNetworkId); // // void removeNetwork(String aNetworkId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TNetwork.java // public class TNetwork { // // public final String id; // public final String gateway; // public final String pool; // public final String interfaceSuffix; // // public TNetwork(String id, String gateway, String pool, String aSuffix) { // this.id = id; // this.gateway = gateway; // this.pool = pool; // interfaceSuffix = aSuffix; // } // // @Override // public String toString() { // return "TNetwork{" + // "id='" + id + '\'' + // ", gateway='" + gateway + '\'' + // ", pool='" + pool + '\'' + // ", interfaceSuffix='" + interfaceSuffix + '\'' + // '}'; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/model/CreateNetworkRequest.java // public class CreateNetworkRequest { // // @SerializedName("NetworkID") public String networkID; // @SerializedName("Options") public Map<String, Object> options; // @SerializedName("IPv4Data") public IPAMData[] ipv4Data; // @SerializedName("IPv6Data") public IPAMData[] ipv6Data; // // // @Override // public String toString() { // return "CreateNetworkRequest{" + // "NetworkID='" + networkID + '\'' + // ", Options=" + options + // ", IPv4Data=" + Arrays.toString(ipv4Data) + // ", IPv6Data=" + Arrays.toString(ipv6Data) + // '}'; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/model/SuccessResponse.java // public class SuccessResponse { // // public static final SuccessResponse SUCCESS = new SuccessResponse(); // }
import io.pne.veth.server.handlers.IJsonHandler; import io.pne.veth.server.handlers.dao.INetworkDao; import io.pne.veth.server.handlers.dao.TNetwork; import io.pne.veth.server.handlers.model.CreateNetworkRequest; import io.pne.veth.server.handlers.model.SuccessResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map;
package io.pne.veth.server.handlers.location.networkdriver; public class CreateNetworkHandler implements IJsonHandler<CreateNetworkRequest, SuccessResponse> { private static final Logger LOG = LoggerFactory.getLogger(CreateNetworkHandler.class); private final INetworkDao networkDao; public CreateNetworkHandler(INetworkDao networkDao) { this.networkDao = networkDao; } @Override public SuccessResponse handle(CreateNetworkRequest aRequest) {
// Path: server/src/main/java/io/pne/veth/server/handlers/IJsonHandler.java // public interface IJsonHandler<I,O> { // // O handle(I aRequest); // // Class<I> getRequestClass(); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/INetworkDao.java // public interface INetworkDao { // // void addNetwork(TNetwork aNetwork); // // TNetwork findNetwork(String aNetworkId); // // void removeNetwork(String aNetworkId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/TNetwork.java // public class TNetwork { // // public final String id; // public final String gateway; // public final String pool; // public final String interfaceSuffix; // // public TNetwork(String id, String gateway, String pool, String aSuffix) { // this.id = id; // this.gateway = gateway; // this.pool = pool; // interfaceSuffix = aSuffix; // } // // @Override // public String toString() { // return "TNetwork{" + // "id='" + id + '\'' + // ", gateway='" + gateway + '\'' + // ", pool='" + pool + '\'' + // ", interfaceSuffix='" + interfaceSuffix + '\'' + // '}'; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/model/CreateNetworkRequest.java // public class CreateNetworkRequest { // // @SerializedName("NetworkID") public String networkID; // @SerializedName("Options") public Map<String, Object> options; // @SerializedName("IPv4Data") public IPAMData[] ipv4Data; // @SerializedName("IPv6Data") public IPAMData[] ipv6Data; // // // @Override // public String toString() { // return "CreateNetworkRequest{" + // "NetworkID='" + networkID + '\'' + // ", Options=" + options + // ", IPv4Data=" + Arrays.toString(ipv4Data) + // ", IPv6Data=" + Arrays.toString(ipv6Data) + // '}'; // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/model/SuccessResponse.java // public class SuccessResponse { // // public static final SuccessResponse SUCCESS = new SuccessResponse(); // } // Path: server/src/main/java/io/pne/veth/server/handlers/location/networkdriver/CreateNetworkHandler.java import io.pne.veth.server.handlers.IJsonHandler; import io.pne.veth.server.handlers.dao.INetworkDao; import io.pne.veth.server.handlers.dao.TNetwork; import io.pne.veth.server.handlers.model.CreateNetworkRequest; import io.pne.veth.server.handlers.model.SuccessResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; package io.pne.veth.server.handlers.location.networkdriver; public class CreateNetworkHandler implements IJsonHandler<CreateNetworkRequest, SuccessResponse> { private static final Logger LOG = LoggerFactory.getLogger(CreateNetworkHandler.class); private final INetworkDao networkDao; public CreateNetworkHandler(INetworkDao networkDao) { this.networkDao = networkDao; } @Override public SuccessResponse handle(CreateNetworkRequest aRequest) {
networkDao.addNetwork(new TNetwork(
evsinev/docker-network-veth
server/src/main/java/io/pne/veth/server/handlers/service/impl/CommandServiceImpl.java
// Path: server/src/main/java/io/pne/veth/server/handlers/service/ICommandService.java // public interface ICommandService { // // String executeCommand(ShellCommand aCommand) throws IOException, InterruptedException; // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/model/ShellCommand.java // public class ShellCommand { // // public final String[] arguments; // // private ShellCommand(String[] aArguments) { // arguments = aArguments; // } // // public String getCommand() { // StringBuilder sb = new StringBuilder(); // sb.append(arguments[0]); // for(int i=1; i<arguments.length; i++) { // sb.append(' '); // sb.append(arguments[i]); // } // return sb.toString(); // } // // public static class Builder { // private final List<String> arguments; // // public Builder(String aCommandName) { // arguments = new ArrayList<>(); // arguments.add(aCommandName); // } // // public Builder add(String aArgument) { // arguments.add(aArgument); // return this; // } // // public ShellCommand build() { // return new ShellCommand(arguments.toArray(new String[arguments.size()])); // } // } // // @Override // public String toString() { // return "ShellCommand{" + // "arguments=" + Arrays.toString(arguments) + // '}'; // } // }
import io.pne.veth.server.handlers.service.ICommandService; import io.pne.veth.server.handlers.service.model.ShellCommand; import java.io.*;
package io.pne.veth.server.handlers.service.impl; public class CommandServiceImpl implements ICommandService { @Override
// Path: server/src/main/java/io/pne/veth/server/handlers/service/ICommandService.java // public interface ICommandService { // // String executeCommand(ShellCommand aCommand) throws IOException, InterruptedException; // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/model/ShellCommand.java // public class ShellCommand { // // public final String[] arguments; // // private ShellCommand(String[] aArguments) { // arguments = aArguments; // } // // public String getCommand() { // StringBuilder sb = new StringBuilder(); // sb.append(arguments[0]); // for(int i=1; i<arguments.length; i++) { // sb.append(' '); // sb.append(arguments[i]); // } // return sb.toString(); // } // // public static class Builder { // private final List<String> arguments; // // public Builder(String aCommandName) { // arguments = new ArrayList<>(); // arguments.add(aCommandName); // } // // public Builder add(String aArgument) { // arguments.add(aArgument); // return this; // } // // public ShellCommand build() { // return new ShellCommand(arguments.toArray(new String[arguments.size()])); // } // } // // @Override // public String toString() { // return "ShellCommand{" + // "arguments=" + Arrays.toString(arguments) + // '}'; // } // } // Path: server/src/main/java/io/pne/veth/server/handlers/service/impl/CommandServiceImpl.java import io.pne.veth.server.handlers.service.ICommandService; import io.pne.veth.server.handlers.service.model.ShellCommand; import java.io.*; package io.pne.veth.server.handlers.service.impl; public class CommandServiceImpl implements ICommandService { @Override
public String executeCommand(ShellCommand aCommand) throws IOException, InterruptedException {
evsinev/docker-network-veth
server/src/test/java/io/pne/veth/server/handlers/JsonHandlerTest.java
// Path: server/src/main/java/io/pne/veth/server/handlers/dao/INetworkDao.java // public interface INetworkDao { // // void addNetwork(TNetwork aNetwork); // // TNetwork findNetwork(String aNetworkId); // // void removeNetwork(String aNetworkId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/NetworkDaoImpl.java // public class NetworkDaoImpl implements INetworkDao { // // private static final Logger LOG = LoggerFactory.getLogger(NetworkDaoImpl.class); // // private final Map<String, TNetwork> map = new ConcurrentHashMap<>(); // // @Override // public void addNetwork(TNetwork aNetwork) { // LOG.info("Adding network {} ...", aNetwork); // TNetwork previous = map.put(aNetwork.id, aNetwork); // if(previous != null) { // LOG.warn("The previous network war replaced by new [previous={}, new={}]", previous, aNetwork); // } // } // // @Override // public TNetwork findNetwork(String aNetworkId) { // TNetwork network = map.get(aNetworkId); // if(network == null) { // LOG.warn("No network {} in {}", aNetworkId, map); // } // return network; // } // // @Override // public void removeNetwork(String aNetworkId) { // TNetwork network = map.remove(aNetworkId); // if(network == null) { // LOG.warn("No network {}", aNetworkId); // } else { // LOG.info("Network was removed: {}", network); // } // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/location/networkdriver/CreateNetworkHandler.java // public class CreateNetworkHandler implements IJsonHandler<CreateNetworkRequest, SuccessResponse> { // // private static final Logger LOG = LoggerFactory.getLogger(CreateNetworkHandler.class); // // private final INetworkDao networkDao; // // public CreateNetworkHandler(INetworkDao networkDao) { // this.networkDao = networkDao; // } // // @Override // public SuccessResponse handle(CreateNetworkRequest aRequest) { // networkDao.addNetwork(new TNetwork( // aRequest.networkID // , aRequest.ipv4Data[0].Gateway // , aRequest.ipv4Data[0].Pool // , getInterfaceSuffix(aRequest.options) // )); // // return SuccessResponse.SUCCESS; // } // // private String getInterfaceSuffix(Map<String, Object> aOptions) { // if(aOptions == null) { // return createRandomName("No options"); // } // // Map<String, Object> generic = (Map<String, Object>) aOptions.get("com.docker.network.generic"); // if(generic == null) { // return createRandomName("No com.docker.network.generic, creating"); // } // // Object prefix = generic.get("ip.pne.veth.interface.prefix"); // if(prefix == null) { // return createRandomName("No ip.pne.veth.interface.prefix"); // } // return prefix.toString(); // } // // private String createRandomName(String aMessage) { // String prefix = "veth-" + System.currentTimeMillis(); // LOG.warn("{}, creating random interface prefix: {}", aMessage, prefix); // return prefix; // } // // @Override // public Class<CreateNetworkRequest> getRequestClass() { // return CreateNetworkRequest.class; // } // }
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import io.pne.veth.server.handlers.dao.INetworkDao; import io.pne.veth.server.handlers.dao.NetworkDaoImpl; import io.pne.veth.server.handlers.location.networkdriver.CreateNetworkHandler; import org.junit.Test;
package io.pne.veth.server.handlers; public class JsonHandlerTest { @Test public void test() { Gson gson = new GsonBuilder().setPrettyPrinting().create();
// Path: server/src/main/java/io/pne/veth/server/handlers/dao/INetworkDao.java // public interface INetworkDao { // // void addNetwork(TNetwork aNetwork); // // TNetwork findNetwork(String aNetworkId); // // void removeNetwork(String aNetworkId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/NetworkDaoImpl.java // public class NetworkDaoImpl implements INetworkDao { // // private static final Logger LOG = LoggerFactory.getLogger(NetworkDaoImpl.class); // // private final Map<String, TNetwork> map = new ConcurrentHashMap<>(); // // @Override // public void addNetwork(TNetwork aNetwork) { // LOG.info("Adding network {} ...", aNetwork); // TNetwork previous = map.put(aNetwork.id, aNetwork); // if(previous != null) { // LOG.warn("The previous network war replaced by new [previous={}, new={}]", previous, aNetwork); // } // } // // @Override // public TNetwork findNetwork(String aNetworkId) { // TNetwork network = map.get(aNetworkId); // if(network == null) { // LOG.warn("No network {} in {}", aNetworkId, map); // } // return network; // } // // @Override // public void removeNetwork(String aNetworkId) { // TNetwork network = map.remove(aNetworkId); // if(network == null) { // LOG.warn("No network {}", aNetworkId); // } else { // LOG.info("Network was removed: {}", network); // } // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/location/networkdriver/CreateNetworkHandler.java // public class CreateNetworkHandler implements IJsonHandler<CreateNetworkRequest, SuccessResponse> { // // private static final Logger LOG = LoggerFactory.getLogger(CreateNetworkHandler.class); // // private final INetworkDao networkDao; // // public CreateNetworkHandler(INetworkDao networkDao) { // this.networkDao = networkDao; // } // // @Override // public SuccessResponse handle(CreateNetworkRequest aRequest) { // networkDao.addNetwork(new TNetwork( // aRequest.networkID // , aRequest.ipv4Data[0].Gateway // , aRequest.ipv4Data[0].Pool // , getInterfaceSuffix(aRequest.options) // )); // // return SuccessResponse.SUCCESS; // } // // private String getInterfaceSuffix(Map<String, Object> aOptions) { // if(aOptions == null) { // return createRandomName("No options"); // } // // Map<String, Object> generic = (Map<String, Object>) aOptions.get("com.docker.network.generic"); // if(generic == null) { // return createRandomName("No com.docker.network.generic, creating"); // } // // Object prefix = generic.get("ip.pne.veth.interface.prefix"); // if(prefix == null) { // return createRandomName("No ip.pne.veth.interface.prefix"); // } // return prefix.toString(); // } // // private String createRandomName(String aMessage) { // String prefix = "veth-" + System.currentTimeMillis(); // LOG.warn("{}, creating random interface prefix: {}", aMessage, prefix); // return prefix; // } // // @Override // public Class<CreateNetworkRequest> getRequestClass() { // return CreateNetworkRequest.class; // } // } // Path: server/src/test/java/io/pne/veth/server/handlers/JsonHandlerTest.java import com.google.gson.Gson; import com.google.gson.GsonBuilder; import io.pne.veth.server.handlers.dao.INetworkDao; import io.pne.veth.server.handlers.dao.NetworkDaoImpl; import io.pne.veth.server.handlers.location.networkdriver.CreateNetworkHandler; import org.junit.Test; package io.pne.veth.server.handlers; public class JsonHandlerTest { @Test public void test() { Gson gson = new GsonBuilder().setPrettyPrinting().create();
INetworkDao networkDao = new NetworkDaoImpl();
evsinev/docker-network-veth
server/src/test/java/io/pne/veth/server/handlers/JsonHandlerTest.java
// Path: server/src/main/java/io/pne/veth/server/handlers/dao/INetworkDao.java // public interface INetworkDao { // // void addNetwork(TNetwork aNetwork); // // TNetwork findNetwork(String aNetworkId); // // void removeNetwork(String aNetworkId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/NetworkDaoImpl.java // public class NetworkDaoImpl implements INetworkDao { // // private static final Logger LOG = LoggerFactory.getLogger(NetworkDaoImpl.class); // // private final Map<String, TNetwork> map = new ConcurrentHashMap<>(); // // @Override // public void addNetwork(TNetwork aNetwork) { // LOG.info("Adding network {} ...", aNetwork); // TNetwork previous = map.put(aNetwork.id, aNetwork); // if(previous != null) { // LOG.warn("The previous network war replaced by new [previous={}, new={}]", previous, aNetwork); // } // } // // @Override // public TNetwork findNetwork(String aNetworkId) { // TNetwork network = map.get(aNetworkId); // if(network == null) { // LOG.warn("No network {} in {}", aNetworkId, map); // } // return network; // } // // @Override // public void removeNetwork(String aNetworkId) { // TNetwork network = map.remove(aNetworkId); // if(network == null) { // LOG.warn("No network {}", aNetworkId); // } else { // LOG.info("Network was removed: {}", network); // } // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/location/networkdriver/CreateNetworkHandler.java // public class CreateNetworkHandler implements IJsonHandler<CreateNetworkRequest, SuccessResponse> { // // private static final Logger LOG = LoggerFactory.getLogger(CreateNetworkHandler.class); // // private final INetworkDao networkDao; // // public CreateNetworkHandler(INetworkDao networkDao) { // this.networkDao = networkDao; // } // // @Override // public SuccessResponse handle(CreateNetworkRequest aRequest) { // networkDao.addNetwork(new TNetwork( // aRequest.networkID // , aRequest.ipv4Data[0].Gateway // , aRequest.ipv4Data[0].Pool // , getInterfaceSuffix(aRequest.options) // )); // // return SuccessResponse.SUCCESS; // } // // private String getInterfaceSuffix(Map<String, Object> aOptions) { // if(aOptions == null) { // return createRandomName("No options"); // } // // Map<String, Object> generic = (Map<String, Object>) aOptions.get("com.docker.network.generic"); // if(generic == null) { // return createRandomName("No com.docker.network.generic, creating"); // } // // Object prefix = generic.get("ip.pne.veth.interface.prefix"); // if(prefix == null) { // return createRandomName("No ip.pne.veth.interface.prefix"); // } // return prefix.toString(); // } // // private String createRandomName(String aMessage) { // String prefix = "veth-" + System.currentTimeMillis(); // LOG.warn("{}, creating random interface prefix: {}", aMessage, prefix); // return prefix; // } // // @Override // public Class<CreateNetworkRequest> getRequestClass() { // return CreateNetworkRequest.class; // } // }
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import io.pne.veth.server.handlers.dao.INetworkDao; import io.pne.veth.server.handlers.dao.NetworkDaoImpl; import io.pne.veth.server.handlers.location.networkdriver.CreateNetworkHandler; import org.junit.Test;
package io.pne.veth.server.handlers; public class JsonHandlerTest { @Test public void test() { Gson gson = new GsonBuilder().setPrettyPrinting().create();
// Path: server/src/main/java/io/pne/veth/server/handlers/dao/INetworkDao.java // public interface INetworkDao { // // void addNetwork(TNetwork aNetwork); // // TNetwork findNetwork(String aNetworkId); // // void removeNetwork(String aNetworkId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/NetworkDaoImpl.java // public class NetworkDaoImpl implements INetworkDao { // // private static final Logger LOG = LoggerFactory.getLogger(NetworkDaoImpl.class); // // private final Map<String, TNetwork> map = new ConcurrentHashMap<>(); // // @Override // public void addNetwork(TNetwork aNetwork) { // LOG.info("Adding network {} ...", aNetwork); // TNetwork previous = map.put(aNetwork.id, aNetwork); // if(previous != null) { // LOG.warn("The previous network war replaced by new [previous={}, new={}]", previous, aNetwork); // } // } // // @Override // public TNetwork findNetwork(String aNetworkId) { // TNetwork network = map.get(aNetworkId); // if(network == null) { // LOG.warn("No network {} in {}", aNetworkId, map); // } // return network; // } // // @Override // public void removeNetwork(String aNetworkId) { // TNetwork network = map.remove(aNetworkId); // if(network == null) { // LOG.warn("No network {}", aNetworkId); // } else { // LOG.info("Network was removed: {}", network); // } // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/location/networkdriver/CreateNetworkHandler.java // public class CreateNetworkHandler implements IJsonHandler<CreateNetworkRequest, SuccessResponse> { // // private static final Logger LOG = LoggerFactory.getLogger(CreateNetworkHandler.class); // // private final INetworkDao networkDao; // // public CreateNetworkHandler(INetworkDao networkDao) { // this.networkDao = networkDao; // } // // @Override // public SuccessResponse handle(CreateNetworkRequest aRequest) { // networkDao.addNetwork(new TNetwork( // aRequest.networkID // , aRequest.ipv4Data[0].Gateway // , aRequest.ipv4Data[0].Pool // , getInterfaceSuffix(aRequest.options) // )); // // return SuccessResponse.SUCCESS; // } // // private String getInterfaceSuffix(Map<String, Object> aOptions) { // if(aOptions == null) { // return createRandomName("No options"); // } // // Map<String, Object> generic = (Map<String, Object>) aOptions.get("com.docker.network.generic"); // if(generic == null) { // return createRandomName("No com.docker.network.generic, creating"); // } // // Object prefix = generic.get("ip.pne.veth.interface.prefix"); // if(prefix == null) { // return createRandomName("No ip.pne.veth.interface.prefix"); // } // return prefix.toString(); // } // // private String createRandomName(String aMessage) { // String prefix = "veth-" + System.currentTimeMillis(); // LOG.warn("{}, creating random interface prefix: {}", aMessage, prefix); // return prefix; // } // // @Override // public Class<CreateNetworkRequest> getRequestClass() { // return CreateNetworkRequest.class; // } // } // Path: server/src/test/java/io/pne/veth/server/handlers/JsonHandlerTest.java import com.google.gson.Gson; import com.google.gson.GsonBuilder; import io.pne.veth.server.handlers.dao.INetworkDao; import io.pne.veth.server.handlers.dao.NetworkDaoImpl; import io.pne.veth.server.handlers.location.networkdriver.CreateNetworkHandler; import org.junit.Test; package io.pne.veth.server.handlers; public class JsonHandlerTest { @Test public void test() { Gson gson = new GsonBuilder().setPrettyPrinting().create();
INetworkDao networkDao = new NetworkDaoImpl();
evsinev/docker-network-veth
server/src/test/java/io/pne/veth/server/handlers/JsonHandlerTest.java
// Path: server/src/main/java/io/pne/veth/server/handlers/dao/INetworkDao.java // public interface INetworkDao { // // void addNetwork(TNetwork aNetwork); // // TNetwork findNetwork(String aNetworkId); // // void removeNetwork(String aNetworkId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/NetworkDaoImpl.java // public class NetworkDaoImpl implements INetworkDao { // // private static final Logger LOG = LoggerFactory.getLogger(NetworkDaoImpl.class); // // private final Map<String, TNetwork> map = new ConcurrentHashMap<>(); // // @Override // public void addNetwork(TNetwork aNetwork) { // LOG.info("Adding network {} ...", aNetwork); // TNetwork previous = map.put(aNetwork.id, aNetwork); // if(previous != null) { // LOG.warn("The previous network war replaced by new [previous={}, new={}]", previous, aNetwork); // } // } // // @Override // public TNetwork findNetwork(String aNetworkId) { // TNetwork network = map.get(aNetworkId); // if(network == null) { // LOG.warn("No network {} in {}", aNetworkId, map); // } // return network; // } // // @Override // public void removeNetwork(String aNetworkId) { // TNetwork network = map.remove(aNetworkId); // if(network == null) { // LOG.warn("No network {}", aNetworkId); // } else { // LOG.info("Network was removed: {}", network); // } // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/location/networkdriver/CreateNetworkHandler.java // public class CreateNetworkHandler implements IJsonHandler<CreateNetworkRequest, SuccessResponse> { // // private static final Logger LOG = LoggerFactory.getLogger(CreateNetworkHandler.class); // // private final INetworkDao networkDao; // // public CreateNetworkHandler(INetworkDao networkDao) { // this.networkDao = networkDao; // } // // @Override // public SuccessResponse handle(CreateNetworkRequest aRequest) { // networkDao.addNetwork(new TNetwork( // aRequest.networkID // , aRequest.ipv4Data[0].Gateway // , aRequest.ipv4Data[0].Pool // , getInterfaceSuffix(aRequest.options) // )); // // return SuccessResponse.SUCCESS; // } // // private String getInterfaceSuffix(Map<String, Object> aOptions) { // if(aOptions == null) { // return createRandomName("No options"); // } // // Map<String, Object> generic = (Map<String, Object>) aOptions.get("com.docker.network.generic"); // if(generic == null) { // return createRandomName("No com.docker.network.generic, creating"); // } // // Object prefix = generic.get("ip.pne.veth.interface.prefix"); // if(prefix == null) { // return createRandomName("No ip.pne.veth.interface.prefix"); // } // return prefix.toString(); // } // // private String createRandomName(String aMessage) { // String prefix = "veth-" + System.currentTimeMillis(); // LOG.warn("{}, creating random interface prefix: {}", aMessage, prefix); // return prefix; // } // // @Override // public Class<CreateNetworkRequest> getRequestClass() { // return CreateNetworkRequest.class; // } // }
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import io.pne.veth.server.handlers.dao.INetworkDao; import io.pne.veth.server.handlers.dao.NetworkDaoImpl; import io.pne.veth.server.handlers.location.networkdriver.CreateNetworkHandler; import org.junit.Test;
package io.pne.veth.server.handlers; public class JsonHandlerTest { @Test public void test() { Gson gson = new GsonBuilder().setPrettyPrinting().create(); INetworkDao networkDao = new NetworkDaoImpl();
// Path: server/src/main/java/io/pne/veth/server/handlers/dao/INetworkDao.java // public interface INetworkDao { // // void addNetwork(TNetwork aNetwork); // // TNetwork findNetwork(String aNetworkId); // // void removeNetwork(String aNetworkId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/NetworkDaoImpl.java // public class NetworkDaoImpl implements INetworkDao { // // private static final Logger LOG = LoggerFactory.getLogger(NetworkDaoImpl.class); // // private final Map<String, TNetwork> map = new ConcurrentHashMap<>(); // // @Override // public void addNetwork(TNetwork aNetwork) { // LOG.info("Adding network {} ...", aNetwork); // TNetwork previous = map.put(aNetwork.id, aNetwork); // if(previous != null) { // LOG.warn("The previous network war replaced by new [previous={}, new={}]", previous, aNetwork); // } // } // // @Override // public TNetwork findNetwork(String aNetworkId) { // TNetwork network = map.get(aNetworkId); // if(network == null) { // LOG.warn("No network {} in {}", aNetworkId, map); // } // return network; // } // // @Override // public void removeNetwork(String aNetworkId) { // TNetwork network = map.remove(aNetworkId); // if(network == null) { // LOG.warn("No network {}", aNetworkId); // } else { // LOG.info("Network was removed: {}", network); // } // } // } // // Path: server/src/main/java/io/pne/veth/server/handlers/location/networkdriver/CreateNetworkHandler.java // public class CreateNetworkHandler implements IJsonHandler<CreateNetworkRequest, SuccessResponse> { // // private static final Logger LOG = LoggerFactory.getLogger(CreateNetworkHandler.class); // // private final INetworkDao networkDao; // // public CreateNetworkHandler(INetworkDao networkDao) { // this.networkDao = networkDao; // } // // @Override // public SuccessResponse handle(CreateNetworkRequest aRequest) { // networkDao.addNetwork(new TNetwork( // aRequest.networkID // , aRequest.ipv4Data[0].Gateway // , aRequest.ipv4Data[0].Pool // , getInterfaceSuffix(aRequest.options) // )); // // return SuccessResponse.SUCCESS; // } // // private String getInterfaceSuffix(Map<String, Object> aOptions) { // if(aOptions == null) { // return createRandomName("No options"); // } // // Map<String, Object> generic = (Map<String, Object>) aOptions.get("com.docker.network.generic"); // if(generic == null) { // return createRandomName("No com.docker.network.generic, creating"); // } // // Object prefix = generic.get("ip.pne.veth.interface.prefix"); // if(prefix == null) { // return createRandomName("No ip.pne.veth.interface.prefix"); // } // return prefix.toString(); // } // // private String createRandomName(String aMessage) { // String prefix = "veth-" + System.currentTimeMillis(); // LOG.warn("{}, creating random interface prefix: {}", aMessage, prefix); // return prefix; // } // // @Override // public Class<CreateNetworkRequest> getRequestClass() { // return CreateNetworkRequest.class; // } // } // Path: server/src/test/java/io/pne/veth/server/handlers/JsonHandlerTest.java import com.google.gson.Gson; import com.google.gson.GsonBuilder; import io.pne.veth.server.handlers.dao.INetworkDao; import io.pne.veth.server.handlers.dao.NetworkDaoImpl; import io.pne.veth.server.handlers.location.networkdriver.CreateNetworkHandler; import org.junit.Test; package io.pne.veth.server.handlers; public class JsonHandlerTest { @Test public void test() { Gson gson = new GsonBuilder().setPrettyPrinting().create(); INetworkDao networkDao = new NetworkDaoImpl();
JsonHandler handler = new JsonHandler(gson, new CreateNetworkHandler(networkDao));
evsinev/docker-network-veth
server/src/main/java/io/pne/veth/server/handlers/location/networkdriver/JoinHandler.java
// Path: server/src/main/java/io/pne/veth/server/handlers/IJsonHandler.java // public interface IJsonHandler<I,O> { // // O handle(I aRequest); // // Class<I> getRequestClass(); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/IEndpointDao.java // public interface IEndpointDao { // // void addEndpoint(TEndpoint aEndpoint); // // TEndpoint findEndPoint(String aEndpointId); // // void removeEndpoint(String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/INetworkService.java // public interface INetworkService { // // String getNetworkGateway(String aNetwork, String aEndpointId); // }
import io.pne.veth.server.handlers.IJsonHandler; import io.pne.veth.server.handlers.dao.IEndpointDao; import io.pne.veth.server.handlers.model.*; import io.pne.veth.server.handlers.service.INetworkService; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package io.pne.veth.server.handlers.location.networkdriver; public class JoinHandler implements IJsonHandler<JoinRequest, JoinResponse> { private static final Logger LOG = LoggerFactory.getLogger(JoinHandler.class);
// Path: server/src/main/java/io/pne/veth/server/handlers/IJsonHandler.java // public interface IJsonHandler<I,O> { // // O handle(I aRequest); // // Class<I> getRequestClass(); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/IEndpointDao.java // public interface IEndpointDao { // // void addEndpoint(TEndpoint aEndpoint); // // TEndpoint findEndPoint(String aEndpointId); // // void removeEndpoint(String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/INetworkService.java // public interface INetworkService { // // String getNetworkGateway(String aNetwork, String aEndpointId); // } // Path: server/src/main/java/io/pne/veth/server/handlers/location/networkdriver/JoinHandler.java import io.pne.veth.server.handlers.IJsonHandler; import io.pne.veth.server.handlers.dao.IEndpointDao; import io.pne.veth.server.handlers.model.*; import io.pne.veth.server.handlers.service.INetworkService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package io.pne.veth.server.handlers.location.networkdriver; public class JoinHandler implements IJsonHandler<JoinRequest, JoinResponse> { private static final Logger LOG = LoggerFactory.getLogger(JoinHandler.class);
final IEndpointDao endpointDao;
evsinev/docker-network-veth
server/src/main/java/io/pne/veth/server/handlers/location/networkdriver/JoinHandler.java
// Path: server/src/main/java/io/pne/veth/server/handlers/IJsonHandler.java // public interface IJsonHandler<I,O> { // // O handle(I aRequest); // // Class<I> getRequestClass(); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/IEndpointDao.java // public interface IEndpointDao { // // void addEndpoint(TEndpoint aEndpoint); // // TEndpoint findEndPoint(String aEndpointId); // // void removeEndpoint(String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/INetworkService.java // public interface INetworkService { // // String getNetworkGateway(String aNetwork, String aEndpointId); // }
import io.pne.veth.server.handlers.IJsonHandler; import io.pne.veth.server.handlers.dao.IEndpointDao; import io.pne.veth.server.handlers.model.*; import io.pne.veth.server.handlers.service.INetworkService; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package io.pne.veth.server.handlers.location.networkdriver; public class JoinHandler implements IJsonHandler<JoinRequest, JoinResponse> { private static final Logger LOG = LoggerFactory.getLogger(JoinHandler.class); final IEndpointDao endpointDao;
// Path: server/src/main/java/io/pne/veth/server/handlers/IJsonHandler.java // public interface IJsonHandler<I,O> { // // O handle(I aRequest); // // Class<I> getRequestClass(); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/dao/IEndpointDao.java // public interface IEndpointDao { // // void addEndpoint(TEndpoint aEndpoint); // // TEndpoint findEndPoint(String aEndpointId); // // void removeEndpoint(String aEndpointId); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/service/INetworkService.java // public interface INetworkService { // // String getNetworkGateway(String aNetwork, String aEndpointId); // } // Path: server/src/main/java/io/pne/veth/server/handlers/location/networkdriver/JoinHandler.java import io.pne.veth.server.handlers.IJsonHandler; import io.pne.veth.server.handlers.dao.IEndpointDao; import io.pne.veth.server.handlers.model.*; import io.pne.veth.server.handlers.service.INetworkService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package io.pne.veth.server.handlers.location.networkdriver; public class JoinHandler implements IJsonHandler<JoinRequest, JoinResponse> { private static final Logger LOG = LoggerFactory.getLogger(JoinHandler.class); final IEndpointDao endpointDao;
final INetworkService networkService;
evsinev/docker-network-veth
server/src/main/java/io/pne/veth/server/handlers/location/plugin/PluginActivateHandler.java
// Path: server/src/main/java/io/pne/veth/server/handlers/IJsonHandler.java // public interface IJsonHandler<I,O> { // // O handle(I aRequest); // // Class<I> getRequestClass(); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/model/ActivateResponse.java // public class ActivateResponse { // public ActivateResponse(PluginType anImplements) { // Implements = new PluginType[]{anImplements}; // } // // PluginType[] Implements; // } // // Path: server/src/main/java/io/pne/veth/server/handlers/model/PluginType.java // public enum PluginType { // NetworkDriver // }
import io.pne.veth.server.handlers.IJsonHandler; import io.pne.veth.server.handlers.model.ActivateResponse; import io.pne.veth.server.handlers.model.PluginType;
package io.pne.veth.server.handlers.location.plugin; public class PluginActivateHandler implements IJsonHandler<Void, ActivateResponse> { @Override public ActivateResponse handle(Void aRequest) {
// Path: server/src/main/java/io/pne/veth/server/handlers/IJsonHandler.java // public interface IJsonHandler<I,O> { // // O handle(I aRequest); // // Class<I> getRequestClass(); // } // // Path: server/src/main/java/io/pne/veth/server/handlers/model/ActivateResponse.java // public class ActivateResponse { // public ActivateResponse(PluginType anImplements) { // Implements = new PluginType[]{anImplements}; // } // // PluginType[] Implements; // } // // Path: server/src/main/java/io/pne/veth/server/handlers/model/PluginType.java // public enum PluginType { // NetworkDriver // } // Path: server/src/main/java/io/pne/veth/server/handlers/location/plugin/PluginActivateHandler.java import io.pne.veth.server.handlers.IJsonHandler; import io.pne.veth.server.handlers.model.ActivateResponse; import io.pne.veth.server.handlers.model.PluginType; package io.pne.veth.server.handlers.location.plugin; public class PluginActivateHandler implements IJsonHandler<Void, ActivateResponse> { @Override public ActivateResponse handle(Void aRequest) {
return new ActivateResponse(PluginType.NetworkDriver);