001package org.intellimate.izou.sdk.util; 002 003import org.intellimate.izou.identification.Identifiable; 004import org.intellimate.izou.identification.Identification; 005import org.intellimate.izou.identification.IdentificationManager; 006import org.intellimate.izou.sdk.resource.Resource; 007 008import java.util.ArrayList; 009import java.util.List; 010import java.util.Optional; 011 012/** 013 * provides various utility-methods to create Resources. 014 * @author Leander Kurscheidt 015 * @version 1.0 016 * @see Resource 017 */ 018public interface ResourceCreator extends ContextProvider, Identifiable { 019 /** 020 * creates a new Resource with the specified ID (=Name) 021 * @param id the id 022 * @param <T> the data-type of the resource 023 * @return an Optional which can contain a Resource 024 */ 025 default <T> Optional<Resource<T>> createResource(String id) { 026 return createResource(id, null, null); 027 } 028 029 /** 030 * creates a new Resource with the specified ID (=Name) 031 * @param id the id 032 * @param consumer the consumer of the Resource 033 * @param <T> the data-type of the resource 034 * @return an Optional which can contain a Resource 035 */ 036 default <T> Optional<Resource<T>> createResource(String id, Identification consumer) { 037 return createResource(id, null, consumer); 038 } 039 040 /** 041 * creates a new Resource with the specified ID (=Name) 042 * @param id the id 043 * @param t the data 044 * @param <T> the data-type of the resource 045 * @return an Optional which can contain a Resource 046 */ 047 default <T> Optional<Resource<T>> createResource(String id, T t) { 048 return createResource(id, t, null); 049 } 050 051 /** 052 * creates a new Resource with the specified ID (=Name) 053 * @param id the id 054 * @param t the data 055 * @param consumer the consumer of the Resource 056 * @param <T> the data-type of the resource 057 * @return an Optional which can contain a Resource 058 */ 059 default <T> Optional<Resource<T>> createResource(String id, T t, Identification consumer) { 060 if (id == null || id.isEmpty()) { 061 getContext().getLogger().error("resource id is null or empty"); 062 return Optional.empty(); 063 } 064 Optional<Resource<T>> generated = IdentificationManager.getInstance().getIdentification(this) 065 .map(idProvider -> new Resource<>(id, idProvider, t, consumer)); 066 if (!generated.isPresent()) 067 getContext().getLogger().error("unable to generate Resource"); 068 return generated; 069 } 070 071 /** 072 * utility method to create a list from an Optional. 073 * @param optional the Optional to create the List from 074 * @param <T> the type 075 * @return a List containing something is the optional is not empty 076 */ 077 default <T> List<T> optionalToList(Optional<T> optional) { 078 return optional 079 .map(t -> { 080 List<T> list = new ArrayList<>(); 081 list.add(t); 082 return list; 083 }) 084 .orElse(new ArrayList<>()); 085 } 086}