001package org.kuali.common.devops.cache; 002 003import static org.kuali.common.util.base.Precondition.checkNotBlank; 004import static org.springframework.beans.BeanUtils.copyProperties; 005 006import java.util.Set; 007 008import javax.validation.ConstraintViolation; 009 010import org.kuali.common.core.build.ViolationsBuilder; 011import org.kuali.common.core.validate.annotation.IdiotProofImmutable; 012import org.kuali.common.http.model.HttpContext; 013import org.kuali.common.http.model.HttpWaitResult; 014import org.kuali.common.http.service.DefaultHttpService; 015import org.kuali.common.http.service.HttpService; 016import org.kuali.common.util.nullify.NullUtils; 017 018import com.google.common.cache.CacheLoader; 019 020@IdiotProofImmutable 021public final class UrlLoader extends CacheLoader<String, HttpWaitResult> { 022 023 private final HttpContext context; 024 private final HttpService service; 025 026 @Override 027 public HttpWaitResult load(String url) { 028 checkNotBlank(url, "url"); 029 HttpContext.Builder builder = HttpContext.builder(); 030 copyProperties(context, builder); 031 builder.setUrl(url); 032 HttpContext context = builder.build(); 033 return service.wait(context); 034 } 035 036 private UrlLoader(Builder builder) { 037 this.context = builder.context; 038 this.service = builder.service; 039 } 040 041 public static UrlLoader newUrlLoader() { 042 return builder().build(); 043 } 044 045 public static UrlLoader newUrlLoader(HttpContext context) { 046 return builder().context(context).build(); 047 } 048 049 public static UrlLoader newUrlLoader(HttpContext context, HttpService service) { 050 return builder().context(context).service(service).build(); 051 } 052 053 public static Builder builder() { 054 return new Builder(); 055 } 056 057 public static class Builder extends ViolationsBuilder<UrlLoader> { 058 059 private HttpContext context = HttpContext.builder(NullUtils.NONE).build(); 060 private HttpService service = new DefaultHttpService(); 061 062 @Override 063 public Set<ConstraintViolation<UrlLoader>> violations() { 064 return violations(make()); 065 } 066 067 @Override 068 public UrlLoader build() { 069 return validate(make()); 070 } 071 072 private UrlLoader make() { 073 return new UrlLoader(this); 074 } 075 076 public Builder context(HttpContext context) { 077 this.context = context; 078 return this; 079 } 080 081 public Builder service(HttpService service) { 082 this.service = service; 083 return this; 084 } 085 086 public HttpContext getContext() { 087 return context; 088 } 089 090 public void setContext(HttpContext context) { 091 this.context = context; 092 } 093 094 public HttpService getService() { 095 return service; 096 } 097 098 public void setService(HttpService service) { 099 this.service = service; 100 } 101 102 } 103 104 public HttpContext getContext() { 105 return context; 106 } 107 108 public HttpService getService() { 109 return service; 110 } 111 112}