Skip to content

Instantly share code, notes, and snippets.

@GrakovNe
Created August 1, 2018 19:26
Show Gist options
  • Select an option

  • Save GrakovNe/82ae8f80d92824638a46d1f21647f585 to your computer and use it in GitHub Desktop.

Select an option

Save GrakovNe/82ae8f80d92824638a46d1f21647f585 to your computer and use it in GitHub Desktop.
package net.thumbtack.adtech.campaign.manager.api.services;
import org.springframework.stereotype.Service;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import net.thumbtack.adtech.api.commons.exception.EntityNotFoundException;
import net.thumbtack.adtech.campaign.manager.api.form.advertiser.AdvertiserCreateForm;
import net.thumbtack.adtech.campaign.manager.api.providers.AdvertiserCredentialsProvider;
import net.thumbtack.adtech.campaign.manager.domain.Advertiser;
import net.thumbtack.adtech.campaign.manager.repositories.AdvertiserRepository;
import net.thumbtack.adtech.campaign.manager.repositories.enums.StateRepository;
import static java.util.Optional.ofNullable;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toMap;
/**
* CoreAdvertiserService.
*/
@Service
public class CoreAdvertiserService {
private final AdvertiserRepository repository;
private final StateRepository stateRepository;
private Map<String, AdvertiserCredentialsProvider> credentialsProviders;
public CoreAdvertiserService(AdvertiserRepository repository,
StateRepository stateRepository,
List<AdvertiserCredentialsProvider> credentialsProviders) {
this.repository = repository;
this.stateRepository = stateRepository;
this.credentialsProviders = credentialsProviders
.stream()
.filter(p -> p.getChannelName() != null)
.collect(toMap(AdvertiserCredentialsProvider::getChannelName, p -> p));
}
/**
* fetchOne.
*/
public Advertiser fetchOne(Integer id) {
return repository.findById(id).orElseThrow(() -> new EntityNotFoundException(Advertiser.class));
}
public Advertiser createOne(AdvertiserCreateForm form) {
Advertiser advertiser = new Advertiser();
advertiser.setName(form.getName());
advertiser.setCrmId(new BigInteger(form.getCrmId()));
advertiser.setApplicationId(form.getApplicationId());
advertiser.setGoogleAnalyticsKey(form.getGoogleAnalyticsKey());
advertiser.setState(stateRepository.getActive());
final Advertiser saved = repository.save(advertiser);
credentialsProviders
.entrySet()
.stream()
.collect(toMap(Map.Entry::getValue, e -> form.getCredentials().get(e.getKey())))
.forEach((p, c) -> p.saveCredentials(saved.getId(), c));
return saved;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment