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
yammer/tenacity
tenacity-core/src/test/java/com/yammer/tenacity/tests/DependencyKeyFactory.java
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/properties/TenacityPropertyKey.java // public interface TenacityPropertyKey extends HystrixCommandKey, HystrixThreadPoolKey { // default Predicate<TenacityPropertyKey> isEqualPredicate() { // return (value) -> value.name().equals(name()); // } // // default TenacityPropertyKey validate(Collection<TenacityPropertyKey> keys) { // return keys.stream() // .filter(isEqualPredicate()) // .findAny() // .orElseThrow(() -> new NoSuchElementException("No TenacityPropertyKey " + name())); // } // }
import com.yammer.tenacity.core.properties.TenacityPropertyKey; import com.yammer.tenacity.core.properties.TenacityPropertyKeyFactory;
package com.yammer.tenacity.tests; public class DependencyKeyFactory implements TenacityPropertyKeyFactory { @Override
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/properties/TenacityPropertyKey.java // public interface TenacityPropertyKey extends HystrixCommandKey, HystrixThreadPoolKey { // default Predicate<TenacityPropertyKey> isEqualPredicate() { // return (value) -> value.name().equals(name()); // } // // default TenacityPropertyKey validate(Collection<TenacityPropertyKey> keys) { // return keys.stream() // .filter(isEqualPredicate()) // .findAny() // .orElseThrow(() -> new NoSuchElementException("No TenacityPropertyKey " + name())); // } // } // Path: tenacity-core/src/test/java/com/yammer/tenacity/tests/DependencyKeyFactory.java import com.yammer.tenacity.core.properties.TenacityPropertyKey; import com.yammer.tenacity.core.properties.TenacityPropertyKeyFactory; package com.yammer.tenacity.tests; public class DependencyKeyFactory implements TenacityPropertyKeyFactory { @Override
public TenacityPropertyKey from(String value) {
yammer/tenacity
tenacity-core/src/main/java/com/yammer/tenacity/core/auth/TenacityAuthenticator.java
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/TenacityCommand.java // public abstract class TenacityCommand<R> extends HystrixCommand<R> { // protected TenacityCommand(TenacityPropertyKey tenacityPropertyKey) { // this(tenacityPropertyKey, tenacityPropertyKey); // } // // protected TenacityCommand(TenacityPropertyKey commandKey, // TenacityPropertyKey threadpoolKey) { // super(HystrixCommand.Setter.withGroupKey(tenacityGroupKey()) // .andCommandKey(commandKey) // .andThreadPoolKey(threadpoolKey)); // } // // static HystrixCommandGroupKey tenacityGroupKey() { // return commandGroupKeyFrom("TENACITY"); // } // // public static HystrixCommandGroupKey commandGroupKeyFrom(String key) { // return HystrixCommandGroupKey.Factory.asKey(key); // } // // public static HystrixCommandProperties getCommandProperties(TenacityPropertyKey key) { // return HystrixPropertiesFactory.getCommandProperties(key, null); // } // // public HystrixCommandProperties getCommandProperties() { // return HystrixPropertiesFactory.getCommandProperties(getCommandKey(), null); // } // // public static HystrixThreadPoolProperties getThreadpoolProperties(TenacityPropertyKey key) { // return HystrixPropertiesFactory.getThreadPoolProperties(key, null); // } // // public static <R> Builder<R> builder(TenacityPropertyKey tenacityPropertyKey) { // return new Builder<>(tenacityPropertyKey); // } // // public HystrixThreadPoolProperties getThreadpoolProperties() { // return HystrixPropertiesFactory.getThreadPoolProperties(getThreadPoolKey(), null); // } // // public HystrixCommandMetrics getCommandMetrics() { // return HystrixCommandMetrics.getInstance(getCommandKey()); // } // // public static HystrixCommandMetrics getCommandMetrics(TenacityPropertyKey key) { // return HystrixCommandMetrics.getInstance(key); // } // // public HystrixThreadPoolMetrics getThreadpoolMetrics() { // return HystrixThreadPoolMetrics.getInstance(getThreadPoolKey()); // } // // public static HystrixThreadPoolMetrics getThreadpoolMetrics(TenacityPropertyKey key) { // return HystrixThreadPoolMetrics.getInstance(key); // } // // public HystrixCircuitBreaker getCircuitBreaker() { // return HystrixCircuitBreaker.Factory.getInstance(getCommandKey()); // } // // public static HystrixCircuitBreaker getCircuitBreaker(TenacityPropertyKey key) { // return HystrixCircuitBreaker.Factory.getInstance(key); // } // // public CumulativeCommandEventCounterStream getCumulativeCommandEventCounterStream() { // return CumulativeCommandEventCounterStream.getInstance(getCommandKey(), getCommandProperties()); // } // // public RollingCommandEventCounterStream getRollingCommandEventCounterStream() { // return RollingCommandEventCounterStream.getInstance(getCommandKey(), getCommandProperties()); // } // // public static class Builder<R> { // protected final TenacityPropertyKey key; // protected Supplier<R> run; // protected Supplier<R> fallback; // // public Builder(TenacityPropertyKey key) { // this.key = key; // } // // public Builder<R> run(Supplier<R> fun) { // run = fun; // return this; // } // // public Builder<R> fallback(Supplier<R> fun) { // fallback = fun; // return this; // } // // public TenacityCommand<R> build() { // if (run == null) { // throw new IllegalStateException("Run must be supplied."); // } // if (fallback == null) { // return new TenacityCommand<R>(key) { // @Override // protected R run() throws Exception { // return run.get(); // } // }; // } else { // return new TenacityCommand<R>(key) { // @Override // protected R run() throws Exception { // return run.get(); // } // // @Override // protected R getFallback() { // return fallback.get(); // } // }; // } // } // // public R execute() { // return build().execute(); // } // // public Future<R> queue() { // return build().queue(); // } // // public Observable<R> observe() { // return build().observe(); // } // // public Observable<R> lazyObservable() { // return build().toObservable(); // } // } // // @Override // protected abstract R run() throws Exception; // } // // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/properties/TenacityPropertyKey.java // public interface TenacityPropertyKey extends HystrixCommandKey, HystrixThreadPoolKey { // default Predicate<TenacityPropertyKey> isEqualPredicate() { // return (value) -> value.name().equals(name()); // } // // default TenacityPropertyKey validate(Collection<TenacityPropertyKey> keys) { // return keys.stream() // .filter(isEqualPredicate()) // .findAny() // .orElseThrow(() -> new NoSuchElementException("No TenacityPropertyKey " + name())); // } // }
import com.yammer.tenacity.core.TenacityCommand; import com.yammer.tenacity.core.properties.TenacityPropertyKey; import io.dropwizard.auth.AuthenticationException; import io.dropwizard.auth.Authenticator; import java.security.Principal; import java.util.Optional;
package com.yammer.tenacity.core.auth; public class TenacityAuthenticator<C, P extends Principal> implements Authenticator<C, P> { private final Authenticator<C, P> underlying;
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/TenacityCommand.java // public abstract class TenacityCommand<R> extends HystrixCommand<R> { // protected TenacityCommand(TenacityPropertyKey tenacityPropertyKey) { // this(tenacityPropertyKey, tenacityPropertyKey); // } // // protected TenacityCommand(TenacityPropertyKey commandKey, // TenacityPropertyKey threadpoolKey) { // super(HystrixCommand.Setter.withGroupKey(tenacityGroupKey()) // .andCommandKey(commandKey) // .andThreadPoolKey(threadpoolKey)); // } // // static HystrixCommandGroupKey tenacityGroupKey() { // return commandGroupKeyFrom("TENACITY"); // } // // public static HystrixCommandGroupKey commandGroupKeyFrom(String key) { // return HystrixCommandGroupKey.Factory.asKey(key); // } // // public static HystrixCommandProperties getCommandProperties(TenacityPropertyKey key) { // return HystrixPropertiesFactory.getCommandProperties(key, null); // } // // public HystrixCommandProperties getCommandProperties() { // return HystrixPropertiesFactory.getCommandProperties(getCommandKey(), null); // } // // public static HystrixThreadPoolProperties getThreadpoolProperties(TenacityPropertyKey key) { // return HystrixPropertiesFactory.getThreadPoolProperties(key, null); // } // // public static <R> Builder<R> builder(TenacityPropertyKey tenacityPropertyKey) { // return new Builder<>(tenacityPropertyKey); // } // // public HystrixThreadPoolProperties getThreadpoolProperties() { // return HystrixPropertiesFactory.getThreadPoolProperties(getThreadPoolKey(), null); // } // // public HystrixCommandMetrics getCommandMetrics() { // return HystrixCommandMetrics.getInstance(getCommandKey()); // } // // public static HystrixCommandMetrics getCommandMetrics(TenacityPropertyKey key) { // return HystrixCommandMetrics.getInstance(key); // } // // public HystrixThreadPoolMetrics getThreadpoolMetrics() { // return HystrixThreadPoolMetrics.getInstance(getThreadPoolKey()); // } // // public static HystrixThreadPoolMetrics getThreadpoolMetrics(TenacityPropertyKey key) { // return HystrixThreadPoolMetrics.getInstance(key); // } // // public HystrixCircuitBreaker getCircuitBreaker() { // return HystrixCircuitBreaker.Factory.getInstance(getCommandKey()); // } // // public static HystrixCircuitBreaker getCircuitBreaker(TenacityPropertyKey key) { // return HystrixCircuitBreaker.Factory.getInstance(key); // } // // public CumulativeCommandEventCounterStream getCumulativeCommandEventCounterStream() { // return CumulativeCommandEventCounterStream.getInstance(getCommandKey(), getCommandProperties()); // } // // public RollingCommandEventCounterStream getRollingCommandEventCounterStream() { // return RollingCommandEventCounterStream.getInstance(getCommandKey(), getCommandProperties()); // } // // public static class Builder<R> { // protected final TenacityPropertyKey key; // protected Supplier<R> run; // protected Supplier<R> fallback; // // public Builder(TenacityPropertyKey key) { // this.key = key; // } // // public Builder<R> run(Supplier<R> fun) { // run = fun; // return this; // } // // public Builder<R> fallback(Supplier<R> fun) { // fallback = fun; // return this; // } // // public TenacityCommand<R> build() { // if (run == null) { // throw new IllegalStateException("Run must be supplied."); // } // if (fallback == null) { // return new TenacityCommand<R>(key) { // @Override // protected R run() throws Exception { // return run.get(); // } // }; // } else { // return new TenacityCommand<R>(key) { // @Override // protected R run() throws Exception { // return run.get(); // } // // @Override // protected R getFallback() { // return fallback.get(); // } // }; // } // } // // public R execute() { // return build().execute(); // } // // public Future<R> queue() { // return build().queue(); // } // // public Observable<R> observe() { // return build().observe(); // } // // public Observable<R> lazyObservable() { // return build().toObservable(); // } // } // // @Override // protected abstract R run() throws Exception; // } // // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/properties/TenacityPropertyKey.java // public interface TenacityPropertyKey extends HystrixCommandKey, HystrixThreadPoolKey { // default Predicate<TenacityPropertyKey> isEqualPredicate() { // return (value) -> value.name().equals(name()); // } // // default TenacityPropertyKey validate(Collection<TenacityPropertyKey> keys) { // return keys.stream() // .filter(isEqualPredicate()) // .findAny() // .orElseThrow(() -> new NoSuchElementException("No TenacityPropertyKey " + name())); // } // } // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/auth/TenacityAuthenticator.java import com.yammer.tenacity.core.TenacityCommand; import com.yammer.tenacity.core.properties.TenacityPropertyKey; import io.dropwizard.auth.AuthenticationException; import io.dropwizard.auth.Authenticator; import java.security.Principal; import java.util.Optional; package com.yammer.tenacity.core.auth; public class TenacityAuthenticator<C, P extends Principal> implements Authenticator<C, P> { private final Authenticator<C, P> underlying;
private final TenacityPropertyKey tenacityPropertyKey;
yammer/tenacity
tenacity-core/src/main/java/com/yammer/tenacity/core/auth/TenacityAuthenticator.java
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/TenacityCommand.java // public abstract class TenacityCommand<R> extends HystrixCommand<R> { // protected TenacityCommand(TenacityPropertyKey tenacityPropertyKey) { // this(tenacityPropertyKey, tenacityPropertyKey); // } // // protected TenacityCommand(TenacityPropertyKey commandKey, // TenacityPropertyKey threadpoolKey) { // super(HystrixCommand.Setter.withGroupKey(tenacityGroupKey()) // .andCommandKey(commandKey) // .andThreadPoolKey(threadpoolKey)); // } // // static HystrixCommandGroupKey tenacityGroupKey() { // return commandGroupKeyFrom("TENACITY"); // } // // public static HystrixCommandGroupKey commandGroupKeyFrom(String key) { // return HystrixCommandGroupKey.Factory.asKey(key); // } // // public static HystrixCommandProperties getCommandProperties(TenacityPropertyKey key) { // return HystrixPropertiesFactory.getCommandProperties(key, null); // } // // public HystrixCommandProperties getCommandProperties() { // return HystrixPropertiesFactory.getCommandProperties(getCommandKey(), null); // } // // public static HystrixThreadPoolProperties getThreadpoolProperties(TenacityPropertyKey key) { // return HystrixPropertiesFactory.getThreadPoolProperties(key, null); // } // // public static <R> Builder<R> builder(TenacityPropertyKey tenacityPropertyKey) { // return new Builder<>(tenacityPropertyKey); // } // // public HystrixThreadPoolProperties getThreadpoolProperties() { // return HystrixPropertiesFactory.getThreadPoolProperties(getThreadPoolKey(), null); // } // // public HystrixCommandMetrics getCommandMetrics() { // return HystrixCommandMetrics.getInstance(getCommandKey()); // } // // public static HystrixCommandMetrics getCommandMetrics(TenacityPropertyKey key) { // return HystrixCommandMetrics.getInstance(key); // } // // public HystrixThreadPoolMetrics getThreadpoolMetrics() { // return HystrixThreadPoolMetrics.getInstance(getThreadPoolKey()); // } // // public static HystrixThreadPoolMetrics getThreadpoolMetrics(TenacityPropertyKey key) { // return HystrixThreadPoolMetrics.getInstance(key); // } // // public HystrixCircuitBreaker getCircuitBreaker() { // return HystrixCircuitBreaker.Factory.getInstance(getCommandKey()); // } // // public static HystrixCircuitBreaker getCircuitBreaker(TenacityPropertyKey key) { // return HystrixCircuitBreaker.Factory.getInstance(key); // } // // public CumulativeCommandEventCounterStream getCumulativeCommandEventCounterStream() { // return CumulativeCommandEventCounterStream.getInstance(getCommandKey(), getCommandProperties()); // } // // public RollingCommandEventCounterStream getRollingCommandEventCounterStream() { // return RollingCommandEventCounterStream.getInstance(getCommandKey(), getCommandProperties()); // } // // public static class Builder<R> { // protected final TenacityPropertyKey key; // protected Supplier<R> run; // protected Supplier<R> fallback; // // public Builder(TenacityPropertyKey key) { // this.key = key; // } // // public Builder<R> run(Supplier<R> fun) { // run = fun; // return this; // } // // public Builder<R> fallback(Supplier<R> fun) { // fallback = fun; // return this; // } // // public TenacityCommand<R> build() { // if (run == null) { // throw new IllegalStateException("Run must be supplied."); // } // if (fallback == null) { // return new TenacityCommand<R>(key) { // @Override // protected R run() throws Exception { // return run.get(); // } // }; // } else { // return new TenacityCommand<R>(key) { // @Override // protected R run() throws Exception { // return run.get(); // } // // @Override // protected R getFallback() { // return fallback.get(); // } // }; // } // } // // public R execute() { // return build().execute(); // } // // public Future<R> queue() { // return build().queue(); // } // // public Observable<R> observe() { // return build().observe(); // } // // public Observable<R> lazyObservable() { // return build().toObservable(); // } // } // // @Override // protected abstract R run() throws Exception; // } // // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/properties/TenacityPropertyKey.java // public interface TenacityPropertyKey extends HystrixCommandKey, HystrixThreadPoolKey { // default Predicate<TenacityPropertyKey> isEqualPredicate() { // return (value) -> value.name().equals(name()); // } // // default TenacityPropertyKey validate(Collection<TenacityPropertyKey> keys) { // return keys.stream() // .filter(isEqualPredicate()) // .findAny() // .orElseThrow(() -> new NoSuchElementException("No TenacityPropertyKey " + name())); // } // }
import com.yammer.tenacity.core.TenacityCommand; import com.yammer.tenacity.core.properties.TenacityPropertyKey; import io.dropwizard.auth.AuthenticationException; import io.dropwizard.auth.Authenticator; import java.security.Principal; import java.util.Optional;
package com.yammer.tenacity.core.auth; public class TenacityAuthenticator<C, P extends Principal> implements Authenticator<C, P> { private final Authenticator<C, P> underlying; private final TenacityPropertyKey tenacityPropertyKey; private TenacityAuthenticator(Authenticator<C, P> underlying, TenacityPropertyKey tenacityPropertyKey) { this.underlying = underlying; this.tenacityPropertyKey = tenacityPropertyKey; } public static <C, P extends Principal> Authenticator<C, P> wrap(Authenticator<C, P> authenticator, TenacityPropertyKey tenacityPropertyKey) { return new TenacityAuthenticator<>(authenticator, tenacityPropertyKey); } @Override public Optional<P> authenticate(C credentials) throws AuthenticationException { return new TenacityAuthenticate(credentials).execute(); }
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/TenacityCommand.java // public abstract class TenacityCommand<R> extends HystrixCommand<R> { // protected TenacityCommand(TenacityPropertyKey tenacityPropertyKey) { // this(tenacityPropertyKey, tenacityPropertyKey); // } // // protected TenacityCommand(TenacityPropertyKey commandKey, // TenacityPropertyKey threadpoolKey) { // super(HystrixCommand.Setter.withGroupKey(tenacityGroupKey()) // .andCommandKey(commandKey) // .andThreadPoolKey(threadpoolKey)); // } // // static HystrixCommandGroupKey tenacityGroupKey() { // return commandGroupKeyFrom("TENACITY"); // } // // public static HystrixCommandGroupKey commandGroupKeyFrom(String key) { // return HystrixCommandGroupKey.Factory.asKey(key); // } // // public static HystrixCommandProperties getCommandProperties(TenacityPropertyKey key) { // return HystrixPropertiesFactory.getCommandProperties(key, null); // } // // public HystrixCommandProperties getCommandProperties() { // return HystrixPropertiesFactory.getCommandProperties(getCommandKey(), null); // } // // public static HystrixThreadPoolProperties getThreadpoolProperties(TenacityPropertyKey key) { // return HystrixPropertiesFactory.getThreadPoolProperties(key, null); // } // // public static <R> Builder<R> builder(TenacityPropertyKey tenacityPropertyKey) { // return new Builder<>(tenacityPropertyKey); // } // // public HystrixThreadPoolProperties getThreadpoolProperties() { // return HystrixPropertiesFactory.getThreadPoolProperties(getThreadPoolKey(), null); // } // // public HystrixCommandMetrics getCommandMetrics() { // return HystrixCommandMetrics.getInstance(getCommandKey()); // } // // public static HystrixCommandMetrics getCommandMetrics(TenacityPropertyKey key) { // return HystrixCommandMetrics.getInstance(key); // } // // public HystrixThreadPoolMetrics getThreadpoolMetrics() { // return HystrixThreadPoolMetrics.getInstance(getThreadPoolKey()); // } // // public static HystrixThreadPoolMetrics getThreadpoolMetrics(TenacityPropertyKey key) { // return HystrixThreadPoolMetrics.getInstance(key); // } // // public HystrixCircuitBreaker getCircuitBreaker() { // return HystrixCircuitBreaker.Factory.getInstance(getCommandKey()); // } // // public static HystrixCircuitBreaker getCircuitBreaker(TenacityPropertyKey key) { // return HystrixCircuitBreaker.Factory.getInstance(key); // } // // public CumulativeCommandEventCounterStream getCumulativeCommandEventCounterStream() { // return CumulativeCommandEventCounterStream.getInstance(getCommandKey(), getCommandProperties()); // } // // public RollingCommandEventCounterStream getRollingCommandEventCounterStream() { // return RollingCommandEventCounterStream.getInstance(getCommandKey(), getCommandProperties()); // } // // public static class Builder<R> { // protected final TenacityPropertyKey key; // protected Supplier<R> run; // protected Supplier<R> fallback; // // public Builder(TenacityPropertyKey key) { // this.key = key; // } // // public Builder<R> run(Supplier<R> fun) { // run = fun; // return this; // } // // public Builder<R> fallback(Supplier<R> fun) { // fallback = fun; // return this; // } // // public TenacityCommand<R> build() { // if (run == null) { // throw new IllegalStateException("Run must be supplied."); // } // if (fallback == null) { // return new TenacityCommand<R>(key) { // @Override // protected R run() throws Exception { // return run.get(); // } // }; // } else { // return new TenacityCommand<R>(key) { // @Override // protected R run() throws Exception { // return run.get(); // } // // @Override // protected R getFallback() { // return fallback.get(); // } // }; // } // } // // public R execute() { // return build().execute(); // } // // public Future<R> queue() { // return build().queue(); // } // // public Observable<R> observe() { // return build().observe(); // } // // public Observable<R> lazyObservable() { // return build().toObservable(); // } // } // // @Override // protected abstract R run() throws Exception; // } // // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/properties/TenacityPropertyKey.java // public interface TenacityPropertyKey extends HystrixCommandKey, HystrixThreadPoolKey { // default Predicate<TenacityPropertyKey> isEqualPredicate() { // return (value) -> value.name().equals(name()); // } // // default TenacityPropertyKey validate(Collection<TenacityPropertyKey> keys) { // return keys.stream() // .filter(isEqualPredicate()) // .findAny() // .orElseThrow(() -> new NoSuchElementException("No TenacityPropertyKey " + name())); // } // } // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/auth/TenacityAuthenticator.java import com.yammer.tenacity.core.TenacityCommand; import com.yammer.tenacity.core.properties.TenacityPropertyKey; import io.dropwizard.auth.AuthenticationException; import io.dropwizard.auth.Authenticator; import java.security.Principal; import java.util.Optional; package com.yammer.tenacity.core.auth; public class TenacityAuthenticator<C, P extends Principal> implements Authenticator<C, P> { private final Authenticator<C, P> underlying; private final TenacityPropertyKey tenacityPropertyKey; private TenacityAuthenticator(Authenticator<C, P> underlying, TenacityPropertyKey tenacityPropertyKey) { this.underlying = underlying; this.tenacityPropertyKey = tenacityPropertyKey; } public static <C, P extends Principal> Authenticator<C, P> wrap(Authenticator<C, P> authenticator, TenacityPropertyKey tenacityPropertyKey) { return new TenacityAuthenticator<>(authenticator, tenacityPropertyKey); } @Override public Optional<P> authenticate(C credentials) throws AuthenticationException { return new TenacityAuthenticate(credentials).execute(); }
private class TenacityAuthenticate extends TenacityCommand<Optional<P>> {
yammer/tenacity
tenacity-core/src/main/java/com/yammer/tenacity/core/servlets/TenacityConfigurationServlet.java
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/resources/TenacityConfigurationResource.java // @Path(TenacityConfigurationResource.PATH) // public class TenacityConfigurationResource { // public static final String PATH = "/tenacity/configuration"; // private final TenacityPropertyKeyFactory factory; // // public TenacityConfigurationResource(TenacityPropertyKeyFactory factory) { // this.factory = checkNotNull(factory); // } // // @GET @Timed @Produces(MediaType.APPLICATION_JSON) @Path("{key}") // public Response get(@PathParam("key") String key) { // try { // return Response.ok(TenacityPropertyStore.getTenacityConfiguration(factory.from(key))).build(); // } catch (IllegalArgumentException err) { // return Response.status(Response.Status.NOT_FOUND).build(); // } // } // }
import com.fasterxml.jackson.databind.ObjectMapper; import com.yammer.tenacity.core.resources.TenacityConfigurationResource; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException;
package com.yammer.tenacity.core.servlets; public class TenacityConfigurationServlet extends TenacityServlet { private static final long serialVersionUID = 0;
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/resources/TenacityConfigurationResource.java // @Path(TenacityConfigurationResource.PATH) // public class TenacityConfigurationResource { // public static final String PATH = "/tenacity/configuration"; // private final TenacityPropertyKeyFactory factory; // // public TenacityConfigurationResource(TenacityPropertyKeyFactory factory) { // this.factory = checkNotNull(factory); // } // // @GET @Timed @Produces(MediaType.APPLICATION_JSON) @Path("{key}") // public Response get(@PathParam("key") String key) { // try { // return Response.ok(TenacityPropertyStore.getTenacityConfiguration(factory.from(key))).build(); // } catch (IllegalArgumentException err) { // return Response.status(Response.Status.NOT_FOUND).build(); // } // } // } // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/servlets/TenacityConfigurationServlet.java import com.fasterxml.jackson.databind.ObjectMapper; import com.yammer.tenacity.core.resources.TenacityConfigurationResource; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; package com.yammer.tenacity.core.servlets; public class TenacityConfigurationServlet extends TenacityServlet { private static final long serialVersionUID = 0;
private transient final TenacityConfigurationResource configurationResource;
yammer/tenacity
tenacity-core/src/main/java/com/yammer/tenacity/core/properties/ArchaiusPropertyRegister.java
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/config/BreakerboxConfiguration.java // public class BreakerboxConfiguration { // @NotNull @Valid // private String urls = ""; // // @NotNull @Valid // private Duration initialDelay = Duration.seconds(0); // // @NotNull @Valid // private Duration delay = Duration.seconds(60); // // @NotNull @Valid // private Duration waitForInitialLoad = Duration.milliseconds(0); // // public BreakerboxConfiguration() { /* Jackson */ } // // public String getUrls() { // return urls; // } // // public void setUrls(String urls) { // this.urls = urls; // } // // public Duration getInitialDelay() { // return initialDelay; // } // // public void setInitialDelay(Duration initialDelay) { // this.initialDelay = initialDelay; // } // // public Duration getDelay() { // return delay; // } // // public void setDelay(Duration delay) { // this.delay = delay; // } // // public Duration getWaitForInitialLoad() { // return waitForInitialLoad; // } // // public void setWaitForInitialLoad(Duration waitForInitialLoad) { // this.waitForInitialLoad = waitForInitialLoad; // } // // public boolean isWaitForInitialLoad() { // return waitForInitialLoad.getQuantity() > 0; // } // }
import com.google.common.primitives.Ints; import com.netflix.config.ConfigurationManager; import com.netflix.config.DynamicConfiguration; import com.netflix.config.FixedDelayPollingScheduler; import com.netflix.config.PolledConfigurationSource; import com.netflix.config.sources.URLConfigurationSource; import com.yammer.tenacity.core.config.BreakerboxConfiguration; import io.dropwizard.util.Duration; import org.apache.commons.configuration.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.CountDownLatch;
package com.yammer.tenacity.core.properties; public class ArchaiusPropertyRegister { private static final Logger LOGGER = LoggerFactory.getLogger(ArchaiusPropertyRegister.class); private static class TenacityPollingScheduler extends FixedDelayPollingScheduler { private static final Logger LOGGER = LoggerFactory.getLogger(TenacityPollingScheduler.class); public TenacityPollingScheduler(int initialDelayMillis, int delayMillis, boolean ignoreDeletesFromSource) { super(initialDelayMillis, delayMillis, ignoreDeletesFromSource); } @Override protected synchronized void initialLoad(PolledConfigurationSource source, Configuration config) { try { super.initialLoad(source, config); } catch (Exception err) { LOGGER.warn("Initial dynamic configuration load failed", err); } } }
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/config/BreakerboxConfiguration.java // public class BreakerboxConfiguration { // @NotNull @Valid // private String urls = ""; // // @NotNull @Valid // private Duration initialDelay = Duration.seconds(0); // // @NotNull @Valid // private Duration delay = Duration.seconds(60); // // @NotNull @Valid // private Duration waitForInitialLoad = Duration.milliseconds(0); // // public BreakerboxConfiguration() { /* Jackson */ } // // public String getUrls() { // return urls; // } // // public void setUrls(String urls) { // this.urls = urls; // } // // public Duration getInitialDelay() { // return initialDelay; // } // // public void setInitialDelay(Duration initialDelay) { // this.initialDelay = initialDelay; // } // // public Duration getDelay() { // return delay; // } // // public void setDelay(Duration delay) { // this.delay = delay; // } // // public Duration getWaitForInitialLoad() { // return waitForInitialLoad; // } // // public void setWaitForInitialLoad(Duration waitForInitialLoad) { // this.waitForInitialLoad = waitForInitialLoad; // } // // public boolean isWaitForInitialLoad() { // return waitForInitialLoad.getQuantity() > 0; // } // } // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/properties/ArchaiusPropertyRegister.java import com.google.common.primitives.Ints; import com.netflix.config.ConfigurationManager; import com.netflix.config.DynamicConfiguration; import com.netflix.config.FixedDelayPollingScheduler; import com.netflix.config.PolledConfigurationSource; import com.netflix.config.sources.URLConfigurationSource; import com.yammer.tenacity.core.config.BreakerboxConfiguration; import io.dropwizard.util.Duration; import org.apache.commons.configuration.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.CountDownLatch; package com.yammer.tenacity.core.properties; public class ArchaiusPropertyRegister { private static final Logger LOGGER = LoggerFactory.getLogger(ArchaiusPropertyRegister.class); private static class TenacityPollingScheduler extends FixedDelayPollingScheduler { private static final Logger LOGGER = LoggerFactory.getLogger(TenacityPollingScheduler.class); public TenacityPollingScheduler(int initialDelayMillis, int delayMillis, boolean ignoreDeletesFromSource) { super(initialDelayMillis, delayMillis, ignoreDeletesFromSource); } @Override protected synchronized void initialLoad(PolledConfigurationSource source, Configuration config) { try { super.initialLoad(source, config); } catch (Exception err) { LOGGER.warn("Initial dynamic configuration load failed", err); } } }
public void register(BreakerboxConfiguration breakerboxConfiguration) {
yammer/tenacity
tenacity-client/src/main/java/com/yammer/tenacity/client/TenacityClientBuilder.java
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/http/TenacityJerseyClientBuilder.java // public class TenacityJerseyClientBuilder { // protected final TenacityPropertyKey tenacityPropertyKey; // //50ms by default, because with lower values we have seen issues with it racing with Tenacity/Hystrix's timeout // protected Duration timeoutPadding = Duration.milliseconds(50); // // private TenacityJerseyClientBuilder(TenacityPropertyKey tenacityPropertyKey) { // this.tenacityPropertyKey = tenacityPropertyKey; // } // // public TenacityJerseyClientBuilder usingTimeoutPadding(Duration timeoutPadding) { // this.timeoutPadding = timeoutPadding; // return this; // } // // public Client build(Client client) { // return new TenacityJerseyClient( // client, // tenacityPropertyKey, // timeoutPadding // ); // } // // public static TenacityJerseyClientBuilder builder(TenacityPropertyKey key) { // return new TenacityJerseyClientBuilder(key); // } // } // // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/properties/TenacityPropertyKey.java // public interface TenacityPropertyKey extends HystrixCommandKey, HystrixThreadPoolKey { // default Predicate<TenacityPropertyKey> isEqualPredicate() { // return (value) -> value.name().equals(name()); // } // // default TenacityPropertyKey validate(Collection<TenacityPropertyKey> keys) { // return keys.stream() // .filter(isEqualPredicate()) // .findAny() // .orElseThrow(() -> new NoSuchElementException("No TenacityPropertyKey " + name())); // } // }
import com.yammer.tenacity.core.http.TenacityJerseyClientBuilder; import com.yammer.tenacity.core.properties.TenacityPropertyKey; import io.dropwizard.client.JerseyClientBuilder; import io.dropwizard.client.JerseyClientConfiguration; import io.dropwizard.setup.Environment; import javax.ws.rs.client.Client;
package com.yammer.tenacity.client; public class TenacityClientBuilder { protected JerseyClientConfiguration jerseyConfiguration = new JerseyClientConfiguration(); protected final Environment environment;
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/http/TenacityJerseyClientBuilder.java // public class TenacityJerseyClientBuilder { // protected final TenacityPropertyKey tenacityPropertyKey; // //50ms by default, because with lower values we have seen issues with it racing with Tenacity/Hystrix's timeout // protected Duration timeoutPadding = Duration.milliseconds(50); // // private TenacityJerseyClientBuilder(TenacityPropertyKey tenacityPropertyKey) { // this.tenacityPropertyKey = tenacityPropertyKey; // } // // public TenacityJerseyClientBuilder usingTimeoutPadding(Duration timeoutPadding) { // this.timeoutPadding = timeoutPadding; // return this; // } // // public Client build(Client client) { // return new TenacityJerseyClient( // client, // tenacityPropertyKey, // timeoutPadding // ); // } // // public static TenacityJerseyClientBuilder builder(TenacityPropertyKey key) { // return new TenacityJerseyClientBuilder(key); // } // } // // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/properties/TenacityPropertyKey.java // public interface TenacityPropertyKey extends HystrixCommandKey, HystrixThreadPoolKey { // default Predicate<TenacityPropertyKey> isEqualPredicate() { // return (value) -> value.name().equals(name()); // } // // default TenacityPropertyKey validate(Collection<TenacityPropertyKey> keys) { // return keys.stream() // .filter(isEqualPredicate()) // .findAny() // .orElseThrow(() -> new NoSuchElementException("No TenacityPropertyKey " + name())); // } // } // Path: tenacity-client/src/main/java/com/yammer/tenacity/client/TenacityClientBuilder.java import com.yammer.tenacity.core.http.TenacityJerseyClientBuilder; import com.yammer.tenacity.core.properties.TenacityPropertyKey; import io.dropwizard.client.JerseyClientBuilder; import io.dropwizard.client.JerseyClientConfiguration; import io.dropwizard.setup.Environment; import javax.ws.rs.client.Client; package com.yammer.tenacity.client; public class TenacityClientBuilder { protected JerseyClientConfiguration jerseyConfiguration = new JerseyClientConfiguration(); protected final Environment environment;
protected final TenacityPropertyKey tenacityPropertyKey;
yammer/tenacity
tenacity-client/src/main/java/com/yammer/tenacity/client/TenacityClientBuilder.java
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/http/TenacityJerseyClientBuilder.java // public class TenacityJerseyClientBuilder { // protected final TenacityPropertyKey tenacityPropertyKey; // //50ms by default, because with lower values we have seen issues with it racing with Tenacity/Hystrix's timeout // protected Duration timeoutPadding = Duration.milliseconds(50); // // private TenacityJerseyClientBuilder(TenacityPropertyKey tenacityPropertyKey) { // this.tenacityPropertyKey = tenacityPropertyKey; // } // // public TenacityJerseyClientBuilder usingTimeoutPadding(Duration timeoutPadding) { // this.timeoutPadding = timeoutPadding; // return this; // } // // public Client build(Client client) { // return new TenacityJerseyClient( // client, // tenacityPropertyKey, // timeoutPadding // ); // } // // public static TenacityJerseyClientBuilder builder(TenacityPropertyKey key) { // return new TenacityJerseyClientBuilder(key); // } // } // // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/properties/TenacityPropertyKey.java // public interface TenacityPropertyKey extends HystrixCommandKey, HystrixThreadPoolKey { // default Predicate<TenacityPropertyKey> isEqualPredicate() { // return (value) -> value.name().equals(name()); // } // // default TenacityPropertyKey validate(Collection<TenacityPropertyKey> keys) { // return keys.stream() // .filter(isEqualPredicate()) // .findAny() // .orElseThrow(() -> new NoSuchElementException("No TenacityPropertyKey " + name())); // } // }
import com.yammer.tenacity.core.http.TenacityJerseyClientBuilder; import com.yammer.tenacity.core.properties.TenacityPropertyKey; import io.dropwizard.client.JerseyClientBuilder; import io.dropwizard.client.JerseyClientConfiguration; import io.dropwizard.setup.Environment; import javax.ws.rs.client.Client;
package com.yammer.tenacity.client; public class TenacityClientBuilder { protected JerseyClientConfiguration jerseyConfiguration = new JerseyClientConfiguration(); protected final Environment environment; protected final TenacityPropertyKey tenacityPropertyKey; public TenacityClientBuilder(Environment environment, TenacityPropertyKey tenacityPropertyKey) { this.environment = environment; this.tenacityPropertyKey = tenacityPropertyKey; } public TenacityClientBuilder using(JerseyClientConfiguration jerseyConfiguration) { this.jerseyConfiguration = jerseyConfiguration; return this; } public TenacityClient build() { final Client client = new JerseyClientBuilder(environment) .using(jerseyConfiguration) .build("tenacity-" + tenacityPropertyKey);
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/http/TenacityJerseyClientBuilder.java // public class TenacityJerseyClientBuilder { // protected final TenacityPropertyKey tenacityPropertyKey; // //50ms by default, because with lower values we have seen issues with it racing with Tenacity/Hystrix's timeout // protected Duration timeoutPadding = Duration.milliseconds(50); // // private TenacityJerseyClientBuilder(TenacityPropertyKey tenacityPropertyKey) { // this.tenacityPropertyKey = tenacityPropertyKey; // } // // public TenacityJerseyClientBuilder usingTimeoutPadding(Duration timeoutPadding) { // this.timeoutPadding = timeoutPadding; // return this; // } // // public Client build(Client client) { // return new TenacityJerseyClient( // client, // tenacityPropertyKey, // timeoutPadding // ); // } // // public static TenacityJerseyClientBuilder builder(TenacityPropertyKey key) { // return new TenacityJerseyClientBuilder(key); // } // } // // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/properties/TenacityPropertyKey.java // public interface TenacityPropertyKey extends HystrixCommandKey, HystrixThreadPoolKey { // default Predicate<TenacityPropertyKey> isEqualPredicate() { // return (value) -> value.name().equals(name()); // } // // default TenacityPropertyKey validate(Collection<TenacityPropertyKey> keys) { // return keys.stream() // .filter(isEqualPredicate()) // .findAny() // .orElseThrow(() -> new NoSuchElementException("No TenacityPropertyKey " + name())); // } // } // Path: tenacity-client/src/main/java/com/yammer/tenacity/client/TenacityClientBuilder.java import com.yammer.tenacity.core.http.TenacityJerseyClientBuilder; import com.yammer.tenacity.core.properties.TenacityPropertyKey; import io.dropwizard.client.JerseyClientBuilder; import io.dropwizard.client.JerseyClientConfiguration; import io.dropwizard.setup.Environment; import javax.ws.rs.client.Client; package com.yammer.tenacity.client; public class TenacityClientBuilder { protected JerseyClientConfiguration jerseyConfiguration = new JerseyClientConfiguration(); protected final Environment environment; protected final TenacityPropertyKey tenacityPropertyKey; public TenacityClientBuilder(Environment environment, TenacityPropertyKey tenacityPropertyKey) { this.environment = environment; this.tenacityPropertyKey = tenacityPropertyKey; } public TenacityClientBuilder using(JerseyClientConfiguration jerseyConfiguration) { this.jerseyConfiguration = jerseyConfiguration; return this; } public TenacityClient build() { final Client client = new JerseyClientBuilder(environment) .using(jerseyConfiguration) .build("tenacity-" + tenacityPropertyKey);
return new TenacityClient(environment.metrics(), TenacityJerseyClientBuilder
yammer/tenacity
tenacity-core/src/main/java/com/yammer/tenacity/core/properties/TenacityPropertyRegister.java
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/config/BreakerboxConfiguration.java // public class BreakerboxConfiguration { // @NotNull @Valid // private String urls = ""; // // @NotNull @Valid // private Duration initialDelay = Duration.seconds(0); // // @NotNull @Valid // private Duration delay = Duration.seconds(60); // // @NotNull @Valid // private Duration waitForInitialLoad = Duration.milliseconds(0); // // public BreakerboxConfiguration() { /* Jackson */ } // // public String getUrls() { // return urls; // } // // public void setUrls(String urls) { // this.urls = urls; // } // // public Duration getInitialDelay() { // return initialDelay; // } // // public void setInitialDelay(Duration initialDelay) { // this.initialDelay = initialDelay; // } // // public Duration getDelay() { // return delay; // } // // public void setDelay(Duration delay) { // this.delay = delay; // } // // public Duration getWaitForInitialLoad() { // return waitForInitialLoad; // } // // public void setWaitForInitialLoad(Duration waitForInitialLoad) { // this.waitForInitialLoad = waitForInitialLoad; // } // // public boolean isWaitForInitialLoad() { // return waitForInitialLoad.getQuantity() > 0; // } // } // // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/config/TenacityConfiguration.java // public class TenacityConfiguration { // @NotNull @Valid // private ThreadPoolConfiguration threadpool = new ThreadPoolConfiguration(); // // @NotNull @Valid // private CircuitBreakerConfiguration circuitBreaker = new CircuitBreakerConfiguration(); // // @NotNull @Valid // private SemaphoreConfiguration semaphore = new SemaphoreConfiguration(); // // @Min(value = 0) // @Max(Integer.MAX_VALUE) // private int executionIsolationThreadTimeoutInMillis = 1000; // // private HystrixCommandProperties.ExecutionIsolationStrategy executionIsolationStrategy = null; // // public TenacityConfiguration() { /* Jackson */ } // // public TenacityConfiguration(ThreadPoolConfiguration threadpool, // CircuitBreakerConfiguration circuitBreaker, // SemaphoreConfiguration semaphore, // int executionIsolationThreadTimeoutInMillis) { // this(threadpool, circuitBreaker, semaphore, executionIsolationThreadTimeoutInMillis, null); // } // // public TenacityConfiguration(ThreadPoolConfiguration threadpool, // CircuitBreakerConfiguration circuitBreaker, // SemaphoreConfiguration semaphore, // int executionIsolationThreadTimeoutInMillis, // HystrixCommandProperties.ExecutionIsolationStrategy executionIsolationStrategy) { // this.threadpool = threadpool; // this.circuitBreaker = circuitBreaker; // this.semaphore = semaphore; // this.executionIsolationThreadTimeoutInMillis = executionIsolationThreadTimeoutInMillis; // this.executionIsolationStrategy = executionIsolationStrategy; // } // // public ThreadPoolConfiguration getThreadpool() { // return threadpool; // } // // public CircuitBreakerConfiguration getCircuitBreaker() { // return circuitBreaker; // } // // public int getExecutionIsolationThreadTimeoutInMillis() { // return executionIsolationThreadTimeoutInMillis; // } // // public void setThreadpool(ThreadPoolConfiguration threadpool) { // this.threadpool = threadpool; // } // // public void setCircuitBreaker(CircuitBreakerConfiguration circuitBreaker) { // this.circuitBreaker = circuitBreaker; // } // // public void setExecutionIsolationThreadTimeoutInMillis(int executionIsolationThreadTimeoutInMillis) { // this.executionIsolationThreadTimeoutInMillis = executionIsolationThreadTimeoutInMillis; // } // // public SemaphoreConfiguration getSemaphore() { // return semaphore; // } // // public void setSemaphore(SemaphoreConfiguration semaphore) { // this.semaphore = semaphore; // } // // public boolean hasExecutionIsolationStrategy() { // return Objects.nonNull(executionIsolationStrategy); // } // // public HystrixCommandProperties.ExecutionIsolationStrategy getExecutionIsolationStrategy() { // return executionIsolationStrategy; // } // // public void setExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy executionIsolationStrategy) { // this.executionIsolationStrategy = executionIsolationStrategy; // } // // @Override // public int hashCode() { // return Objects.hash(threadpool, circuitBreaker, semaphore, executionIsolationThreadTimeoutInMillis, executionIsolationStrategy); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // final TenacityConfiguration other = (TenacityConfiguration) obj; // return Objects.equals(this.threadpool, other.threadpool) // && Objects.equals(this.circuitBreaker, other.circuitBreaker) // && Objects.equals(this.semaphore, other.semaphore) // && Objects.equals(this.executionIsolationThreadTimeoutInMillis, other.executionIsolationThreadTimeoutInMillis) // && Objects.equals(this.executionIsolationStrategy, other.executionIsolationStrategy); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("threadpool", threadpool) // .add("circuitBreaker", circuitBreaker) // .add("semaphore", semaphore) // .add("executionIsolationThreadTimeoutInMillis", executionIsolationThreadTimeoutInMillis) // .add("executionIsolationStrategy", executionIsolationStrategy) // .toString(); // } // }
import com.google.common.collect.ImmutableMap; import com.netflix.config.ConfigurationManager; import com.yammer.tenacity.core.config.BreakerboxConfiguration; import com.yammer.tenacity.core.config.TenacityConfiguration; import io.dropwizard.util.Duration; import org.apache.commons.configuration.AbstractConfiguration; import java.util.Map;
package com.yammer.tenacity.core.properties; public class TenacityPropertyRegister { protected final ImmutableMap<TenacityPropertyKey, TenacityConfiguration> configurations;
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/config/BreakerboxConfiguration.java // public class BreakerboxConfiguration { // @NotNull @Valid // private String urls = ""; // // @NotNull @Valid // private Duration initialDelay = Duration.seconds(0); // // @NotNull @Valid // private Duration delay = Duration.seconds(60); // // @NotNull @Valid // private Duration waitForInitialLoad = Duration.milliseconds(0); // // public BreakerboxConfiguration() { /* Jackson */ } // // public String getUrls() { // return urls; // } // // public void setUrls(String urls) { // this.urls = urls; // } // // public Duration getInitialDelay() { // return initialDelay; // } // // public void setInitialDelay(Duration initialDelay) { // this.initialDelay = initialDelay; // } // // public Duration getDelay() { // return delay; // } // // public void setDelay(Duration delay) { // this.delay = delay; // } // // public Duration getWaitForInitialLoad() { // return waitForInitialLoad; // } // // public void setWaitForInitialLoad(Duration waitForInitialLoad) { // this.waitForInitialLoad = waitForInitialLoad; // } // // public boolean isWaitForInitialLoad() { // return waitForInitialLoad.getQuantity() > 0; // } // } // // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/config/TenacityConfiguration.java // public class TenacityConfiguration { // @NotNull @Valid // private ThreadPoolConfiguration threadpool = new ThreadPoolConfiguration(); // // @NotNull @Valid // private CircuitBreakerConfiguration circuitBreaker = new CircuitBreakerConfiguration(); // // @NotNull @Valid // private SemaphoreConfiguration semaphore = new SemaphoreConfiguration(); // // @Min(value = 0) // @Max(Integer.MAX_VALUE) // private int executionIsolationThreadTimeoutInMillis = 1000; // // private HystrixCommandProperties.ExecutionIsolationStrategy executionIsolationStrategy = null; // // public TenacityConfiguration() { /* Jackson */ } // // public TenacityConfiguration(ThreadPoolConfiguration threadpool, // CircuitBreakerConfiguration circuitBreaker, // SemaphoreConfiguration semaphore, // int executionIsolationThreadTimeoutInMillis) { // this(threadpool, circuitBreaker, semaphore, executionIsolationThreadTimeoutInMillis, null); // } // // public TenacityConfiguration(ThreadPoolConfiguration threadpool, // CircuitBreakerConfiguration circuitBreaker, // SemaphoreConfiguration semaphore, // int executionIsolationThreadTimeoutInMillis, // HystrixCommandProperties.ExecutionIsolationStrategy executionIsolationStrategy) { // this.threadpool = threadpool; // this.circuitBreaker = circuitBreaker; // this.semaphore = semaphore; // this.executionIsolationThreadTimeoutInMillis = executionIsolationThreadTimeoutInMillis; // this.executionIsolationStrategy = executionIsolationStrategy; // } // // public ThreadPoolConfiguration getThreadpool() { // return threadpool; // } // // public CircuitBreakerConfiguration getCircuitBreaker() { // return circuitBreaker; // } // // public int getExecutionIsolationThreadTimeoutInMillis() { // return executionIsolationThreadTimeoutInMillis; // } // // public void setThreadpool(ThreadPoolConfiguration threadpool) { // this.threadpool = threadpool; // } // // public void setCircuitBreaker(CircuitBreakerConfiguration circuitBreaker) { // this.circuitBreaker = circuitBreaker; // } // // public void setExecutionIsolationThreadTimeoutInMillis(int executionIsolationThreadTimeoutInMillis) { // this.executionIsolationThreadTimeoutInMillis = executionIsolationThreadTimeoutInMillis; // } // // public SemaphoreConfiguration getSemaphore() { // return semaphore; // } // // public void setSemaphore(SemaphoreConfiguration semaphore) { // this.semaphore = semaphore; // } // // public boolean hasExecutionIsolationStrategy() { // return Objects.nonNull(executionIsolationStrategy); // } // // public HystrixCommandProperties.ExecutionIsolationStrategy getExecutionIsolationStrategy() { // return executionIsolationStrategy; // } // // public void setExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy executionIsolationStrategy) { // this.executionIsolationStrategy = executionIsolationStrategy; // } // // @Override // public int hashCode() { // return Objects.hash(threadpool, circuitBreaker, semaphore, executionIsolationThreadTimeoutInMillis, executionIsolationStrategy); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // final TenacityConfiguration other = (TenacityConfiguration) obj; // return Objects.equals(this.threadpool, other.threadpool) // && Objects.equals(this.circuitBreaker, other.circuitBreaker) // && Objects.equals(this.semaphore, other.semaphore) // && Objects.equals(this.executionIsolationThreadTimeoutInMillis, other.executionIsolationThreadTimeoutInMillis) // && Objects.equals(this.executionIsolationStrategy, other.executionIsolationStrategy); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("threadpool", threadpool) // .add("circuitBreaker", circuitBreaker) // .add("semaphore", semaphore) // .add("executionIsolationThreadTimeoutInMillis", executionIsolationThreadTimeoutInMillis) // .add("executionIsolationStrategy", executionIsolationStrategy) // .toString(); // } // } // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/properties/TenacityPropertyRegister.java import com.google.common.collect.ImmutableMap; import com.netflix.config.ConfigurationManager; import com.yammer.tenacity.core.config.BreakerboxConfiguration; import com.yammer.tenacity.core.config.TenacityConfiguration; import io.dropwizard.util.Duration; import org.apache.commons.configuration.AbstractConfiguration; import java.util.Map; package com.yammer.tenacity.core.properties; public class TenacityPropertyRegister { protected final ImmutableMap<TenacityPropertyKey, TenacityConfiguration> configurations;
protected final BreakerboxConfiguration breakerboxConfiguration;
yammer/tenacity
tenacity-client/src/test/java/com/yammer/tenacity/client/tests/TenacityResourcesJerseyTest.java
// Path: tenacity-client/src/main/java/com/yammer/tenacity/client/TenacityClientBuilder.java // public class TenacityClientBuilder { // protected JerseyClientConfiguration jerseyConfiguration = new JerseyClientConfiguration(); // protected final Environment environment; // protected final TenacityPropertyKey tenacityPropertyKey; // // public TenacityClientBuilder(Environment environment, // TenacityPropertyKey tenacityPropertyKey) { // this.environment = environment; // this.tenacityPropertyKey = tenacityPropertyKey; // } // // public TenacityClientBuilder using(JerseyClientConfiguration jerseyConfiguration) { // this.jerseyConfiguration = jerseyConfiguration; // return this; // } // // public TenacityClient build() { // final Client client = new JerseyClientBuilder(environment) // .using(jerseyConfiguration) // .build("tenacity-" + tenacityPropertyKey); // return new TenacityClient(environment.metrics(), TenacityJerseyClientBuilder // .builder(tenacityPropertyKey) // .build(client)); // } // }
import com.google.common.io.Resources; import com.yammer.tenacity.client.TenacityClientBuilder; import io.dropwizard.Configuration; import io.dropwizard.client.JerseyClientBuilder; import io.dropwizard.testing.junit.DropwizardAppRule; import org.junit.BeforeClass; import org.junit.ClassRule; import java.net.URI;
package com.yammer.tenacity.client.tests; public class TenacityResourcesJerseyTest extends TenacityResources { @ClassRule public static DropwizardAppRule<Configuration> APP_RULE = new DropwizardAppRule<>(TenacityServletService.class, Resources.getResource("tenacityPropertyKeyServletService.yml").getPath()); @BeforeClass public static void initialization() {
// Path: tenacity-client/src/main/java/com/yammer/tenacity/client/TenacityClientBuilder.java // public class TenacityClientBuilder { // protected JerseyClientConfiguration jerseyConfiguration = new JerseyClientConfiguration(); // protected final Environment environment; // protected final TenacityPropertyKey tenacityPropertyKey; // // public TenacityClientBuilder(Environment environment, // TenacityPropertyKey tenacityPropertyKey) { // this.environment = environment; // this.tenacityPropertyKey = tenacityPropertyKey; // } // // public TenacityClientBuilder using(JerseyClientConfiguration jerseyConfiguration) { // this.jerseyConfiguration = jerseyConfiguration; // return this; // } // // public TenacityClient build() { // final Client client = new JerseyClientBuilder(environment) // .using(jerseyConfiguration) // .build("tenacity-" + tenacityPropertyKey); // return new TenacityClient(environment.metrics(), TenacityJerseyClientBuilder // .builder(tenacityPropertyKey) // .build(client)); // } // } // Path: tenacity-client/src/test/java/com/yammer/tenacity/client/tests/TenacityResourcesJerseyTest.java import com.google.common.io.Resources; import com.yammer.tenacity.client.TenacityClientBuilder; import io.dropwizard.Configuration; import io.dropwizard.client.JerseyClientBuilder; import io.dropwizard.testing.junit.DropwizardAppRule; import org.junit.BeforeClass; import org.junit.ClassRule; import java.net.URI; package com.yammer.tenacity.client.tests; public class TenacityResourcesJerseyTest extends TenacityResources { @ClassRule public static DropwizardAppRule<Configuration> APP_RULE = new DropwizardAppRule<>(TenacityServletService.class, Resources.getResource("tenacityPropertyKeyServletService.yml").getPath()); @BeforeClass public static void initialization() {
CLIENT = new TenacityClientBuilder(APP_RULE.getEnvironment(), ServletKeys.KEY_ONE).build();
AfterLifeLochie/fontbox
src/main/java/net/afterlifelochie/fontbox/layout/ObjectBounds.java
// Path: src/main/java/net/afterlifelochie/fontbox/document/property/FloatMode.java // public enum FloatMode { // NONE, LEFT, RIGHT; // }
import net.afterlifelochie.fontbox.document.property.FloatMode;
package net.afterlifelochie.fontbox.layout; public class ObjectBounds { public int x, y; public int width, height;
// Path: src/main/java/net/afterlifelochie/fontbox/document/property/FloatMode.java // public enum FloatMode { // NONE, LEFT, RIGHT; // } // Path: src/main/java/net/afterlifelochie/fontbox/layout/ObjectBounds.java import net.afterlifelochie.fontbox.document.property.FloatMode; package net.afterlifelochie.fontbox.layout; public class ObjectBounds { public int x, y; public int width, height;
public FloatMode floating;
AfterLifeLochie/fontbox
src/main/java/net/afterlifelochie/fontbox/data/FormattedString.java
// Path: src/main/java/net/afterlifelochie/fontbox/document/formatting/TextFormat.java // public class TextFormat implements Cloneable { // // public final EnumSet<DecorationStyle> decorations; // public final GLFont font; // public final ColorFormat color; // // public TextFormat(GLFont font) { // this(font, EnumSet.noneOf(DecorationStyle.class), null); // } // // public TextFormat(GLFont font, EnumSet<DecorationStyle> decorations) { // this(font, decorations, null); // } // // public TextFormat(GLFont font, ColorFormat color) { // this(font, EnumSet.noneOf(DecorationStyle.class), color); // } // // public TextFormat(GLFont font, EnumSet<DecorationStyle> decorations, ColorFormat color) { // this.decorations = decorations; // this.font = font; // this.color = color; // } // // @Override // public TextFormat clone() { // EnumSet<DecorationStyle> style = EnumSet.noneOf(DecorationStyle.class); // style.addAll(decorations); // return new TextFormat(font, style, (color != null) ? color.clone() : null); // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof TextFormat)) // return false; // TextFormat that = (TextFormat) o; // if (!font.equals(that.font) || !decorations.equals(that.decorations)) // return false; // if ((that.color != null && color == null) || (that.color == null && color != null)) // return false; // if (that.color != null && color != null) // if (!color.equals(that.color)) // return false; // return true; // } // }
import net.afterlifelochie.fontbox.document.formatting.TextFormat;
package net.afterlifelochie.fontbox.data; public class FormattedString { public final String string;
// Path: src/main/java/net/afterlifelochie/fontbox/document/formatting/TextFormat.java // public class TextFormat implements Cloneable { // // public final EnumSet<DecorationStyle> decorations; // public final GLFont font; // public final ColorFormat color; // // public TextFormat(GLFont font) { // this(font, EnumSet.noneOf(DecorationStyle.class), null); // } // // public TextFormat(GLFont font, EnumSet<DecorationStyle> decorations) { // this(font, decorations, null); // } // // public TextFormat(GLFont font, ColorFormat color) { // this(font, EnumSet.noneOf(DecorationStyle.class), color); // } // // public TextFormat(GLFont font, EnumSet<DecorationStyle> decorations, ColorFormat color) { // this.decorations = decorations; // this.font = font; // this.color = color; // } // // @Override // public TextFormat clone() { // EnumSet<DecorationStyle> style = EnumSet.noneOf(DecorationStyle.class); // style.addAll(decorations); // return new TextFormat(font, style, (color != null) ? color.clone() : null); // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof TextFormat)) // return false; // TextFormat that = (TextFormat) o; // if (!font.equals(that.font) || !decorations.equals(that.decorations)) // return false; // if ((that.color != null && color == null) || (that.color == null && color != null)) // return false; // if (that.color != null && color != null) // if (!color.equals(that.color)) // return false; // return true; // } // } // Path: src/main/java/net/afterlifelochie/fontbox/data/FormattedString.java import net.afterlifelochie.fontbox.document.formatting.TextFormat; package net.afterlifelochie.fontbox.data; public class FormattedString { public final String string;
public final TextFormat[] format;
MaChristmann/mobile-trial
test/src/com/android/vending/licensing/StrictPolicyTest.java
// Path: library/src/com/google/android/vending/licensing/Policy.java // public interface Policy { // // /** // * Change these values to make it more difficult for tools to automatically // * strip LVL protection from your APK. // */ // // /** // * LICENSED means that the server returned back a valid license response // */ // public static final int LICENSED = 0x0100; // /** // * NOT_LICENSED means that the server returned back a valid license response // * that indicated that the user definitively is not licensed // */ // public static final int NOT_LICENSED = 0x0231; // /** // * RETRY means that the license response was unable to be determined --- // * perhaps as a result of faulty networking // */ // public static final int RETRY = 0x0123; // // /** // * Provide results from contact with the license server. Retry counts are // * incremented if the current value of response is RETRY. Results will be // * used for any future policy decisions. // * // * @param response the result from validating the server response // * @param rawData the raw server response data, can be null for RETRY // */ // void processServerResponse(int response, ResponseData rawData); // // /** // * Check if the user should be allowed access to the application. // */ // boolean allowAccess(); // }
import com.google.android.vending.licensing.Policy; import com.google.android.vending.licensing.StrictPolicy; import junit.framework.TestCase;
/* * Copyright (C) 2010 The Android Open Source Project * * 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.android.vending.licensing; /** * Test suite for StrictPolicy. */ public class StrictPolicyTest extends TestCase { /** * Verify that initial response is to deny access. */ public void testInitialResponse() { StrictPolicy p = new StrictPolicy(); boolean result = p.allowAccess(); assertFalse(result); } /** * Verify that after receiving a LICENSED response, the policy grants * access. */ public void testLicensedResonse() { StrictPolicy p = new StrictPolicy();
// Path: library/src/com/google/android/vending/licensing/Policy.java // public interface Policy { // // /** // * Change these values to make it more difficult for tools to automatically // * strip LVL protection from your APK. // */ // // /** // * LICENSED means that the server returned back a valid license response // */ // public static final int LICENSED = 0x0100; // /** // * NOT_LICENSED means that the server returned back a valid license response // * that indicated that the user definitively is not licensed // */ // public static final int NOT_LICENSED = 0x0231; // /** // * RETRY means that the license response was unable to be determined --- // * perhaps as a result of faulty networking // */ // public static final int RETRY = 0x0123; // // /** // * Provide results from contact with the license server. Retry counts are // * incremented if the current value of response is RETRY. Results will be // * used for any future policy decisions. // * // * @param response the result from validating the server response // * @param rawData the raw server response data, can be null for RETRY // */ // void processServerResponse(int response, ResponseData rawData); // // /** // * Check if the user should be allowed access to the application. // */ // boolean allowAccess(); // } // Path: test/src/com/android/vending/licensing/StrictPolicyTest.java import com.google.android.vending.licensing.Policy; import com.google.android.vending.licensing.StrictPolicy; import junit.framework.TestCase; /* * Copyright (C) 2010 The Android Open Source Project * * 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.android.vending.licensing; /** * Test suite for StrictPolicy. */ public class StrictPolicyTest extends TestCase { /** * Verify that initial response is to deny access. */ public void testInitialResponse() { StrictPolicy p = new StrictPolicy(); boolean result = p.allowAccess(); assertFalse(result); } /** * Verify that after receiving a LICENSED response, the policy grants * access. */ public void testLicensedResonse() { StrictPolicy p = new StrictPolicy();
p.processServerResponse(Policy.LICENSED, null);
MaChristmann/mobile-trial
library/src/org/mobiletrial/license/LicenseChecker.java
// Path: library/src/com/google/android/vending/licensing/Policy.java // public interface Policy { // // /** // * Change these values to make it more difficult for tools to automatically // * strip LVL protection from your APK. // */ // // /** // * LICENSED means that the server returned back a valid license response // */ // public static final int LICENSED = 0x0100; // /** // * NOT_LICENSED means that the server returned back a valid license response // * that indicated that the user definitively is not licensed // */ // public static final int NOT_LICENSED = 0x0231; // /** // * RETRY means that the license response was unable to be determined --- // * perhaps as a result of faulty networking // */ // public static final int RETRY = 0x0123; // // /** // * Provide results from contact with the license server. Retry counts are // * incremented if the current value of response is RETRY. Results will be // * used for any future policy decisions. // * // * @param response the result from validating the server response // * @param rawData the raw server response data, can be null for RETRY // */ // void processServerResponse(int response, ResponseData rawData); // // /** // * Check if the user should be allowed access to the application. // */ // boolean allowAccess(); // }
import java.net.URL; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec; import java.util.Date; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.Set; import android.content.Context; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Handler; import android.os.HandlerThread; import android.provider.Settings.Secure; import android.util.Log; import com.google.android.vending.licensing.NullDeviceLimiter; import com.google.android.vending.licensing.Policy; import com.google.android.vending.licensing.util.Base64; import com.google.android.vending.licensing.util.Base64DecoderException;
/* * Copyright (C) 2010 The Android Open Source Project * * 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 org.mobiletrial.license; /** * Client library for Android Market license verifications. * <p> * The LicenseChecker is configured via a {@link Policy} which contains the * logic to determine whether a user should have access to the application. For * example, the Policy can define a threshold for allowable number of server or * client failures before the library reports the user as not having access. * <p> * Must also provide the Base64-encoded RSA public key associated with your * developer account. The public key is obtainable from the publisher site. */ public class LicenseChecker { private static final String TAG = "LicenseChecker"; private static final String KEY_FACTORY_ALGORITHM = "RSA"; // Timeout value (in milliseconds) for calls to service. private static final int TIMEOUT_MS = 100 * 1000; private static final SecureRandom RANDOM = new SecureRandom(); private static final boolean DEBUG_LICENSE_ERROR = false; private ILicensingService mService; private Context mContext; private PublicKey mPublicKey;
// Path: library/src/com/google/android/vending/licensing/Policy.java // public interface Policy { // // /** // * Change these values to make it more difficult for tools to automatically // * strip LVL protection from your APK. // */ // // /** // * LICENSED means that the server returned back a valid license response // */ // public static final int LICENSED = 0x0100; // /** // * NOT_LICENSED means that the server returned back a valid license response // * that indicated that the user definitively is not licensed // */ // public static final int NOT_LICENSED = 0x0231; // /** // * RETRY means that the license response was unable to be determined --- // * perhaps as a result of faulty networking // */ // public static final int RETRY = 0x0123; // // /** // * Provide results from contact with the license server. Retry counts are // * incremented if the current value of response is RETRY. Results will be // * used for any future policy decisions. // * // * @param response the result from validating the server response // * @param rawData the raw server response data, can be null for RETRY // */ // void processServerResponse(int response, ResponseData rawData); // // /** // * Check if the user should be allowed access to the application. // */ // boolean allowAccess(); // } // Path: library/src/org/mobiletrial/license/LicenseChecker.java import java.net.URL; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec; import java.util.Date; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.Set; import android.content.Context; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Handler; import android.os.HandlerThread; import android.provider.Settings.Secure; import android.util.Log; import com.google.android.vending.licensing.NullDeviceLimiter; import com.google.android.vending.licensing.Policy; import com.google.android.vending.licensing.util.Base64; import com.google.android.vending.licensing.util.Base64DecoderException; /* * Copyright (C) 2010 The Android Open Source Project * * 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 org.mobiletrial.license; /** * Client library for Android Market license verifications. * <p> * The LicenseChecker is configured via a {@link Policy} which contains the * logic to determine whether a user should have access to the application. For * example, the Policy can define a threshold for allowable number of server or * client failures before the library reports the user as not having access. * <p> * Must also provide the Base64-encoded RSA public key associated with your * developer account. The public key is obtainable from the publisher site. */ public class LicenseChecker { private static final String TAG = "LicenseChecker"; private static final String KEY_FACTORY_ALGORITHM = "RSA"; // Timeout value (in milliseconds) for calls to service. private static final int TIMEOUT_MS = 100 * 1000; private static final SecureRandom RANDOM = new SecureRandom(); private static final boolean DEBUG_LICENSE_ERROR = false; private ILicensingService mService; private Context mContext; private PublicKey mPublicKey;
private final Policy mPolicy;
MaChristmann/mobile-trial
library/src/org/mobiletrial/license/LicenseValidator.java
// Path: library/src/com/google/android/vending/licensing/Policy.java // public interface Policy { // // /** // * Change these values to make it more difficult for tools to automatically // * strip LVL protection from your APK. // */ // // /** // * LICENSED means that the server returned back a valid license response // */ // public static final int LICENSED = 0x0100; // /** // * NOT_LICENSED means that the server returned back a valid license response // * that indicated that the user definitively is not licensed // */ // public static final int NOT_LICENSED = 0x0231; // /** // * RETRY means that the license response was unable to be determined --- // * perhaps as a result of faulty networking // */ // public static final int RETRY = 0x0123; // // /** // * Provide results from contact with the license server. Retry counts are // * incremented if the current value of response is RETRY. Results will be // * used for any future policy decisions. // * // * @param response the result from validating the server response // * @param rawData the raw server response data, can be null for RETRY // */ // void processServerResponse(int response, ResponseData rawData); // // /** // * Check if the user should be allowed access to the application. // */ // boolean allowAccess(); // }
import com.google.android.vending.licensing.DeviceLimiter; import com.google.android.vending.licensing.Policy; import com.google.android.vending.licensing.ResponseData; import com.google.android.vending.licensing.util.Base64; import com.google.android.vending.licensing.util.Base64DecoderException; import android.text.TextUtils; import android.util.Log; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.Signature; import java.security.SignatureException;
/* * Copyright (C) 2010 The Android Open Source Project * * 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 org.mobiletrial.license; /** * Contains data related to a licensing request and methods to verify * and process the response. */ public class LicenseValidator { private static final String TAG = "LicenseValidator"; // Server response codes. private static final int LICENSED = 0x0; private static final int NOT_LICENSED = 0x1; private static final int LICENSED_OLD_KEY = 0x2; private static final int ERROR_NOT_MARKET_MANAGED = 0x3; private static final int ERROR_SERVER_FAILURE = 0x4; private static final int ERROR_OVER_QUOTA = 0x5; private static final int ERROR_CONTACTING_SERVER = 0x101; private static final int ERROR_INVALID_PACKAGE_NAME = 0x102; private static final int ERROR_NON_MATCHING_UID = 0x103;
// Path: library/src/com/google/android/vending/licensing/Policy.java // public interface Policy { // // /** // * Change these values to make it more difficult for tools to automatically // * strip LVL protection from your APK. // */ // // /** // * LICENSED means that the server returned back a valid license response // */ // public static final int LICENSED = 0x0100; // /** // * NOT_LICENSED means that the server returned back a valid license response // * that indicated that the user definitively is not licensed // */ // public static final int NOT_LICENSED = 0x0231; // /** // * RETRY means that the license response was unable to be determined --- // * perhaps as a result of faulty networking // */ // public static final int RETRY = 0x0123; // // /** // * Provide results from contact with the license server. Retry counts are // * incremented if the current value of response is RETRY. Results will be // * used for any future policy decisions. // * // * @param response the result from validating the server response // * @param rawData the raw server response data, can be null for RETRY // */ // void processServerResponse(int response, ResponseData rawData); // // /** // * Check if the user should be allowed access to the application. // */ // boolean allowAccess(); // } // Path: library/src/org/mobiletrial/license/LicenseValidator.java import com.google.android.vending.licensing.DeviceLimiter; import com.google.android.vending.licensing.Policy; import com.google.android.vending.licensing.ResponseData; import com.google.android.vending.licensing.util.Base64; import com.google.android.vending.licensing.util.Base64DecoderException; import android.text.TextUtils; import android.util.Log; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.Signature; import java.security.SignatureException; /* * Copyright (C) 2010 The Android Open Source Project * * 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 org.mobiletrial.license; /** * Contains data related to a licensing request and methods to verify * and process the response. */ public class LicenseValidator { private static final String TAG = "LicenseValidator"; // Server response codes. private static final int LICENSED = 0x0; private static final int NOT_LICENSED = 0x1; private static final int LICENSED_OLD_KEY = 0x2; private static final int ERROR_NOT_MARKET_MANAGED = 0x3; private static final int ERROR_SERVER_FAILURE = 0x4; private static final int ERROR_OVER_QUOTA = 0x5; private static final int ERROR_CONTACTING_SERVER = 0x101; private static final int ERROR_INVALID_PACKAGE_NAME = 0x102; private static final int ERROR_NON_MATCHING_UID = 0x103;
private final Policy mPolicy;
MaChristmann/mobile-trial
library/src/org/mobiletrial/license/ServerLicensingService.java
// Path: library/src/org/mobiletrial/license/connect/RestClient.java // public class RestClient { // // private static final int ERROR_CONTACTING_SERVER = 0x101; // private static final int ERROR_SERVER_FAILURE = 0x4; // // private String TAG = "RestClient"; // // private URL mServiceUrl; // private Context mContext; // // public RestClient(Context context, URL serviceUrl){ // mContext = context; // mServiceUrl = serviceUrl; // } // // public void post(final String path, final JSONObject requestJson, final OnRequestFinishedListener listener) { // Thread t = new Thread(){ // public void run() { // Looper.prepare(); //For Preparing Message Pool for the child Thread // // // Register Schemes for http and https // final SchemeRegistry schemeRegistry = new SchemeRegistry(); // schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // schemeRegistry.register(new Scheme("https", createAdditionalCertsSSLSocketFactory(), 443)); // // final HttpParams params = new BasicHttpParams(); // final ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params,schemeRegistry); // HttpClient client = new DefaultHttpClient(cm, params); // // HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit // // // HttpResponse response; // try{ // String urlStr = mServiceUrl.toExternalForm(); // if(urlStr.charAt(urlStr.length()-1) != '/') // urlStr += "/"; // urlStr += path; // URI actionURI = new URI(urlStr); // // HttpPost post = new HttpPost(actionURI); // StringEntity se = new StringEntity( requestJson.toString()); // se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); // post.setEntity(se); // response = client.execute(post); // // /* Checking response */ // if(response==null){ // listener.gotError(ERROR_CONTACTING_SERVER); // Log.w(TAG, "Error contacting licensing server."); // return; // } // int statusCode = response.getStatusLine().getStatusCode(); // if (statusCode != HttpStatus.SC_OK) { // Log.w(TAG, "An error has occurred on the licensing server."); // listener.gotError(ERROR_SERVER_FAILURE); // return; // } // // /* Convert response to JSON */ // InputStream in = response.getEntity().getContent(); //Get the data in the entity // String responseStr = inputstreamToString(in); // listener.gotResponse(responseStr); // // } catch(ClientProtocolException e){ // Log.w(TAG, "ClientProtocolExeption: " + e.getLocalizedMessage()); // e.printStackTrace(); // } catch(IOException e){ // Log.w(TAG, "Error on contacting server: " + e.getLocalizedMessage()); // listener.gotError(ERROR_CONTACTING_SERVER); // } catch (URISyntaxException e) { // //This shouldn't happen // Log.w(TAG, "Could not build URI.. Your service Url is propably not a valid Url: " + e.getLocalizedMessage()); // e.printStackTrace(); // } // Looper.loop(); //Loop in the message queue // } // }; // t.start(); // } // // // protected SSLSocketFactory createAdditionalCertsSSLSocketFactory() { // try { // final KeyStore ks = KeyStore.getInstance("BKS"); // // // Load the BKS keystore file // final InputStream in = mContext.getResources().openRawResource( R.raw.mystore); // try { // // Password which you use at creating the keystore // ks.load(in, mContext.getString( R.string.mobiletrial_keystore_passwd ).toCharArray()); // } finally { // in.close(); // } // return new AdditionalKeyStoresSSLSocketFactory(ks); // // } catch( Exception e ) { // //If this error happens, perhaps you are using an incompatible version of bouncycastle // //Tested Versions are: bcprov-jdk16-146.jar (Works with Android 4.1, Android 4.0.3) // Log.w(TAG, "Couldn't load additional keystore: " + e.getLocalizedMessage()); // throw new RuntimeException(); // } // } // // public static abstract class OnRequestFinishedListener{ // public abstract void gotResponse(String response); // public abstract void gotError(int errorCode); // } // // private String inputstreamToString(InputStream in) throws IOException{ // BufferedReader streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8")); // StringBuilder responseStrBuilder = new StringBuilder(); // // String inputStr; // while ((inputStr = streamReader.readLine()) != null) // responseStrBuilder.append(inputStr); // return responseStrBuilder.toString(); // } // }
import java.net.URL; import java.net.URLEncoder; import java.util.Date; import org.json.JSONException; import org.json.JSONObject; import org.mobiletrial.license.connect.RestClient; import android.content.Context; import android.text.TextUtils; import android.util.Log;
package org.mobiletrial.license; public class ServerLicensingService implements ILicensingService { private static final String TAG = "ServerLicensingService"; private static final String PARAM_TIMESTAMP = "ts"; private static final String PARAM_VERSIONCODE = "vc"; private static final String PARAM_NONCE = "n"; private static final int ERROR_SERVER_FAILURE = 0x4; private Context mContext; private URL mWebserviceUrl; public ServerLicensingService(Context context, URL websericeUrl){ this.mContext = context; this.mWebserviceUrl = websericeUrl; } @Override public void checkLicense(int nonce, String packageName, String versionCode, String userId, final ILicenseResultListener listener){
// Path: library/src/org/mobiletrial/license/connect/RestClient.java // public class RestClient { // // private static final int ERROR_CONTACTING_SERVER = 0x101; // private static final int ERROR_SERVER_FAILURE = 0x4; // // private String TAG = "RestClient"; // // private URL mServiceUrl; // private Context mContext; // // public RestClient(Context context, URL serviceUrl){ // mContext = context; // mServiceUrl = serviceUrl; // } // // public void post(final String path, final JSONObject requestJson, final OnRequestFinishedListener listener) { // Thread t = new Thread(){ // public void run() { // Looper.prepare(); //For Preparing Message Pool for the child Thread // // // Register Schemes for http and https // final SchemeRegistry schemeRegistry = new SchemeRegistry(); // schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // schemeRegistry.register(new Scheme("https", createAdditionalCertsSSLSocketFactory(), 443)); // // final HttpParams params = new BasicHttpParams(); // final ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params,schemeRegistry); // HttpClient client = new DefaultHttpClient(cm, params); // // HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit // // // HttpResponse response; // try{ // String urlStr = mServiceUrl.toExternalForm(); // if(urlStr.charAt(urlStr.length()-1) != '/') // urlStr += "/"; // urlStr += path; // URI actionURI = new URI(urlStr); // // HttpPost post = new HttpPost(actionURI); // StringEntity se = new StringEntity( requestJson.toString()); // se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); // post.setEntity(se); // response = client.execute(post); // // /* Checking response */ // if(response==null){ // listener.gotError(ERROR_CONTACTING_SERVER); // Log.w(TAG, "Error contacting licensing server."); // return; // } // int statusCode = response.getStatusLine().getStatusCode(); // if (statusCode != HttpStatus.SC_OK) { // Log.w(TAG, "An error has occurred on the licensing server."); // listener.gotError(ERROR_SERVER_FAILURE); // return; // } // // /* Convert response to JSON */ // InputStream in = response.getEntity().getContent(); //Get the data in the entity // String responseStr = inputstreamToString(in); // listener.gotResponse(responseStr); // // } catch(ClientProtocolException e){ // Log.w(TAG, "ClientProtocolExeption: " + e.getLocalizedMessage()); // e.printStackTrace(); // } catch(IOException e){ // Log.w(TAG, "Error on contacting server: " + e.getLocalizedMessage()); // listener.gotError(ERROR_CONTACTING_SERVER); // } catch (URISyntaxException e) { // //This shouldn't happen // Log.w(TAG, "Could not build URI.. Your service Url is propably not a valid Url: " + e.getLocalizedMessage()); // e.printStackTrace(); // } // Looper.loop(); //Loop in the message queue // } // }; // t.start(); // } // // // protected SSLSocketFactory createAdditionalCertsSSLSocketFactory() { // try { // final KeyStore ks = KeyStore.getInstance("BKS"); // // // Load the BKS keystore file // final InputStream in = mContext.getResources().openRawResource( R.raw.mystore); // try { // // Password which you use at creating the keystore // ks.load(in, mContext.getString( R.string.mobiletrial_keystore_passwd ).toCharArray()); // } finally { // in.close(); // } // return new AdditionalKeyStoresSSLSocketFactory(ks); // // } catch( Exception e ) { // //If this error happens, perhaps you are using an incompatible version of bouncycastle // //Tested Versions are: bcprov-jdk16-146.jar (Works with Android 4.1, Android 4.0.3) // Log.w(TAG, "Couldn't load additional keystore: " + e.getLocalizedMessage()); // throw new RuntimeException(); // } // } // // public static abstract class OnRequestFinishedListener{ // public abstract void gotResponse(String response); // public abstract void gotError(int errorCode); // } // // private String inputstreamToString(InputStream in) throws IOException{ // BufferedReader streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8")); // StringBuilder responseStrBuilder = new StringBuilder(); // // String inputStr; // while ((inputStr = streamReader.readLine()) != null) // responseStrBuilder.append(inputStr); // return responseStrBuilder.toString(); // } // } // Path: library/src/org/mobiletrial/license/ServerLicensingService.java import java.net.URL; import java.net.URLEncoder; import java.util.Date; import org.json.JSONException; import org.json.JSONObject; import org.mobiletrial.license.connect.RestClient; import android.content.Context; import android.text.TextUtils; import android.util.Log; package org.mobiletrial.license; public class ServerLicensingService implements ILicensingService { private static final String TAG = "ServerLicensingService"; private static final String PARAM_TIMESTAMP = "ts"; private static final String PARAM_VERSIONCODE = "vc"; private static final String PARAM_NONCE = "n"; private static final int ERROR_SERVER_FAILURE = 0x4; private Context mContext; private URL mWebserviceUrl; public ServerLicensingService(Context context, URL websericeUrl){ this.mContext = context; this.mWebserviceUrl = websericeUrl; } @Override public void checkLicense(int nonce, String packageName, String versionCode, String userId, final ILicenseResultListener listener){
RestClient client = new RestClient(mContext, mWebserviceUrl);
julman99/futuristic
futuristic-core/src/test/java/io/futuristic/FuturesTest.java
// Path: futuristic-core/src/test/java/io/futuristic/util/DummyExceptions.java // public class DummyExceptions { // // private DummyExceptions(){ // // } // // public static class DummyException1 extends RuntimeException { // // } // // public static class DummyException2 extends RuntimeException { // // } // // }
import io.futuristic.util.DummyExceptions; import org.junit.Test; import java.util.concurrent.Executors; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail;
package io.futuristic; /** * @autor: julio */ public class FuturesTest { @Test public void testWithCallback() throws Exception { Future<Integer> future = Futures.withCallback(c -> c.completed(1)); int result = future.await(); assertEquals(1, result); } @Test public void testWithCallable() throws Exception { Future<Integer> future = Futures.withCallable(() -> 1); int result = future.await(); assertEquals(1, result); } @Test public void testWithCallableAndExecutor() throws Exception { Future<Integer> future = Futures.withCallable(Executors.newCachedThreadPool(), () -> 1); int result = future.await(); assertEquals(1, result); } @Test public void testWithValue() throws Exception { Future<Integer> future = Futures.withValue(1); int result = future.await(); assertEquals(1, result); } @Test public void testWithException() {
// Path: futuristic-core/src/test/java/io/futuristic/util/DummyExceptions.java // public class DummyExceptions { // // private DummyExceptions(){ // // } // // public static class DummyException1 extends RuntimeException { // // } // // public static class DummyException2 extends RuntimeException { // // } // // } // Path: futuristic-core/src/test/java/io/futuristic/FuturesTest.java import io.futuristic.util.DummyExceptions; import org.junit.Test; import java.util.concurrent.Executors; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; package io.futuristic; /** * @autor: julio */ public class FuturesTest { @Test public void testWithCallback() throws Exception { Future<Integer> future = Futures.withCallback(c -> c.completed(1)); int result = future.await(); assertEquals(1, result); } @Test public void testWithCallable() throws Exception { Future<Integer> future = Futures.withCallable(() -> 1); int result = future.await(); assertEquals(1, result); } @Test public void testWithCallableAndExecutor() throws Exception { Future<Integer> future = Futures.withCallable(Executors.newCachedThreadPool(), () -> 1); int result = future.await(); assertEquals(1, result); } @Test public void testWithValue() throws Exception { Future<Integer> future = Futures.withValue(1); int result = future.await(); assertEquals(1, result); } @Test public void testWithException() {
Exception exception = new DummyExceptions.DummyException1();
julman99/futuristic
futuristic-core/src/test/java/io/futuristic/FutureWithTriggerTest.java
// Path: futuristic-core/src/test/java/io/futuristic/util/DummyExceptions.java // public class DummyExceptions { // // private DummyExceptions(){ // // } // // public static class DummyException1 extends RuntimeException { // // } // // public static class DummyException2 extends RuntimeException { // // } // // } // // Path: futuristic-core/src/test/java/io/futuristic/util/Triggerer.java // public class Triggerer { // // public static <T> void triggerValue(T value, FutureWithTrigger<T> futureWithTrigger){ // futureWithTrigger.getTrigger().completed(value); // } // // public static <T> void triggerValueAsync(long delay, T value, FutureWithTrigger<T> futureWithTrigger){ // new Timer().schedule(new TimerTask() { // @Override // public void run() { // futureWithTrigger.getTrigger().completed(value); // } // }, delay); // } // // public static <T> void triggerError(Exception error, FutureWithTrigger<T> futureWithTrigger){ // futureWithTrigger.getTrigger().failed(error); // } // // public static <T> void triggerErrorAsync(long delay, Exception error, FutureWithTrigger<T> futureWithTrigger){ // new Timer().schedule(new TimerTask() { // @Override // public void run() { // futureWithTrigger.getTrigger().failed(error); // } // }, delay); // } // // }
import io.futuristic.util.DummyExceptions; import io.futuristic.util.Triggerer; import org.junit.Test; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import static org.junit.Assert.*;
package io.futuristic; /** * @autor: julio */ public class FutureWithTriggerTest { @Test public void testGetSync() throws Exception { FutureWithTrigger futureWithTrigger = new FutureWithTrigger(); Object test = new Object();
// Path: futuristic-core/src/test/java/io/futuristic/util/DummyExceptions.java // public class DummyExceptions { // // private DummyExceptions(){ // // } // // public static class DummyException1 extends RuntimeException { // // } // // public static class DummyException2 extends RuntimeException { // // } // // } // // Path: futuristic-core/src/test/java/io/futuristic/util/Triggerer.java // public class Triggerer { // // public static <T> void triggerValue(T value, FutureWithTrigger<T> futureWithTrigger){ // futureWithTrigger.getTrigger().completed(value); // } // // public static <T> void triggerValueAsync(long delay, T value, FutureWithTrigger<T> futureWithTrigger){ // new Timer().schedule(new TimerTask() { // @Override // public void run() { // futureWithTrigger.getTrigger().completed(value); // } // }, delay); // } // // public static <T> void triggerError(Exception error, FutureWithTrigger<T> futureWithTrigger){ // futureWithTrigger.getTrigger().failed(error); // } // // public static <T> void triggerErrorAsync(long delay, Exception error, FutureWithTrigger<T> futureWithTrigger){ // new Timer().schedule(new TimerTask() { // @Override // public void run() { // futureWithTrigger.getTrigger().failed(error); // } // }, delay); // } // // } // Path: futuristic-core/src/test/java/io/futuristic/FutureWithTriggerTest.java import io.futuristic.util.DummyExceptions; import io.futuristic.util.Triggerer; import org.junit.Test; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import static org.junit.Assert.*; package io.futuristic; /** * @autor: julio */ public class FutureWithTriggerTest { @Test public void testGetSync() throws Exception { FutureWithTrigger futureWithTrigger = new FutureWithTrigger(); Object test = new Object();
Triggerer.triggerValue(test, futureWithTrigger);
julman99/futuristic
futuristic-core/src/test/java/io/futuristic/FutureWithTriggerTest.java
// Path: futuristic-core/src/test/java/io/futuristic/util/DummyExceptions.java // public class DummyExceptions { // // private DummyExceptions(){ // // } // // public static class DummyException1 extends RuntimeException { // // } // // public static class DummyException2 extends RuntimeException { // // } // // } // // Path: futuristic-core/src/test/java/io/futuristic/util/Triggerer.java // public class Triggerer { // // public static <T> void triggerValue(T value, FutureWithTrigger<T> futureWithTrigger){ // futureWithTrigger.getTrigger().completed(value); // } // // public static <T> void triggerValueAsync(long delay, T value, FutureWithTrigger<T> futureWithTrigger){ // new Timer().schedule(new TimerTask() { // @Override // public void run() { // futureWithTrigger.getTrigger().completed(value); // } // }, delay); // } // // public static <T> void triggerError(Exception error, FutureWithTrigger<T> futureWithTrigger){ // futureWithTrigger.getTrigger().failed(error); // } // // public static <T> void triggerErrorAsync(long delay, Exception error, FutureWithTrigger<T> futureWithTrigger){ // new Timer().schedule(new TimerTask() { // @Override // public void run() { // futureWithTrigger.getTrigger().failed(error); // } // }, delay); // } // // }
import io.futuristic.util.DummyExceptions; import io.futuristic.util.Triggerer; import org.junit.Test; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import static org.junit.Assert.*;
assertEquals(exception, catchedException); } } @Test public void testErrorCatchingFuture() { FutureWithTrigger<Object> futureWithTrigger = new FutureWithTrigger<>(); RuntimeException exception = new RuntimeException(); AtomicReference<RuntimeException> exceptionReference = new AtomicReference<>(); Triggerer.triggerValue(new Object(), futureWithTrigger); try { futureWithTrigger.getFuture().consume(v -> { throw exception; }).trapFuture(RuntimeException.class, e -> { exceptionReference.set(e); throw e; }).await(); fail("Exception should have been thrown"); } catch (Exception catchedException) { assertEquals(exception, exceptionReference.get()); assertEquals(exception, catchedException); } } @Test public void testErrorCatchingRightType() { FutureWithTrigger<Object> futureWithTrigger = new FutureWithTrigger<>();
// Path: futuristic-core/src/test/java/io/futuristic/util/DummyExceptions.java // public class DummyExceptions { // // private DummyExceptions(){ // // } // // public static class DummyException1 extends RuntimeException { // // } // // public static class DummyException2 extends RuntimeException { // // } // // } // // Path: futuristic-core/src/test/java/io/futuristic/util/Triggerer.java // public class Triggerer { // // public static <T> void triggerValue(T value, FutureWithTrigger<T> futureWithTrigger){ // futureWithTrigger.getTrigger().completed(value); // } // // public static <T> void triggerValueAsync(long delay, T value, FutureWithTrigger<T> futureWithTrigger){ // new Timer().schedule(new TimerTask() { // @Override // public void run() { // futureWithTrigger.getTrigger().completed(value); // } // }, delay); // } // // public static <T> void triggerError(Exception error, FutureWithTrigger<T> futureWithTrigger){ // futureWithTrigger.getTrigger().failed(error); // } // // public static <T> void triggerErrorAsync(long delay, Exception error, FutureWithTrigger<T> futureWithTrigger){ // new Timer().schedule(new TimerTask() { // @Override // public void run() { // futureWithTrigger.getTrigger().failed(error); // } // }, delay); // } // // } // Path: futuristic-core/src/test/java/io/futuristic/FutureWithTriggerTest.java import io.futuristic.util.DummyExceptions; import io.futuristic.util.Triggerer; import org.junit.Test; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import static org.junit.Assert.*; assertEquals(exception, catchedException); } } @Test public void testErrorCatchingFuture() { FutureWithTrigger<Object> futureWithTrigger = new FutureWithTrigger<>(); RuntimeException exception = new RuntimeException(); AtomicReference<RuntimeException> exceptionReference = new AtomicReference<>(); Triggerer.triggerValue(new Object(), futureWithTrigger); try { futureWithTrigger.getFuture().consume(v -> { throw exception; }).trapFuture(RuntimeException.class, e -> { exceptionReference.set(e); throw e; }).await(); fail("Exception should have been thrown"); } catch (Exception catchedException) { assertEquals(exception, exceptionReference.get()); assertEquals(exception, catchedException); } } @Test public void testErrorCatchingRightType() { FutureWithTrigger<Object> futureWithTrigger = new FutureWithTrigger<>();
DummyExceptions.DummyException1 exception = new DummyExceptions.DummyException1();
julman99/futuristic
futuristic-http-gson/src/main/java/io/futuristic/JsonHttpClient.java
// Path: futuristic-http/src/main/java/io/futuristic/http/BaseHttpClient.java // public abstract class BaseHttpClient<T> { // // private HttpAsyncEngine engine; // private HttpParams defaultHeaders = new HttpParams(); // // public BaseHttpClient(HttpAsyncEngine engine) { // this.engine = engine; // } // // public void addDefaultHeader(String key, String value) { // defaultHeaders.put(key, value); // } // // // public Future<HttpResponse<T>> request(final HttpRequest.Builder request) { // return this.request(request.build()); // } // // public Future<HttpResponse<T>> request(final HttpRequest request) { // request.getHeaders().putAll(defaultHeaders); // return engine.dispatch(request) // .map(response -> { // if (response.getStatusCode() / 100 != 2) { // String reason = response.getStatusMessage(); // if (response.getBody() != null) { // reason += " - " + new String(ByteStreams.toByteArray(response.getBody())); // } // throw new HttpException(response.getStatusCode(), reason); // } else { // return buildResponse(response); // } // }); // } // // private HttpResponse<T> buildResponse(HttpResponse<InputStream> originalResponse){ // final int statusCode = originalResponse.getStatusCode(); // final String statusMessage = originalResponse.getStatusMessage(); // final T object = responseToObject(originalResponse); // final HttpParams headers = originalResponse.getHeader(); // // return new HttpResponse<T>() { // @Override // public int getStatusCode() { // return statusCode; // } // // @Override // public String getStatusMessage() { // return statusMessage; // } // // @Override // public T getBody() { // return object; // } // // @Override // public HttpParams getHeader() { // return headers; // } // }; // } // // protected abstract T responseToObject(HttpResponse<InputStream> response); // // } // // Path: futuristic-http/src/main/java/io/futuristic/http/HttpAsyncEngine.java // public interface HttpAsyncEngine { // // Future<HttpResponse<InputStream>> dispatch(HttpRequest request); // // void shutdown(); // // } // // Path: futuristic-http/src/main/java/io/futuristic/http/HttpResponse.java // public interface HttpResponse<T> { // // HttpParams getHeader(); // // int getStatusCode(); // // String getStatusMessage(); // // T getBody(); // // }
import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; import io.futuristic.http.BaseHttpClient; import io.futuristic.http.HttpAsyncEngine; import io.futuristic.http.HttpResponse; import java.io.InputStream; import java.io.InputStreamReader;
package io.futuristic; /** * Client to perform http requests that return a json element * @author julio */ public class JsonHttpClient extends BaseHttpClient<JsonElement> { public JsonHttpClient(HttpAsyncEngine client) { super(client); } @Override
// Path: futuristic-http/src/main/java/io/futuristic/http/BaseHttpClient.java // public abstract class BaseHttpClient<T> { // // private HttpAsyncEngine engine; // private HttpParams defaultHeaders = new HttpParams(); // // public BaseHttpClient(HttpAsyncEngine engine) { // this.engine = engine; // } // // public void addDefaultHeader(String key, String value) { // defaultHeaders.put(key, value); // } // // // public Future<HttpResponse<T>> request(final HttpRequest.Builder request) { // return this.request(request.build()); // } // // public Future<HttpResponse<T>> request(final HttpRequest request) { // request.getHeaders().putAll(defaultHeaders); // return engine.dispatch(request) // .map(response -> { // if (response.getStatusCode() / 100 != 2) { // String reason = response.getStatusMessage(); // if (response.getBody() != null) { // reason += " - " + new String(ByteStreams.toByteArray(response.getBody())); // } // throw new HttpException(response.getStatusCode(), reason); // } else { // return buildResponse(response); // } // }); // } // // private HttpResponse<T> buildResponse(HttpResponse<InputStream> originalResponse){ // final int statusCode = originalResponse.getStatusCode(); // final String statusMessage = originalResponse.getStatusMessage(); // final T object = responseToObject(originalResponse); // final HttpParams headers = originalResponse.getHeader(); // // return new HttpResponse<T>() { // @Override // public int getStatusCode() { // return statusCode; // } // // @Override // public String getStatusMessage() { // return statusMessage; // } // // @Override // public T getBody() { // return object; // } // // @Override // public HttpParams getHeader() { // return headers; // } // }; // } // // protected abstract T responseToObject(HttpResponse<InputStream> response); // // } // // Path: futuristic-http/src/main/java/io/futuristic/http/HttpAsyncEngine.java // public interface HttpAsyncEngine { // // Future<HttpResponse<InputStream>> dispatch(HttpRequest request); // // void shutdown(); // // } // // Path: futuristic-http/src/main/java/io/futuristic/http/HttpResponse.java // public interface HttpResponse<T> { // // HttpParams getHeader(); // // int getStatusCode(); // // String getStatusMessage(); // // T getBody(); // // } // Path: futuristic-http-gson/src/main/java/io/futuristic/JsonHttpClient.java import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; import io.futuristic.http.BaseHttpClient; import io.futuristic.http.HttpAsyncEngine; import io.futuristic.http.HttpResponse; import java.io.InputStream; import java.io.InputStreamReader; package io.futuristic; /** * Client to perform http requests that return a json element * @author julio */ public class JsonHttpClient extends BaseHttpClient<JsonElement> { public JsonHttpClient(HttpAsyncEngine client) { super(client); } @Override
protected JsonElement responseToObject(HttpResponse<InputStream> response) {
julman99/futuristic
futuristic-core/src/test/java/io/futuristic/CallbackLinkTest.java
// Path: futuristic-core/src/main/java/io/futuristic/Callback.java // public interface Callback<T> { // // void completed(T result); // void failed(Exception throwable); // // } // // Path: futuristic-core/src/main/java/io/futuristic/CallbackLink.java // public final class CallbackLink<T> { // // private final AtomicBoolean done = new AtomicBoolean(false); // private final AtomicBoolean forwarded = new AtomicBoolean(false); // // private T result = null; // private Exception error = null; // // private Queue<Callback<T>> callbacksTo = new ConcurrentLinkedQueue<>(); // // public CallbackLink() { // } // // public Callback<T> getFrom(){ // return new Callback<T>() { // @Override // public void completed(T result) { // CallbackLink.this.done.set(true); // CallbackLink.this.result = result; // CallbackLink.this.forward(); // } // // @Override // public void failed(Exception exception) { // CallbackLink.this.done.set(true); // CallbackLink.this.error = exception; // CallbackLink.this.forward(); // } // }; // } // // public void addTo(Callback<T> callbackTo){ // this.callbacksTo.add(callbackTo); // forward(); // } // // private void forward(){ // if(done.get()){ // while(true) { // Callback<T> next = callbacksTo.poll(); // if(next == null){ // break; // } else { // if(error == null){ // next.completed(result); // } else { // next.failed(error); // } // } // } // // } // } // }
import io.futuristic.Callback; import io.futuristic.CallbackLink; import org.junit.Test; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
package io.futuristic; /** * @autor: julio */ public class CallbackLinkTest { @Test public void testLinkSuccessFirstTo(){
// Path: futuristic-core/src/main/java/io/futuristic/Callback.java // public interface Callback<T> { // // void completed(T result); // void failed(Exception throwable); // // } // // Path: futuristic-core/src/main/java/io/futuristic/CallbackLink.java // public final class CallbackLink<T> { // // private final AtomicBoolean done = new AtomicBoolean(false); // private final AtomicBoolean forwarded = new AtomicBoolean(false); // // private T result = null; // private Exception error = null; // // private Queue<Callback<T>> callbacksTo = new ConcurrentLinkedQueue<>(); // // public CallbackLink() { // } // // public Callback<T> getFrom(){ // return new Callback<T>() { // @Override // public void completed(T result) { // CallbackLink.this.done.set(true); // CallbackLink.this.result = result; // CallbackLink.this.forward(); // } // // @Override // public void failed(Exception exception) { // CallbackLink.this.done.set(true); // CallbackLink.this.error = exception; // CallbackLink.this.forward(); // } // }; // } // // public void addTo(Callback<T> callbackTo){ // this.callbacksTo.add(callbackTo); // forward(); // } // // private void forward(){ // if(done.get()){ // while(true) { // Callback<T> next = callbacksTo.poll(); // if(next == null){ // break; // } else { // if(error == null){ // next.completed(result); // } else { // next.failed(error); // } // } // } // // } // } // } // Path: futuristic-core/src/test/java/io/futuristic/CallbackLinkTest.java import io.futuristic.Callback; import io.futuristic.CallbackLink; import org.junit.Test; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; package io.futuristic; /** * @autor: julio */ public class CallbackLinkTest { @Test public void testLinkSuccessFirstTo(){
CallbackLink<AtomicBoolean> callbackLink = new CallbackLink<>();
julman99/futuristic
futuristic-core/src/test/java/io/futuristic/CallbackLinkTest.java
// Path: futuristic-core/src/main/java/io/futuristic/Callback.java // public interface Callback<T> { // // void completed(T result); // void failed(Exception throwable); // // } // // Path: futuristic-core/src/main/java/io/futuristic/CallbackLink.java // public final class CallbackLink<T> { // // private final AtomicBoolean done = new AtomicBoolean(false); // private final AtomicBoolean forwarded = new AtomicBoolean(false); // // private T result = null; // private Exception error = null; // // private Queue<Callback<T>> callbacksTo = new ConcurrentLinkedQueue<>(); // // public CallbackLink() { // } // // public Callback<T> getFrom(){ // return new Callback<T>() { // @Override // public void completed(T result) { // CallbackLink.this.done.set(true); // CallbackLink.this.result = result; // CallbackLink.this.forward(); // } // // @Override // public void failed(Exception exception) { // CallbackLink.this.done.set(true); // CallbackLink.this.error = exception; // CallbackLink.this.forward(); // } // }; // } // // public void addTo(Callback<T> callbackTo){ // this.callbacksTo.add(callbackTo); // forward(); // } // // private void forward(){ // if(done.get()){ // while(true) { // Callback<T> next = callbacksTo.poll(); // if(next == null){ // break; // } else { // if(error == null){ // next.completed(result); // } else { // next.failed(error); // } // } // } // // } // } // }
import io.futuristic.Callback; import io.futuristic.CallbackLink; import org.junit.Test; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
package io.futuristic; /** * @autor: julio */ public class CallbackLinkTest { @Test public void testLinkSuccessFirstTo(){ CallbackLink<AtomicBoolean> callbackLink = new CallbackLink<>();
// Path: futuristic-core/src/main/java/io/futuristic/Callback.java // public interface Callback<T> { // // void completed(T result); // void failed(Exception throwable); // // } // // Path: futuristic-core/src/main/java/io/futuristic/CallbackLink.java // public final class CallbackLink<T> { // // private final AtomicBoolean done = new AtomicBoolean(false); // private final AtomicBoolean forwarded = new AtomicBoolean(false); // // private T result = null; // private Exception error = null; // // private Queue<Callback<T>> callbacksTo = new ConcurrentLinkedQueue<>(); // // public CallbackLink() { // } // // public Callback<T> getFrom(){ // return new Callback<T>() { // @Override // public void completed(T result) { // CallbackLink.this.done.set(true); // CallbackLink.this.result = result; // CallbackLink.this.forward(); // } // // @Override // public void failed(Exception exception) { // CallbackLink.this.done.set(true); // CallbackLink.this.error = exception; // CallbackLink.this.forward(); // } // }; // } // // public void addTo(Callback<T> callbackTo){ // this.callbacksTo.add(callbackTo); // forward(); // } // // private void forward(){ // if(done.get()){ // while(true) { // Callback<T> next = callbacksTo.poll(); // if(next == null){ // break; // } else { // if(error == null){ // next.completed(result); // } else { // next.failed(error); // } // } // } // // } // } // } // Path: futuristic-core/src/test/java/io/futuristic/CallbackLinkTest.java import io.futuristic.Callback; import io.futuristic.CallbackLink; import org.junit.Test; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; package io.futuristic; /** * @autor: julio */ public class CallbackLinkTest { @Test public void testLinkSuccessFirstTo(){ CallbackLink<AtomicBoolean> callbackLink = new CallbackLink<>();
callbackLink.addTo(new Callback<AtomicBoolean>() {
julman99/futuristic
futuristic-core/src/main/java/io/futuristic/Future.java
// Path: futuristic-core/src/main/java/io/futuristic/function/ConsumerWithException.java // public interface ConsumerWithException<T> { // // /** // * Performs this operation on the given argument. // * // * @param t the input argument // */ // void accept(T t) throws Exception; // } // // Path: futuristic-core/src/main/java/io/futuristic/function/ExceptionTrapper.java // public interface ExceptionTrapper<E extends Exception, R> { // // R trap(E exception) throws Exception; // // } // // Path: futuristic-core/src/main/java/io/futuristic/function/FunctionWithException.java // public interface FunctionWithException<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument // * @return the function result // */ // R apply(T t) throws Exception; // }
import io.futuristic.function.ConsumerWithException; import io.futuristic.function.ExceptionTrapper; import io.futuristic.function.FunctionWithException;
package io.futuristic; /** * @autor: julio */ public interface Future<T> { /** * Blocks the call until the future value is available. * @return * @throws Exception */ public T await() throws Exception; /** * Called when the future value is available. * @param consumer * @return */
// Path: futuristic-core/src/main/java/io/futuristic/function/ConsumerWithException.java // public interface ConsumerWithException<T> { // // /** // * Performs this operation on the given argument. // * // * @param t the input argument // */ // void accept(T t) throws Exception; // } // // Path: futuristic-core/src/main/java/io/futuristic/function/ExceptionTrapper.java // public interface ExceptionTrapper<E extends Exception, R> { // // R trap(E exception) throws Exception; // // } // // Path: futuristic-core/src/main/java/io/futuristic/function/FunctionWithException.java // public interface FunctionWithException<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument // * @return the function result // */ // R apply(T t) throws Exception; // } // Path: futuristic-core/src/main/java/io/futuristic/Future.java import io.futuristic.function.ConsumerWithException; import io.futuristic.function.ExceptionTrapper; import io.futuristic.function.FunctionWithException; package io.futuristic; /** * @autor: julio */ public interface Future<T> { /** * Blocks the call until the future value is available. * @return * @throws Exception */ public T await() throws Exception; /** * Called when the future value is available. * @param consumer * @return */
public Future<T> consume(ConsumerWithException<T> consumer);
julman99/futuristic
futuristic-core/src/main/java/io/futuristic/Future.java
// Path: futuristic-core/src/main/java/io/futuristic/function/ConsumerWithException.java // public interface ConsumerWithException<T> { // // /** // * Performs this operation on the given argument. // * // * @param t the input argument // */ // void accept(T t) throws Exception; // } // // Path: futuristic-core/src/main/java/io/futuristic/function/ExceptionTrapper.java // public interface ExceptionTrapper<E extends Exception, R> { // // R trap(E exception) throws Exception; // // } // // Path: futuristic-core/src/main/java/io/futuristic/function/FunctionWithException.java // public interface FunctionWithException<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument // * @return the function result // */ // R apply(T t) throws Exception; // }
import io.futuristic.function.ConsumerWithException; import io.futuristic.function.ExceptionTrapper; import io.futuristic.function.FunctionWithException;
package io.futuristic; /** * @autor: julio */ public interface Future<T> { /** * Blocks the call until the future value is available. * @return * @throws Exception */ public T await() throws Exception; /** * Called when the future value is available. * @param consumer * @return */ public Future<T> consume(ConsumerWithException<T> consumer); /** * Called when the future value is available. * @param callback * @return */ default void consume(Callback<T> callback){ this .consume(r -> callback.completed(r)) .trap(Exception.class, e -> { callback.failed(e); throw e; }); } /** * Called when the future value is available. The mapper should map the result of the future to a different * object * @param mapper * @param <R> * @return */
// Path: futuristic-core/src/main/java/io/futuristic/function/ConsumerWithException.java // public interface ConsumerWithException<T> { // // /** // * Performs this operation on the given argument. // * // * @param t the input argument // */ // void accept(T t) throws Exception; // } // // Path: futuristic-core/src/main/java/io/futuristic/function/ExceptionTrapper.java // public interface ExceptionTrapper<E extends Exception, R> { // // R trap(E exception) throws Exception; // // } // // Path: futuristic-core/src/main/java/io/futuristic/function/FunctionWithException.java // public interface FunctionWithException<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument // * @return the function result // */ // R apply(T t) throws Exception; // } // Path: futuristic-core/src/main/java/io/futuristic/Future.java import io.futuristic.function.ConsumerWithException; import io.futuristic.function.ExceptionTrapper; import io.futuristic.function.FunctionWithException; package io.futuristic; /** * @autor: julio */ public interface Future<T> { /** * Blocks the call until the future value is available. * @return * @throws Exception */ public T await() throws Exception; /** * Called when the future value is available. * @param consumer * @return */ public Future<T> consume(ConsumerWithException<T> consumer); /** * Called when the future value is available. * @param callback * @return */ default void consume(Callback<T> callback){ this .consume(r -> callback.completed(r)) .trap(Exception.class, e -> { callback.failed(e); throw e; }); } /** * Called when the future value is available. The mapper should map the result of the future to a different * object * @param mapper * @param <R> * @return */
public <R> Future<R> map(FunctionWithException<T, R> mapper);
julman99/futuristic
futuristic-core/src/main/java/io/futuristic/Future.java
// Path: futuristic-core/src/main/java/io/futuristic/function/ConsumerWithException.java // public interface ConsumerWithException<T> { // // /** // * Performs this operation on the given argument. // * // * @param t the input argument // */ // void accept(T t) throws Exception; // } // // Path: futuristic-core/src/main/java/io/futuristic/function/ExceptionTrapper.java // public interface ExceptionTrapper<E extends Exception, R> { // // R trap(E exception) throws Exception; // // } // // Path: futuristic-core/src/main/java/io/futuristic/function/FunctionWithException.java // public interface FunctionWithException<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument // * @return the function result // */ // R apply(T t) throws Exception; // }
import io.futuristic.function.ConsumerWithException; import io.futuristic.function.ExceptionTrapper; import io.futuristic.function.FunctionWithException;
package io.futuristic; /** * @autor: julio */ public interface Future<T> { /** * Blocks the call until the future value is available. * @return * @throws Exception */ public T await() throws Exception; /** * Called when the future value is available. * @param consumer * @return */ public Future<T> consume(ConsumerWithException<T> consumer); /** * Called when the future value is available. * @param callback * @return */ default void consume(Callback<T> callback){ this .consume(r -> callback.completed(r)) .trap(Exception.class, e -> { callback.failed(e); throw e; }); } /** * Called when the future value is available. The mapper should map the result of the future to a different * object * @param mapper * @param <R> * @return */ public <R> Future<R> map(FunctionWithException<T, R> mapper); /** * Called when the future value is available. The mapper should map the result of the future to a different * {@link Future} object. * object * @param mapper * @param <R> * @return */ public <R> Future<R> mapFuture(FunctionWithException<T, Future<R>> mapper); /** * Called when there is an {@link java.lang.Exception}. The trapper will only be called if the Exception of * the type specified as the first parameter of the class. The trapper should return a value to recover from the * {@link java.lang.Exception} or should rethrow the exception * @param exceptionClass The class of the Exception to trap * @param trapper * @param <E> * @return */
// Path: futuristic-core/src/main/java/io/futuristic/function/ConsumerWithException.java // public interface ConsumerWithException<T> { // // /** // * Performs this operation on the given argument. // * // * @param t the input argument // */ // void accept(T t) throws Exception; // } // // Path: futuristic-core/src/main/java/io/futuristic/function/ExceptionTrapper.java // public interface ExceptionTrapper<E extends Exception, R> { // // R trap(E exception) throws Exception; // // } // // Path: futuristic-core/src/main/java/io/futuristic/function/FunctionWithException.java // public interface FunctionWithException<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument // * @return the function result // */ // R apply(T t) throws Exception; // } // Path: futuristic-core/src/main/java/io/futuristic/Future.java import io.futuristic.function.ConsumerWithException; import io.futuristic.function.ExceptionTrapper; import io.futuristic.function.FunctionWithException; package io.futuristic; /** * @autor: julio */ public interface Future<T> { /** * Blocks the call until the future value is available. * @return * @throws Exception */ public T await() throws Exception; /** * Called when the future value is available. * @param consumer * @return */ public Future<T> consume(ConsumerWithException<T> consumer); /** * Called when the future value is available. * @param callback * @return */ default void consume(Callback<T> callback){ this .consume(r -> callback.completed(r)) .trap(Exception.class, e -> { callback.failed(e); throw e; }); } /** * Called when the future value is available. The mapper should map the result of the future to a different * object * @param mapper * @param <R> * @return */ public <R> Future<R> map(FunctionWithException<T, R> mapper); /** * Called when the future value is available. The mapper should map the result of the future to a different * {@link Future} object. * object * @param mapper * @param <R> * @return */ public <R> Future<R> mapFuture(FunctionWithException<T, Future<R>> mapper); /** * Called when there is an {@link java.lang.Exception}. The trapper will only be called if the Exception of * the type specified as the first parameter of the class. The trapper should return a value to recover from the * {@link java.lang.Exception} or should rethrow the exception * @param exceptionClass The class of the Exception to trap * @param trapper * @param <E> * @return */
public <E extends Exception> Future<T> trap(Class<E> exceptionClass, ExceptionTrapper<E, T> trapper);
julman99/futuristic
futuristic-http/src/main/java/io/futuristic/http/HttpUrlEncodedBody.java
// Path: futuristic-http/src/main/java/io/futuristic/http/util/GenericBuilder.java // public interface GenericBuilder<T> { // // public T build(); // // }
import io.futuristic.http.util.GenericBuilder; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.UnsupportedEncodingException;
package io.futuristic.http; /** * @autor: julio */ public final class HttpUrlEncodedBody extends HttpParams implements HttpBody { private HttpUrlEncodedBody(){ } private HttpUrlEncodedBody(HttpParams params){ this.putAll(params); } @Override public int getContentLength() { return this.toUrlEncodedString().length(); } @Override public String getContentType() { return "application/x-www-form-urlencoded"; } @Override public InputStream toInputStream() { try { return new ByteArrayInputStream(this.toUrlEncodedString().getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { //nothing because UTF-8 is hardcoded } return null; }
// Path: futuristic-http/src/main/java/io/futuristic/http/util/GenericBuilder.java // public interface GenericBuilder<T> { // // public T build(); // // } // Path: futuristic-http/src/main/java/io/futuristic/http/HttpUrlEncodedBody.java import io.futuristic.http.util.GenericBuilder; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.UnsupportedEncodingException; package io.futuristic.http; /** * @autor: julio */ public final class HttpUrlEncodedBody extends HttpParams implements HttpBody { private HttpUrlEncodedBody(){ } private HttpUrlEncodedBody(HttpParams params){ this.putAll(params); } @Override public int getContentLength() { return this.toUrlEncodedString().length(); } @Override public String getContentType() { return "application/x-www-form-urlencoded"; } @Override public InputStream toInputStream() { try { return new ByteArrayInputStream(this.toUrlEncodedString().getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { //nothing because UTF-8 is hardcoded } return null; }
public final static class Builder implements GenericBuilder<HttpUrlEncodedBody> {
julman99/futuristic
futuristic-http/src/test/java/io/futuristic/http/HttpParamsTest.java
// Path: futuristic-http/src/main/java/io/futuristic/http/HttpParams.java // public class HttpParams implements Multimap<String, String> { // // private static final Comparator<String> KEY_COMPARATOR = new StringCaseInsensitiveComparator(); // private static final Comparator<String> VALUES_COMPARATOR = Comparator.naturalOrder(); // // private Multimap<String, String> params = TreeMultimap.create(KEY_COMPARATOR, VALUES_COMPARATOR); // // public HttpParams(){ // // } // // @Override // public int size() { // return params.size(); // } // // @Override // public boolean isEmpty() { // return params.isEmpty(); // } // // @Override // public boolean containsKey(Object key) { // return params.containsKey(key); // } // // @Override // public boolean containsValue(Object value) { // return params.containsValue(value); // } // // @Override // public boolean containsEntry(Object key, Object value) { // return params.containsEntry(key, value); // } // // @Override // public boolean put(String key, String value) { // return params.put(key, value); // } // // public boolean put(String key, Object value) { // return params.put(key, value.toString()); // } // // @Override // public boolean remove(Object key, Object value) { // return params.remove(key, value); // } // // @Override // public boolean putAll(String key, Iterable<? extends String> values) { // return params.putAll(key, values); // } // // @Override // public boolean putAll(Multimap<? extends String, ? extends String> multimap) { // if(multimap != null){ // return params.putAll(multimap); // } else { // return false; // } // // } // // public boolean putAll(Map<String, String> values){ // boolean modified = false; // for(Map.Entry<String, String> entry: values.entrySet()){ // modified |= this.put(entry.getKey(), entry.getValue()); // } // return modified; // } // // @Override // public Collection<String> replaceValues(String key, Iterable<? extends String> values) { // return params.replaceValues(key, values); // } // // @Override // public Collection<String> removeAll(Object key) { // return params.removeAll(key); // } // // @Override // public void clear() { // params.clear(); // } // // @Override // public Collection<String> get(String key) { // return params.get(key); // } // // public String getFirst(String key){ // Collection<String> res = get(key); // if(res.isEmpty()){ // return null; // } else { // return res.iterator().next(); // } // } // // @Override // public Set<String> keySet() { // return params.keySet(); // } // // @Override // public Multiset<String> keys() { // return params.keys(); // } // // @Override // public Collection<String> values() { // return params.values(); // } // // @Override // public Collection<Map.Entry<String, String>> entries() { // return params.entries(); // } // // @Override // public Map<String, Collection<String>> asMap() { // return params.asMap(); // } // // public String toUrlEncodedString(){ // StringBuilder builder = new StringBuilder(); // // int i = 0; // for(Map.Entry<String, String> entry: this.entries()){ // String encodedValue = null; // try { // if(i > 0){ // builder.append("&"); // } // encodedValue = URLEncoder.encode(entry.getValue(), "UTF-8"); // builder.append(entry.getKey()); // builder.append("="); // builder.append(encodedValue); // i++; // } catch (UnsupportedEncodingException e) { // //nothing because UTF-8 is hardcoded // } // } // // return builder.toString(); // } // }
import io.futuristic.http.HttpParams; import org.junit.Test; import java.util.ArrayList; import java.util.HashSet; import java.util.Map; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
package io.futuristic.http; /** * @autor: julio */ public class HttpParamsTest { @Test public void testInsensitive(){
// Path: futuristic-http/src/main/java/io/futuristic/http/HttpParams.java // public class HttpParams implements Multimap<String, String> { // // private static final Comparator<String> KEY_COMPARATOR = new StringCaseInsensitiveComparator(); // private static final Comparator<String> VALUES_COMPARATOR = Comparator.naturalOrder(); // // private Multimap<String, String> params = TreeMultimap.create(KEY_COMPARATOR, VALUES_COMPARATOR); // // public HttpParams(){ // // } // // @Override // public int size() { // return params.size(); // } // // @Override // public boolean isEmpty() { // return params.isEmpty(); // } // // @Override // public boolean containsKey(Object key) { // return params.containsKey(key); // } // // @Override // public boolean containsValue(Object value) { // return params.containsValue(value); // } // // @Override // public boolean containsEntry(Object key, Object value) { // return params.containsEntry(key, value); // } // // @Override // public boolean put(String key, String value) { // return params.put(key, value); // } // // public boolean put(String key, Object value) { // return params.put(key, value.toString()); // } // // @Override // public boolean remove(Object key, Object value) { // return params.remove(key, value); // } // // @Override // public boolean putAll(String key, Iterable<? extends String> values) { // return params.putAll(key, values); // } // // @Override // public boolean putAll(Multimap<? extends String, ? extends String> multimap) { // if(multimap != null){ // return params.putAll(multimap); // } else { // return false; // } // // } // // public boolean putAll(Map<String, String> values){ // boolean modified = false; // for(Map.Entry<String, String> entry: values.entrySet()){ // modified |= this.put(entry.getKey(), entry.getValue()); // } // return modified; // } // // @Override // public Collection<String> replaceValues(String key, Iterable<? extends String> values) { // return params.replaceValues(key, values); // } // // @Override // public Collection<String> removeAll(Object key) { // return params.removeAll(key); // } // // @Override // public void clear() { // params.clear(); // } // // @Override // public Collection<String> get(String key) { // return params.get(key); // } // // public String getFirst(String key){ // Collection<String> res = get(key); // if(res.isEmpty()){ // return null; // } else { // return res.iterator().next(); // } // } // // @Override // public Set<String> keySet() { // return params.keySet(); // } // // @Override // public Multiset<String> keys() { // return params.keys(); // } // // @Override // public Collection<String> values() { // return params.values(); // } // // @Override // public Collection<Map.Entry<String, String>> entries() { // return params.entries(); // } // // @Override // public Map<String, Collection<String>> asMap() { // return params.asMap(); // } // // public String toUrlEncodedString(){ // StringBuilder builder = new StringBuilder(); // // int i = 0; // for(Map.Entry<String, String> entry: this.entries()){ // String encodedValue = null; // try { // if(i > 0){ // builder.append("&"); // } // encodedValue = URLEncoder.encode(entry.getValue(), "UTF-8"); // builder.append(entry.getKey()); // builder.append("="); // builder.append(encodedValue); // i++; // } catch (UnsupportedEncodingException e) { // //nothing because UTF-8 is hardcoded // } // } // // return builder.toString(); // } // } // Path: futuristic-http/src/test/java/io/futuristic/http/HttpParamsTest.java import io.futuristic.http.HttpParams; import org.junit.Test; import java.util.ArrayList; import java.util.HashSet; import java.util.Map; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; package io.futuristic.http; /** * @autor: julio */ public class HttpParamsTest { @Test public void testInsensitive(){
HttpParams p = new HttpParams();
julman99/futuristic
futuristic-core/src/main/java/io/futuristic/FutureWithValue.java
// Path: futuristic-core/src/main/java/io/futuristic/function/ConsumerWithException.java // public interface ConsumerWithException<T> { // // /** // * Performs this operation on the given argument. // * // * @param t the input argument // */ // void accept(T t) throws Exception; // } // // Path: futuristic-core/src/main/java/io/futuristic/function/ExceptionTrapper.java // public interface ExceptionTrapper<E extends Exception, R> { // // R trap(E exception) throws Exception; // // } // // Path: futuristic-core/src/main/java/io/futuristic/function/FunctionWithException.java // public interface FunctionWithException<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument // * @return the function result // */ // R apply(T t) throws Exception; // }
import io.futuristic.function.ConsumerWithException; import io.futuristic.function.ExceptionTrapper; import io.futuristic.function.FunctionWithException;
package io.futuristic; /** * @autor: julio */ final class FutureWithValue<T> implements Future<T> { private final T value; FutureWithValue(T value) { this.value = value; } @Override public T await() throws Exception { return value; } @Override
// Path: futuristic-core/src/main/java/io/futuristic/function/ConsumerWithException.java // public interface ConsumerWithException<T> { // // /** // * Performs this operation on the given argument. // * // * @param t the input argument // */ // void accept(T t) throws Exception; // } // // Path: futuristic-core/src/main/java/io/futuristic/function/ExceptionTrapper.java // public interface ExceptionTrapper<E extends Exception, R> { // // R trap(E exception) throws Exception; // // } // // Path: futuristic-core/src/main/java/io/futuristic/function/FunctionWithException.java // public interface FunctionWithException<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument // * @return the function result // */ // R apply(T t) throws Exception; // } // Path: futuristic-core/src/main/java/io/futuristic/FutureWithValue.java import io.futuristic.function.ConsumerWithException; import io.futuristic.function.ExceptionTrapper; import io.futuristic.function.FunctionWithException; package io.futuristic; /** * @autor: julio */ final class FutureWithValue<T> implements Future<T> { private final T value; FutureWithValue(T value) { this.value = value; } @Override public T await() throws Exception { return value; } @Override
public Future<T> consume(ConsumerWithException<T> consumer) {
julman99/futuristic
futuristic-core/src/main/java/io/futuristic/FutureWithValue.java
// Path: futuristic-core/src/main/java/io/futuristic/function/ConsumerWithException.java // public interface ConsumerWithException<T> { // // /** // * Performs this operation on the given argument. // * // * @param t the input argument // */ // void accept(T t) throws Exception; // } // // Path: futuristic-core/src/main/java/io/futuristic/function/ExceptionTrapper.java // public interface ExceptionTrapper<E extends Exception, R> { // // R trap(E exception) throws Exception; // // } // // Path: futuristic-core/src/main/java/io/futuristic/function/FunctionWithException.java // public interface FunctionWithException<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument // * @return the function result // */ // R apply(T t) throws Exception; // }
import io.futuristic.function.ConsumerWithException; import io.futuristic.function.ExceptionTrapper; import io.futuristic.function.FunctionWithException;
package io.futuristic; /** * @autor: julio */ final class FutureWithValue<T> implements Future<T> { private final T value; FutureWithValue(T value) { this.value = value; } @Override public T await() throws Exception { return value; } @Override public Future<T> consume(ConsumerWithException<T> consumer) { try { consumer.accept(value); return this; } catch (Exception ex) { return new FutureWithException<>(ex); } } @Override
// Path: futuristic-core/src/main/java/io/futuristic/function/ConsumerWithException.java // public interface ConsumerWithException<T> { // // /** // * Performs this operation on the given argument. // * // * @param t the input argument // */ // void accept(T t) throws Exception; // } // // Path: futuristic-core/src/main/java/io/futuristic/function/ExceptionTrapper.java // public interface ExceptionTrapper<E extends Exception, R> { // // R trap(E exception) throws Exception; // // } // // Path: futuristic-core/src/main/java/io/futuristic/function/FunctionWithException.java // public interface FunctionWithException<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument // * @return the function result // */ // R apply(T t) throws Exception; // } // Path: futuristic-core/src/main/java/io/futuristic/FutureWithValue.java import io.futuristic.function.ConsumerWithException; import io.futuristic.function.ExceptionTrapper; import io.futuristic.function.FunctionWithException; package io.futuristic; /** * @autor: julio */ final class FutureWithValue<T> implements Future<T> { private final T value; FutureWithValue(T value) { this.value = value; } @Override public T await() throws Exception { return value; } @Override public Future<T> consume(ConsumerWithException<T> consumer) { try { consumer.accept(value); return this; } catch (Exception ex) { return new FutureWithException<>(ex); } } @Override
public <R> Future<R> map(FunctionWithException<T, R> mapper) {
julman99/futuristic
futuristic-core/src/main/java/io/futuristic/FutureWithValue.java
// Path: futuristic-core/src/main/java/io/futuristic/function/ConsumerWithException.java // public interface ConsumerWithException<T> { // // /** // * Performs this operation on the given argument. // * // * @param t the input argument // */ // void accept(T t) throws Exception; // } // // Path: futuristic-core/src/main/java/io/futuristic/function/ExceptionTrapper.java // public interface ExceptionTrapper<E extends Exception, R> { // // R trap(E exception) throws Exception; // // } // // Path: futuristic-core/src/main/java/io/futuristic/function/FunctionWithException.java // public interface FunctionWithException<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument // * @return the function result // */ // R apply(T t) throws Exception; // }
import io.futuristic.function.ConsumerWithException; import io.futuristic.function.ExceptionTrapper; import io.futuristic.function.FunctionWithException;
public Future<T> consume(ConsumerWithException<T> consumer) { try { consumer.accept(value); return this; } catch (Exception ex) { return new FutureWithException<>(ex); } } @Override public <R> Future<R> map(FunctionWithException<T, R> mapper) { try { R mapped = mapper.apply(value); return new FutureWithValue<>(mapped); } catch (Exception ex) { return new FutureWithException<>(ex); } } @Override public <R> Future<R> mapFuture(FunctionWithException<T, Future<R>> mapper) { try { Future<R> mapped = mapper.apply(value); return mapped; } catch (Exception ex) { return new FutureWithException<>(ex); } } @Override
// Path: futuristic-core/src/main/java/io/futuristic/function/ConsumerWithException.java // public interface ConsumerWithException<T> { // // /** // * Performs this operation on the given argument. // * // * @param t the input argument // */ // void accept(T t) throws Exception; // } // // Path: futuristic-core/src/main/java/io/futuristic/function/ExceptionTrapper.java // public interface ExceptionTrapper<E extends Exception, R> { // // R trap(E exception) throws Exception; // // } // // Path: futuristic-core/src/main/java/io/futuristic/function/FunctionWithException.java // public interface FunctionWithException<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument // * @return the function result // */ // R apply(T t) throws Exception; // } // Path: futuristic-core/src/main/java/io/futuristic/FutureWithValue.java import io.futuristic.function.ConsumerWithException; import io.futuristic.function.ExceptionTrapper; import io.futuristic.function.FunctionWithException; public Future<T> consume(ConsumerWithException<T> consumer) { try { consumer.accept(value); return this; } catch (Exception ex) { return new FutureWithException<>(ex); } } @Override public <R> Future<R> map(FunctionWithException<T, R> mapper) { try { R mapped = mapper.apply(value); return new FutureWithValue<>(mapped); } catch (Exception ex) { return new FutureWithException<>(ex); } } @Override public <R> Future<R> mapFuture(FunctionWithException<T, Future<R>> mapper) { try { Future<R> mapped = mapper.apply(value); return mapped; } catch (Exception ex) { return new FutureWithException<>(ex); } } @Override
public <E extends Exception> Future<T> trap(Class<E> exceptionClass, ExceptionTrapper<E, T> trapper) {
julman99/futuristic
futuristic-core/src/main/java/io/futuristic/FutureWithTrigger.java
// Path: futuristic-core/src/main/java/io/futuristic/function/ConsumerWithException.java // public interface ConsumerWithException<T> { // // /** // * Performs this operation on the given argument. // * // * @param t the input argument // */ // void accept(T t) throws Exception; // } // // Path: futuristic-core/src/main/java/io/futuristic/function/ExceptionTrapper.java // public interface ExceptionTrapper<E extends Exception, R> { // // R trap(E exception) throws Exception; // // } // // Path: futuristic-core/src/main/java/io/futuristic/function/FunctionWithException.java // public interface FunctionWithException<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument // * @return the function result // */ // R apply(T t) throws Exception; // }
import io.futuristic.function.ConsumerWithException; import io.futuristic.function.ExceptionTrapper; import io.futuristic.function.FunctionWithException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicReference;
private Future<T> createFuture(){ return new Future<T>() { @Override public T await() throws Exception{ final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<T> resultReference = new AtomicReference<>(); final AtomicReference<Exception> errorReference = new AtomicReference<>(); FutureWithTrigger.this.callbackLink.addTo(new Callback<T>() { @Override public void completed(T result) { resultReference.set(result); latch.countDown(); } @Override public void failed(Exception throwable) { errorReference.set(throwable); latch.countDown(); } }); latch.await(); if(errorReference.get() == null){ return resultReference.get(); } else { throw errorReference.get(); } } @Override
// Path: futuristic-core/src/main/java/io/futuristic/function/ConsumerWithException.java // public interface ConsumerWithException<T> { // // /** // * Performs this operation on the given argument. // * // * @param t the input argument // */ // void accept(T t) throws Exception; // } // // Path: futuristic-core/src/main/java/io/futuristic/function/ExceptionTrapper.java // public interface ExceptionTrapper<E extends Exception, R> { // // R trap(E exception) throws Exception; // // } // // Path: futuristic-core/src/main/java/io/futuristic/function/FunctionWithException.java // public interface FunctionWithException<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument // * @return the function result // */ // R apply(T t) throws Exception; // } // Path: futuristic-core/src/main/java/io/futuristic/FutureWithTrigger.java import io.futuristic.function.ConsumerWithException; import io.futuristic.function.ExceptionTrapper; import io.futuristic.function.FunctionWithException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicReference; private Future<T> createFuture(){ return new Future<T>() { @Override public T await() throws Exception{ final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<T> resultReference = new AtomicReference<>(); final AtomicReference<Exception> errorReference = new AtomicReference<>(); FutureWithTrigger.this.callbackLink.addTo(new Callback<T>() { @Override public void completed(T result) { resultReference.set(result); latch.countDown(); } @Override public void failed(Exception throwable) { errorReference.set(throwable); latch.countDown(); } }); latch.await(); if(errorReference.get() == null){ return resultReference.get(); } else { throw errorReference.get(); } } @Override
public Future<T> consume(ConsumerWithException<T> consumer) {
julman99/futuristic
futuristic-core/src/main/java/io/futuristic/FutureWithTrigger.java
// Path: futuristic-core/src/main/java/io/futuristic/function/ConsumerWithException.java // public interface ConsumerWithException<T> { // // /** // * Performs this operation on the given argument. // * // * @param t the input argument // */ // void accept(T t) throws Exception; // } // // Path: futuristic-core/src/main/java/io/futuristic/function/ExceptionTrapper.java // public interface ExceptionTrapper<E extends Exception, R> { // // R trap(E exception) throws Exception; // // } // // Path: futuristic-core/src/main/java/io/futuristic/function/FunctionWithException.java // public interface FunctionWithException<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument // * @return the function result // */ // R apply(T t) throws Exception; // }
import io.futuristic.function.ConsumerWithException; import io.futuristic.function.ExceptionTrapper; import io.futuristic.function.FunctionWithException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicReference;
return resultReference.get(); } else { throw errorReference.get(); } } @Override public Future<T> consume(ConsumerWithException<T> consumer) { FutureWithTrigger<T> nextFuture = new FutureWithTrigger<>(); FutureWithTrigger.this.callbackLink.addTo(new Callback<T>() { @Override public void completed(T result) { try { consumer.accept(result); } catch (Exception e) { this.failed(e); return; } nextFuture.getTrigger().completed(result); } @Override public void failed(Exception throwable) { nextFuture.getTrigger().failed(throwable); } }); return nextFuture.getFuture(); } @Override
// Path: futuristic-core/src/main/java/io/futuristic/function/ConsumerWithException.java // public interface ConsumerWithException<T> { // // /** // * Performs this operation on the given argument. // * // * @param t the input argument // */ // void accept(T t) throws Exception; // } // // Path: futuristic-core/src/main/java/io/futuristic/function/ExceptionTrapper.java // public interface ExceptionTrapper<E extends Exception, R> { // // R trap(E exception) throws Exception; // // } // // Path: futuristic-core/src/main/java/io/futuristic/function/FunctionWithException.java // public interface FunctionWithException<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument // * @return the function result // */ // R apply(T t) throws Exception; // } // Path: futuristic-core/src/main/java/io/futuristic/FutureWithTrigger.java import io.futuristic.function.ConsumerWithException; import io.futuristic.function.ExceptionTrapper; import io.futuristic.function.FunctionWithException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicReference; return resultReference.get(); } else { throw errorReference.get(); } } @Override public Future<T> consume(ConsumerWithException<T> consumer) { FutureWithTrigger<T> nextFuture = new FutureWithTrigger<>(); FutureWithTrigger.this.callbackLink.addTo(new Callback<T>() { @Override public void completed(T result) { try { consumer.accept(result); } catch (Exception e) { this.failed(e); return; } nextFuture.getTrigger().completed(result); } @Override public void failed(Exception throwable) { nextFuture.getTrigger().failed(throwable); } }); return nextFuture.getFuture(); } @Override
public <R> Future<R> map(FunctionWithException<T, R> mapper) {
julman99/futuristic
futuristic-core/src/main/java/io/futuristic/FutureWithTrigger.java
// Path: futuristic-core/src/main/java/io/futuristic/function/ConsumerWithException.java // public interface ConsumerWithException<T> { // // /** // * Performs this operation on the given argument. // * // * @param t the input argument // */ // void accept(T t) throws Exception; // } // // Path: futuristic-core/src/main/java/io/futuristic/function/ExceptionTrapper.java // public interface ExceptionTrapper<E extends Exception, R> { // // R trap(E exception) throws Exception; // // } // // Path: futuristic-core/src/main/java/io/futuristic/function/FunctionWithException.java // public interface FunctionWithException<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument // * @return the function result // */ // R apply(T t) throws Exception; // }
import io.futuristic.function.ConsumerWithException; import io.futuristic.function.ExceptionTrapper; import io.futuristic.function.FunctionWithException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicReference;
} @Override public <R> Future<R> map(FunctionWithException<T, R> mapper) { return mapFuture(t -> new FutureWithValue<R>(mapper.apply(t))); } @Override public <R> Future<R> mapFuture(FunctionWithException<T, Future<R>> mapper) { FutureWithTrigger<R> nextFuture = new FutureWithTrigger<>(); FutureWithTrigger.this.callbackLink.addTo(new Callback<T>() { @Override public void completed(T result) { try { Future<R> mapped = mapper.apply(result); mapped.consume(nextFuture.getTrigger()); } catch (Exception ex) { failed(ex); } } @Override public void failed(Exception throwable) { nextFuture.getTrigger().failed(throwable); } }); return nextFuture.getFuture(); } @Override
// Path: futuristic-core/src/main/java/io/futuristic/function/ConsumerWithException.java // public interface ConsumerWithException<T> { // // /** // * Performs this operation on the given argument. // * // * @param t the input argument // */ // void accept(T t) throws Exception; // } // // Path: futuristic-core/src/main/java/io/futuristic/function/ExceptionTrapper.java // public interface ExceptionTrapper<E extends Exception, R> { // // R trap(E exception) throws Exception; // // } // // Path: futuristic-core/src/main/java/io/futuristic/function/FunctionWithException.java // public interface FunctionWithException<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument // * @return the function result // */ // R apply(T t) throws Exception; // } // Path: futuristic-core/src/main/java/io/futuristic/FutureWithTrigger.java import io.futuristic.function.ConsumerWithException; import io.futuristic.function.ExceptionTrapper; import io.futuristic.function.FunctionWithException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicReference; } @Override public <R> Future<R> map(FunctionWithException<T, R> mapper) { return mapFuture(t -> new FutureWithValue<R>(mapper.apply(t))); } @Override public <R> Future<R> mapFuture(FunctionWithException<T, Future<R>> mapper) { FutureWithTrigger<R> nextFuture = new FutureWithTrigger<>(); FutureWithTrigger.this.callbackLink.addTo(new Callback<T>() { @Override public void completed(T result) { try { Future<R> mapped = mapper.apply(result); mapped.consume(nextFuture.getTrigger()); } catch (Exception ex) { failed(ex); } } @Override public void failed(Exception throwable) { nextFuture.getTrigger().failed(throwable); } }); return nextFuture.getFuture(); } @Override
public <E extends Exception> Future<T> trap(Class<E> exceptionClass, ExceptionTrapper<E, T> trapper) {
julman99/futuristic
futuristic-http/src/main/java/io/futuristic/http/HttpRequest.java
// Path: futuristic-http/src/main/java/io/futuristic/http/util/GenericBuilder.java // public interface GenericBuilder<T> { // // public T build(); // // }
import io.futuristic.http.util.GenericBuilder;
package io.futuristic.http; /** * @autor: julio */ public interface HttpRequest { static final String HEADER_CONTENT_TYPE = "Content-Type"; static final String HEADER_CONTENT_LENGTH = "Content-Length"; String getUrl(); HttpParams getHeaders(); HttpBody getBody(); HttpVerb getVerb(); boolean followRedirects();
// Path: futuristic-http/src/main/java/io/futuristic/http/util/GenericBuilder.java // public interface GenericBuilder<T> { // // public T build(); // // } // Path: futuristic-http/src/main/java/io/futuristic/http/HttpRequest.java import io.futuristic.http.util.GenericBuilder; package io.futuristic.http; /** * @autor: julio */ public interface HttpRequest { static final String HEADER_CONTENT_TYPE = "Content-Type"; static final String HEADER_CONTENT_LENGTH = "Content-Length"; String getUrl(); HttpParams getHeaders(); HttpBody getBody(); HttpVerb getVerb(); boolean followRedirects();
static final class Builder<T> implements GenericBuilder<HttpRequest> {
julman99/futuristic
futuristic-http/src/main/java/io/futuristic/http/BaseHttpClient.java
// Path: futuristic-core/src/main/java/io/futuristic/Future.java // public interface Future<T> { // // /** // * Blocks the call until the future value is available. // * @return // * @throws Exception // */ // public T await() throws Exception; // // /** // * Called when the future value is available. // * @param consumer // * @return // */ // public Future<T> consume(ConsumerWithException<T> consumer); // // /** // * Called when the future value is available. // * @param callback // * @return // */ // default void consume(Callback<T> callback){ // this // .consume(r -> callback.completed(r)) // .trap(Exception.class, e -> { // callback.failed(e); // throw e; // }); // } // // /** // * Called when the future value is available. The mapper should map the result of the future to a different // * object // * @param mapper // * @param <R> // * @return // */ // public <R> Future<R> map(FunctionWithException<T, R> mapper); // // /** // * Called when the future value is available. The mapper should map the result of the future to a different // * {@link Future} object. // * object // * @param mapper // * @param <R> // * @return // */ // public <R> Future<R> mapFuture(FunctionWithException<T, Future<R>> mapper); // // /** // * Called when there is an {@link java.lang.Exception}. The trapper will only be called if the Exception of // * the type specified as the first parameter of the class. The trapper should return a value to recover from the // * {@link java.lang.Exception} or should rethrow the exception // * @param exceptionClass The class of the Exception to trap // * @param trapper // * @param <E> // * @return // */ // public <E extends Exception> Future<T> trap(Class<E> exceptionClass, ExceptionTrapper<E, T> trapper); // // /** // * Called when there is an {@link java.lang.Exception}. The trapper will only be called if the Exception of // * the type specified as the first parameter of the class. The trapper should return a future value to recover from // * the {@link java.lang.Exception} or should rethrow the exception // * @param exceptionClass The class of the Exception to trap // * @param trapper // * @param <E> // * @return // */ // public <E extends Exception> Future<T> trapFuture(Class<E> exceptionClass, ExceptionTrapper<E, Future<T>> trapper); // }
import io.futuristic.Future; import com.google.common.io.ByteStreams; import java.io.InputStream;
package io.futuristic.http; /** * @autor: julio */ public abstract class BaseHttpClient<T> { private HttpAsyncEngine engine; private HttpParams defaultHeaders = new HttpParams(); public BaseHttpClient(HttpAsyncEngine engine) { this.engine = engine; } public void addDefaultHeader(String key, String value) { defaultHeaders.put(key, value); }
// Path: futuristic-core/src/main/java/io/futuristic/Future.java // public interface Future<T> { // // /** // * Blocks the call until the future value is available. // * @return // * @throws Exception // */ // public T await() throws Exception; // // /** // * Called when the future value is available. // * @param consumer // * @return // */ // public Future<T> consume(ConsumerWithException<T> consumer); // // /** // * Called when the future value is available. // * @param callback // * @return // */ // default void consume(Callback<T> callback){ // this // .consume(r -> callback.completed(r)) // .trap(Exception.class, e -> { // callback.failed(e); // throw e; // }); // } // // /** // * Called when the future value is available. The mapper should map the result of the future to a different // * object // * @param mapper // * @param <R> // * @return // */ // public <R> Future<R> map(FunctionWithException<T, R> mapper); // // /** // * Called when the future value is available. The mapper should map the result of the future to a different // * {@link Future} object. // * object // * @param mapper // * @param <R> // * @return // */ // public <R> Future<R> mapFuture(FunctionWithException<T, Future<R>> mapper); // // /** // * Called when there is an {@link java.lang.Exception}. The trapper will only be called if the Exception of // * the type specified as the first parameter of the class. The trapper should return a value to recover from the // * {@link java.lang.Exception} or should rethrow the exception // * @param exceptionClass The class of the Exception to trap // * @param trapper // * @param <E> // * @return // */ // public <E extends Exception> Future<T> trap(Class<E> exceptionClass, ExceptionTrapper<E, T> trapper); // // /** // * Called when there is an {@link java.lang.Exception}. The trapper will only be called if the Exception of // * the type specified as the first parameter of the class. The trapper should return a future value to recover from // * the {@link java.lang.Exception} or should rethrow the exception // * @param exceptionClass The class of the Exception to trap // * @param trapper // * @param <E> // * @return // */ // public <E extends Exception> Future<T> trapFuture(Class<E> exceptionClass, ExceptionTrapper<E, Future<T>> trapper); // } // Path: futuristic-http/src/main/java/io/futuristic/http/BaseHttpClient.java import io.futuristic.Future; import com.google.common.io.ByteStreams; import java.io.InputStream; package io.futuristic.http; /** * @autor: julio */ public abstract class BaseHttpClient<T> { private HttpAsyncEngine engine; private HttpParams defaultHeaders = new HttpParams(); public BaseHttpClient(HttpAsyncEngine engine) { this.engine = engine; } public void addDefaultHeader(String key, String value) { defaultHeaders.put(key, value); }
public Future<HttpResponse<T>> request(final HttpRequest.Builder request) {
julman99/futuristic
futuristic-core/src/main/java/io/futuristic/FutureWithException.java
// Path: futuristic-core/src/main/java/io/futuristic/function/ConsumerWithException.java // public interface ConsumerWithException<T> { // // /** // * Performs this operation on the given argument. // * // * @param t the input argument // */ // void accept(T t) throws Exception; // } // // Path: futuristic-core/src/main/java/io/futuristic/function/ExceptionTrapper.java // public interface ExceptionTrapper<E extends Exception, R> { // // R trap(E exception) throws Exception; // // } // // Path: futuristic-core/src/main/java/io/futuristic/function/FunctionWithException.java // public interface FunctionWithException<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument // * @return the function result // */ // R apply(T t) throws Exception; // }
import io.futuristic.function.ConsumerWithException; import io.futuristic.function.ExceptionTrapper; import io.futuristic.function.FunctionWithException;
package io.futuristic; /** * @autor: julio */ final class FutureWithException<T> implements Future<T> { private final Exception exception; FutureWithException(Exception exception) { this.exception = exception; } @Override public T await() throws Exception { throw exception; } @Override
// Path: futuristic-core/src/main/java/io/futuristic/function/ConsumerWithException.java // public interface ConsumerWithException<T> { // // /** // * Performs this operation on the given argument. // * // * @param t the input argument // */ // void accept(T t) throws Exception; // } // // Path: futuristic-core/src/main/java/io/futuristic/function/ExceptionTrapper.java // public interface ExceptionTrapper<E extends Exception, R> { // // R trap(E exception) throws Exception; // // } // // Path: futuristic-core/src/main/java/io/futuristic/function/FunctionWithException.java // public interface FunctionWithException<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument // * @return the function result // */ // R apply(T t) throws Exception; // } // Path: futuristic-core/src/main/java/io/futuristic/FutureWithException.java import io.futuristic.function.ConsumerWithException; import io.futuristic.function.ExceptionTrapper; import io.futuristic.function.FunctionWithException; package io.futuristic; /** * @autor: julio */ final class FutureWithException<T> implements Future<T> { private final Exception exception; FutureWithException(Exception exception) { this.exception = exception; } @Override public T await() throws Exception { throw exception; } @Override
public Future<T> consume(ConsumerWithException<T> consumer) {
julman99/futuristic
futuristic-core/src/main/java/io/futuristic/FutureWithException.java
// Path: futuristic-core/src/main/java/io/futuristic/function/ConsumerWithException.java // public interface ConsumerWithException<T> { // // /** // * Performs this operation on the given argument. // * // * @param t the input argument // */ // void accept(T t) throws Exception; // } // // Path: futuristic-core/src/main/java/io/futuristic/function/ExceptionTrapper.java // public interface ExceptionTrapper<E extends Exception, R> { // // R trap(E exception) throws Exception; // // } // // Path: futuristic-core/src/main/java/io/futuristic/function/FunctionWithException.java // public interface FunctionWithException<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument // * @return the function result // */ // R apply(T t) throws Exception; // }
import io.futuristic.function.ConsumerWithException; import io.futuristic.function.ExceptionTrapper; import io.futuristic.function.FunctionWithException;
package io.futuristic; /** * @autor: julio */ final class FutureWithException<T> implements Future<T> { private final Exception exception; FutureWithException(Exception exception) { this.exception = exception; } @Override public T await() throws Exception { throw exception; } @Override public Future<T> consume(ConsumerWithException<T> consumer) { return this; } @Override
// Path: futuristic-core/src/main/java/io/futuristic/function/ConsumerWithException.java // public interface ConsumerWithException<T> { // // /** // * Performs this operation on the given argument. // * // * @param t the input argument // */ // void accept(T t) throws Exception; // } // // Path: futuristic-core/src/main/java/io/futuristic/function/ExceptionTrapper.java // public interface ExceptionTrapper<E extends Exception, R> { // // R trap(E exception) throws Exception; // // } // // Path: futuristic-core/src/main/java/io/futuristic/function/FunctionWithException.java // public interface FunctionWithException<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument // * @return the function result // */ // R apply(T t) throws Exception; // } // Path: futuristic-core/src/main/java/io/futuristic/FutureWithException.java import io.futuristic.function.ConsumerWithException; import io.futuristic.function.ExceptionTrapper; import io.futuristic.function.FunctionWithException; package io.futuristic; /** * @autor: julio */ final class FutureWithException<T> implements Future<T> { private final Exception exception; FutureWithException(Exception exception) { this.exception = exception; } @Override public T await() throws Exception { throw exception; } @Override public Future<T> consume(ConsumerWithException<T> consumer) { return this; } @Override
public <R> Future<R> map(FunctionWithException<T, R> mapper) {
julman99/futuristic
futuristic-core/src/main/java/io/futuristic/FutureWithException.java
// Path: futuristic-core/src/main/java/io/futuristic/function/ConsumerWithException.java // public interface ConsumerWithException<T> { // // /** // * Performs this operation on the given argument. // * // * @param t the input argument // */ // void accept(T t) throws Exception; // } // // Path: futuristic-core/src/main/java/io/futuristic/function/ExceptionTrapper.java // public interface ExceptionTrapper<E extends Exception, R> { // // R trap(E exception) throws Exception; // // } // // Path: futuristic-core/src/main/java/io/futuristic/function/FunctionWithException.java // public interface FunctionWithException<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument // * @return the function result // */ // R apply(T t) throws Exception; // }
import io.futuristic.function.ConsumerWithException; import io.futuristic.function.ExceptionTrapper; import io.futuristic.function.FunctionWithException;
package io.futuristic; /** * @autor: julio */ final class FutureWithException<T> implements Future<T> { private final Exception exception; FutureWithException(Exception exception) { this.exception = exception; } @Override public T await() throws Exception { throw exception; } @Override public Future<T> consume(ConsumerWithException<T> consumer) { return this; } @Override public <R> Future<R> map(FunctionWithException<T, R> mapper) { return (Future<R>) this; } @Override public <R> Future<R> mapFuture(FunctionWithException<T, Future<R>> mapper) { return (Future<R>) this; } @Override
// Path: futuristic-core/src/main/java/io/futuristic/function/ConsumerWithException.java // public interface ConsumerWithException<T> { // // /** // * Performs this operation on the given argument. // * // * @param t the input argument // */ // void accept(T t) throws Exception; // } // // Path: futuristic-core/src/main/java/io/futuristic/function/ExceptionTrapper.java // public interface ExceptionTrapper<E extends Exception, R> { // // R trap(E exception) throws Exception; // // } // // Path: futuristic-core/src/main/java/io/futuristic/function/FunctionWithException.java // public interface FunctionWithException<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument // * @return the function result // */ // R apply(T t) throws Exception; // } // Path: futuristic-core/src/main/java/io/futuristic/FutureWithException.java import io.futuristic.function.ConsumerWithException; import io.futuristic.function.ExceptionTrapper; import io.futuristic.function.FunctionWithException; package io.futuristic; /** * @autor: julio */ final class FutureWithException<T> implements Future<T> { private final Exception exception; FutureWithException(Exception exception) { this.exception = exception; } @Override public T await() throws Exception { throw exception; } @Override public Future<T> consume(ConsumerWithException<T> consumer) { return this; } @Override public <R> Future<R> map(FunctionWithException<T, R> mapper) { return (Future<R>) this; } @Override public <R> Future<R> mapFuture(FunctionWithException<T, Future<R>> mapper) { return (Future<R>) this; } @Override
public <E extends Exception> Future<T> trap(Class<E> exceptionClass, ExceptionTrapper<E, T> trapper) {
yDelouis/selfoss-android
app/src/main/java/fr/ydelouis/selfoss/config/model/ConfigManager.java
// Path: app/src/main/java/fr/ydelouis/selfoss/model/DatabaseHelper.java // public class DatabaseHelper extends OrmLiteSqliteOpenHelper { // // public static final String ACTION_TABLES_CLEARED = "fr.ydelouis.selfoss.ACTION_TABLES_CLEARED"; // // private static final String DATABASE_NAME = "selfoss.db"; // private static final int DATABASE_VERSION = 5; // // private Context context; // // public DatabaseHelper(Context context) { // super(context, DATABASE_NAME, null, DATABASE_VERSION); // this.context = context; // } // // @Override // public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) { // try { // TableUtils.createTable(connectionSource, Tag.class); // TableUtils.createTable(connectionSource, Source.class); // TableUtils.createTable(connectionSource, Article.class); // TableUtils.createTable(connectionSource, ArticleSyncAction.class); // } catch (SQLException e) { // e.printStackTrace(); // } // } // // @Override // public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int oldVersion, int newVersion) { // try { // if (oldVersion < 2) { // TableUtils.dropTable(connectionSource, Article.class, true); // TableUtils.createTable(connectionSource, Article.class); // } // if (oldVersion < 3) { // TableUtils.createTable(connectionSource, Source.class); // } // if (oldVersion < 4) { // TableUtils.dropTable(connectionSource, Article.class, true); // TableUtils.createTable(connectionSource, Article.class); // } // if (oldVersion < 5) { // TableUtils.dropTable(connectionSource, Article.class, true); // TableUtils.createTable(connectionSource, Article.class); // } // } catch (SQLException e) { // e.printStackTrace(); // } // } // // public void clearTables() { // try { // TableUtils.clearTable(getConnectionSource(), Tag.class); // TableUtils.clearTable(getConnectionSource(), Source.class); // TableUtils.clearTable(getConnectionSource(), Article.class); // TableUtils.clearTable(getConnectionSource(), ArticleSyncAction.class); // context.sendBroadcast(new Intent(ACTION_TABLES_CLEARED)); // } catch (SQLException e) { // e.printStackTrace(); // } // } // } // // Path: app/src/main/java/fr/ydelouis/selfoss/sync/SyncManager.java // @EBean // public class SyncManager { // // private static final String AUTHORITY = BuildConfig.AUTHORITY; // // public static void setPeriodicSync(ConfigManager configManager, Config config) { // Account account = configManager.getAccountForConfig(config); // if (account != null) { // ContentResolver.setSyncAutomatically(account, AUTHORITY, config.getSyncPeriod() > 0); // ContentResolver.addPeriodicSync(account, AUTHORITY, new Bundle(), config.getSyncPeriod()); // } // } // // @Bean protected ConfigManager configManager; // // public void requestSync() { // Account account = configManager.getAccount(); // if (account != null) { // Bundle extras = new Bundle(); // extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); // extras.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true); // ContentResolver.requestSync(account, AUTHORITY, extras); // } // } // // public boolean isActive() { // Account account = configManager.getAccount(); // if (account != null) { // return ContentResolver.isSyncActive(account, AUTHORITY); // } else { // return false; // } // } // // }
import android.accounts.Account; import android.accounts.AccountManager; import android.content.Context; import org.androidannotations.annotations.AfterInject; import org.androidannotations.annotations.EBean; import org.androidannotations.annotations.RootContext; import org.androidannotations.annotations.SystemService; import fr.ydelouis.selfoss.BuildConfig; import fr.ydelouis.selfoss.model.DatabaseHelper; import fr.ydelouis.selfoss.sync.SyncManager;
package fr.ydelouis.selfoss.config.model; @EBean public class ConfigManager { public static final String ACCOUNT_TYPE = BuildConfig.ACCOUNT_TYPE; private static final String KEY_USERNAME = "username"; private static final String KEY_SYNC_PERIOD = "syncPeriod"; private static final String KEY_TRUST_ALL_CERTIFICATES = "trustAllCertificates"; private static final String KEY_USE_HTTPS = "useHttps"; private static final String KEY_SYNC_OVER_WIFI_ONLY = "syncOverWifiOnly"; @SystemService protected AccountManager accountManager; @RootContext protected Context context;
// Path: app/src/main/java/fr/ydelouis/selfoss/model/DatabaseHelper.java // public class DatabaseHelper extends OrmLiteSqliteOpenHelper { // // public static final String ACTION_TABLES_CLEARED = "fr.ydelouis.selfoss.ACTION_TABLES_CLEARED"; // // private static final String DATABASE_NAME = "selfoss.db"; // private static final int DATABASE_VERSION = 5; // // private Context context; // // public DatabaseHelper(Context context) { // super(context, DATABASE_NAME, null, DATABASE_VERSION); // this.context = context; // } // // @Override // public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) { // try { // TableUtils.createTable(connectionSource, Tag.class); // TableUtils.createTable(connectionSource, Source.class); // TableUtils.createTable(connectionSource, Article.class); // TableUtils.createTable(connectionSource, ArticleSyncAction.class); // } catch (SQLException e) { // e.printStackTrace(); // } // } // // @Override // public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int oldVersion, int newVersion) { // try { // if (oldVersion < 2) { // TableUtils.dropTable(connectionSource, Article.class, true); // TableUtils.createTable(connectionSource, Article.class); // } // if (oldVersion < 3) { // TableUtils.createTable(connectionSource, Source.class); // } // if (oldVersion < 4) { // TableUtils.dropTable(connectionSource, Article.class, true); // TableUtils.createTable(connectionSource, Article.class); // } // if (oldVersion < 5) { // TableUtils.dropTable(connectionSource, Article.class, true); // TableUtils.createTable(connectionSource, Article.class); // } // } catch (SQLException e) { // e.printStackTrace(); // } // } // // public void clearTables() { // try { // TableUtils.clearTable(getConnectionSource(), Tag.class); // TableUtils.clearTable(getConnectionSource(), Source.class); // TableUtils.clearTable(getConnectionSource(), Article.class); // TableUtils.clearTable(getConnectionSource(), ArticleSyncAction.class); // context.sendBroadcast(new Intent(ACTION_TABLES_CLEARED)); // } catch (SQLException e) { // e.printStackTrace(); // } // } // } // // Path: app/src/main/java/fr/ydelouis/selfoss/sync/SyncManager.java // @EBean // public class SyncManager { // // private static final String AUTHORITY = BuildConfig.AUTHORITY; // // public static void setPeriodicSync(ConfigManager configManager, Config config) { // Account account = configManager.getAccountForConfig(config); // if (account != null) { // ContentResolver.setSyncAutomatically(account, AUTHORITY, config.getSyncPeriod() > 0); // ContentResolver.addPeriodicSync(account, AUTHORITY, new Bundle(), config.getSyncPeriod()); // } // } // // @Bean protected ConfigManager configManager; // // public void requestSync() { // Account account = configManager.getAccount(); // if (account != null) { // Bundle extras = new Bundle(); // extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); // extras.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true); // ContentResolver.requestSync(account, AUTHORITY, extras); // } // } // // public boolean isActive() { // Account account = configManager.getAccount(); // if (account != null) { // return ContentResolver.isSyncActive(account, AUTHORITY); // } else { // return false; // } // } // // } // Path: app/src/main/java/fr/ydelouis/selfoss/config/model/ConfigManager.java import android.accounts.Account; import android.accounts.AccountManager; import android.content.Context; import org.androidannotations.annotations.AfterInject; import org.androidannotations.annotations.EBean; import org.androidannotations.annotations.RootContext; import org.androidannotations.annotations.SystemService; import fr.ydelouis.selfoss.BuildConfig; import fr.ydelouis.selfoss.model.DatabaseHelper; import fr.ydelouis.selfoss.sync.SyncManager; package fr.ydelouis.selfoss.config.model; @EBean public class ConfigManager { public static final String ACCOUNT_TYPE = BuildConfig.ACCOUNT_TYPE; private static final String KEY_USERNAME = "username"; private static final String KEY_SYNC_PERIOD = "syncPeriod"; private static final String KEY_TRUST_ALL_CERTIFICATES = "trustAllCertificates"; private static final String KEY_USE_HTTPS = "useHttps"; private static final String KEY_SYNC_OVER_WIFI_ONLY = "syncOverWifiOnly"; @SystemService protected AccountManager accountManager; @RootContext protected Context context;
private DatabaseHelper databaseHelper;
yDelouis/selfoss-android
app/src/main/java/fr/ydelouis/selfoss/config/model/ConfigManager.java
// Path: app/src/main/java/fr/ydelouis/selfoss/model/DatabaseHelper.java // public class DatabaseHelper extends OrmLiteSqliteOpenHelper { // // public static final String ACTION_TABLES_CLEARED = "fr.ydelouis.selfoss.ACTION_TABLES_CLEARED"; // // private static final String DATABASE_NAME = "selfoss.db"; // private static final int DATABASE_VERSION = 5; // // private Context context; // // public DatabaseHelper(Context context) { // super(context, DATABASE_NAME, null, DATABASE_VERSION); // this.context = context; // } // // @Override // public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) { // try { // TableUtils.createTable(connectionSource, Tag.class); // TableUtils.createTable(connectionSource, Source.class); // TableUtils.createTable(connectionSource, Article.class); // TableUtils.createTable(connectionSource, ArticleSyncAction.class); // } catch (SQLException e) { // e.printStackTrace(); // } // } // // @Override // public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int oldVersion, int newVersion) { // try { // if (oldVersion < 2) { // TableUtils.dropTable(connectionSource, Article.class, true); // TableUtils.createTable(connectionSource, Article.class); // } // if (oldVersion < 3) { // TableUtils.createTable(connectionSource, Source.class); // } // if (oldVersion < 4) { // TableUtils.dropTable(connectionSource, Article.class, true); // TableUtils.createTable(connectionSource, Article.class); // } // if (oldVersion < 5) { // TableUtils.dropTable(connectionSource, Article.class, true); // TableUtils.createTable(connectionSource, Article.class); // } // } catch (SQLException e) { // e.printStackTrace(); // } // } // // public void clearTables() { // try { // TableUtils.clearTable(getConnectionSource(), Tag.class); // TableUtils.clearTable(getConnectionSource(), Source.class); // TableUtils.clearTable(getConnectionSource(), Article.class); // TableUtils.clearTable(getConnectionSource(), ArticleSyncAction.class); // context.sendBroadcast(new Intent(ACTION_TABLES_CLEARED)); // } catch (SQLException e) { // e.printStackTrace(); // } // } // } // // Path: app/src/main/java/fr/ydelouis/selfoss/sync/SyncManager.java // @EBean // public class SyncManager { // // private static final String AUTHORITY = BuildConfig.AUTHORITY; // // public static void setPeriodicSync(ConfigManager configManager, Config config) { // Account account = configManager.getAccountForConfig(config); // if (account != null) { // ContentResolver.setSyncAutomatically(account, AUTHORITY, config.getSyncPeriod() > 0); // ContentResolver.addPeriodicSync(account, AUTHORITY, new Bundle(), config.getSyncPeriod()); // } // } // // @Bean protected ConfigManager configManager; // // public void requestSync() { // Account account = configManager.getAccount(); // if (account != null) { // Bundle extras = new Bundle(); // extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); // extras.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true); // ContentResolver.requestSync(account, AUTHORITY, extras); // } // } // // public boolean isActive() { // Account account = configManager.getAccount(); // if (account != null) { // return ContentResolver.isSyncActive(account, AUTHORITY); // } else { // return false; // } // } // // }
import android.accounts.Account; import android.accounts.AccountManager; import android.content.Context; import org.androidannotations.annotations.AfterInject; import org.androidannotations.annotations.EBean; import org.androidannotations.annotations.RootContext; import org.androidannotations.annotations.SystemService; import fr.ydelouis.selfoss.BuildConfig; import fr.ydelouis.selfoss.model.DatabaseHelper; import fr.ydelouis.selfoss.sync.SyncManager;
private static final String KEY_SYNC_PERIOD = "syncPeriod"; private static final String KEY_TRUST_ALL_CERTIFICATES = "trustAllCertificates"; private static final String KEY_USE_HTTPS = "useHttps"; private static final String KEY_SYNC_OVER_WIFI_ONLY = "syncOverWifiOnly"; @SystemService protected AccountManager accountManager; @RootContext protected Context context; private DatabaseHelper databaseHelper; @AfterInject protected void init() { databaseHelper = new DatabaseHelper(context); } public void save(Config config) { Account account = getAccount(); if (account != null && !account.name.equals(config.getUrl())) { remove(account); account = null; } if (account == null) { account = new Account(config.getUrl(), ACCOUNT_TYPE); accountManager.addAccountExplicitly(account, config.getPassword(), null); } accountManager.setUserData(account, KEY_USERNAME, config.getUsername()); accountManager.setUserData(account, KEY_USE_HTTPS, String.valueOf(config.useHttps())); accountManager.setUserData(account, KEY_TRUST_ALL_CERTIFICATES, String.valueOf(config.trustAllCertificates())); accountManager.setUserData(account, KEY_SYNC_PERIOD, String.valueOf(config.getSyncPeriod())); accountManager.setUserData(account, KEY_SYNC_OVER_WIFI_ONLY, String.valueOf(config.syncOverWifiOnly()));
// Path: app/src/main/java/fr/ydelouis/selfoss/model/DatabaseHelper.java // public class DatabaseHelper extends OrmLiteSqliteOpenHelper { // // public static final String ACTION_TABLES_CLEARED = "fr.ydelouis.selfoss.ACTION_TABLES_CLEARED"; // // private static final String DATABASE_NAME = "selfoss.db"; // private static final int DATABASE_VERSION = 5; // // private Context context; // // public DatabaseHelper(Context context) { // super(context, DATABASE_NAME, null, DATABASE_VERSION); // this.context = context; // } // // @Override // public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) { // try { // TableUtils.createTable(connectionSource, Tag.class); // TableUtils.createTable(connectionSource, Source.class); // TableUtils.createTable(connectionSource, Article.class); // TableUtils.createTable(connectionSource, ArticleSyncAction.class); // } catch (SQLException e) { // e.printStackTrace(); // } // } // // @Override // public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int oldVersion, int newVersion) { // try { // if (oldVersion < 2) { // TableUtils.dropTable(connectionSource, Article.class, true); // TableUtils.createTable(connectionSource, Article.class); // } // if (oldVersion < 3) { // TableUtils.createTable(connectionSource, Source.class); // } // if (oldVersion < 4) { // TableUtils.dropTable(connectionSource, Article.class, true); // TableUtils.createTable(connectionSource, Article.class); // } // if (oldVersion < 5) { // TableUtils.dropTable(connectionSource, Article.class, true); // TableUtils.createTable(connectionSource, Article.class); // } // } catch (SQLException e) { // e.printStackTrace(); // } // } // // public void clearTables() { // try { // TableUtils.clearTable(getConnectionSource(), Tag.class); // TableUtils.clearTable(getConnectionSource(), Source.class); // TableUtils.clearTable(getConnectionSource(), Article.class); // TableUtils.clearTable(getConnectionSource(), ArticleSyncAction.class); // context.sendBroadcast(new Intent(ACTION_TABLES_CLEARED)); // } catch (SQLException e) { // e.printStackTrace(); // } // } // } // // Path: app/src/main/java/fr/ydelouis/selfoss/sync/SyncManager.java // @EBean // public class SyncManager { // // private static final String AUTHORITY = BuildConfig.AUTHORITY; // // public static void setPeriodicSync(ConfigManager configManager, Config config) { // Account account = configManager.getAccountForConfig(config); // if (account != null) { // ContentResolver.setSyncAutomatically(account, AUTHORITY, config.getSyncPeriod() > 0); // ContentResolver.addPeriodicSync(account, AUTHORITY, new Bundle(), config.getSyncPeriod()); // } // } // // @Bean protected ConfigManager configManager; // // public void requestSync() { // Account account = configManager.getAccount(); // if (account != null) { // Bundle extras = new Bundle(); // extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); // extras.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true); // ContentResolver.requestSync(account, AUTHORITY, extras); // } // } // // public boolean isActive() { // Account account = configManager.getAccount(); // if (account != null) { // return ContentResolver.isSyncActive(account, AUTHORITY); // } else { // return false; // } // } // // } // Path: app/src/main/java/fr/ydelouis/selfoss/config/model/ConfigManager.java import android.accounts.Account; import android.accounts.AccountManager; import android.content.Context; import org.androidannotations.annotations.AfterInject; import org.androidannotations.annotations.EBean; import org.androidannotations.annotations.RootContext; import org.androidannotations.annotations.SystemService; import fr.ydelouis.selfoss.BuildConfig; import fr.ydelouis.selfoss.model.DatabaseHelper; import fr.ydelouis.selfoss.sync.SyncManager; private static final String KEY_SYNC_PERIOD = "syncPeriod"; private static final String KEY_TRUST_ALL_CERTIFICATES = "trustAllCertificates"; private static final String KEY_USE_HTTPS = "useHttps"; private static final String KEY_SYNC_OVER_WIFI_ONLY = "syncOverWifiOnly"; @SystemService protected AccountManager accountManager; @RootContext protected Context context; private DatabaseHelper databaseHelper; @AfterInject protected void init() { databaseHelper = new DatabaseHelper(context); } public void save(Config config) { Account account = getAccount(); if (account != null && !account.name.equals(config.getUrl())) { remove(account); account = null; } if (account == null) { account = new Account(config.getUrl(), ACCOUNT_TYPE); accountManager.addAccountExplicitly(account, config.getPassword(), null); } accountManager.setUserData(account, KEY_USERNAME, config.getUsername()); accountManager.setUserData(account, KEY_USE_HTTPS, String.valueOf(config.useHttps())); accountManager.setUserData(account, KEY_TRUST_ALL_CERTIFICATES, String.valueOf(config.trustAllCertificates())); accountManager.setUserData(account, KEY_SYNC_PERIOD, String.valueOf(config.getSyncPeriod())); accountManager.setUserData(account, KEY_SYNC_OVER_WIFI_ONLY, String.valueOf(config.syncOverWifiOnly()));
SyncManager.setPeriodicSync(this, config);
yDelouis/selfoss-android
app/src/main/java/fr/ydelouis/selfoss/sync/SyncManager.java
// Path: app/src/main/java/fr/ydelouis/selfoss/config/model/Config.java // public class Config { // // private String url; // private boolean trustAllCertificates; // private boolean useHttps; // private String username; // private String password; // private long syncPeriod; // private boolean syncOverWifiOnly; // // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public boolean trustAllCertificates() { // return trustAllCertificates; // } // // public void setTrustAllCertificates(boolean trustAllCertificates) { // this.trustAllCertificates = trustAllCertificates; // } // // public boolean useHttps() { // return useHttps; // } // // public void setUseHttps(boolean useHttps) { // this.useHttps = useHttps; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public long getSyncPeriod() { // return syncPeriod; // } // // public void setSyncPeriod(long syncPeriod) { // this.syncPeriod = syncPeriod; // } // // public boolean requireAuth() { // return username != null; // } // // public boolean syncOverWifiOnly() { // return syncOverWifiOnly; // } // // public void setSyncOverWifiOnly(boolean syncOverWifiOnly) { // this.syncOverWifiOnly = syncOverWifiOnly; // } // } // // Path: app/src/main/java/fr/ydelouis/selfoss/config/model/ConfigManager.java // @EBean // public class ConfigManager { // // public static final String ACCOUNT_TYPE = BuildConfig.ACCOUNT_TYPE; // // private static final String KEY_USERNAME = "username"; // private static final String KEY_SYNC_PERIOD = "syncPeriod"; // private static final String KEY_TRUST_ALL_CERTIFICATES = "trustAllCertificates"; // private static final String KEY_USE_HTTPS = "useHttps"; // private static final String KEY_SYNC_OVER_WIFI_ONLY = "syncOverWifiOnly"; // // @SystemService protected AccountManager accountManager; // @RootContext protected Context context; // private DatabaseHelper databaseHelper; // // @AfterInject // protected void init() { // databaseHelper = new DatabaseHelper(context); // } // // public void save(Config config) { // Account account = getAccount(); // if (account != null && !account.name.equals(config.getUrl())) { // remove(account); // account = null; // } // if (account == null) { // account = new Account(config.getUrl(), ACCOUNT_TYPE); // accountManager.addAccountExplicitly(account, config.getPassword(), null); // } // accountManager.setUserData(account, KEY_USERNAME, config.getUsername()); // accountManager.setUserData(account, KEY_USE_HTTPS, String.valueOf(config.useHttps())); // accountManager.setUserData(account, KEY_TRUST_ALL_CERTIFICATES, String.valueOf(config.trustAllCertificates())); // accountManager.setUserData(account, KEY_SYNC_PERIOD, String.valueOf(config.getSyncPeriod())); // accountManager.setUserData(account, KEY_SYNC_OVER_WIFI_ONLY, String.valueOf(config.syncOverWifiOnly())); // // SyncManager.setPeriodicSync(this, config); // } // // public Config get() { // Account account = getAccount(); // Config config = null; // if (account != null) { // config = new Config(); // config.setUrl(account.name); // config.setTrustAllCertificates(Boolean.valueOf(accountManager.getUserData(account, KEY_TRUST_ALL_CERTIFICATES))); // config.setUsername(accountManager.getUserData(account, KEY_USERNAME)); // config.setPassword(accountManager.getPassword(account)); // config.setUseHttps(Boolean.valueOf(accountManager.getUserData(account, KEY_USE_HTTPS))); // config.setSyncOverWifiOnly(Boolean.valueOf(accountManager.getUserData(account, KEY_SYNC_OVER_WIFI_ONLY))); // String syncPeriod = accountManager.getUserData(account, KEY_SYNC_PERIOD); // if (syncPeriod != null) { // config.setSyncPeriod(Long.valueOf(syncPeriod)); // } // } // return config; // } // // public Account getAccountForConfig(Config config) { // Account[] accounts = accountManager.getAccountsByType(ACCOUNT_TYPE); // for (Account account : accounts) { // if (account.name.equals(config.getUrl())) { // return account; // } // } // return null; // } // // public Account getAccount() { // Account[] accounts = accountManager.getAccountsByType(ACCOUNT_TYPE); // if (accounts.length > 0) { // return accounts[0]; // } // return null; // } // // private void remove(Account account) { // accountManager.removeAccount(account, null, null); // databaseHelper.clearTables(); // } // }
import android.accounts.Account; import android.content.ContentResolver; import android.os.Bundle; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EBean; import fr.ydelouis.selfoss.BuildConfig; import fr.ydelouis.selfoss.config.model.Config; import fr.ydelouis.selfoss.config.model.ConfigManager;
package fr.ydelouis.selfoss.sync; @EBean public class SyncManager { private static final String AUTHORITY = BuildConfig.AUTHORITY;
// Path: app/src/main/java/fr/ydelouis/selfoss/config/model/Config.java // public class Config { // // private String url; // private boolean trustAllCertificates; // private boolean useHttps; // private String username; // private String password; // private long syncPeriod; // private boolean syncOverWifiOnly; // // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public boolean trustAllCertificates() { // return trustAllCertificates; // } // // public void setTrustAllCertificates(boolean trustAllCertificates) { // this.trustAllCertificates = trustAllCertificates; // } // // public boolean useHttps() { // return useHttps; // } // // public void setUseHttps(boolean useHttps) { // this.useHttps = useHttps; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public long getSyncPeriod() { // return syncPeriod; // } // // public void setSyncPeriod(long syncPeriod) { // this.syncPeriod = syncPeriod; // } // // public boolean requireAuth() { // return username != null; // } // // public boolean syncOverWifiOnly() { // return syncOverWifiOnly; // } // // public void setSyncOverWifiOnly(boolean syncOverWifiOnly) { // this.syncOverWifiOnly = syncOverWifiOnly; // } // } // // Path: app/src/main/java/fr/ydelouis/selfoss/config/model/ConfigManager.java // @EBean // public class ConfigManager { // // public static final String ACCOUNT_TYPE = BuildConfig.ACCOUNT_TYPE; // // private static final String KEY_USERNAME = "username"; // private static final String KEY_SYNC_PERIOD = "syncPeriod"; // private static final String KEY_TRUST_ALL_CERTIFICATES = "trustAllCertificates"; // private static final String KEY_USE_HTTPS = "useHttps"; // private static final String KEY_SYNC_OVER_WIFI_ONLY = "syncOverWifiOnly"; // // @SystemService protected AccountManager accountManager; // @RootContext protected Context context; // private DatabaseHelper databaseHelper; // // @AfterInject // protected void init() { // databaseHelper = new DatabaseHelper(context); // } // // public void save(Config config) { // Account account = getAccount(); // if (account != null && !account.name.equals(config.getUrl())) { // remove(account); // account = null; // } // if (account == null) { // account = new Account(config.getUrl(), ACCOUNT_TYPE); // accountManager.addAccountExplicitly(account, config.getPassword(), null); // } // accountManager.setUserData(account, KEY_USERNAME, config.getUsername()); // accountManager.setUserData(account, KEY_USE_HTTPS, String.valueOf(config.useHttps())); // accountManager.setUserData(account, KEY_TRUST_ALL_CERTIFICATES, String.valueOf(config.trustAllCertificates())); // accountManager.setUserData(account, KEY_SYNC_PERIOD, String.valueOf(config.getSyncPeriod())); // accountManager.setUserData(account, KEY_SYNC_OVER_WIFI_ONLY, String.valueOf(config.syncOverWifiOnly())); // // SyncManager.setPeriodicSync(this, config); // } // // public Config get() { // Account account = getAccount(); // Config config = null; // if (account != null) { // config = new Config(); // config.setUrl(account.name); // config.setTrustAllCertificates(Boolean.valueOf(accountManager.getUserData(account, KEY_TRUST_ALL_CERTIFICATES))); // config.setUsername(accountManager.getUserData(account, KEY_USERNAME)); // config.setPassword(accountManager.getPassword(account)); // config.setUseHttps(Boolean.valueOf(accountManager.getUserData(account, KEY_USE_HTTPS))); // config.setSyncOverWifiOnly(Boolean.valueOf(accountManager.getUserData(account, KEY_SYNC_OVER_WIFI_ONLY))); // String syncPeriod = accountManager.getUserData(account, KEY_SYNC_PERIOD); // if (syncPeriod != null) { // config.setSyncPeriod(Long.valueOf(syncPeriod)); // } // } // return config; // } // // public Account getAccountForConfig(Config config) { // Account[] accounts = accountManager.getAccountsByType(ACCOUNT_TYPE); // for (Account account : accounts) { // if (account.name.equals(config.getUrl())) { // return account; // } // } // return null; // } // // public Account getAccount() { // Account[] accounts = accountManager.getAccountsByType(ACCOUNT_TYPE); // if (accounts.length > 0) { // return accounts[0]; // } // return null; // } // // private void remove(Account account) { // accountManager.removeAccount(account, null, null); // databaseHelper.clearTables(); // } // } // Path: app/src/main/java/fr/ydelouis/selfoss/sync/SyncManager.java import android.accounts.Account; import android.content.ContentResolver; import android.os.Bundle; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EBean; import fr.ydelouis.selfoss.BuildConfig; import fr.ydelouis.selfoss.config.model.Config; import fr.ydelouis.selfoss.config.model.ConfigManager; package fr.ydelouis.selfoss.sync; @EBean public class SyncManager { private static final String AUTHORITY = BuildConfig.AUTHORITY;
public static void setPeriodicSync(ConfigManager configManager, Config config) {
yDelouis/selfoss-android
app/src/main/java/fr/ydelouis/selfoss/sync/SyncManager.java
// Path: app/src/main/java/fr/ydelouis/selfoss/config/model/Config.java // public class Config { // // private String url; // private boolean trustAllCertificates; // private boolean useHttps; // private String username; // private String password; // private long syncPeriod; // private boolean syncOverWifiOnly; // // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public boolean trustAllCertificates() { // return trustAllCertificates; // } // // public void setTrustAllCertificates(boolean trustAllCertificates) { // this.trustAllCertificates = trustAllCertificates; // } // // public boolean useHttps() { // return useHttps; // } // // public void setUseHttps(boolean useHttps) { // this.useHttps = useHttps; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public long getSyncPeriod() { // return syncPeriod; // } // // public void setSyncPeriod(long syncPeriod) { // this.syncPeriod = syncPeriod; // } // // public boolean requireAuth() { // return username != null; // } // // public boolean syncOverWifiOnly() { // return syncOverWifiOnly; // } // // public void setSyncOverWifiOnly(boolean syncOverWifiOnly) { // this.syncOverWifiOnly = syncOverWifiOnly; // } // } // // Path: app/src/main/java/fr/ydelouis/selfoss/config/model/ConfigManager.java // @EBean // public class ConfigManager { // // public static final String ACCOUNT_TYPE = BuildConfig.ACCOUNT_TYPE; // // private static final String KEY_USERNAME = "username"; // private static final String KEY_SYNC_PERIOD = "syncPeriod"; // private static final String KEY_TRUST_ALL_CERTIFICATES = "trustAllCertificates"; // private static final String KEY_USE_HTTPS = "useHttps"; // private static final String KEY_SYNC_OVER_WIFI_ONLY = "syncOverWifiOnly"; // // @SystemService protected AccountManager accountManager; // @RootContext protected Context context; // private DatabaseHelper databaseHelper; // // @AfterInject // protected void init() { // databaseHelper = new DatabaseHelper(context); // } // // public void save(Config config) { // Account account = getAccount(); // if (account != null && !account.name.equals(config.getUrl())) { // remove(account); // account = null; // } // if (account == null) { // account = new Account(config.getUrl(), ACCOUNT_TYPE); // accountManager.addAccountExplicitly(account, config.getPassword(), null); // } // accountManager.setUserData(account, KEY_USERNAME, config.getUsername()); // accountManager.setUserData(account, KEY_USE_HTTPS, String.valueOf(config.useHttps())); // accountManager.setUserData(account, KEY_TRUST_ALL_CERTIFICATES, String.valueOf(config.trustAllCertificates())); // accountManager.setUserData(account, KEY_SYNC_PERIOD, String.valueOf(config.getSyncPeriod())); // accountManager.setUserData(account, KEY_SYNC_OVER_WIFI_ONLY, String.valueOf(config.syncOverWifiOnly())); // // SyncManager.setPeriodicSync(this, config); // } // // public Config get() { // Account account = getAccount(); // Config config = null; // if (account != null) { // config = new Config(); // config.setUrl(account.name); // config.setTrustAllCertificates(Boolean.valueOf(accountManager.getUserData(account, KEY_TRUST_ALL_CERTIFICATES))); // config.setUsername(accountManager.getUserData(account, KEY_USERNAME)); // config.setPassword(accountManager.getPassword(account)); // config.setUseHttps(Boolean.valueOf(accountManager.getUserData(account, KEY_USE_HTTPS))); // config.setSyncOverWifiOnly(Boolean.valueOf(accountManager.getUserData(account, KEY_SYNC_OVER_WIFI_ONLY))); // String syncPeriod = accountManager.getUserData(account, KEY_SYNC_PERIOD); // if (syncPeriod != null) { // config.setSyncPeriod(Long.valueOf(syncPeriod)); // } // } // return config; // } // // public Account getAccountForConfig(Config config) { // Account[] accounts = accountManager.getAccountsByType(ACCOUNT_TYPE); // for (Account account : accounts) { // if (account.name.equals(config.getUrl())) { // return account; // } // } // return null; // } // // public Account getAccount() { // Account[] accounts = accountManager.getAccountsByType(ACCOUNT_TYPE); // if (accounts.length > 0) { // return accounts[0]; // } // return null; // } // // private void remove(Account account) { // accountManager.removeAccount(account, null, null); // databaseHelper.clearTables(); // } // }
import android.accounts.Account; import android.content.ContentResolver; import android.os.Bundle; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EBean; import fr.ydelouis.selfoss.BuildConfig; import fr.ydelouis.selfoss.config.model.Config; import fr.ydelouis.selfoss.config.model.ConfigManager;
package fr.ydelouis.selfoss.sync; @EBean public class SyncManager { private static final String AUTHORITY = BuildConfig.AUTHORITY;
// Path: app/src/main/java/fr/ydelouis/selfoss/config/model/Config.java // public class Config { // // private String url; // private boolean trustAllCertificates; // private boolean useHttps; // private String username; // private String password; // private long syncPeriod; // private boolean syncOverWifiOnly; // // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public boolean trustAllCertificates() { // return trustAllCertificates; // } // // public void setTrustAllCertificates(boolean trustAllCertificates) { // this.trustAllCertificates = trustAllCertificates; // } // // public boolean useHttps() { // return useHttps; // } // // public void setUseHttps(boolean useHttps) { // this.useHttps = useHttps; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public long getSyncPeriod() { // return syncPeriod; // } // // public void setSyncPeriod(long syncPeriod) { // this.syncPeriod = syncPeriod; // } // // public boolean requireAuth() { // return username != null; // } // // public boolean syncOverWifiOnly() { // return syncOverWifiOnly; // } // // public void setSyncOverWifiOnly(boolean syncOverWifiOnly) { // this.syncOverWifiOnly = syncOverWifiOnly; // } // } // // Path: app/src/main/java/fr/ydelouis/selfoss/config/model/ConfigManager.java // @EBean // public class ConfigManager { // // public static final String ACCOUNT_TYPE = BuildConfig.ACCOUNT_TYPE; // // private static final String KEY_USERNAME = "username"; // private static final String KEY_SYNC_PERIOD = "syncPeriod"; // private static final String KEY_TRUST_ALL_CERTIFICATES = "trustAllCertificates"; // private static final String KEY_USE_HTTPS = "useHttps"; // private static final String KEY_SYNC_OVER_WIFI_ONLY = "syncOverWifiOnly"; // // @SystemService protected AccountManager accountManager; // @RootContext protected Context context; // private DatabaseHelper databaseHelper; // // @AfterInject // protected void init() { // databaseHelper = new DatabaseHelper(context); // } // // public void save(Config config) { // Account account = getAccount(); // if (account != null && !account.name.equals(config.getUrl())) { // remove(account); // account = null; // } // if (account == null) { // account = new Account(config.getUrl(), ACCOUNT_TYPE); // accountManager.addAccountExplicitly(account, config.getPassword(), null); // } // accountManager.setUserData(account, KEY_USERNAME, config.getUsername()); // accountManager.setUserData(account, KEY_USE_HTTPS, String.valueOf(config.useHttps())); // accountManager.setUserData(account, KEY_TRUST_ALL_CERTIFICATES, String.valueOf(config.trustAllCertificates())); // accountManager.setUserData(account, KEY_SYNC_PERIOD, String.valueOf(config.getSyncPeriod())); // accountManager.setUserData(account, KEY_SYNC_OVER_WIFI_ONLY, String.valueOf(config.syncOverWifiOnly())); // // SyncManager.setPeriodicSync(this, config); // } // // public Config get() { // Account account = getAccount(); // Config config = null; // if (account != null) { // config = new Config(); // config.setUrl(account.name); // config.setTrustAllCertificates(Boolean.valueOf(accountManager.getUserData(account, KEY_TRUST_ALL_CERTIFICATES))); // config.setUsername(accountManager.getUserData(account, KEY_USERNAME)); // config.setPassword(accountManager.getPassword(account)); // config.setUseHttps(Boolean.valueOf(accountManager.getUserData(account, KEY_USE_HTTPS))); // config.setSyncOverWifiOnly(Boolean.valueOf(accountManager.getUserData(account, KEY_SYNC_OVER_WIFI_ONLY))); // String syncPeriod = accountManager.getUserData(account, KEY_SYNC_PERIOD); // if (syncPeriod != null) { // config.setSyncPeriod(Long.valueOf(syncPeriod)); // } // } // return config; // } // // public Account getAccountForConfig(Config config) { // Account[] accounts = accountManager.getAccountsByType(ACCOUNT_TYPE); // for (Account account : accounts) { // if (account.name.equals(config.getUrl())) { // return account; // } // } // return null; // } // // public Account getAccount() { // Account[] accounts = accountManager.getAccountsByType(ACCOUNT_TYPE); // if (accounts.length > 0) { // return accounts[0]; // } // return null; // } // // private void remove(Account account) { // accountManager.removeAccount(account, null, null); // databaseHelper.clearTables(); // } // } // Path: app/src/main/java/fr/ydelouis/selfoss/sync/SyncManager.java import android.accounts.Account; import android.content.ContentResolver; import android.os.Bundle; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EBean; import fr.ydelouis.selfoss.BuildConfig; import fr.ydelouis.selfoss.config.model.Config; import fr.ydelouis.selfoss.config.model.ConfigManager; package fr.ydelouis.selfoss.sync; @EBean public class SyncManager { private static final String AUTHORITY = BuildConfig.AUTHORITY;
public static void setPeriodicSync(ConfigManager configManager, Config config) {
yDelouis/selfoss-android
app/src/main/java/fr/ydelouis/selfoss/entity/Tag.java
// Path: app/src/main/java/fr/ydelouis/selfoss/model/TagDao.java // public class TagDao extends BaseDaoImpl<Tag, String> { // // public static final String COLUMN_NAME = "name"; // // public TagDao(ConnectionSource connectionSource) throws SQLException { // super(connectionSource, Tag.class); // } // // public List<Tag> queryForNames(List<String> tagsNames) { // try { // return queryBuilder().where().in(COLUMN_NAME, safeStringCollection(tagsNames)).query(); // } catch (SQLException e) { // e.printStackTrace(); // return new ArrayList<Tag>(); // } // } // // private List<SelectArg> safeStringCollection(List<String> strings) { // List<SelectArg> safeStrings = new ArrayList<SelectArg>(); // for (String string : strings) { // safeStrings.add(new SelectArg(string)); // } // return safeStrings; // } // } // // Path: app/src/main/java/fr/ydelouis/selfoss/util/ColorUtil.java // public class ColorUtil { // // public static int parseColor(String colorString) { // try { // return Color.parseColor(colorString); // } catch (IllegalArgumentException e) { // if (isShortColorCode(colorString)) { // return parseShortColorCode(colorString); // } else { // return Color.BLACK; // } // } // } // // private static boolean isShortColorCode(String colorString) { // return colorString.length() == 4 && colorString.startsWith("#") && isHexadecimalColor(colorString); // } // // private static boolean isHexadecimalColor(String colorString) { // try { // Long.parseLong(colorString.substring(1), 16); // return true; // } catch (NumberFormatException e) { // return false; // } // } // // private static int parseShortColorCode(String colorString) { // String rgb = colorString.substring(1); // int r = Integer.parseInt(rgb.substring(0, 1)+rgb.substring(0, 1), 16); // int g = Integer.parseInt(rgb.substring(1, 2)+rgb.substring(1, 2), 16); // int b = Integer.parseInt(rgb.substring(2, 3)+rgb.substring(2, 3), 16); // return Color.rgb(r, g, b); // } // }
import android.content.Context; import android.os.Parcel; import android.os.Parcelable; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import fr.ydelouis.selfoss.R; import fr.ydelouis.selfoss.model.TagDao; import fr.ydelouis.selfoss.util.ColorUtil;
private int nameId; @DatabaseField private int color; @DatabaseField private int unread; public Tag() { } private Tag(int nameId) { this.nameId = nameId; } public String getName(Context context) { if (nameId != 0) return context.getString(nameId); return name; } public void setName(String name) { this.name = name; } public int getColor() { return color; } @JsonProperty("color") public void setColor(String color) {
// Path: app/src/main/java/fr/ydelouis/selfoss/model/TagDao.java // public class TagDao extends BaseDaoImpl<Tag, String> { // // public static final String COLUMN_NAME = "name"; // // public TagDao(ConnectionSource connectionSource) throws SQLException { // super(connectionSource, Tag.class); // } // // public List<Tag> queryForNames(List<String> tagsNames) { // try { // return queryBuilder().where().in(COLUMN_NAME, safeStringCollection(tagsNames)).query(); // } catch (SQLException e) { // e.printStackTrace(); // return new ArrayList<Tag>(); // } // } // // private List<SelectArg> safeStringCollection(List<String> strings) { // List<SelectArg> safeStrings = new ArrayList<SelectArg>(); // for (String string : strings) { // safeStrings.add(new SelectArg(string)); // } // return safeStrings; // } // } // // Path: app/src/main/java/fr/ydelouis/selfoss/util/ColorUtil.java // public class ColorUtil { // // public static int parseColor(String colorString) { // try { // return Color.parseColor(colorString); // } catch (IllegalArgumentException e) { // if (isShortColorCode(colorString)) { // return parseShortColorCode(colorString); // } else { // return Color.BLACK; // } // } // } // // private static boolean isShortColorCode(String colorString) { // return colorString.length() == 4 && colorString.startsWith("#") && isHexadecimalColor(colorString); // } // // private static boolean isHexadecimalColor(String colorString) { // try { // Long.parseLong(colorString.substring(1), 16); // return true; // } catch (NumberFormatException e) { // return false; // } // } // // private static int parseShortColorCode(String colorString) { // String rgb = colorString.substring(1); // int r = Integer.parseInt(rgb.substring(0, 1)+rgb.substring(0, 1), 16); // int g = Integer.parseInt(rgb.substring(1, 2)+rgb.substring(1, 2), 16); // int b = Integer.parseInt(rgb.substring(2, 3)+rgb.substring(2, 3), 16); // return Color.rgb(r, g, b); // } // } // Path: app/src/main/java/fr/ydelouis/selfoss/entity/Tag.java import android.content.Context; import android.os.Parcel; import android.os.Parcelable; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import fr.ydelouis.selfoss.R; import fr.ydelouis.selfoss.model.TagDao; import fr.ydelouis.selfoss.util.ColorUtil; private int nameId; @DatabaseField private int color; @DatabaseField private int unread; public Tag() { } private Tag(int nameId) { this.nameId = nameId; } public String getName(Context context) { if (nameId != 0) return context.getString(nameId); return name; } public void setName(String name) { this.name = name; } public int getColor() { return color; } @JsonProperty("color") public void setColor(String color) {
this.color = ColorUtil.parseColor(color);
yDelouis/selfoss-android
app/src/main/java/fr/ydelouis/selfoss/view/TypeView.java
// Path: app/src/main/java/fr/ydelouis/selfoss/entity/ArticleType.java // public enum ArticleType { // // Newest(R.id.newest, R.string.newest, ""), // Unread(R.id.unread, R.string.unread, "unread"), // Starred(R.id.starred, R.string.starred, "starred"); // // private int id; // private int nameResId; // private String apiName; // // private ArticleType(int id, int nameResId, String apiName) { // this.id = id; // this.nameResId = nameResId; // this.apiName = apiName; // } // // public int getId() { // return id; // } // // public String getName(Context context) { // return context.getString(nameResId); // } // // @Override // public String toString() { // return apiName; // } // // public static ArticleType fromId(int id) { // for (ArticleType type : ArticleType.values()) { // if (type.getId() == id) { // return type; // } // } // throw new IllegalArgumentException("There is no ArticleType for this id : " + id); // } // }
import android.content.Context; import android.graphics.Typeface; import android.util.AttributeSet; import android.view.View; import android.widget.RelativeLayout; import android.widget.TextView; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.EViewGroup; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; import fr.ydelouis.selfoss.R; import fr.ydelouis.selfoss.entity.ArticleType;
package fr.ydelouis.selfoss.view; @EViewGroup(R.layout.view_type) public class TypeView extends RelativeLayout {
// Path: app/src/main/java/fr/ydelouis/selfoss/entity/ArticleType.java // public enum ArticleType { // // Newest(R.id.newest, R.string.newest, ""), // Unread(R.id.unread, R.string.unread, "unread"), // Starred(R.id.starred, R.string.starred, "starred"); // // private int id; // private int nameResId; // private String apiName; // // private ArticleType(int id, int nameResId, String apiName) { // this.id = id; // this.nameResId = nameResId; // this.apiName = apiName; // } // // public int getId() { // return id; // } // // public String getName(Context context) { // return context.getString(nameResId); // } // // @Override // public String toString() { // return apiName; // } // // public static ArticleType fromId(int id) { // for (ArticleType type : ArticleType.values()) { // if (type.getId() == id) { // return type; // } // } // throw new IllegalArgumentException("There is no ArticleType for this id : " + id); // } // } // Path: app/src/main/java/fr/ydelouis/selfoss/view/TypeView.java import android.content.Context; import android.graphics.Typeface; import android.util.AttributeSet; import android.view.View; import android.widget.RelativeLayout; import android.widget.TextView; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.EViewGroup; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; import fr.ydelouis.selfoss.R; import fr.ydelouis.selfoss.entity.ArticleType; package fr.ydelouis.selfoss.view; @EViewGroup(R.layout.view_type) public class TypeView extends RelativeLayout {
private ArticleType type;
yDelouis/selfoss-android
app/src/main/java/fr/ydelouis/selfoss/view/TagView.java
// Path: app/src/main/java/fr/ydelouis/selfoss/entity/Tag.java // @DatabaseTable(daoClass = TagDao.class) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Tag implements Parcelable { // // public static final Tag ALL = new Tag(R.string.allTags); // // public static final Comparator<Tag> COMPARATOR_UNREAD_INVERSE = new Comparator<Tag>() { // @Override // public int compare(Tag lhs, Tag rhs) { // return - Integer.valueOf(lhs.getUnread()).compareTo(rhs.getUnread()); // } // }; // // public static List<Integer> colorsOfTags(List<Tag> tags) { // List<Integer> colors = new ArrayList<Integer>(); // for (Tag tag : tags) { // colors.add(tag.getColor()); // } // return colors; // } // // @DatabaseField(id = true, columnName = TagDao.COLUMN_NAME) // @JsonProperty("tag") // private String name; // private int nameId; // @DatabaseField // private int color; // @DatabaseField // private int unread; // // public Tag() { // // } // // private Tag(int nameId) { // this.nameId = nameId; // } // // public String getName(Context context) { // if (nameId != 0) // return context.getString(nameId); // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getColor() { // return color; // } // // @JsonProperty("color") // public void setColor(String color) { // this.color = ColorUtil.parseColor(color); // } // // public int getUnread() { // return unread; // } // // public void setUnread(int unread) { // this.unread = unread; // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Tag)) // return false; // Tag oTag = (Tag) o; // if (name == null) // return nameId == oTag.nameId; // return name.equals(oTag.name); // } // // @Override // public String toString() { // if (name == null) // return "All"; // return name; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.name); // dest.writeInt(this.nameId); // dest.writeInt(this.color); // dest.writeInt(this.unread); // } // // private Tag(Parcel in) { // this.name = in.readString(); // this.nameId = in.readInt(); // this.color = in.readInt(); // this.unread = in.readInt(); // } // // public static Parcelable.Creator<Tag> CREATOR = new Parcelable.Creator<Tag>() { // public Tag createFromParcel(Parcel source) { // return new Tag(source); // } // // public Tag[] newArray(int size) { // return new Tag[size]; // } // }; // }
import android.content.Context; import android.graphics.Typeface; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.OvalShape; import android.util.AttributeSet; import android.view.View; import android.widget.RelativeLayout; import android.widget.TextView; import org.androidannotations.annotations.EViewGroup; import org.androidannotations.annotations.ViewById; import java.util.List; import fr.ydelouis.selfoss.R; import fr.ydelouis.selfoss.entity.Tag;
package fr.ydelouis.selfoss.view; @EViewGroup(R.layout.view_tag) public class TagView extends RelativeLayout {
// Path: app/src/main/java/fr/ydelouis/selfoss/entity/Tag.java // @DatabaseTable(daoClass = TagDao.class) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Tag implements Parcelable { // // public static final Tag ALL = new Tag(R.string.allTags); // // public static final Comparator<Tag> COMPARATOR_UNREAD_INVERSE = new Comparator<Tag>() { // @Override // public int compare(Tag lhs, Tag rhs) { // return - Integer.valueOf(lhs.getUnread()).compareTo(rhs.getUnread()); // } // }; // // public static List<Integer> colorsOfTags(List<Tag> tags) { // List<Integer> colors = new ArrayList<Integer>(); // for (Tag tag : tags) { // colors.add(tag.getColor()); // } // return colors; // } // // @DatabaseField(id = true, columnName = TagDao.COLUMN_NAME) // @JsonProperty("tag") // private String name; // private int nameId; // @DatabaseField // private int color; // @DatabaseField // private int unread; // // public Tag() { // // } // // private Tag(int nameId) { // this.nameId = nameId; // } // // public String getName(Context context) { // if (nameId != 0) // return context.getString(nameId); // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getColor() { // return color; // } // // @JsonProperty("color") // public void setColor(String color) { // this.color = ColorUtil.parseColor(color); // } // // public int getUnread() { // return unread; // } // // public void setUnread(int unread) { // this.unread = unread; // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Tag)) // return false; // Tag oTag = (Tag) o; // if (name == null) // return nameId == oTag.nameId; // return name.equals(oTag.name); // } // // @Override // public String toString() { // if (name == null) // return "All"; // return name; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.name); // dest.writeInt(this.nameId); // dest.writeInt(this.color); // dest.writeInt(this.unread); // } // // private Tag(Parcel in) { // this.name = in.readString(); // this.nameId = in.readInt(); // this.color = in.readInt(); // this.unread = in.readInt(); // } // // public static Parcelable.Creator<Tag> CREATOR = new Parcelable.Creator<Tag>() { // public Tag createFromParcel(Parcel source) { // return new Tag(source); // } // // public Tag[] newArray(int size) { // return new Tag[size]; // } // }; // } // Path: app/src/main/java/fr/ydelouis/selfoss/view/TagView.java import android.content.Context; import android.graphics.Typeface; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.OvalShape; import android.util.AttributeSet; import android.view.View; import android.widget.RelativeLayout; import android.widget.TextView; import org.androidannotations.annotations.EViewGroup; import org.androidannotations.annotations.ViewById; import java.util.List; import fr.ydelouis.selfoss.R; import fr.ydelouis.selfoss.entity.Tag; package fr.ydelouis.selfoss.view; @EViewGroup(R.layout.view_tag) public class TagView extends RelativeLayout {
private Tag tag;
MegaApuTurkUltra/Scratch-ApuC
antlr-src/org/antlr/v4/runtime/misc/IntervalSet.java
// Path: antlr-src/org/antlr/v4/runtime/Token.java // public interface Token { // public static final int INVALID_TYPE = 0; // // /** During lookahead operations, this "token" signifies we hit rule end ATN state // * and did not follow it despite needing to. // */ // public static final int EPSILON = -2; // // public static final int MIN_USER_TOKEN_TYPE = 1; // // public static final int EOF = IntStream.EOF; // // /** All tokens go to the parser (unless skip() is called in that rule) // * on a particular "channel". The parser tunes to a particular channel // * so that whitespace etc... can go to the parser on a "hidden" channel. // */ // public static final int DEFAULT_CHANNEL = 0; // // /** Anything on different channel than DEFAULT_CHANNEL is not parsed // * by parser. // */ // public static final int HIDDEN_CHANNEL = 1; // // /** // * Get the text of the token. // */ // String getText(); // // /** Get the token type of the token */ // int getType(); // // /** The line number on which the 1st character of this token was matched, // * line=1..n // */ // int getLine(); // // /** The index of the first character of this token relative to the // * beginning of the line at which it occurs, 0..n-1 // */ // int getCharPositionInLine(); // // /** Return the channel this token. Each token can arrive at the parser // * on a different channel, but the parser only "tunes" to a single channel. // * The parser ignores everything not on DEFAULT_CHANNEL. // */ // int getChannel(); // // /** An index from 0..n-1 of the token object in the input stream. // * This must be valid in order to print token streams and // * use TokenRewriteStream. // * // * Return -1 to indicate that this token was conjured up since // * it doesn't have a valid index. // */ // int getTokenIndex(); // // /** The starting character index of the token // * This method is optional; return -1 if not implemented. // */ // int getStartIndex(); // // /** The last character index of the token. // * This method is optional; return -1 if not implemented. // */ // int getStopIndex(); // // /** Gets the {@link TokenSource} which created this token. // */ // TokenSource getTokenSource(); // // /** // * Gets the {@link CharStream} from which this token was derived. // */ // CharStream getInputStream(); // }
import org.antlr.v4.runtime.Token; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Set; import org.antlr.v4.runtime.Lexer;
return false; /* for (ListIterator iter = intervals.listIterator(); iter.hasNext();) { Interval I = (Interval) iter.next(); if ( el<I.a ) { break; // list is sorted and el is before this interval; not here } if ( el>=I.a && el<=I.b ) { return true; // found in this interval } } return false; */ } /** {@inheritDoc} */ @Override public boolean isNil() { return intervals==null || intervals.isEmpty(); } /** {@inheritDoc} */ @Override public int getSingleElement() { if ( intervals!=null && intervals.size()==1 ) { Interval I = intervals.get(0); if ( I.a == I.b ) { return I.a; } }
// Path: antlr-src/org/antlr/v4/runtime/Token.java // public interface Token { // public static final int INVALID_TYPE = 0; // // /** During lookahead operations, this "token" signifies we hit rule end ATN state // * and did not follow it despite needing to. // */ // public static final int EPSILON = -2; // // public static final int MIN_USER_TOKEN_TYPE = 1; // // public static final int EOF = IntStream.EOF; // // /** All tokens go to the parser (unless skip() is called in that rule) // * on a particular "channel". The parser tunes to a particular channel // * so that whitespace etc... can go to the parser on a "hidden" channel. // */ // public static final int DEFAULT_CHANNEL = 0; // // /** Anything on different channel than DEFAULT_CHANNEL is not parsed // * by parser. // */ // public static final int HIDDEN_CHANNEL = 1; // // /** // * Get the text of the token. // */ // String getText(); // // /** Get the token type of the token */ // int getType(); // // /** The line number on which the 1st character of this token was matched, // * line=1..n // */ // int getLine(); // // /** The index of the first character of this token relative to the // * beginning of the line at which it occurs, 0..n-1 // */ // int getCharPositionInLine(); // // /** Return the channel this token. Each token can arrive at the parser // * on a different channel, but the parser only "tunes" to a single channel. // * The parser ignores everything not on DEFAULT_CHANNEL. // */ // int getChannel(); // // /** An index from 0..n-1 of the token object in the input stream. // * This must be valid in order to print token streams and // * use TokenRewriteStream. // * // * Return -1 to indicate that this token was conjured up since // * it doesn't have a valid index. // */ // int getTokenIndex(); // // /** The starting character index of the token // * This method is optional; return -1 if not implemented. // */ // int getStartIndex(); // // /** The last character index of the token. // * This method is optional; return -1 if not implemented. // */ // int getStopIndex(); // // /** Gets the {@link TokenSource} which created this token. // */ // TokenSource getTokenSource(); // // /** // * Gets the {@link CharStream} from which this token was derived. // */ // CharStream getInputStream(); // } // Path: antlr-src/org/antlr/v4/runtime/misc/IntervalSet.java import org.antlr.v4.runtime.Token; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Set; import org.antlr.v4.runtime.Lexer; return false; /* for (ListIterator iter = intervals.listIterator(); iter.hasNext();) { Interval I = (Interval) iter.next(); if ( el<I.a ) { break; // list is sorted and el is before this interval; not here } if ( el>=I.a && el<=I.b ) { return true; // found in this interval } } return false; */ } /** {@inheritDoc} */ @Override public boolean isNil() { return intervals==null || intervals.isEmpty(); } /** {@inheritDoc} */ @Override public int getSingleElement() { if ( intervals!=null && intervals.size()==1 ) { Interval I = intervals.get(0); if ( I.a == I.b ) { return I.a; } }
return Token.INVALID_TYPE;
MegaApuTurkUltra/Scratch-ApuC
src/apu/scratch/converter/IdeMain.java
// Path: src/apu/scratch/converter/IdeFrame.java // static interface SaveCallback { // public void codeSaved(String code, boolean save); // }
import java.awt.BorderLayout; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import javax.swing.ToolTipManager; import apu.scratch.converter.IdeFrame.SaveCallback; import chrriis.dj.nativeswing.swtimpl.NativeInterface; import chrriis.dj.nativeswing.swtimpl.components.JWebBrowser;
in.close(); } Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { IdeFrame.launch(true); try { sb2 = new JWebBrowser(); sb2.setBarsVisible(false); sb2.setButtonBarVisible(false); sb2.setJavascriptEnabled(true); sb2.setMenuBarVisible(false); sb2.setStatusBarVisible(false); sb2.navigate(new File("scratchblocks2/index.html").toURI().toString()); IdeFrame.instance.sbRender.setLayout(new BorderLayout()); IdeFrame.instance.sbRender.add(sb2, BorderLayout.CENTER); } catch (Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(IdeFrame.instance, "Unable to load Scratchblocks2", "Warning", JOptionPane.WARNING_MESSAGE); IdeFrame.instance.sbRender.add(new JLabel( "Unable to load Scratchblocks2")); }
// Path: src/apu/scratch/converter/IdeFrame.java // static interface SaveCallback { // public void codeSaved(String code, boolean save); // } // Path: src/apu/scratch/converter/IdeMain.java import java.awt.BorderLayout; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import javax.swing.ToolTipManager; import apu.scratch.converter.IdeFrame.SaveCallback; import chrriis.dj.nativeswing.swtimpl.NativeInterface; import chrriis.dj.nativeswing.swtimpl.components.JWebBrowser; in.close(); } Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { IdeFrame.launch(true); try { sb2 = new JWebBrowser(); sb2.setBarsVisible(false); sb2.setButtonBarVisible(false); sb2.setJavascriptEnabled(true); sb2.setMenuBarVisible(false); sb2.setStatusBarVisible(false); sb2.navigate(new File("scratchblocks2/index.html").toURI().toString()); IdeFrame.instance.sbRender.setLayout(new BorderLayout()); IdeFrame.instance.sbRender.add(sb2, BorderLayout.CENTER); } catch (Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(IdeFrame.instance, "Unable to load Scratchblocks2", "Warning", JOptionPane.WARNING_MESSAGE); IdeFrame.instance.sbRender.add(new JLabel( "Unable to load Scratchblocks2")); }
IdeFrame.instance.callback = new SaveCallback() {
jpmml/jpmml-sparkml
src/test/java/org/jpmml/sparkml/ClassificationTest.java
// Path: src/main/java/org/jpmml/sparkml/model/HasRegressionTableOptions.java // public interface HasRegressionTableOptions extends HasSparkMLOptions { // // String OPTION_LOOKUP_THRESHOLD = "lookup_threshold"; // // String OPTION_REPRESENTATION = "representation"; // } // // Path: src/main/java/org/jpmml/sparkml/model/HasTreeOptions.java // public interface HasTreeOptions extends HasSparkMLOptions, HasNativeConfiguration { // // /** // * @see TreeModelCompactor // */ // String OPTION_COMPACT = "compact"; // // String OPTION_ESTIMATE_FEATURE_IMPORTANCES = "estimate_featureImportances"; // // @Override // default // public Map<String, ?> getNativeConfiguration(){ // Map<String, Object> result = new LinkedHashMap<>(); // result.put(HasTreeOptions.OPTION_COMPACT, Boolean.FALSE); // // return result; // } // }
import java.util.Map; import java.util.function.Predicate; import com.google.common.base.Equivalence; import org.dmg.pmml.general_regression.GeneralRegressionModel; import org.jpmml.evaluator.ResultField; import org.jpmml.evaluator.testing.ArchiveBatch; import org.jpmml.evaluator.testing.PMMLEquivalence; import org.jpmml.sparkml.model.HasRegressionTableOptions; import org.jpmml.sparkml.model.HasTreeOptions; import org.junit.Test;
/* * Copyright (c) 2016 Villu Ruusmann * * This file is part of JPMML-SparkML * * JPMML-SparkML is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JPMML-SparkML is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with JPMML-SparkML. If not, see <http://www.gnu.org/licenses/>. */ package org.jpmml.sparkml; public class ClassificationTest extends SparkMLTest implements Algorithms, Datasets { @Override public ArchiveBatch createBatch(String name, String dataset, Predicate<ResultField> predicate, Equivalence<Object> equivalence){ predicate = excludePredictionFields(predicate); ArchiveBatch result = new SparkMLTestBatch(name, dataset, predicate, equivalence){ @Override public ClassificationTest getIntegrationTest(){ return ClassificationTest.this; } @Override public Map<String, Object> getOptions(String name, String dataset){ Map<String, Object> options = super.getOptions(name, dataset); if((LOGISTIC_REGRESSION).equals(name) && (AUDIT).equals(dataset)){
// Path: src/main/java/org/jpmml/sparkml/model/HasRegressionTableOptions.java // public interface HasRegressionTableOptions extends HasSparkMLOptions { // // String OPTION_LOOKUP_THRESHOLD = "lookup_threshold"; // // String OPTION_REPRESENTATION = "representation"; // } // // Path: src/main/java/org/jpmml/sparkml/model/HasTreeOptions.java // public interface HasTreeOptions extends HasSparkMLOptions, HasNativeConfiguration { // // /** // * @see TreeModelCompactor // */ // String OPTION_COMPACT = "compact"; // // String OPTION_ESTIMATE_FEATURE_IMPORTANCES = "estimate_featureImportances"; // // @Override // default // public Map<String, ?> getNativeConfiguration(){ // Map<String, Object> result = new LinkedHashMap<>(); // result.put(HasTreeOptions.OPTION_COMPACT, Boolean.FALSE); // // return result; // } // } // Path: src/test/java/org/jpmml/sparkml/ClassificationTest.java import java.util.Map; import java.util.function.Predicate; import com.google.common.base.Equivalence; import org.dmg.pmml.general_regression.GeneralRegressionModel; import org.jpmml.evaluator.ResultField; import org.jpmml.evaluator.testing.ArchiveBatch; import org.jpmml.evaluator.testing.PMMLEquivalence; import org.jpmml.sparkml.model.HasRegressionTableOptions; import org.jpmml.sparkml.model.HasTreeOptions; import org.junit.Test; /* * Copyright (c) 2016 Villu Ruusmann * * This file is part of JPMML-SparkML * * JPMML-SparkML is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JPMML-SparkML is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with JPMML-SparkML. If not, see <http://www.gnu.org/licenses/>. */ package org.jpmml.sparkml; public class ClassificationTest extends SparkMLTest implements Algorithms, Datasets { @Override public ArchiveBatch createBatch(String name, String dataset, Predicate<ResultField> predicate, Equivalence<Object> equivalence){ predicate = excludePredictionFields(predicate); ArchiveBatch result = new SparkMLTestBatch(name, dataset, predicate, equivalence){ @Override public ClassificationTest getIntegrationTest(){ return ClassificationTest.this; } @Override public Map<String, Object> getOptions(String name, String dataset){ Map<String, Object> options = super.getOptions(name, dataset); if((LOGISTIC_REGRESSION).equals(name) && (AUDIT).equals(dataset)){
options.put(HasRegressionTableOptions.OPTION_REPRESENTATION, GeneralRegressionModel.class.getSimpleName());
jpmml/jpmml-sparkml
src/test/java/org/jpmml/sparkml/ClassificationTest.java
// Path: src/main/java/org/jpmml/sparkml/model/HasRegressionTableOptions.java // public interface HasRegressionTableOptions extends HasSparkMLOptions { // // String OPTION_LOOKUP_THRESHOLD = "lookup_threshold"; // // String OPTION_REPRESENTATION = "representation"; // } // // Path: src/main/java/org/jpmml/sparkml/model/HasTreeOptions.java // public interface HasTreeOptions extends HasSparkMLOptions, HasNativeConfiguration { // // /** // * @see TreeModelCompactor // */ // String OPTION_COMPACT = "compact"; // // String OPTION_ESTIMATE_FEATURE_IMPORTANCES = "estimate_featureImportances"; // // @Override // default // public Map<String, ?> getNativeConfiguration(){ // Map<String, Object> result = new LinkedHashMap<>(); // result.put(HasTreeOptions.OPTION_COMPACT, Boolean.FALSE); // // return result; // } // }
import java.util.Map; import java.util.function.Predicate; import com.google.common.base.Equivalence; import org.dmg.pmml.general_regression.GeneralRegressionModel; import org.jpmml.evaluator.ResultField; import org.jpmml.evaluator.testing.ArchiveBatch; import org.jpmml.evaluator.testing.PMMLEquivalence; import org.jpmml.sparkml.model.HasRegressionTableOptions; import org.jpmml.sparkml.model.HasTreeOptions; import org.junit.Test;
/* * Copyright (c) 2016 Villu Ruusmann * * This file is part of JPMML-SparkML * * JPMML-SparkML is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JPMML-SparkML is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with JPMML-SparkML. If not, see <http://www.gnu.org/licenses/>. */ package org.jpmml.sparkml; public class ClassificationTest extends SparkMLTest implements Algorithms, Datasets { @Override public ArchiveBatch createBatch(String name, String dataset, Predicate<ResultField> predicate, Equivalence<Object> equivalence){ predicate = excludePredictionFields(predicate); ArchiveBatch result = new SparkMLTestBatch(name, dataset, predicate, equivalence){ @Override public ClassificationTest getIntegrationTest(){ return ClassificationTest.this; } @Override public Map<String, Object> getOptions(String name, String dataset){ Map<String, Object> options = super.getOptions(name, dataset); if((LOGISTIC_REGRESSION).equals(name) && (AUDIT).equals(dataset)){ options.put(HasRegressionTableOptions.OPTION_REPRESENTATION, GeneralRegressionModel.class.getSimpleName()); } // End if if((DECISION_TREE).equals(name) || (GBT).equals(name) || (RANDOM_FOREST).equals(name)){
// Path: src/main/java/org/jpmml/sparkml/model/HasRegressionTableOptions.java // public interface HasRegressionTableOptions extends HasSparkMLOptions { // // String OPTION_LOOKUP_THRESHOLD = "lookup_threshold"; // // String OPTION_REPRESENTATION = "representation"; // } // // Path: src/main/java/org/jpmml/sparkml/model/HasTreeOptions.java // public interface HasTreeOptions extends HasSparkMLOptions, HasNativeConfiguration { // // /** // * @see TreeModelCompactor // */ // String OPTION_COMPACT = "compact"; // // String OPTION_ESTIMATE_FEATURE_IMPORTANCES = "estimate_featureImportances"; // // @Override // default // public Map<String, ?> getNativeConfiguration(){ // Map<String, Object> result = new LinkedHashMap<>(); // result.put(HasTreeOptions.OPTION_COMPACT, Boolean.FALSE); // // return result; // } // } // Path: src/test/java/org/jpmml/sparkml/ClassificationTest.java import java.util.Map; import java.util.function.Predicate; import com.google.common.base.Equivalence; import org.dmg.pmml.general_regression.GeneralRegressionModel; import org.jpmml.evaluator.ResultField; import org.jpmml.evaluator.testing.ArchiveBatch; import org.jpmml.evaluator.testing.PMMLEquivalence; import org.jpmml.sparkml.model.HasRegressionTableOptions; import org.jpmml.sparkml.model.HasTreeOptions; import org.junit.Test; /* * Copyright (c) 2016 Villu Ruusmann * * This file is part of JPMML-SparkML * * JPMML-SparkML is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JPMML-SparkML is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with JPMML-SparkML. If not, see <http://www.gnu.org/licenses/>. */ package org.jpmml.sparkml; public class ClassificationTest extends SparkMLTest implements Algorithms, Datasets { @Override public ArchiveBatch createBatch(String name, String dataset, Predicate<ResultField> predicate, Equivalence<Object> equivalence){ predicate = excludePredictionFields(predicate); ArchiveBatch result = new SparkMLTestBatch(name, dataset, predicate, equivalence){ @Override public ClassificationTest getIntegrationTest(){ return ClassificationTest.this; } @Override public Map<String, Object> getOptions(String name, String dataset){ Map<String, Object> options = super.getOptions(name, dataset); if((LOGISTIC_REGRESSION).equals(name) && (AUDIT).equals(dataset)){ options.put(HasRegressionTableOptions.OPTION_REPRESENTATION, GeneralRegressionModel.class.getSimpleName()); } // End if if((DECISION_TREE).equals(name) || (GBT).equals(name) || (RANDOM_FOREST).equals(name)){
options.put(HasTreeOptions.OPTION_ESTIMATE_FEATURE_IMPORTANCES, Boolean.TRUE);
jpmml/jpmml-sparkml
src/test/java/org/jpmml/sparkml/SparkMLTestBatch.java
// Path: src/main/java/org/jpmml/sparkml/model/HasRegressionTableOptions.java // public interface HasRegressionTableOptions extends HasSparkMLOptions { // // String OPTION_LOOKUP_THRESHOLD = "lookup_threshold"; // // String OPTION_REPRESENTATION = "representation"; // }
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.Predicate; import com.google.common.base.Equivalence; import com.google.common.io.ByteStreams; import com.google.common.io.CharStreams; import com.google.common.io.MoreFiles; import org.apache.spark.ml.PipelineModel; import org.apache.spark.ml.util.MLReader; import org.apache.spark.sql.Column; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.types.DataType; import org.apache.spark.sql.types.StructField; import org.apache.spark.sql.types.StructType; import org.dmg.pmml.PMML; import org.jpmml.evaluator.ResultField; import org.jpmml.evaluator.testing.IntegrationTestBatch; import org.jpmml.evaluator.testing.PMMLEquivalence; import org.jpmml.sparkml.model.HasRegressionTableOptions;
/* * Copyright (c) 2020 Villu Ruusmann * * This file is part of JPMML-SparkML * * JPMML-SparkML is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JPMML-SparkML is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with JPMML-SparkML. If not, see <http://www.gnu.org/licenses/>. */ package org.jpmml.sparkml; abstract public class SparkMLTestBatch extends IntegrationTestBatch { public SparkMLTestBatch(String name, String dataset, Predicate<ResultField> predicate, Equivalence<Object> equivalence){ super(name, dataset, predicate, equivalence); } @Override abstract public SparkMLTest getIntegrationTest(); public Map<String, Object> getOptions(String name, String dataset){ Map<String, Object> options = new LinkedHashMap<>();
// Path: src/main/java/org/jpmml/sparkml/model/HasRegressionTableOptions.java // public interface HasRegressionTableOptions extends HasSparkMLOptions { // // String OPTION_LOOKUP_THRESHOLD = "lookup_threshold"; // // String OPTION_REPRESENTATION = "representation"; // } // Path: src/test/java/org/jpmml/sparkml/SparkMLTestBatch.java import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.Predicate; import com.google.common.base.Equivalence; import com.google.common.io.ByteStreams; import com.google.common.io.CharStreams; import com.google.common.io.MoreFiles; import org.apache.spark.ml.PipelineModel; import org.apache.spark.ml.util.MLReader; import org.apache.spark.sql.Column; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.types.DataType; import org.apache.spark.sql.types.StructField; import org.apache.spark.sql.types.StructType; import org.dmg.pmml.PMML; import org.jpmml.evaluator.ResultField; import org.jpmml.evaluator.testing.IntegrationTestBatch; import org.jpmml.evaluator.testing.PMMLEquivalence; import org.jpmml.sparkml.model.HasRegressionTableOptions; /* * Copyright (c) 2020 Villu Ruusmann * * This file is part of JPMML-SparkML * * JPMML-SparkML is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JPMML-SparkML is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with JPMML-SparkML. If not, see <http://www.gnu.org/licenses/>. */ package org.jpmml.sparkml; abstract public class SparkMLTestBatch extends IntegrationTestBatch { public SparkMLTestBatch(String name, String dataset, Predicate<ResultField> predicate, Equivalence<Object> equivalence){ super(name, dataset, predicate, equivalence); } @Override abstract public SparkMLTest getIntegrationTest(); public Map<String, Object> getOptions(String name, String dataset){ Map<String, Object> options = new LinkedHashMap<>();
options.put(HasRegressionTableOptions.OPTION_LOOKUP_THRESHOLD, 5);
jpmml/jpmml-sparkml
src/main/java/org/jpmml/sparkml/ClassificationModelConverter.java
// Path: src/main/java/org/jpmml/sparkml/model/HasPredictionModelOptions.java // public interface HasPredictionModelOptions extends HasSparkMLOptions { // // String OPTION_KEEP_PREDICTIONCOL = "keep_predictionCol"; // }
import java.util.ArrayList; import java.util.List; import org.apache.spark.ml.PredictionModel; import org.apache.spark.ml.linalg.Vector; import org.apache.spark.ml.param.shared.HasFeaturesCol; import org.apache.spark.ml.param.shared.HasLabelCol; import org.apache.spark.ml.param.shared.HasPredictionCol; import org.apache.spark.ml.param.shared.HasProbabilityCol; import org.dmg.pmml.DataType; import org.dmg.pmml.FieldName; import org.dmg.pmml.MapValues; import org.dmg.pmml.MiningFunction; import org.dmg.pmml.Model; import org.dmg.pmml.OpType; import org.dmg.pmml.OutputField; import org.dmg.pmml.ResultFeature; import org.jpmml.converter.CategoricalLabel; import org.jpmml.converter.ContinuousFeature; import org.jpmml.converter.DerivedOutputField; import org.jpmml.converter.Feature; import org.jpmml.converter.FieldNameUtil; import org.jpmml.converter.IndexFeature; import org.jpmml.converter.Label; import org.jpmml.converter.LabelUtil; import org.jpmml.converter.ModelUtil; import org.jpmml.converter.PMMLUtil; import org.jpmml.sparkml.model.HasPredictionModelOptions;
/* * Copyright (c) 2016 Villu Ruusmann * * This file is part of JPMML-SparkML * * JPMML-SparkML is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JPMML-SparkML is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with JPMML-SparkML. If not, see <http://www.gnu.org/licenses/>. */ package org.jpmml.sparkml; abstract public class ClassificationModelConverter<T extends PredictionModel<Vector, T> & HasLabelCol & HasFeaturesCol & HasPredictionCol> extends PredictionModelConverter<T> { public ClassificationModelConverter(T model){ super(model); } @Override public MiningFunction getMiningFunction(){ return MiningFunction.CLASSIFICATION; } @Override public List<OutputField> registerOutputFields(Label label, Model pmmlModel, SparkMLEncoder encoder){ T model = getTransformer(); CategoricalLabel categoricalLabel = (CategoricalLabel)label; List<Integer> categories = LabelUtil.createTargetCategories(categoricalLabel.size()); String predictionCol = model.getPredictionCol();
// Path: src/main/java/org/jpmml/sparkml/model/HasPredictionModelOptions.java // public interface HasPredictionModelOptions extends HasSparkMLOptions { // // String OPTION_KEEP_PREDICTIONCOL = "keep_predictionCol"; // } // Path: src/main/java/org/jpmml/sparkml/ClassificationModelConverter.java import java.util.ArrayList; import java.util.List; import org.apache.spark.ml.PredictionModel; import org.apache.spark.ml.linalg.Vector; import org.apache.spark.ml.param.shared.HasFeaturesCol; import org.apache.spark.ml.param.shared.HasLabelCol; import org.apache.spark.ml.param.shared.HasPredictionCol; import org.apache.spark.ml.param.shared.HasProbabilityCol; import org.dmg.pmml.DataType; import org.dmg.pmml.FieldName; import org.dmg.pmml.MapValues; import org.dmg.pmml.MiningFunction; import org.dmg.pmml.Model; import org.dmg.pmml.OpType; import org.dmg.pmml.OutputField; import org.dmg.pmml.ResultFeature; import org.jpmml.converter.CategoricalLabel; import org.jpmml.converter.ContinuousFeature; import org.jpmml.converter.DerivedOutputField; import org.jpmml.converter.Feature; import org.jpmml.converter.FieldNameUtil; import org.jpmml.converter.IndexFeature; import org.jpmml.converter.Label; import org.jpmml.converter.LabelUtil; import org.jpmml.converter.ModelUtil; import org.jpmml.converter.PMMLUtil; import org.jpmml.sparkml.model.HasPredictionModelOptions; /* * Copyright (c) 2016 Villu Ruusmann * * This file is part of JPMML-SparkML * * JPMML-SparkML is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JPMML-SparkML is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with JPMML-SparkML. If not, see <http://www.gnu.org/licenses/>. */ package org.jpmml.sparkml; abstract public class ClassificationModelConverter<T extends PredictionModel<Vector, T> & HasLabelCol & HasFeaturesCol & HasPredictionCol> extends PredictionModelConverter<T> { public ClassificationModelConverter(T model){ super(model); } @Override public MiningFunction getMiningFunction(){ return MiningFunction.CLASSIFICATION; } @Override public List<OutputField> registerOutputFields(Label label, Model pmmlModel, SparkMLEncoder encoder){ T model = getTransformer(); CategoricalLabel categoricalLabel = (CategoricalLabel)label; List<Integer> categories = LabelUtil.createTargetCategories(categoricalLabel.size()); String predictionCol = model.getPredictionCol();
Boolean keepPredictionCol = (Boolean)getOption(HasPredictionModelOptions.OPTION_KEEP_PREDICTIONCOL, Boolean.TRUE);
jpmml/jpmml-sparkml
src/test/java/org/jpmml/sparkml/RegressionTest.java
// Path: src/main/java/org/jpmml/sparkml/model/HasRegressionTableOptions.java // public interface HasRegressionTableOptions extends HasSparkMLOptions { // // String OPTION_LOOKUP_THRESHOLD = "lookup_threshold"; // // String OPTION_REPRESENTATION = "representation"; // } // // Path: src/main/java/org/jpmml/sparkml/model/HasTreeOptions.java // public interface HasTreeOptions extends HasSparkMLOptions, HasNativeConfiguration { // // /** // * @see TreeModelCompactor // */ // String OPTION_COMPACT = "compact"; // // String OPTION_ESTIMATE_FEATURE_IMPORTANCES = "estimate_featureImportances"; // // @Override // default // public Map<String, ?> getNativeConfiguration(){ // Map<String, Object> result = new LinkedHashMap<>(); // result.put(HasTreeOptions.OPTION_COMPACT, Boolean.FALSE); // // return result; // } // }
import java.util.Map; import java.util.function.Predicate; import com.google.common.base.Equivalence; import org.dmg.pmml.FieldName; import org.dmg.pmml.general_regression.GeneralRegressionModel; import org.jpmml.evaluator.ResultField; import org.jpmml.evaluator.testing.ArchiveBatch; import org.jpmml.evaluator.testing.PMMLEquivalence; import org.jpmml.sparkml.model.HasRegressionTableOptions; import org.jpmml.sparkml.model.HasTreeOptions; import org.junit.Test;
/* * Copyright (c) 2016 Villu Ruusmann * * This file is part of JPMML-SparkML * * JPMML-SparkML is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JPMML-SparkML is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with JPMML-SparkML. If not, see <http://www.gnu.org/licenses/>. */ package org.jpmml.sparkml; public class RegressionTest extends SparkMLTest implements Algorithms, Datasets { @Override public ArchiveBatch createBatch(String name, String dataset, Predicate<ResultField> predicate, Equivalence<Object> equivalence){ predicate = excludePredictionFields(predicate); ArchiveBatch result = new SparkMLTestBatch(name, dataset, predicate, equivalence){ @Override public RegressionTest getIntegrationTest(){ return RegressionTest.this; } @Override public Map<String, Object> getOptions(String name, String dataset){ Map<String, Object> options = super.getOptions(name, dataset); if((LINEAR_REGRESION).equals(name) && (AUTO).equals(dataset)){
// Path: src/main/java/org/jpmml/sparkml/model/HasRegressionTableOptions.java // public interface HasRegressionTableOptions extends HasSparkMLOptions { // // String OPTION_LOOKUP_THRESHOLD = "lookup_threshold"; // // String OPTION_REPRESENTATION = "representation"; // } // // Path: src/main/java/org/jpmml/sparkml/model/HasTreeOptions.java // public interface HasTreeOptions extends HasSparkMLOptions, HasNativeConfiguration { // // /** // * @see TreeModelCompactor // */ // String OPTION_COMPACT = "compact"; // // String OPTION_ESTIMATE_FEATURE_IMPORTANCES = "estimate_featureImportances"; // // @Override // default // public Map<String, ?> getNativeConfiguration(){ // Map<String, Object> result = new LinkedHashMap<>(); // result.put(HasTreeOptions.OPTION_COMPACT, Boolean.FALSE); // // return result; // } // } // Path: src/test/java/org/jpmml/sparkml/RegressionTest.java import java.util.Map; import java.util.function.Predicate; import com.google.common.base.Equivalence; import org.dmg.pmml.FieldName; import org.dmg.pmml.general_regression.GeneralRegressionModel; import org.jpmml.evaluator.ResultField; import org.jpmml.evaluator.testing.ArchiveBatch; import org.jpmml.evaluator.testing.PMMLEquivalence; import org.jpmml.sparkml.model.HasRegressionTableOptions; import org.jpmml.sparkml.model.HasTreeOptions; import org.junit.Test; /* * Copyright (c) 2016 Villu Ruusmann * * This file is part of JPMML-SparkML * * JPMML-SparkML is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JPMML-SparkML is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with JPMML-SparkML. If not, see <http://www.gnu.org/licenses/>. */ package org.jpmml.sparkml; public class RegressionTest extends SparkMLTest implements Algorithms, Datasets { @Override public ArchiveBatch createBatch(String name, String dataset, Predicate<ResultField> predicate, Equivalence<Object> equivalence){ predicate = excludePredictionFields(predicate); ArchiveBatch result = new SparkMLTestBatch(name, dataset, predicate, equivalence){ @Override public RegressionTest getIntegrationTest(){ return RegressionTest.this; } @Override public Map<String, Object> getOptions(String name, String dataset){ Map<String, Object> options = super.getOptions(name, dataset); if((LINEAR_REGRESION).equals(name) && (AUTO).equals(dataset)){
options.put(HasRegressionTableOptions.OPTION_REPRESENTATION, GeneralRegressionModel.class.getSimpleName());
jpmml/jpmml-sparkml
src/test/java/org/jpmml/sparkml/RegressionTest.java
// Path: src/main/java/org/jpmml/sparkml/model/HasRegressionTableOptions.java // public interface HasRegressionTableOptions extends HasSparkMLOptions { // // String OPTION_LOOKUP_THRESHOLD = "lookup_threshold"; // // String OPTION_REPRESENTATION = "representation"; // } // // Path: src/main/java/org/jpmml/sparkml/model/HasTreeOptions.java // public interface HasTreeOptions extends HasSparkMLOptions, HasNativeConfiguration { // // /** // * @see TreeModelCompactor // */ // String OPTION_COMPACT = "compact"; // // String OPTION_ESTIMATE_FEATURE_IMPORTANCES = "estimate_featureImportances"; // // @Override // default // public Map<String, ?> getNativeConfiguration(){ // Map<String, Object> result = new LinkedHashMap<>(); // result.put(HasTreeOptions.OPTION_COMPACT, Boolean.FALSE); // // return result; // } // }
import java.util.Map; import java.util.function.Predicate; import com.google.common.base.Equivalence; import org.dmg.pmml.FieldName; import org.dmg.pmml.general_regression.GeneralRegressionModel; import org.jpmml.evaluator.ResultField; import org.jpmml.evaluator.testing.ArchiveBatch; import org.jpmml.evaluator.testing.PMMLEquivalence; import org.jpmml.sparkml.model.HasRegressionTableOptions; import org.jpmml.sparkml.model.HasTreeOptions; import org.junit.Test;
/* * Copyright (c) 2016 Villu Ruusmann * * This file is part of JPMML-SparkML * * JPMML-SparkML is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JPMML-SparkML is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with JPMML-SparkML. If not, see <http://www.gnu.org/licenses/>. */ package org.jpmml.sparkml; public class RegressionTest extends SparkMLTest implements Algorithms, Datasets { @Override public ArchiveBatch createBatch(String name, String dataset, Predicate<ResultField> predicate, Equivalence<Object> equivalence){ predicate = excludePredictionFields(predicate); ArchiveBatch result = new SparkMLTestBatch(name, dataset, predicate, equivalence){ @Override public RegressionTest getIntegrationTest(){ return RegressionTest.this; } @Override public Map<String, Object> getOptions(String name, String dataset){ Map<String, Object> options = super.getOptions(name, dataset); if((LINEAR_REGRESION).equals(name) && (AUTO).equals(dataset)){ options.put(HasRegressionTableOptions.OPTION_REPRESENTATION, GeneralRegressionModel.class.getSimpleName()); } // End if if((DECISION_TREE).equals(name) || (GBT).equals(name) || (RANDOM_FOREST).equals(name)){
// Path: src/main/java/org/jpmml/sparkml/model/HasRegressionTableOptions.java // public interface HasRegressionTableOptions extends HasSparkMLOptions { // // String OPTION_LOOKUP_THRESHOLD = "lookup_threshold"; // // String OPTION_REPRESENTATION = "representation"; // } // // Path: src/main/java/org/jpmml/sparkml/model/HasTreeOptions.java // public interface HasTreeOptions extends HasSparkMLOptions, HasNativeConfiguration { // // /** // * @see TreeModelCompactor // */ // String OPTION_COMPACT = "compact"; // // String OPTION_ESTIMATE_FEATURE_IMPORTANCES = "estimate_featureImportances"; // // @Override // default // public Map<String, ?> getNativeConfiguration(){ // Map<String, Object> result = new LinkedHashMap<>(); // result.put(HasTreeOptions.OPTION_COMPACT, Boolean.FALSE); // // return result; // } // } // Path: src/test/java/org/jpmml/sparkml/RegressionTest.java import java.util.Map; import java.util.function.Predicate; import com.google.common.base.Equivalence; import org.dmg.pmml.FieldName; import org.dmg.pmml.general_regression.GeneralRegressionModel; import org.jpmml.evaluator.ResultField; import org.jpmml.evaluator.testing.ArchiveBatch; import org.jpmml.evaluator.testing.PMMLEquivalence; import org.jpmml.sparkml.model.HasRegressionTableOptions; import org.jpmml.sparkml.model.HasTreeOptions; import org.junit.Test; /* * Copyright (c) 2016 Villu Ruusmann * * This file is part of JPMML-SparkML * * JPMML-SparkML is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JPMML-SparkML is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with JPMML-SparkML. If not, see <http://www.gnu.org/licenses/>. */ package org.jpmml.sparkml; public class RegressionTest extends SparkMLTest implements Algorithms, Datasets { @Override public ArchiveBatch createBatch(String name, String dataset, Predicate<ResultField> predicate, Equivalence<Object> equivalence){ predicate = excludePredictionFields(predicate); ArchiveBatch result = new SparkMLTestBatch(name, dataset, predicate, equivalence){ @Override public RegressionTest getIntegrationTest(){ return RegressionTest.this; } @Override public Map<String, Object> getOptions(String name, String dataset){ Map<String, Object> options = super.getOptions(name, dataset); if((LINEAR_REGRESION).equals(name) && (AUTO).equals(dataset)){ options.put(HasRegressionTableOptions.OPTION_REPRESENTATION, GeneralRegressionModel.class.getSimpleName()); } // End if if((DECISION_TREE).equals(name) || (GBT).equals(name) || (RANDOM_FOREST).equals(name)){
options.put(HasTreeOptions.OPTION_ESTIMATE_FEATURE_IMPORTANCES, Boolean.TRUE);
jpmml/jpmml-sparkml
src/main/java/org/jpmml/sparkml/RegressionModelConverter.java
// Path: src/main/java/org/jpmml/sparkml/model/HasPredictionModelOptions.java // public interface HasPredictionModelOptions extends HasSparkMLOptions { // // String OPTION_KEEP_PREDICTIONCOL = "keep_predictionCol"; // }
import org.dmg.pmml.OutputField; import org.jpmml.converter.ContinuousFeature; import org.jpmml.converter.DerivedOutputField; import org.jpmml.converter.Label; import org.jpmml.converter.ModelUtil; import org.jpmml.sparkml.model.HasPredictionModelOptions; import java.util.Collections; import java.util.List; import org.apache.spark.ml.PredictionModel; import org.apache.spark.ml.linalg.Vector; import org.apache.spark.ml.param.shared.HasFeaturesCol; import org.apache.spark.ml.param.shared.HasLabelCol; import org.apache.spark.ml.param.shared.HasPredictionCol; import org.dmg.pmml.FieldName; import org.dmg.pmml.MiningFunction; import org.dmg.pmml.Model; import org.dmg.pmml.OpType;
/* * Copyright (c) 2016 Villu Ruusmann * * This file is part of JPMML-SparkML * * JPMML-SparkML is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JPMML-SparkML is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with JPMML-SparkML. If not, see <http://www.gnu.org/licenses/>. */ package org.jpmml.sparkml; abstract public class RegressionModelConverter<T extends PredictionModel<Vector, T> & HasLabelCol & HasFeaturesCol & HasPredictionCol> extends PredictionModelConverter<T> { public RegressionModelConverter(T model){ super(model); } @Override public MiningFunction getMiningFunction(){ return MiningFunction.REGRESSION; } @Override public List<OutputField> registerOutputFields(Label label, Model pmmlModel, SparkMLEncoder encoder){ T model = getTransformer(); String predictionCol = model.getPredictionCol();
// Path: src/main/java/org/jpmml/sparkml/model/HasPredictionModelOptions.java // public interface HasPredictionModelOptions extends HasSparkMLOptions { // // String OPTION_KEEP_PREDICTIONCOL = "keep_predictionCol"; // } // Path: src/main/java/org/jpmml/sparkml/RegressionModelConverter.java import org.dmg.pmml.OutputField; import org.jpmml.converter.ContinuousFeature; import org.jpmml.converter.DerivedOutputField; import org.jpmml.converter.Label; import org.jpmml.converter.ModelUtil; import org.jpmml.sparkml.model.HasPredictionModelOptions; import java.util.Collections; import java.util.List; import org.apache.spark.ml.PredictionModel; import org.apache.spark.ml.linalg.Vector; import org.apache.spark.ml.param.shared.HasFeaturesCol; import org.apache.spark.ml.param.shared.HasLabelCol; import org.apache.spark.ml.param.shared.HasPredictionCol; import org.dmg.pmml.FieldName; import org.dmg.pmml.MiningFunction; import org.dmg.pmml.Model; import org.dmg.pmml.OpType; /* * Copyright (c) 2016 Villu Ruusmann * * This file is part of JPMML-SparkML * * JPMML-SparkML is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JPMML-SparkML is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with JPMML-SparkML. If not, see <http://www.gnu.org/licenses/>. */ package org.jpmml.sparkml; abstract public class RegressionModelConverter<T extends PredictionModel<Vector, T> & HasLabelCol & HasFeaturesCol & HasPredictionCol> extends PredictionModelConverter<T> { public RegressionModelConverter(T model){ super(model); } @Override public MiningFunction getMiningFunction(){ return MiningFunction.REGRESSION; } @Override public List<OutputField> registerOutputFields(Label label, Model pmmlModel, SparkMLEncoder encoder){ T model = getTransformer(); String predictionCol = model.getPredictionCol();
Boolean keepPredictionCol = (Boolean)getOption(HasPredictionModelOptions.OPTION_KEEP_PREDICTIONCOL, Boolean.TRUE);
jpmml/jpmml-sparkml
src/main/java/org/jpmml/sparkml/Main.java
// Path: src/main/java/org/jpmml/sparkml/model/HasPredictionModelOptions.java // public interface HasPredictionModelOptions extends HasSparkMLOptions { // // String OPTION_KEEP_PREDICTIONCOL = "keep_predictionCol"; // } // // Path: src/main/java/org/jpmml/sparkml/model/HasRegressionTableOptions.java // public interface HasRegressionTableOptions extends HasSparkMLOptions { // // String OPTION_LOOKUP_THRESHOLD = "lookup_threshold"; // // String OPTION_REPRESENTATION = "representation"; // } // // Path: src/main/java/org/jpmml/sparkml/model/HasTreeOptions.java // public interface HasTreeOptions extends HasSparkMLOptions, HasNativeConfiguration { // // /** // * @see TreeModelCompactor // */ // String OPTION_COMPACT = "compact"; // // String OPTION_ESTIMATE_FEATURE_IMPORTANCES = "estimate_featureImportances"; // // @Override // default // public Map<String, ?> getNativeConfiguration(){ // Map<String, Object> result = new LinkedHashMap<>(); // result.put(HasTreeOptions.OPTION_COMPACT, Boolean.FALSE); // // return result; // } // }
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.LinkedHashMap; import java.util.Map; import java.util.zip.ZipFile; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import com.google.common.io.CharStreams; import org.apache.spark.ml.PipelineModel; import org.apache.spark.sql.types.DataType; import org.apache.spark.sql.types.StructType; import org.dmg.pmml.PMML; import org.jpmml.model.metro.MetroJAXBUtil; import org.jpmml.sparkml.model.HasPredictionModelOptions; import org.jpmml.sparkml.model.HasRegressionTableOptions; import org.jpmml.sparkml.model.HasTreeOptions; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
} catch(IOException ioe){ break zipFile; } try { pipelineDir = File.createTempFile("PipelineModel", ""); if(!pipelineDir.delete()){ throw new IOException(); } pipelineDir.mkdirs(); ZipUtil.uncompress(zipFile, pipelineDir); } finally { zipFile.close(); } } long begin = System.currentTimeMillis(); pipelineModel = PipelineModel.load(pipelineDir.getAbsolutePath()); long end = System.currentTimeMillis(); logger.info("Loaded pipeline model in {} ms.", (end - begin)); } catch(Exception e){ logger.error("Failed to load pipeline model", e); throw e; } Map<String, Object> options = new LinkedHashMap<>();
// Path: src/main/java/org/jpmml/sparkml/model/HasPredictionModelOptions.java // public interface HasPredictionModelOptions extends HasSparkMLOptions { // // String OPTION_KEEP_PREDICTIONCOL = "keep_predictionCol"; // } // // Path: src/main/java/org/jpmml/sparkml/model/HasRegressionTableOptions.java // public interface HasRegressionTableOptions extends HasSparkMLOptions { // // String OPTION_LOOKUP_THRESHOLD = "lookup_threshold"; // // String OPTION_REPRESENTATION = "representation"; // } // // Path: src/main/java/org/jpmml/sparkml/model/HasTreeOptions.java // public interface HasTreeOptions extends HasSparkMLOptions, HasNativeConfiguration { // // /** // * @see TreeModelCompactor // */ // String OPTION_COMPACT = "compact"; // // String OPTION_ESTIMATE_FEATURE_IMPORTANCES = "estimate_featureImportances"; // // @Override // default // public Map<String, ?> getNativeConfiguration(){ // Map<String, Object> result = new LinkedHashMap<>(); // result.put(HasTreeOptions.OPTION_COMPACT, Boolean.FALSE); // // return result; // } // } // Path: src/main/java/org/jpmml/sparkml/Main.java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.LinkedHashMap; import java.util.Map; import java.util.zip.ZipFile; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import com.google.common.io.CharStreams; import org.apache.spark.ml.PipelineModel; import org.apache.spark.sql.types.DataType; import org.apache.spark.sql.types.StructType; import org.dmg.pmml.PMML; import org.jpmml.model.metro.MetroJAXBUtil; import org.jpmml.sparkml.model.HasPredictionModelOptions; import org.jpmml.sparkml.model.HasRegressionTableOptions; import org.jpmml.sparkml.model.HasTreeOptions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; } catch(IOException ioe){ break zipFile; } try { pipelineDir = File.createTempFile("PipelineModel", ""); if(!pipelineDir.delete()){ throw new IOException(); } pipelineDir.mkdirs(); ZipUtil.uncompress(zipFile, pipelineDir); } finally { zipFile.close(); } } long begin = System.currentTimeMillis(); pipelineModel = PipelineModel.load(pipelineDir.getAbsolutePath()); long end = System.currentTimeMillis(); logger.info("Loaded pipeline model in {} ms.", (end - begin)); } catch(Exception e){ logger.error("Failed to load pipeline model", e); throw e; } Map<String, Object> options = new LinkedHashMap<>();
options.put(HasPredictionModelOptions.OPTION_KEEP_PREDICTIONCOL, this.keepPredictionCol);
jpmml/jpmml-sparkml
src/main/java/org/jpmml/sparkml/Main.java
// Path: src/main/java/org/jpmml/sparkml/model/HasPredictionModelOptions.java // public interface HasPredictionModelOptions extends HasSparkMLOptions { // // String OPTION_KEEP_PREDICTIONCOL = "keep_predictionCol"; // } // // Path: src/main/java/org/jpmml/sparkml/model/HasRegressionTableOptions.java // public interface HasRegressionTableOptions extends HasSparkMLOptions { // // String OPTION_LOOKUP_THRESHOLD = "lookup_threshold"; // // String OPTION_REPRESENTATION = "representation"; // } // // Path: src/main/java/org/jpmml/sparkml/model/HasTreeOptions.java // public interface HasTreeOptions extends HasSparkMLOptions, HasNativeConfiguration { // // /** // * @see TreeModelCompactor // */ // String OPTION_COMPACT = "compact"; // // String OPTION_ESTIMATE_FEATURE_IMPORTANCES = "estimate_featureImportances"; // // @Override // default // public Map<String, ?> getNativeConfiguration(){ // Map<String, Object> result = new LinkedHashMap<>(); // result.put(HasTreeOptions.OPTION_COMPACT, Boolean.FALSE); // // return result; // } // }
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.LinkedHashMap; import java.util.Map; import java.util.zip.ZipFile; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import com.google.common.io.CharStreams; import org.apache.spark.ml.PipelineModel; import org.apache.spark.sql.types.DataType; import org.apache.spark.sql.types.StructType; import org.dmg.pmml.PMML; import org.jpmml.model.metro.MetroJAXBUtil; import org.jpmml.sparkml.model.HasPredictionModelOptions; import org.jpmml.sparkml.model.HasRegressionTableOptions; import org.jpmml.sparkml.model.HasTreeOptions; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
break zipFile; } try { pipelineDir = File.createTempFile("PipelineModel", ""); if(!pipelineDir.delete()){ throw new IOException(); } pipelineDir.mkdirs(); ZipUtil.uncompress(zipFile, pipelineDir); } finally { zipFile.close(); } } long begin = System.currentTimeMillis(); pipelineModel = PipelineModel.load(pipelineDir.getAbsolutePath()); long end = System.currentTimeMillis(); logger.info("Loaded pipeline model in {} ms.", (end - begin)); } catch(Exception e){ logger.error("Failed to load pipeline model", e); throw e; } Map<String, Object> options = new LinkedHashMap<>(); options.put(HasPredictionModelOptions.OPTION_KEEP_PREDICTIONCOL, this.keepPredictionCol);
// Path: src/main/java/org/jpmml/sparkml/model/HasPredictionModelOptions.java // public interface HasPredictionModelOptions extends HasSparkMLOptions { // // String OPTION_KEEP_PREDICTIONCOL = "keep_predictionCol"; // } // // Path: src/main/java/org/jpmml/sparkml/model/HasRegressionTableOptions.java // public interface HasRegressionTableOptions extends HasSparkMLOptions { // // String OPTION_LOOKUP_THRESHOLD = "lookup_threshold"; // // String OPTION_REPRESENTATION = "representation"; // } // // Path: src/main/java/org/jpmml/sparkml/model/HasTreeOptions.java // public interface HasTreeOptions extends HasSparkMLOptions, HasNativeConfiguration { // // /** // * @see TreeModelCompactor // */ // String OPTION_COMPACT = "compact"; // // String OPTION_ESTIMATE_FEATURE_IMPORTANCES = "estimate_featureImportances"; // // @Override // default // public Map<String, ?> getNativeConfiguration(){ // Map<String, Object> result = new LinkedHashMap<>(); // result.put(HasTreeOptions.OPTION_COMPACT, Boolean.FALSE); // // return result; // } // } // Path: src/main/java/org/jpmml/sparkml/Main.java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.LinkedHashMap; import java.util.Map; import java.util.zip.ZipFile; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import com.google.common.io.CharStreams; import org.apache.spark.ml.PipelineModel; import org.apache.spark.sql.types.DataType; import org.apache.spark.sql.types.StructType; import org.dmg.pmml.PMML; import org.jpmml.model.metro.MetroJAXBUtil; import org.jpmml.sparkml.model.HasPredictionModelOptions; import org.jpmml.sparkml.model.HasRegressionTableOptions; import org.jpmml.sparkml.model.HasTreeOptions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; break zipFile; } try { pipelineDir = File.createTempFile("PipelineModel", ""); if(!pipelineDir.delete()){ throw new IOException(); } pipelineDir.mkdirs(); ZipUtil.uncompress(zipFile, pipelineDir); } finally { zipFile.close(); } } long begin = System.currentTimeMillis(); pipelineModel = PipelineModel.load(pipelineDir.getAbsolutePath()); long end = System.currentTimeMillis(); logger.info("Loaded pipeline model in {} ms.", (end - begin)); } catch(Exception e){ logger.error("Failed to load pipeline model", e); throw e; } Map<String, Object> options = new LinkedHashMap<>(); options.put(HasPredictionModelOptions.OPTION_KEEP_PREDICTIONCOL, this.keepPredictionCol);
options.put(HasTreeOptions.OPTION_COMPACT, this.compact);
jpmml/jpmml-sparkml
src/main/java/org/jpmml/sparkml/Main.java
// Path: src/main/java/org/jpmml/sparkml/model/HasPredictionModelOptions.java // public interface HasPredictionModelOptions extends HasSparkMLOptions { // // String OPTION_KEEP_PREDICTIONCOL = "keep_predictionCol"; // } // // Path: src/main/java/org/jpmml/sparkml/model/HasRegressionTableOptions.java // public interface HasRegressionTableOptions extends HasSparkMLOptions { // // String OPTION_LOOKUP_THRESHOLD = "lookup_threshold"; // // String OPTION_REPRESENTATION = "representation"; // } // // Path: src/main/java/org/jpmml/sparkml/model/HasTreeOptions.java // public interface HasTreeOptions extends HasSparkMLOptions, HasNativeConfiguration { // // /** // * @see TreeModelCompactor // */ // String OPTION_COMPACT = "compact"; // // String OPTION_ESTIMATE_FEATURE_IMPORTANCES = "estimate_featureImportances"; // // @Override // default // public Map<String, ?> getNativeConfiguration(){ // Map<String, Object> result = new LinkedHashMap<>(); // result.put(HasTreeOptions.OPTION_COMPACT, Boolean.FALSE); // // return result; // } // }
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.LinkedHashMap; import java.util.Map; import java.util.zip.ZipFile; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import com.google.common.io.CharStreams; import org.apache.spark.ml.PipelineModel; import org.apache.spark.sql.types.DataType; import org.apache.spark.sql.types.StructType; import org.dmg.pmml.PMML; import org.jpmml.model.metro.MetroJAXBUtil; import org.jpmml.sparkml.model.HasPredictionModelOptions; import org.jpmml.sparkml.model.HasRegressionTableOptions; import org.jpmml.sparkml.model.HasTreeOptions; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
try { pipelineDir = File.createTempFile("PipelineModel", ""); if(!pipelineDir.delete()){ throw new IOException(); } pipelineDir.mkdirs(); ZipUtil.uncompress(zipFile, pipelineDir); } finally { zipFile.close(); } } long begin = System.currentTimeMillis(); pipelineModel = PipelineModel.load(pipelineDir.getAbsolutePath()); long end = System.currentTimeMillis(); logger.info("Loaded pipeline model in {} ms.", (end - begin)); } catch(Exception e){ logger.error("Failed to load pipeline model", e); throw e; } Map<String, Object> options = new LinkedHashMap<>(); options.put(HasPredictionModelOptions.OPTION_KEEP_PREDICTIONCOL, this.keepPredictionCol); options.put(HasTreeOptions.OPTION_COMPACT, this.compact); options.put(HasTreeOptions.OPTION_ESTIMATE_FEATURE_IMPORTANCES, this.estimateFeatureImportances);
// Path: src/main/java/org/jpmml/sparkml/model/HasPredictionModelOptions.java // public interface HasPredictionModelOptions extends HasSparkMLOptions { // // String OPTION_KEEP_PREDICTIONCOL = "keep_predictionCol"; // } // // Path: src/main/java/org/jpmml/sparkml/model/HasRegressionTableOptions.java // public interface HasRegressionTableOptions extends HasSparkMLOptions { // // String OPTION_LOOKUP_THRESHOLD = "lookup_threshold"; // // String OPTION_REPRESENTATION = "representation"; // } // // Path: src/main/java/org/jpmml/sparkml/model/HasTreeOptions.java // public interface HasTreeOptions extends HasSparkMLOptions, HasNativeConfiguration { // // /** // * @see TreeModelCompactor // */ // String OPTION_COMPACT = "compact"; // // String OPTION_ESTIMATE_FEATURE_IMPORTANCES = "estimate_featureImportances"; // // @Override // default // public Map<String, ?> getNativeConfiguration(){ // Map<String, Object> result = new LinkedHashMap<>(); // result.put(HasTreeOptions.OPTION_COMPACT, Boolean.FALSE); // // return result; // } // } // Path: src/main/java/org/jpmml/sparkml/Main.java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.LinkedHashMap; import java.util.Map; import java.util.zip.ZipFile; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import com.google.common.io.CharStreams; import org.apache.spark.ml.PipelineModel; import org.apache.spark.sql.types.DataType; import org.apache.spark.sql.types.StructType; import org.dmg.pmml.PMML; import org.jpmml.model.metro.MetroJAXBUtil; import org.jpmml.sparkml.model.HasPredictionModelOptions; import org.jpmml.sparkml.model.HasRegressionTableOptions; import org.jpmml.sparkml.model.HasTreeOptions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; try { pipelineDir = File.createTempFile("PipelineModel", ""); if(!pipelineDir.delete()){ throw new IOException(); } pipelineDir.mkdirs(); ZipUtil.uncompress(zipFile, pipelineDir); } finally { zipFile.close(); } } long begin = System.currentTimeMillis(); pipelineModel = PipelineModel.load(pipelineDir.getAbsolutePath()); long end = System.currentTimeMillis(); logger.info("Loaded pipeline model in {} ms.", (end - begin)); } catch(Exception e){ logger.error("Failed to load pipeline model", e); throw e; } Map<String, Object> options = new LinkedHashMap<>(); options.put(HasPredictionModelOptions.OPTION_KEEP_PREDICTIONCOL, this.keepPredictionCol); options.put(HasTreeOptions.OPTION_COMPACT, this.compact); options.put(HasTreeOptions.OPTION_ESTIMATE_FEATURE_IMPORTANCES, this.estimateFeatureImportances);
options.put(HasRegressionTableOptions.OPTION_LOOKUP_THRESHOLD, this.lookupThreshold);
jpmml/jpmml-sparkml
src/main/java/org/jpmml/sparkml/model/KMeansModelConverter.java
// Path: src/main/java/org/jpmml/sparkml/ClusteringModelConverter.java // abstract // public class ClusteringModelConverter<T extends Model<T> & HasFeaturesCol & HasPredictionCol> extends ModelConverter<T> { // // public ClusteringModelConverter(T model){ // super(model); // } // // abstract // public int getNumberOfClusters(); // // @Override // public MiningFunction getMiningFunction(){ // return MiningFunction.CLUSTERING; // } // // @Override // public List<Feature> getFeatures(SparkMLEncoder encoder){ // T model = getTransformer(); // // String featuresCol = model.getFeaturesCol(); // // return encoder.getFeatures(featuresCol); // } // // @Override // public List<OutputField> registerOutputFields(Label label, org.dmg.pmml.Model pmmlModel, SparkMLEncoder encoder){ // T model = getTransformer(); // // List<Integer> clusters = LabelUtil.createTargetCategories(getNumberOfClusters()); // // String predictionCol = model.getPredictionCol(); // // OutputField pmmlPredictedOutputField = ModelUtil.createPredictedField(FieldNameUtil.create("pmml", predictionCol), OpType.CATEGORICAL, DataType.STRING) // .setFinalResult(false); // // DerivedOutputField pmmlPredictedField = encoder.createDerivedField(pmmlModel, pmmlPredictedOutputField, true); // // OutputField predictedOutputField = new OutputField(FieldName.create(predictionCol), OpType.CATEGORICAL, DataType.INTEGER) // .setResultFeature(ResultFeature.TRANSFORMED_VALUE) // .setExpression(new FieldRef(pmmlPredictedField.getName())); // // DerivedOutputField predictedField = encoder.createDerivedField(pmmlModel, predictedOutputField, true); // // encoder.putOnlyFeature(predictionCol, new IndexFeature(encoder, predictedField, clusters)); // // return Collections.emptyList(); // } // } // // Path: src/main/java/org/jpmml/sparkml/VectorUtil.java // public class VectorUtil { // // private VectorUtil(){ // } // // static // public List<Double> toList(Vector vector){ // DenseVector denseVector = vector.toDense(); // // double[] values = denseVector.values(); // // return Doubles.asList(values); // } // }
import org.jpmml.converter.PMMLUtil; import org.jpmml.converter.Schema; import org.jpmml.converter.clustering.ClusteringModelUtil; import org.jpmml.sparkml.ClusteringModelConverter; import org.jpmml.sparkml.VectorUtil; import java.util.ArrayList; import java.util.List; import org.apache.spark.ml.clustering.KMeansModel; import org.apache.spark.ml.linalg.Vector; import org.dmg.pmml.CompareFunction; import org.dmg.pmml.ComparisonMeasure; import org.dmg.pmml.MiningFunction; import org.dmg.pmml.SquaredEuclidean; import org.dmg.pmml.clustering.Cluster; import org.dmg.pmml.clustering.ClusteringModel; import org.jpmml.converter.ModelUtil;
/* * Copyright (c) 2016 Villu Ruusmann * * This file is part of JPMML-SparkML * * JPMML-SparkML is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JPMML-SparkML is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with JPMML-SparkML. If not, see <http://www.gnu.org/licenses/>. */ package org.jpmml.sparkml.model; public class KMeansModelConverter extends ClusteringModelConverter<KMeansModel> { public KMeansModelConverter(KMeansModel model){ super(model); } @Override public int getNumberOfClusters(){ KMeansModel model = getTransformer(); return model.getK(); } @Override public ClusteringModel encodeModel(Schema schema){ KMeansModel model = getTransformer(); List<Cluster> clusters = new ArrayList<>(); Vector[] clusterCenters = model.clusterCenters(); for(int i = 0; i < clusterCenters.length; i++){
// Path: src/main/java/org/jpmml/sparkml/ClusteringModelConverter.java // abstract // public class ClusteringModelConverter<T extends Model<T> & HasFeaturesCol & HasPredictionCol> extends ModelConverter<T> { // // public ClusteringModelConverter(T model){ // super(model); // } // // abstract // public int getNumberOfClusters(); // // @Override // public MiningFunction getMiningFunction(){ // return MiningFunction.CLUSTERING; // } // // @Override // public List<Feature> getFeatures(SparkMLEncoder encoder){ // T model = getTransformer(); // // String featuresCol = model.getFeaturesCol(); // // return encoder.getFeatures(featuresCol); // } // // @Override // public List<OutputField> registerOutputFields(Label label, org.dmg.pmml.Model pmmlModel, SparkMLEncoder encoder){ // T model = getTransformer(); // // List<Integer> clusters = LabelUtil.createTargetCategories(getNumberOfClusters()); // // String predictionCol = model.getPredictionCol(); // // OutputField pmmlPredictedOutputField = ModelUtil.createPredictedField(FieldNameUtil.create("pmml", predictionCol), OpType.CATEGORICAL, DataType.STRING) // .setFinalResult(false); // // DerivedOutputField pmmlPredictedField = encoder.createDerivedField(pmmlModel, pmmlPredictedOutputField, true); // // OutputField predictedOutputField = new OutputField(FieldName.create(predictionCol), OpType.CATEGORICAL, DataType.INTEGER) // .setResultFeature(ResultFeature.TRANSFORMED_VALUE) // .setExpression(new FieldRef(pmmlPredictedField.getName())); // // DerivedOutputField predictedField = encoder.createDerivedField(pmmlModel, predictedOutputField, true); // // encoder.putOnlyFeature(predictionCol, new IndexFeature(encoder, predictedField, clusters)); // // return Collections.emptyList(); // } // } // // Path: src/main/java/org/jpmml/sparkml/VectorUtil.java // public class VectorUtil { // // private VectorUtil(){ // } // // static // public List<Double> toList(Vector vector){ // DenseVector denseVector = vector.toDense(); // // double[] values = denseVector.values(); // // return Doubles.asList(values); // } // } // Path: src/main/java/org/jpmml/sparkml/model/KMeansModelConverter.java import org.jpmml.converter.PMMLUtil; import org.jpmml.converter.Schema; import org.jpmml.converter.clustering.ClusteringModelUtil; import org.jpmml.sparkml.ClusteringModelConverter; import org.jpmml.sparkml.VectorUtil; import java.util.ArrayList; import java.util.List; import org.apache.spark.ml.clustering.KMeansModel; import org.apache.spark.ml.linalg.Vector; import org.dmg.pmml.CompareFunction; import org.dmg.pmml.ComparisonMeasure; import org.dmg.pmml.MiningFunction; import org.dmg.pmml.SquaredEuclidean; import org.dmg.pmml.clustering.Cluster; import org.dmg.pmml.clustering.ClusteringModel; import org.jpmml.converter.ModelUtil; /* * Copyright (c) 2016 Villu Ruusmann * * This file is part of JPMML-SparkML * * JPMML-SparkML is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JPMML-SparkML is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with JPMML-SparkML. If not, see <http://www.gnu.org/licenses/>. */ package org.jpmml.sparkml.model; public class KMeansModelConverter extends ClusteringModelConverter<KMeansModel> { public KMeansModelConverter(KMeansModel model){ super(model); } @Override public int getNumberOfClusters(){ KMeansModel model = getTransformer(); return model.getK(); } @Override public ClusteringModel encodeModel(Schema schema){ KMeansModel model = getTransformer(); List<Cluster> clusters = new ArrayList<>(); Vector[] clusterCenters = model.clusterCenters(); for(int i = 0; i < clusterCenters.length; i++){
Cluster cluster = new Cluster(PMMLUtil.createRealArray(VectorUtil.toList(clusterCenters[i])))
jpmml/jpmml-sparkml
src/main/java/org/jpmml/sparkml/PMMLBuilder.java
// Path: src/main/java/org/jpmml/sparkml/model/HasFeatureImportances.java // public interface HasFeatureImportances { // // Vector getFeatureImportances(); // } // // Path: src/main/java/org/jpmml/sparkml/model/HasTreeOptions.java // public interface HasTreeOptions extends HasSparkMLOptions, HasNativeConfiguration { // // /** // * @see TreeModelCompactor // */ // String OPTION_COMPACT = "compact"; // // String OPTION_ESTIMATE_FEATURE_IMPORTANCES = "estimate_featureImportances"; // // @Override // default // public Map<String, ?> getNativeConfiguration(){ // Map<String, Object> result = new LinkedHashMap<>(); // result.put(HasTreeOptions.OPTION_COMPACT, Boolean.FALSE); // // return result; // } // }
import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Objects; import java.util.function.Function; import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.xml.bind.JAXBException; import com.google.common.collect.Iterables; import org.apache.spark.ml.PipelineModel; import org.apache.spark.ml.PipelineStage; import org.apache.spark.ml.Transformer; import org.apache.spark.ml.linalg.Vector; import org.apache.spark.ml.param.shared.HasPredictionCol; import org.apache.spark.ml.param.shared.HasProbabilityCol; import org.apache.spark.ml.regression.GeneralizedLinearRegressionModel; import org.apache.spark.ml.tuning.CrossValidatorModel; import org.apache.spark.ml.tuning.TrainValidationSplitModel; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.types.StructType; import org.dmg.pmml.DerivedField; import org.dmg.pmml.FieldName; import org.dmg.pmml.MiningField; import org.dmg.pmml.MiningFunction; import org.dmg.pmml.MiningSchema; import org.dmg.pmml.Output; import org.dmg.pmml.OutputField; import org.dmg.pmml.PMML; import org.dmg.pmml.ResultFeature; import org.dmg.pmml.VerificationField; import org.jpmml.converter.Feature; import org.jpmml.converter.ModelUtil; import org.jpmml.converter.SchemaUtil; import org.jpmml.converter.mining.MiningModelUtil; import org.jpmml.model.metro.MetroJAXBUtil; import org.jpmml.sparkml.model.HasFeatureImportances; import org.jpmml.sparkml.model.HasTreeOptions;
SparkMLEncoder encoder = new SparkMLEncoder(schema, converterFactory); Map<FieldName, DerivedField> derivedFields = encoder.getDerivedFields(); List<org.dmg.pmml.Model> models = new ArrayList<>(); List<String> predictionColumns = new ArrayList<>(); List<String> probabilityColumns = new ArrayList<>(); // Transformations preceding the last model List<FieldName> preProcessorNames = Collections.emptyList(); Iterable<Transformer> transformers = getTransformers(pipelineModel); for(Transformer transformer : transformers){ TransformerConverter<?> converter = converterFactory.newConverter(transformer); if(converter instanceof FeatureConverter){ FeatureConverter<?> featureConverter = (FeatureConverter<?>)converter; featureConverter.registerFeatures(encoder); } else if(converter instanceof ModelConverter){ ModelConverter<?> modelConverter = (ModelConverter<?>)converter; org.dmg.pmml.Model model = modelConverter.registerModel(encoder); models.add(model); featureImportances:
// Path: src/main/java/org/jpmml/sparkml/model/HasFeatureImportances.java // public interface HasFeatureImportances { // // Vector getFeatureImportances(); // } // // Path: src/main/java/org/jpmml/sparkml/model/HasTreeOptions.java // public interface HasTreeOptions extends HasSparkMLOptions, HasNativeConfiguration { // // /** // * @see TreeModelCompactor // */ // String OPTION_COMPACT = "compact"; // // String OPTION_ESTIMATE_FEATURE_IMPORTANCES = "estimate_featureImportances"; // // @Override // default // public Map<String, ?> getNativeConfiguration(){ // Map<String, Object> result = new LinkedHashMap<>(); // result.put(HasTreeOptions.OPTION_COMPACT, Boolean.FALSE); // // return result; // } // } // Path: src/main/java/org/jpmml/sparkml/PMMLBuilder.java import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Objects; import java.util.function.Function; import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.xml.bind.JAXBException; import com.google.common.collect.Iterables; import org.apache.spark.ml.PipelineModel; import org.apache.spark.ml.PipelineStage; import org.apache.spark.ml.Transformer; import org.apache.spark.ml.linalg.Vector; import org.apache.spark.ml.param.shared.HasPredictionCol; import org.apache.spark.ml.param.shared.HasProbabilityCol; import org.apache.spark.ml.regression.GeneralizedLinearRegressionModel; import org.apache.spark.ml.tuning.CrossValidatorModel; import org.apache.spark.ml.tuning.TrainValidationSplitModel; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.types.StructType; import org.dmg.pmml.DerivedField; import org.dmg.pmml.FieldName; import org.dmg.pmml.MiningField; import org.dmg.pmml.MiningFunction; import org.dmg.pmml.MiningSchema; import org.dmg.pmml.Output; import org.dmg.pmml.OutputField; import org.dmg.pmml.PMML; import org.dmg.pmml.ResultFeature; import org.dmg.pmml.VerificationField; import org.jpmml.converter.Feature; import org.jpmml.converter.ModelUtil; import org.jpmml.converter.SchemaUtil; import org.jpmml.converter.mining.MiningModelUtil; import org.jpmml.model.metro.MetroJAXBUtil; import org.jpmml.sparkml.model.HasFeatureImportances; import org.jpmml.sparkml.model.HasTreeOptions; SparkMLEncoder encoder = new SparkMLEncoder(schema, converterFactory); Map<FieldName, DerivedField> derivedFields = encoder.getDerivedFields(); List<org.dmg.pmml.Model> models = new ArrayList<>(); List<String> predictionColumns = new ArrayList<>(); List<String> probabilityColumns = new ArrayList<>(); // Transformations preceding the last model List<FieldName> preProcessorNames = Collections.emptyList(); Iterable<Transformer> transformers = getTransformers(pipelineModel); for(Transformer transformer : transformers){ TransformerConverter<?> converter = converterFactory.newConverter(transformer); if(converter instanceof FeatureConverter){ FeatureConverter<?> featureConverter = (FeatureConverter<?>)converter; featureConverter.registerFeatures(encoder); } else if(converter instanceof ModelConverter){ ModelConverter<?> modelConverter = (ModelConverter<?>)converter; org.dmg.pmml.Model model = modelConverter.registerModel(encoder); models.add(model); featureImportances:
if(modelConverter instanceof HasFeatureImportances){
jpmml/jpmml-sparkml
src/main/java/org/jpmml/sparkml/PMMLBuilder.java
// Path: src/main/java/org/jpmml/sparkml/model/HasFeatureImportances.java // public interface HasFeatureImportances { // // Vector getFeatureImportances(); // } // // Path: src/main/java/org/jpmml/sparkml/model/HasTreeOptions.java // public interface HasTreeOptions extends HasSparkMLOptions, HasNativeConfiguration { // // /** // * @see TreeModelCompactor // */ // String OPTION_COMPACT = "compact"; // // String OPTION_ESTIMATE_FEATURE_IMPORTANCES = "estimate_featureImportances"; // // @Override // default // public Map<String, ?> getNativeConfiguration(){ // Map<String, Object> result = new LinkedHashMap<>(); // result.put(HasTreeOptions.OPTION_COMPACT, Boolean.FALSE); // // return result; // } // }
import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Objects; import java.util.function.Function; import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.xml.bind.JAXBException; import com.google.common.collect.Iterables; import org.apache.spark.ml.PipelineModel; import org.apache.spark.ml.PipelineStage; import org.apache.spark.ml.Transformer; import org.apache.spark.ml.linalg.Vector; import org.apache.spark.ml.param.shared.HasPredictionCol; import org.apache.spark.ml.param.shared.HasProbabilityCol; import org.apache.spark.ml.regression.GeneralizedLinearRegressionModel; import org.apache.spark.ml.tuning.CrossValidatorModel; import org.apache.spark.ml.tuning.TrainValidationSplitModel; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.types.StructType; import org.dmg.pmml.DerivedField; import org.dmg.pmml.FieldName; import org.dmg.pmml.MiningField; import org.dmg.pmml.MiningFunction; import org.dmg.pmml.MiningSchema; import org.dmg.pmml.Output; import org.dmg.pmml.OutputField; import org.dmg.pmml.PMML; import org.dmg.pmml.ResultFeature; import org.dmg.pmml.VerificationField; import org.jpmml.converter.Feature; import org.jpmml.converter.ModelUtil; import org.jpmml.converter.SchemaUtil; import org.jpmml.converter.mining.MiningModelUtil; import org.jpmml.model.metro.MetroJAXBUtil; import org.jpmml.sparkml.model.HasFeatureImportances; import org.jpmml.sparkml.model.HasTreeOptions;
List<org.dmg.pmml.Model> models = new ArrayList<>(); List<String> predictionColumns = new ArrayList<>(); List<String> probabilityColumns = new ArrayList<>(); // Transformations preceding the last model List<FieldName> preProcessorNames = Collections.emptyList(); Iterable<Transformer> transformers = getTransformers(pipelineModel); for(Transformer transformer : transformers){ TransformerConverter<?> converter = converterFactory.newConverter(transformer); if(converter instanceof FeatureConverter){ FeatureConverter<?> featureConverter = (FeatureConverter<?>)converter; featureConverter.registerFeatures(encoder); } else if(converter instanceof ModelConverter){ ModelConverter<?> modelConverter = (ModelConverter<?>)converter; org.dmg.pmml.Model model = modelConverter.registerModel(encoder); models.add(model); featureImportances: if(modelConverter instanceof HasFeatureImportances){ HasFeatureImportances hasFeatureImportances = (HasFeatureImportances)modelConverter;
// Path: src/main/java/org/jpmml/sparkml/model/HasFeatureImportances.java // public interface HasFeatureImportances { // // Vector getFeatureImportances(); // } // // Path: src/main/java/org/jpmml/sparkml/model/HasTreeOptions.java // public interface HasTreeOptions extends HasSparkMLOptions, HasNativeConfiguration { // // /** // * @see TreeModelCompactor // */ // String OPTION_COMPACT = "compact"; // // String OPTION_ESTIMATE_FEATURE_IMPORTANCES = "estimate_featureImportances"; // // @Override // default // public Map<String, ?> getNativeConfiguration(){ // Map<String, Object> result = new LinkedHashMap<>(); // result.put(HasTreeOptions.OPTION_COMPACT, Boolean.FALSE); // // return result; // } // } // Path: src/main/java/org/jpmml/sparkml/PMMLBuilder.java import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Objects; import java.util.function.Function; import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.xml.bind.JAXBException; import com.google.common.collect.Iterables; import org.apache.spark.ml.PipelineModel; import org.apache.spark.ml.PipelineStage; import org.apache.spark.ml.Transformer; import org.apache.spark.ml.linalg.Vector; import org.apache.spark.ml.param.shared.HasPredictionCol; import org.apache.spark.ml.param.shared.HasProbabilityCol; import org.apache.spark.ml.regression.GeneralizedLinearRegressionModel; import org.apache.spark.ml.tuning.CrossValidatorModel; import org.apache.spark.ml.tuning.TrainValidationSplitModel; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.types.StructType; import org.dmg.pmml.DerivedField; import org.dmg.pmml.FieldName; import org.dmg.pmml.MiningField; import org.dmg.pmml.MiningFunction; import org.dmg.pmml.MiningSchema; import org.dmg.pmml.Output; import org.dmg.pmml.OutputField; import org.dmg.pmml.PMML; import org.dmg.pmml.ResultFeature; import org.dmg.pmml.VerificationField; import org.jpmml.converter.Feature; import org.jpmml.converter.ModelUtil; import org.jpmml.converter.SchemaUtil; import org.jpmml.converter.mining.MiningModelUtil; import org.jpmml.model.metro.MetroJAXBUtil; import org.jpmml.sparkml.model.HasFeatureImportances; import org.jpmml.sparkml.model.HasTreeOptions; List<org.dmg.pmml.Model> models = new ArrayList<>(); List<String> predictionColumns = new ArrayList<>(); List<String> probabilityColumns = new ArrayList<>(); // Transformations preceding the last model List<FieldName> preProcessorNames = Collections.emptyList(); Iterable<Transformer> transformers = getTransformers(pipelineModel); for(Transformer transformer : transformers){ TransformerConverter<?> converter = converterFactory.newConverter(transformer); if(converter instanceof FeatureConverter){ FeatureConverter<?> featureConverter = (FeatureConverter<?>)converter; featureConverter.registerFeatures(encoder); } else if(converter instanceof ModelConverter){ ModelConverter<?> modelConverter = (ModelConverter<?>)converter; org.dmg.pmml.Model model = modelConverter.registerModel(encoder); models.add(model); featureImportances: if(modelConverter instanceof HasFeatureImportances){ HasFeatureImportances hasFeatureImportances = (HasFeatureImportances)modelConverter;
Boolean estimateFeatureImportances = (Boolean)modelConverter.getOption(HasTreeOptions.OPTION_ESTIMATE_FEATURE_IMPORTANCES, Boolean.FALSE);
qiniu/android-netdiag
library/src/main/java/com/qiniu/android/netdiag/NsLookup.java
// Path: library/src/main/java/com/qiniu/android/netdiag/localdns/Record.java // public final class Record { // /** // * A 记录 类型 // */ // public static final int TYPE_A = 1; // // /** // * CName 类型 // */ // public static final int TYPE_CNAME = 5; // // /** // * 具体的值,A 记录时为IP,Cname时为指向的域名 // */ // public final String value; // // /** // * 记录类型,A或者CName // */ // public final int type; // // /** // * TTL dns结果缓存时间 // */ // public final int ttl; // // /** // * 时间戳,用来判断超时 // */ // public final long timeStamp; // // public Record(String value, int type, int ttl, long timeStamp) { // this.value = value; // this.type = type; // this.ttl = ttl; // this.timeStamp = timeStamp; // } // // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || !(o instanceof Record)) { // return false; // } // Record another = (Record) o; // return this.value.equals(another.value) // && this.type == another.type // && this.ttl == another.ttl // && this.timeStamp == another.timeStamp; // } // // public boolean isA() { // return type == TYPE_A; // } // // // public String toString() { // String t; // if (type == TYPE_A) { // t = "A"; // } else if (type == TYPE_CNAME) { // t = "CNAME"; // } else { // t = "type-" + type; // } // // return String.format(Locale.ENGLISH, "%s\t%s\t%d", t, value, ttl); // } // } // // Path: library/src/main/java/com/qiniu/android/netdiag/localdns/Resolver.java // public final class Resolver { // private static final Random random = new Random(); // // final InetAddress address; // // public Resolver(InetAddress address) { // this.address = address; // } // // public Record[] resolve(String domain) throws IOException { // int id; // synchronized (random) { // id = random.nextInt() & 0XFF; // } // byte[] query = DnsMessage.buildQuery(domain, id); // byte[] answer = udpCommunicate(query); // if (answer == null) { // throw new DnsException(domain, "cant get answer"); // } // // return DnsMessage.parseResponse(answer, id, domain); // } // // private byte[] udpCommunicate(byte[] question) throws IOException { // DatagramSocket socket = null; // try { // socket = new DatagramSocket(); // DatagramPacket packet = new DatagramPacket(question, question.length, // address, 53); // socket.setSoTimeout(10000); // socket.send(packet); // packet = new DatagramPacket(new byte[1500], 1500); // socket.receive(packet); // // return packet.getData(); // } finally { // if (socket != null) { // socket.close(); // } // } // } // }
import com.qiniu.android.netdiag.localdns.Record; import com.qiniu.android.netdiag.localdns.Resolver; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException;
this.complete = complete; } public static void start(String domain, Output output, Callback complete) { start(domain, null, output, complete); } public static void start(String domain, String serverIp, Output output, Callback complete) { if (serverIp == null) { String[] s = DNS.local(); if (s != null) { serverIp = s[0]; } } final NsLookup t = new NsLookup(domain, serverIp, output, complete); Util.runInBack(new Runnable() { @Override public void run() { t.run(); } }); } private void run() { if (serverIp == null) { Result r = new Result(-1, 0, null); complete.complete(r); return; }
// Path: library/src/main/java/com/qiniu/android/netdiag/localdns/Record.java // public final class Record { // /** // * A 记录 类型 // */ // public static final int TYPE_A = 1; // // /** // * CName 类型 // */ // public static final int TYPE_CNAME = 5; // // /** // * 具体的值,A 记录时为IP,Cname时为指向的域名 // */ // public final String value; // // /** // * 记录类型,A或者CName // */ // public final int type; // // /** // * TTL dns结果缓存时间 // */ // public final int ttl; // // /** // * 时间戳,用来判断超时 // */ // public final long timeStamp; // // public Record(String value, int type, int ttl, long timeStamp) { // this.value = value; // this.type = type; // this.ttl = ttl; // this.timeStamp = timeStamp; // } // // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || !(o instanceof Record)) { // return false; // } // Record another = (Record) o; // return this.value.equals(another.value) // && this.type == another.type // && this.ttl == another.ttl // && this.timeStamp == another.timeStamp; // } // // public boolean isA() { // return type == TYPE_A; // } // // // public String toString() { // String t; // if (type == TYPE_A) { // t = "A"; // } else if (type == TYPE_CNAME) { // t = "CNAME"; // } else { // t = "type-" + type; // } // // return String.format(Locale.ENGLISH, "%s\t%s\t%d", t, value, ttl); // } // } // // Path: library/src/main/java/com/qiniu/android/netdiag/localdns/Resolver.java // public final class Resolver { // private static final Random random = new Random(); // // final InetAddress address; // // public Resolver(InetAddress address) { // this.address = address; // } // // public Record[] resolve(String domain) throws IOException { // int id; // synchronized (random) { // id = random.nextInt() & 0XFF; // } // byte[] query = DnsMessage.buildQuery(domain, id); // byte[] answer = udpCommunicate(query); // if (answer == null) { // throw new DnsException(domain, "cant get answer"); // } // // return DnsMessage.parseResponse(answer, id, domain); // } // // private byte[] udpCommunicate(byte[] question) throws IOException { // DatagramSocket socket = null; // try { // socket = new DatagramSocket(); // DatagramPacket packet = new DatagramPacket(question, question.length, // address, 53); // socket.setSoTimeout(10000); // socket.send(packet); // packet = new DatagramPacket(new byte[1500], 1500); // socket.receive(packet); // // return packet.getData(); // } finally { // if (socket != null) { // socket.close(); // } // } // } // } // Path: library/src/main/java/com/qiniu/android/netdiag/NsLookup.java import com.qiniu.android.netdiag.localdns.Record; import com.qiniu.android.netdiag.localdns.Resolver; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; this.complete = complete; } public static void start(String domain, Output output, Callback complete) { start(domain, null, output, complete); } public static void start(String domain, String serverIp, Output output, Callback complete) { if (serverIp == null) { String[] s = DNS.local(); if (s != null) { serverIp = s[0]; } } final NsLookup t = new NsLookup(domain, serverIp, output, complete); Util.runInBack(new Runnable() { @Override public void run() { t.run(); } }); } private void run() { if (serverIp == null) { Result r = new Result(-1, 0, null); complete.complete(r); return; }
Resolver r = null;
qiniu/android-netdiag
library/src/main/java/com/qiniu/android/netdiag/NsLookup.java
// Path: library/src/main/java/com/qiniu/android/netdiag/localdns/Record.java // public final class Record { // /** // * A 记录 类型 // */ // public static final int TYPE_A = 1; // // /** // * CName 类型 // */ // public static final int TYPE_CNAME = 5; // // /** // * 具体的值,A 记录时为IP,Cname时为指向的域名 // */ // public final String value; // // /** // * 记录类型,A或者CName // */ // public final int type; // // /** // * TTL dns结果缓存时间 // */ // public final int ttl; // // /** // * 时间戳,用来判断超时 // */ // public final long timeStamp; // // public Record(String value, int type, int ttl, long timeStamp) { // this.value = value; // this.type = type; // this.ttl = ttl; // this.timeStamp = timeStamp; // } // // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || !(o instanceof Record)) { // return false; // } // Record another = (Record) o; // return this.value.equals(another.value) // && this.type == another.type // && this.ttl == another.ttl // && this.timeStamp == another.timeStamp; // } // // public boolean isA() { // return type == TYPE_A; // } // // // public String toString() { // String t; // if (type == TYPE_A) { // t = "A"; // } else if (type == TYPE_CNAME) { // t = "CNAME"; // } else { // t = "type-" + type; // } // // return String.format(Locale.ENGLISH, "%s\t%s\t%d", t, value, ttl); // } // } // // Path: library/src/main/java/com/qiniu/android/netdiag/localdns/Resolver.java // public final class Resolver { // private static final Random random = new Random(); // // final InetAddress address; // // public Resolver(InetAddress address) { // this.address = address; // } // // public Record[] resolve(String domain) throws IOException { // int id; // synchronized (random) { // id = random.nextInt() & 0XFF; // } // byte[] query = DnsMessage.buildQuery(domain, id); // byte[] answer = udpCommunicate(query); // if (answer == null) { // throw new DnsException(domain, "cant get answer"); // } // // return DnsMessage.parseResponse(answer, id, domain); // } // // private byte[] udpCommunicate(byte[] question) throws IOException { // DatagramSocket socket = null; // try { // socket = new DatagramSocket(); // DatagramPacket packet = new DatagramPacket(question, question.length, // address, 53); // socket.setSoTimeout(10000); // socket.send(packet); // packet = new DatagramPacket(new byte[1500], 1500); // socket.receive(packet); // // return packet.getData(); // } finally { // if (socket != null) { // socket.close(); // } // } // } // }
import com.qiniu.android.netdiag.localdns.Record; import com.qiniu.android.netdiag.localdns.Resolver; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException;
} final NsLookup t = new NsLookup(domain, serverIp, output, complete); Util.runInBack(new Runnable() { @Override public void run() { t.run(); } }); } private void run() { if (serverIp == null) { Result r = new Result(-1, 0, null); complete.complete(r); return; } Resolver r = null; output.write("nslookup " + domain + " @" + serverIp); try { r = new Resolver(InetAddress.getByName(serverIp)); } catch (UnknownHostException e) { Result result = new Result(-1, 0, null); output.write("nslookup server invalid"); complete.complete(result); return; } try { long start = System.currentTimeMillis();
// Path: library/src/main/java/com/qiniu/android/netdiag/localdns/Record.java // public final class Record { // /** // * A 记录 类型 // */ // public static final int TYPE_A = 1; // // /** // * CName 类型 // */ // public static final int TYPE_CNAME = 5; // // /** // * 具体的值,A 记录时为IP,Cname时为指向的域名 // */ // public final String value; // // /** // * 记录类型,A或者CName // */ // public final int type; // // /** // * TTL dns结果缓存时间 // */ // public final int ttl; // // /** // * 时间戳,用来判断超时 // */ // public final long timeStamp; // // public Record(String value, int type, int ttl, long timeStamp) { // this.value = value; // this.type = type; // this.ttl = ttl; // this.timeStamp = timeStamp; // } // // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || !(o instanceof Record)) { // return false; // } // Record another = (Record) o; // return this.value.equals(another.value) // && this.type == another.type // && this.ttl == another.ttl // && this.timeStamp == another.timeStamp; // } // // public boolean isA() { // return type == TYPE_A; // } // // // public String toString() { // String t; // if (type == TYPE_A) { // t = "A"; // } else if (type == TYPE_CNAME) { // t = "CNAME"; // } else { // t = "type-" + type; // } // // return String.format(Locale.ENGLISH, "%s\t%s\t%d", t, value, ttl); // } // } // // Path: library/src/main/java/com/qiniu/android/netdiag/localdns/Resolver.java // public final class Resolver { // private static final Random random = new Random(); // // final InetAddress address; // // public Resolver(InetAddress address) { // this.address = address; // } // // public Record[] resolve(String domain) throws IOException { // int id; // synchronized (random) { // id = random.nextInt() & 0XFF; // } // byte[] query = DnsMessage.buildQuery(domain, id); // byte[] answer = udpCommunicate(query); // if (answer == null) { // throw new DnsException(domain, "cant get answer"); // } // // return DnsMessage.parseResponse(answer, id, domain); // } // // private byte[] udpCommunicate(byte[] question) throws IOException { // DatagramSocket socket = null; // try { // socket = new DatagramSocket(); // DatagramPacket packet = new DatagramPacket(question, question.length, // address, 53); // socket.setSoTimeout(10000); // socket.send(packet); // packet = new DatagramPacket(new byte[1500], 1500); // socket.receive(packet); // // return packet.getData(); // } finally { // if (socket != null) { // socket.close(); // } // } // } // } // Path: library/src/main/java/com/qiniu/android/netdiag/NsLookup.java import com.qiniu.android.netdiag.localdns.Record; import com.qiniu.android.netdiag.localdns.Resolver; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; } final NsLookup t = new NsLookup(domain, serverIp, output, complete); Util.runInBack(new Runnable() { @Override public void run() { t.run(); } }); } private void run() { if (serverIp == null) { Result r = new Result(-1, 0, null); complete.complete(r); return; } Resolver r = null; output.write("nslookup " + domain + " @" + serverIp); try { r = new Resolver(InetAddress.getByName(serverIp)); } catch (UnknownHostException e) { Result result = new Result(-1, 0, null); output.write("nslookup server invalid"); complete.complete(result); return; } try { long start = System.currentTimeMillis();
Record[] records = r.resolve(domain);
ykaragol/checkersmaster
CheckersMaster/test/checkers/domain/TestModel.java
// Path: CheckersMaster/src/checkers/sandbox/SquareState.java // public enum SquareState{ // BLANK (null), // WHITE (Player.WHITE), // BLACK (Player.BLACK), // KING_WHITE (Player.WHITE), // KING_BLACK (Player.BLACK); // // public final Player owner; // // private SquareState(Player owner){ // this.owner = owner; // } // // public SquareState convertKing() { // if(this==WHITE || this==BLACK) // return values()[this.ordinal()+2]; // return this; // } // // public SquareState convertNormal() { // if(this==KING_WHITE || this==KING_BLACK) // return values()[this.ordinal()-2]; // return this; // } // // public boolean isKing(){ // return (this==KING_BLACK || this==KING_WHITE); // } // }
import static org.junit.Assert.*; import org.junit.Test; import checkers.sandbox.SquareState;
package checkers.domain; public class TestModel { @Test public void testBaslat() { Model model = new Model(); model.baslat();
// Path: CheckersMaster/src/checkers/sandbox/SquareState.java // public enum SquareState{ // BLANK (null), // WHITE (Player.WHITE), // BLACK (Player.BLACK), // KING_WHITE (Player.WHITE), // KING_BLACK (Player.BLACK); // // public final Player owner; // // private SquareState(Player owner){ // this.owner = owner; // } // // public SquareState convertKing() { // if(this==WHITE || this==BLACK) // return values()[this.ordinal()+2]; // return this; // } // // public SquareState convertNormal() { // if(this==KING_WHITE || this==KING_BLACK) // return values()[this.ordinal()-2]; // return this; // } // // public boolean isKing(){ // return (this==KING_BLACK || this==KING_WHITE); // } // } // Path: CheckersMaster/test/checkers/domain/TestModel.java import static org.junit.Assert.*; import org.junit.Test; import checkers.sandbox.SquareState; package checkers.domain; public class TestModel { @Test public void testBaslat() { Model model = new Model(); model.baslat();
assertEquals(SquareState.WHITE, model.state[0][0]);
ykaragol/checkersmaster
CheckersMaster/src/checkers/domain/CalculationContext.java
// Path: CheckersMaster/src/checkers/algorithm/IAlgorithm.java // public interface IAlgorithm { // Move algorithm(CalculationContext context, Model model, Player whosTurn); // // String getName(); // } // // Path: CheckersMaster/src/checkers/evaluation/IEvaluation.java // public interface IEvaluation { // double evaluate(Model model, Player player); // } // // Path: CheckersMaster/src/checkers/rules/ISuccessor.java // public interface ISuccessor { // List<Move> getSuccessors(Model model, Player player); // }
import checkers.algorithm.IAlgorithm; import checkers.evaluation.IEvaluation; import checkers.rules.ISuccessor;
package checkers.domain; /** * Tüm algoritmalar için yapılandırma parametreleri içerir. * */ public class CalculationContext{ private int depth; private Player player;
// Path: CheckersMaster/src/checkers/algorithm/IAlgorithm.java // public interface IAlgorithm { // Move algorithm(CalculationContext context, Model model, Player whosTurn); // // String getName(); // } // // Path: CheckersMaster/src/checkers/evaluation/IEvaluation.java // public interface IEvaluation { // double evaluate(Model model, Player player); // } // // Path: CheckersMaster/src/checkers/rules/ISuccessor.java // public interface ISuccessor { // List<Move> getSuccessors(Model model, Player player); // } // Path: CheckersMaster/src/checkers/domain/CalculationContext.java import checkers.algorithm.IAlgorithm; import checkers.evaluation.IEvaluation; import checkers.rules.ISuccessor; package checkers.domain; /** * Tüm algoritmalar için yapılandırma parametreleri içerir. * */ public class CalculationContext{ private int depth; private Player player;
private IEvaluation evaluationFunction;
ykaragol/checkersmaster
CheckersMaster/src/checkers/domain/CalculationContext.java
// Path: CheckersMaster/src/checkers/algorithm/IAlgorithm.java // public interface IAlgorithm { // Move algorithm(CalculationContext context, Model model, Player whosTurn); // // String getName(); // } // // Path: CheckersMaster/src/checkers/evaluation/IEvaluation.java // public interface IEvaluation { // double evaluate(Model model, Player player); // } // // Path: CheckersMaster/src/checkers/rules/ISuccessor.java // public interface ISuccessor { // List<Move> getSuccessors(Model model, Player player); // }
import checkers.algorithm.IAlgorithm; import checkers.evaluation.IEvaluation; import checkers.rules.ISuccessor;
package checkers.domain; /** * Tüm algoritmalar için yapılandırma parametreleri içerir. * */ public class CalculationContext{ private int depth; private Player player; private IEvaluation evaluationFunction;
// Path: CheckersMaster/src/checkers/algorithm/IAlgorithm.java // public interface IAlgorithm { // Move algorithm(CalculationContext context, Model model, Player whosTurn); // // String getName(); // } // // Path: CheckersMaster/src/checkers/evaluation/IEvaluation.java // public interface IEvaluation { // double evaluate(Model model, Player player); // } // // Path: CheckersMaster/src/checkers/rules/ISuccessor.java // public interface ISuccessor { // List<Move> getSuccessors(Model model, Player player); // } // Path: CheckersMaster/src/checkers/domain/CalculationContext.java import checkers.algorithm.IAlgorithm; import checkers.evaluation.IEvaluation; import checkers.rules.ISuccessor; package checkers.domain; /** * Tüm algoritmalar için yapılandırma parametreleri içerir. * */ public class CalculationContext{ private int depth; private Player player; private IEvaluation evaluationFunction;
private ISuccessor successorFunction;
ykaragol/checkersmaster
CheckersMaster/src/checkers/domain/CalculationContext.java
// Path: CheckersMaster/src/checkers/algorithm/IAlgorithm.java // public interface IAlgorithm { // Move algorithm(CalculationContext context, Model model, Player whosTurn); // // String getName(); // } // // Path: CheckersMaster/src/checkers/evaluation/IEvaluation.java // public interface IEvaluation { // double evaluate(Model model, Player player); // } // // Path: CheckersMaster/src/checkers/rules/ISuccessor.java // public interface ISuccessor { // List<Move> getSuccessors(Model model, Player player); // }
import checkers.algorithm.IAlgorithm; import checkers.evaluation.IEvaluation; import checkers.rules.ISuccessor;
package checkers.domain; /** * Tüm algoritmalar için yapılandırma parametreleri içerir. * */ public class CalculationContext{ private int depth; private Player player; private IEvaluation evaluationFunction; private ISuccessor successorFunction;
// Path: CheckersMaster/src/checkers/algorithm/IAlgorithm.java // public interface IAlgorithm { // Move algorithm(CalculationContext context, Model model, Player whosTurn); // // String getName(); // } // // Path: CheckersMaster/src/checkers/evaluation/IEvaluation.java // public interface IEvaluation { // double evaluate(Model model, Player player); // } // // Path: CheckersMaster/src/checkers/rules/ISuccessor.java // public interface ISuccessor { // List<Move> getSuccessors(Model model, Player player); // } // Path: CheckersMaster/src/checkers/domain/CalculationContext.java import checkers.algorithm.IAlgorithm; import checkers.evaluation.IEvaluation; import checkers.rules.ISuccessor; package checkers.domain; /** * Tüm algoritmalar için yapılandırma parametreleri içerir. * */ public class CalculationContext{ private int depth; private Player player; private IEvaluation evaluationFunction; private ISuccessor successorFunction;
private IAlgorithm algorithm;
ykaragol/checkersmaster
CheckersMaster/src/checkers/sandbox/SquareState.java
// Path: CheckersMaster/src/checkers/domain/Player.java // public enum Player { // WHITE, // BLACK; // // public Player opposite() { // return this==WHITE ? BLACK : WHITE; // } // }
import checkers.domain.Player;
package checkers.sandbox; public enum SquareState{ BLANK (null),
// Path: CheckersMaster/src/checkers/domain/Player.java // public enum Player { // WHITE, // BLACK; // // public Player opposite() { // return this==WHITE ? BLACK : WHITE; // } // } // Path: CheckersMaster/src/checkers/sandbox/SquareState.java import checkers.domain.Player; package checkers.sandbox; public enum SquareState{ BLANK (null),
WHITE (Player.WHITE),
ykaragol/checkersmaster
CheckersMaster/src/checkers/domain/Move.java
// Path: CheckersMaster/src/checkers/sandbox/SquareState.java // public enum SquareState{ // BLANK (null), // WHITE (Player.WHITE), // BLACK (Player.BLACK), // KING_WHITE (Player.WHITE), // KING_BLACK (Player.BLACK); // // public final Player owner; // // private SquareState(Player owner){ // this.owner = owner; // } // // public SquareState convertKing() { // if(this==WHITE || this==BLACK) // return values()[this.ordinal()+2]; // return this; // } // // public SquareState convertNormal() { // if(this==KING_WHITE || this==KING_BLACK) // return values()[this.ordinal()-2]; // return this; // } // // public boolean isKing(){ // return (this==KING_BLACK || this==KING_WHITE); // } // }
import checkers.sandbox.SquareState;
package checkers.domain; public class Move { private double value = Double.NEGATIVE_INFINITY; public int fromX; public int fromY; public int toX; public int toY; public boolean must = false;
// Path: CheckersMaster/src/checkers/sandbox/SquareState.java // public enum SquareState{ // BLANK (null), // WHITE (Player.WHITE), // BLACK (Player.BLACK), // KING_WHITE (Player.WHITE), // KING_BLACK (Player.BLACK); // // public final Player owner; // // private SquareState(Player owner){ // this.owner = owner; // } // // public SquareState convertKing() { // if(this==WHITE || this==BLACK) // return values()[this.ordinal()+2]; // return this; // } // // public SquareState convertNormal() { // if(this==KING_WHITE || this==KING_BLACK) // return values()[this.ordinal()-2]; // return this; // } // // public boolean isKing(){ // return (this==KING_BLACK || this==KING_WHITE); // } // } // Path: CheckersMaster/src/checkers/domain/Move.java import checkers.sandbox.SquareState; package checkers.domain; public class Move { private double value = Double.NEGATIVE_INFINITY; public int fromX; public int fromY; public int toX; public int toY; public boolean must = false;
public SquareState eat;
ykaragol/checkersmaster
CheckersMaster/src/checkers/domain/Model.java
// Path: CheckersMaster/src/checkers/controller/GameCenter.java // public class GameCenter { // // /** // * Oyunun tahtası // */ // private Model model; // // // /** // // * Tahtada yapılan değişiklikleri dinleyecek sınıflar // // */ // // private List<ModelListener> listeners = new LinkedList<ModelListener>(); // // private Engine blackPlayer; // // //private Engine whitePlayer; // // private Board board; // // private boolean lock=true; // // // public void center(){ // // while(true){ // // //whitePlayer.playTurn(model); // // while(lock){ // // try { // // Thread.sleep(50); // // } catch (InterruptedException e) { // // // TODO Auto-generated catch block // // e.printStackTrace(); // // } // // } // // blackPlayer.playTurn(model); // // } // // } // // public void update(){ // if(gameFinished) // return; // lock=!lock; // if(!lock){ // List<Move> listBlack = successors.getSuccessors(model, Player.BLACK); // if(listBlack==null || listBlack.size()==0){ // System.err.println("yenildim!"); // callback.gameFinished(false); // gameFinished = true; // board.updateUI(); // return; // } // blackPlayer.playTurn(model); // List<Move> listWhite = successors.getSuccessors(model, Player.WHITE); // if(listWhite==null || listWhite.size()==0){ // System.err.println("yendim!"); // callback.gameFinished(true); // gameFinished = true; // } // } // board.updateUI(); // } // // private boolean gameFinished ; // // private Successors successors; // // private MainView callback; // // public GameCenter(){ // model = new Model(); // model.setCallback(this); // initNewGame(); // } // // public void initNewGame() { // model.baslat(); // // blackPlayer = new Engine(Player.BLACK); // CalculationContext calculationContext = new CalculationContext(); // calculationContext.setAlgorithm(new MinimaxAlgorithm()); // calculationContext.setDepth(6); // calculationContext.setEvaluationFunction(new EnhancedWeightenedMenCountEvaluation()); // calculationContext.setPlayer(Player.BLACK); // successors = new Successors(); // calculationContext.setSuccessorFunction(successors); // blackPlayer.setCalculationContext(calculationContext); // if(board!=null) // board.updateUI(); // gameFinished = false; // } // // public void configurationChanged(ConfigurationModel newConfigurationModel){ // CalculationContext calculationContext = new CalculationContext(); // calculationContext.setAlgorithm(newConfigurationModel.getSelectedAlgorithm()); // calculationContext.setDepth(newConfigurationModel.getSelectedDepth()); // calculationContext.setEvaluationFunction(newConfigurationModel.getSelectedEvaluation()); // calculationContext.setPlayer(Player.BLACK); // calculationContext.setSuccessorFunction(successors); // blackPlayer.setCalculationContext(calculationContext); // } // // public Model getModel() { // return model; // } // // public void setBoard(Board board) { // this.board = board; // board.setModel(model); // } // // public void setCallback(MainView mainView) { // this.callback = mainView; // } // } // // Path: CheckersMaster/src/checkers/sandbox/SquareState.java // public enum SquareState{ // BLANK (null), // WHITE (Player.WHITE), // BLACK (Player.BLACK), // KING_WHITE (Player.WHITE), // KING_BLACK (Player.BLACK); // // public final Player owner; // // private SquareState(Player owner){ // this.owner = owner; // } // // public SquareState convertKing() { // if(this==WHITE || this==BLACK) // return values()[this.ordinal()+2]; // return this; // } // // public SquareState convertNormal() { // if(this==KING_WHITE || this==KING_BLACK) // return values()[this.ordinal()-2]; // return this; // } // // public boolean isKing(){ // return (this==KING_BLACK || this==KING_WHITE); // } // }
import checkers.controller.GameCenter; import checkers.sandbox.SquareState;
package checkers.domain; public class Model { public SquareState state[][];
// Path: CheckersMaster/src/checkers/controller/GameCenter.java // public class GameCenter { // // /** // * Oyunun tahtası // */ // private Model model; // // // /** // // * Tahtada yapılan değişiklikleri dinleyecek sınıflar // // */ // // private List<ModelListener> listeners = new LinkedList<ModelListener>(); // // private Engine blackPlayer; // // //private Engine whitePlayer; // // private Board board; // // private boolean lock=true; // // // public void center(){ // // while(true){ // // //whitePlayer.playTurn(model); // // while(lock){ // // try { // // Thread.sleep(50); // // } catch (InterruptedException e) { // // // TODO Auto-generated catch block // // e.printStackTrace(); // // } // // } // // blackPlayer.playTurn(model); // // } // // } // // public void update(){ // if(gameFinished) // return; // lock=!lock; // if(!lock){ // List<Move> listBlack = successors.getSuccessors(model, Player.BLACK); // if(listBlack==null || listBlack.size()==0){ // System.err.println("yenildim!"); // callback.gameFinished(false); // gameFinished = true; // board.updateUI(); // return; // } // blackPlayer.playTurn(model); // List<Move> listWhite = successors.getSuccessors(model, Player.WHITE); // if(listWhite==null || listWhite.size()==0){ // System.err.println("yendim!"); // callback.gameFinished(true); // gameFinished = true; // } // } // board.updateUI(); // } // // private boolean gameFinished ; // // private Successors successors; // // private MainView callback; // // public GameCenter(){ // model = new Model(); // model.setCallback(this); // initNewGame(); // } // // public void initNewGame() { // model.baslat(); // // blackPlayer = new Engine(Player.BLACK); // CalculationContext calculationContext = new CalculationContext(); // calculationContext.setAlgorithm(new MinimaxAlgorithm()); // calculationContext.setDepth(6); // calculationContext.setEvaluationFunction(new EnhancedWeightenedMenCountEvaluation()); // calculationContext.setPlayer(Player.BLACK); // successors = new Successors(); // calculationContext.setSuccessorFunction(successors); // blackPlayer.setCalculationContext(calculationContext); // if(board!=null) // board.updateUI(); // gameFinished = false; // } // // public void configurationChanged(ConfigurationModel newConfigurationModel){ // CalculationContext calculationContext = new CalculationContext(); // calculationContext.setAlgorithm(newConfigurationModel.getSelectedAlgorithm()); // calculationContext.setDepth(newConfigurationModel.getSelectedDepth()); // calculationContext.setEvaluationFunction(newConfigurationModel.getSelectedEvaluation()); // calculationContext.setPlayer(Player.BLACK); // calculationContext.setSuccessorFunction(successors); // blackPlayer.setCalculationContext(calculationContext); // } // // public Model getModel() { // return model; // } // // public void setBoard(Board board) { // this.board = board; // board.setModel(model); // } // // public void setCallback(MainView mainView) { // this.callback = mainView; // } // } // // Path: CheckersMaster/src/checkers/sandbox/SquareState.java // public enum SquareState{ // BLANK (null), // WHITE (Player.WHITE), // BLACK (Player.BLACK), // KING_WHITE (Player.WHITE), // KING_BLACK (Player.BLACK); // // public final Player owner; // // private SquareState(Player owner){ // this.owner = owner; // } // // public SquareState convertKing() { // if(this==WHITE || this==BLACK) // return values()[this.ordinal()+2]; // return this; // } // // public SquareState convertNormal() { // if(this==KING_WHITE || this==KING_BLACK) // return values()[this.ordinal()-2]; // return this; // } // // public boolean isKing(){ // return (this==KING_BLACK || this==KING_WHITE); // } // } // Path: CheckersMaster/src/checkers/domain/Model.java import checkers.controller.GameCenter; import checkers.sandbox.SquareState; package checkers.domain; public class Model { public SquareState state[][];
private GameCenter callBack;
msk610/3D-TETRIS
html/src/com/tetris/game/client/HtmlLauncher.java
// Path: core/src/com/tetris/game/Tetris.java // public class Tetris extends Game { // AssetLoader assets; // ButtonLoader buttonLoader; // Button music, sound; // // @Override // public void create () { // assets = new AssetLoader(); // buttonLoader = new ButtonLoader(assets); // music = buttonLoader.getMusic(); // sound = buttonLoader.getSound(); // setScreen(new Menu(this,assets,buttonLoader,music,sound)); // } // // @Override // public void render () { // super.render(); // } // }
import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.backends.gwt.GwtApplication; import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration; import com.tetris.game.Tetris;
package com.tetris.game.client; public class HtmlLauncher extends GwtApplication { @Override public GwtApplicationConfiguration getConfig () { return new GwtApplicationConfiguration(480, 320); } @Override public ApplicationListener getApplicationListener () {
// Path: core/src/com/tetris/game/Tetris.java // public class Tetris extends Game { // AssetLoader assets; // ButtonLoader buttonLoader; // Button music, sound; // // @Override // public void create () { // assets = new AssetLoader(); // buttonLoader = new ButtonLoader(assets); // music = buttonLoader.getMusic(); // sound = buttonLoader.getSound(); // setScreen(new Menu(this,assets,buttonLoader,music,sound)); // } // // @Override // public void render () { // super.render(); // } // } // Path: html/src/com/tetris/game/client/HtmlLauncher.java import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.backends.gwt.GwtApplication; import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration; import com.tetris.game.Tetris; package com.tetris.game.client; public class HtmlLauncher extends GwtApplication { @Override public GwtApplicationConfiguration getConfig () { return new GwtApplicationConfiguration(480, 320); } @Override public ApplicationListener getApplicationListener () {
return new Tetris();
msk610/3D-TETRIS
ios/src/com/tetris/game/IOSLauncher.java
// Path: core/src/com/tetris/game/Tetris.java // public class Tetris extends Game { // AssetLoader assets; // ButtonLoader buttonLoader; // Button music, sound; // // @Override // public void create () { // assets = new AssetLoader(); // buttonLoader = new ButtonLoader(assets); // music = buttonLoader.getMusic(); // sound = buttonLoader.getSound(); // setScreen(new Menu(this,assets,buttonLoader,music,sound)); // } // // @Override // public void render () { // super.render(); // } // }
import org.robovm.apple.foundation.NSAutoreleasePool; import org.robovm.apple.uikit.UIApplication; import com.badlogic.gdx.backends.iosrobovm.IOSApplication; import com.badlogic.gdx.backends.iosrobovm.IOSApplicationConfiguration; import com.tetris.game.Tetris;
package com.tetris.game; public class IOSLauncher extends IOSApplication.Delegate { @Override protected IOSApplication createApplication() { IOSApplicationConfiguration config = new IOSApplicationConfiguration();
// Path: core/src/com/tetris/game/Tetris.java // public class Tetris extends Game { // AssetLoader assets; // ButtonLoader buttonLoader; // Button music, sound; // // @Override // public void create () { // assets = new AssetLoader(); // buttonLoader = new ButtonLoader(assets); // music = buttonLoader.getMusic(); // sound = buttonLoader.getSound(); // setScreen(new Menu(this,assets,buttonLoader,music,sound)); // } // // @Override // public void render () { // super.render(); // } // } // Path: ios/src/com/tetris/game/IOSLauncher.java import org.robovm.apple.foundation.NSAutoreleasePool; import org.robovm.apple.uikit.UIApplication; import com.badlogic.gdx.backends.iosrobovm.IOSApplication; import com.badlogic.gdx.backends.iosrobovm.IOSApplicationConfiguration; import com.tetris.game.Tetris; package com.tetris.game; public class IOSLauncher extends IOSApplication.Delegate { @Override protected IOSApplication createApplication() { IOSApplicationConfiguration config = new IOSApplicationConfiguration();
return new IOSApplication(new Tetris(), config);
msk610/3D-TETRIS
desktop/src/com/tetris/game/desktop/DesktopLauncher.java
// Path: core/src/com/tetris/game/Tetris.java // public class Tetris extends Game { // AssetLoader assets; // ButtonLoader buttonLoader; // Button music, sound; // // @Override // public void create () { // assets = new AssetLoader(); // buttonLoader = new ButtonLoader(assets); // music = buttonLoader.getMusic(); // sound = buttonLoader.getSound(); // setScreen(new Menu(this,assets,buttonLoader,music,sound)); // } // // @Override // public void render () { // super.render(); // } // }
import com.badlogic.gdx.Files; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import com.tetris.game.Tetris;
package com.tetris.game.desktop; public class DesktopLauncher { public static void main (String[] arg) { LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); config.title = "3D TETRIS"; config.addIcon("Pictures/icon.png", Files.FileType.Internal); config.resizable = false;
// Path: core/src/com/tetris/game/Tetris.java // public class Tetris extends Game { // AssetLoader assets; // ButtonLoader buttonLoader; // Button music, sound; // // @Override // public void create () { // assets = new AssetLoader(); // buttonLoader = new ButtonLoader(assets); // music = buttonLoader.getMusic(); // sound = buttonLoader.getSound(); // setScreen(new Menu(this,assets,buttonLoader,music,sound)); // } // // @Override // public void render () { // super.render(); // } // } // Path: desktop/src/com/tetris/game/desktop/DesktopLauncher.java import com.badlogic.gdx.Files; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import com.tetris.game.Tetris; package com.tetris.game.desktop; public class DesktopLauncher { public static void main (String[] arg) { LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); config.title = "3D TETRIS"; config.addIcon("Pictures/icon.png", Files.FileType.Internal); config.resizable = false;
new LwjglApplication(new Tetris(), config);
msk610/3D-TETRIS
android/src/com/tetris/game/android/AndroidLauncher.java
// Path: core/src/com/tetris/game/Tetris.java // public class Tetris extends Game { // AssetLoader assets; // ButtonLoader buttonLoader; // Button music, sound; // // @Override // public void create () { // assets = new AssetLoader(); // buttonLoader = new ButtonLoader(assets); // music = buttonLoader.getMusic(); // sound = buttonLoader.getSound(); // setScreen(new Menu(this,assets,buttonLoader,music,sound)); // } // // @Override // public void render () { // super.render(); // } // }
import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration; import com.tetris.game.Tetris;
package com.tetris.game.android; public class AndroidLauncher extends AndroidApplication { @Override protected void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
// Path: core/src/com/tetris/game/Tetris.java // public class Tetris extends Game { // AssetLoader assets; // ButtonLoader buttonLoader; // Button music, sound; // // @Override // public void create () { // assets = new AssetLoader(); // buttonLoader = new ButtonLoader(assets); // music = buttonLoader.getMusic(); // sound = buttonLoader.getSound(); // setScreen(new Menu(this,assets,buttonLoader,music,sound)); // } // // @Override // public void render () { // super.render(); // } // } // Path: android/src/com/tetris/game/android/AndroidLauncher.java import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration; import com.tetris.game.Tetris; package com.tetris.game.android; public class AndroidLauncher extends AndroidApplication { @Override protected void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
initialize(new Tetris(), config);
jonhare/COMP3204
app/src/main/java/uk/ac/soton/ecs/comp3204/l3/MeanCenteredFacesDemo.java
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l3/FaceDatasetDemo.java // public static class FaceDatasetProvider { // static File tmpFile; // static { // try { // tmpFile = File.createTempFile("faces", ".zip"); // FileUtils.copyURLToFile(FaceDatasetDemo.class.getResource("att_faces.zip"), tmpFile); // tmpFile.deleteOnExit(); // } catch (final Exception e) { // e.printStackTrace(); // } // } // // public static VFSGroupDataset<FImage> getDataset() throws FileSystemException { // return new VFSGroupDataset<FImage>("zip:" + tmpFile.toURI(), ImageUtilities.FIMAGE_READER); // } // } // // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // }
import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridBagLayout; import java.io.IOException; import javax.swing.JPanel; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.data.dataset.VFSGroupDataset; import org.openimaj.image.DisplayUtilities.ImageComponent; import org.openimaj.image.FImage; import org.openimaj.image.ImageUtilities; import uk.ac.soton.ecs.comp3204.l3.FaceDatasetDemo.FaceDatasetProvider; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration;
package uk.ac.soton.ecs.comp3204.l3; /** * Visualise mean-centered face images * * @author Jonathon Hare ([email protected]) * */ @Demonstration(title = "Mean-centred faces demo") public class MeanCenteredFacesDemo implements Slide { @Override public Component getComponent(int width, int height) throws IOException {
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l3/FaceDatasetDemo.java // public static class FaceDatasetProvider { // static File tmpFile; // static { // try { // tmpFile = File.createTempFile("faces", ".zip"); // FileUtils.copyURLToFile(FaceDatasetDemo.class.getResource("att_faces.zip"), tmpFile); // tmpFile.deleteOnExit(); // } catch (final Exception e) { // e.printStackTrace(); // } // } // // public static VFSGroupDataset<FImage> getDataset() throws FileSystemException { // return new VFSGroupDataset<FImage>("zip:" + tmpFile.toURI(), ImageUtilities.FIMAGE_READER); // } // } // // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // } // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l3/MeanCenteredFacesDemo.java import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridBagLayout; import java.io.IOException; import javax.swing.JPanel; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.data.dataset.VFSGroupDataset; import org.openimaj.image.DisplayUtilities.ImageComponent; import org.openimaj.image.FImage; import org.openimaj.image.ImageUtilities; import uk.ac.soton.ecs.comp3204.l3.FaceDatasetDemo.FaceDatasetProvider; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration; package uk.ac.soton.ecs.comp3204.l3; /** * Visualise mean-centered face images * * @author Jonathon Hare ([email protected]) * */ @Demonstration(title = "Mean-centred faces demo") public class MeanCenteredFacesDemo implements Slide { @Override public Component getComponent(int width, int height) throws IOException {
final VFSGroupDataset<FImage> dataset = FaceDatasetProvider.getDataset();
jonhare/COMP3204
app/src/main/java/uk/ac/soton/ecs/comp3204/l3/MeanCenteredFacesDemo.java
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l3/FaceDatasetDemo.java // public static class FaceDatasetProvider { // static File tmpFile; // static { // try { // tmpFile = File.createTempFile("faces", ".zip"); // FileUtils.copyURLToFile(FaceDatasetDemo.class.getResource("att_faces.zip"), tmpFile); // tmpFile.deleteOnExit(); // } catch (final Exception e) { // e.printStackTrace(); // } // } // // public static VFSGroupDataset<FImage> getDataset() throws FileSystemException { // return new VFSGroupDataset<FImage>("zip:" + tmpFile.toURI(), ImageUtilities.FIMAGE_READER); // } // } // // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // }
import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridBagLayout; import java.io.IOException; import javax.swing.JPanel; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.data.dataset.VFSGroupDataset; import org.openimaj.image.DisplayUtilities.ImageComponent; import org.openimaj.image.FImage; import org.openimaj.image.ImageUtilities; import uk.ac.soton.ecs.comp3204.l3.FaceDatasetDemo.FaceDatasetProvider; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration;
outer.setOpaque(false); outer.setPreferredSize(new Dimension(width, height)); outer.setLayout(new GridBagLayout()); final JPanel base = new JPanel(); base.setOpaque(false); base.setPreferredSize(new Dimension(width, height - 50)); base.setLayout(new FlowLayout()); for (int i = 0; i < 60; i++) { final FImage img = dataset.getRandomInstance().subtract(mean).normalise(); final ImageComponent ic = new ImageComponent(true, false); ic.setAllowPanning(false); ic.setAllowZoom(false); ic.setShowPixelColours(false); ic.setShowXYPosition(false); ic.setImage(ImageUtilities.createBufferedImageForDisplay(img)); base.add(ic); } outer.add(base); return outer; } @Override public void close() { // do nothing } public static void main(String[] args) throws IOException {
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l3/FaceDatasetDemo.java // public static class FaceDatasetProvider { // static File tmpFile; // static { // try { // tmpFile = File.createTempFile("faces", ".zip"); // FileUtils.copyURLToFile(FaceDatasetDemo.class.getResource("att_faces.zip"), tmpFile); // tmpFile.deleteOnExit(); // } catch (final Exception e) { // e.printStackTrace(); // } // } // // public static VFSGroupDataset<FImage> getDataset() throws FileSystemException { // return new VFSGroupDataset<FImage>("zip:" + tmpFile.toURI(), ImageUtilities.FIMAGE_READER); // } // } // // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // } // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l3/MeanCenteredFacesDemo.java import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridBagLayout; import java.io.IOException; import javax.swing.JPanel; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.data.dataset.VFSGroupDataset; import org.openimaj.image.DisplayUtilities.ImageComponent; import org.openimaj.image.FImage; import org.openimaj.image.ImageUtilities; import uk.ac.soton.ecs.comp3204.l3.FaceDatasetDemo.FaceDatasetProvider; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration; outer.setOpaque(false); outer.setPreferredSize(new Dimension(width, height)); outer.setLayout(new GridBagLayout()); final JPanel base = new JPanel(); base.setOpaque(false); base.setPreferredSize(new Dimension(width, height - 50)); base.setLayout(new FlowLayout()); for (int i = 0; i < 60; i++) { final FImage img = dataset.getRandomInstance().subtract(mean).normalise(); final ImageComponent ic = new ImageComponent(true, false); ic.setAllowPanning(false); ic.setAllowZoom(false); ic.setShowPixelColours(false); ic.setShowXYPosition(false); ic.setImage(ImageUtilities.createBufferedImageForDisplay(img)); base.add(ic); } outer.add(base); return outer; } @Override public void close() { // do nothing } public static void main(String[] args) throws IOException {
new SlideshowApplication(new MeanCenteredFacesDemo(), 1024, 768, Utils.BACKGROUND_IMAGE);
jonhare/COMP3204
app/src/main/java/uk/ac/soton/ecs/comp3204/l8/SpectrogramDemo.java
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // }
import java.io.IOException; import org.openimaj.audio.AudioFormat; import org.openimaj.audio.AudioGrabberListener; import org.openimaj.audio.JavaSoundAudioGrabber; import org.openimaj.audio.SampleChunk; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.vis.audio.AudioSpectrogram; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration; import java.awt.Component;
while (grabber.isStopped()) { try { Thread.sleep(50); } catch (final InterruptedException e) { } } return spectrogram; } @Override public void close() { if (grabber != null) { grabber.stop(); grabber = null; } } @Override public void samplesAvailable(SampleChunk s) { spectrogram.setData(s); spectrogram.update(); } /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException {
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // } // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l8/SpectrogramDemo.java import java.io.IOException; import org.openimaj.audio.AudioFormat; import org.openimaj.audio.AudioGrabberListener; import org.openimaj.audio.JavaSoundAudioGrabber; import org.openimaj.audio.SampleChunk; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.vis.audio.AudioSpectrogram; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration; import java.awt.Component; while (grabber.isStopped()) { try { Thread.sleep(50); } catch (final InterruptedException e) { } } return spectrogram; } @Override public void close() { if (grabber != null) { grabber.stop(); grabber = null; } } @Override public void samplesAvailable(SampleChunk s) { spectrogram.setData(s); spectrogram.update(); } /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException {
new SlideshowApplication(new SpectrogramDemo(), 1024, 768, Utils.BACKGROUND_IMAGE);
jonhare/COMP3204
app/src/main/java/uk/ac/soton/ecs/comp3204/l6/Lecture6.java
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // }
import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.openimaj.content.slideshow.PictureSlide; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.JvmArgs; import uk.ac.soton.ecs.comp3204.utils.annotations.Lecture;
slides.add(new HarrisResponseDemo()); for (int i = 19; i <= 20; i++) slides.add(new PictureSlide(Lecture6.class.getResource(String.format("l6.%03d.jpg", i)))); slides.add(new ThresholdedHarrisResponseDemo()); for (int i = 21; i <= 21; i++) slides.add(new PictureSlide(Lecture6.class.getResource(String.format("l6.%03d.jpg", i)))); slides.add(new HarrisPointsDemo()); for (int i = 22; i <= 31; i++) slides.add(new PictureSlide(Lecture6.class.getResource(String.format("l6.%03d.jpg", i)))); slides.add(new MultiscaleHarrisPointsDemo()); for (int i = 32; i <= 38; i++) slides.add(new PictureSlide(Lecture6.class.getResource(String.format("l6.%03d.jpg", i)))); slides.add(new DoGResponseDemo()); for (int i = 39; i <= 40; i++) slides.add(new PictureSlide(Lecture6.class.getResource(String.format("l6.%03d.jpg", i)))); slides.add(new DoGPointsDemo()); for (int i = 41; i <= 41; i++) slides.add(new PictureSlide(Lecture6.class.getResource(String.format("l6.%03d.jpg", i))));
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // } // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l6/Lecture6.java import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.openimaj.content.slideshow.PictureSlide; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.JvmArgs; import uk.ac.soton.ecs.comp3204.utils.annotations.Lecture; slides.add(new HarrisResponseDemo()); for (int i = 19; i <= 20; i++) slides.add(new PictureSlide(Lecture6.class.getResource(String.format("l6.%03d.jpg", i)))); slides.add(new ThresholdedHarrisResponseDemo()); for (int i = 21; i <= 21; i++) slides.add(new PictureSlide(Lecture6.class.getResource(String.format("l6.%03d.jpg", i)))); slides.add(new HarrisPointsDemo()); for (int i = 22; i <= 31; i++) slides.add(new PictureSlide(Lecture6.class.getResource(String.format("l6.%03d.jpg", i)))); slides.add(new MultiscaleHarrisPointsDemo()); for (int i = 32; i <= 38; i++) slides.add(new PictureSlide(Lecture6.class.getResource(String.format("l6.%03d.jpg", i)))); slides.add(new DoGResponseDemo()); for (int i = 39; i <= 40; i++) slides.add(new PictureSlide(Lecture6.class.getResource(String.format("l6.%03d.jpg", i)))); slides.add(new DoGPointsDemo()); for (int i = 41; i <= 41; i++) slides.add(new PictureSlide(Lecture6.class.getResource(String.format("l6.%03d.jpg", i))));
new SlideshowApplication(slides, 1024, 768, Utils.BACKGROUND_IMAGE);
jonhare/COMP3204
app/src/main/java/uk/ac/soton/ecs/comp3204/l4/GlobalThresholdDemo.java
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // }
import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagLayout; import java.awt.image.BufferedImage; import java.io.IOException; import javax.swing.BoxLayout; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.JTextField; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.image.DisplayUtilities.ImageComponent; import org.openimaj.image.FImage; import org.openimaj.image.ImageUtilities; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration;
cb.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if (cb.isSelected()) { final float threshold = slider.getValue() / 255f; ic.setImage(bimg = ImageUtilities .createBufferedImageForDisplay(oimage.clone().threshold(threshold), bimg)); } else { ic.setImage(bimg = ImageUtilities.createBufferedImageForDisplay(oimage, bimg)); } } }); container.add(slider); container.add(valueField); base.add(container); outer.add(base); return outer; } @Override public void close() { // do nothing } public static void main(String[] args) throws IOException { new SlideshowApplication(new GlobalThresholdDemo(), 1024, 768,
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // } // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l4/GlobalThresholdDemo.java import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagLayout; import java.awt.image.BufferedImage; import java.io.IOException; import javax.swing.BoxLayout; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.JTextField; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.image.DisplayUtilities.ImageComponent; import org.openimaj.image.FImage; import org.openimaj.image.ImageUtilities; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration; cb.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if (cb.isSelected()) { final float threshold = slider.getValue() / 255f; ic.setImage(bimg = ImageUtilities .createBufferedImageForDisplay(oimage.clone().threshold(threshold), bimg)); } else { ic.setImage(bimg = ImageUtilities.createBufferedImageForDisplay(oimage, bimg)); } } }); container.add(slider); container.add(valueField); base.add(container); outer.add(base); return outer; } @Override public void close() { // do nothing } public static void main(String[] args) throws IOException { new SlideshowApplication(new GlobalThresholdDemo(), 1024, 768,
Utils.BACKGROUND_IMAGE);
jonhare/COMP3204
app/src/main/java/uk/ac/soton/ecs/comp3204/l0/Lecture0.java
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // }
import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.openimaj.content.slideshow.PictureSlide; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.JvmArgs; import uk.ac.soton.ecs.comp3204.utils.annotations.Lecture;
package uk.ac.soton.ecs.comp3204.l0; @Lecture(title = "L0: Fork Me!", handoutsURL = "", slidesURL = "http://jonhare.github.io/COMP3204/lectures/pdf/L0-forkme.pdf") @JvmArgs(vmArguments = "-Xmx1G") public class Lecture0 { public static void main(String[] args) throws IOException { final List<Slide> slides = new ArrayList<Slide>(); for (int i = 1; i <= 4; i++) slides.add(new PictureSlide(Lecture0.class.getResource(String.format("l0.%03d.jpg", i))));
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // } // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l0/Lecture0.java import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.openimaj.content.slideshow.PictureSlide; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.JvmArgs; import uk.ac.soton.ecs.comp3204.utils.annotations.Lecture; package uk.ac.soton.ecs.comp3204.l0; @Lecture(title = "L0: Fork Me!", handoutsURL = "", slidesURL = "http://jonhare.github.io/COMP3204/lectures/pdf/L0-forkme.pdf") @JvmArgs(vmArguments = "-Xmx1G") public class Lecture0 { public static void main(String[] args) throws IOException { final List<Slide> slides = new ArrayList<Slide>(); for (int i = 1; i <= 4; i++) slides.add(new PictureSlide(Lecture0.class.getResource(String.format("l0.%03d.jpg", i))));
new SlideshowApplication(slides, 1024, 768, Utils.BACKGROUND_IMAGE);
jonhare/COMP3204
app/src/main/java/uk/ac/soton/ecs/comp3204/l4/KMeansSpatialSegmentationDemo.java
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // }
import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.List; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.feature.FloatFVComparison; import org.openimaj.image.DisplayUtilities.ImageComponent; import org.openimaj.image.ImageUtilities; import org.openimaj.image.MBFImage; import org.openimaj.image.colour.ColourSpace; import org.openimaj.image.pixel.PixelSet; import org.openimaj.image.segmentation.KMSpatialColourSegmenter; import org.openimaj.image.segmentation.SegmentationUtilities; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration;
public void run() { ic.setImage(bimg = ImageUtilities.createBufferedImageForDisplay( segmentImage(oimage, (Integer) kSpinner.getValue(), (Integer) wSpinner.getValue()), bimg)); segmentBtn.setEnabled(true); kSpinner.setEnabled(true); wSpinner.setEnabled(true); } }).start(); } }); return base; } protected MBFImage segmentImage(MBFImage oimage, int k, int weight) { final KMSpatialColourSegmenter seg = new KMSpatialColourSegmenter(ColourSpace.CIE_Lab, new float[] { 1, 1, 1, weight, weight }, k, FloatFVComparison.EUCLIDEAN); final List<? extends PixelSet> result = seg.segment(oimage); return SegmentationUtilities.renderSegments(oimage.getWidth(), oimage.getHeight(), result); } @Override public void close() { // do nothing } public static void main(String[] args) throws IOException {
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // } // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l4/KMeansSpatialSegmentationDemo.java import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.List; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.feature.FloatFVComparison; import org.openimaj.image.DisplayUtilities.ImageComponent; import org.openimaj.image.ImageUtilities; import org.openimaj.image.MBFImage; import org.openimaj.image.colour.ColourSpace; import org.openimaj.image.pixel.PixelSet; import org.openimaj.image.segmentation.KMSpatialColourSegmenter; import org.openimaj.image.segmentation.SegmentationUtilities; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration; public void run() { ic.setImage(bimg = ImageUtilities.createBufferedImageForDisplay( segmentImage(oimage, (Integer) kSpinner.getValue(), (Integer) wSpinner.getValue()), bimg)); segmentBtn.setEnabled(true); kSpinner.setEnabled(true); wSpinner.setEnabled(true); } }).start(); } }); return base; } protected MBFImage segmentImage(MBFImage oimage, int k, int weight) { final KMSpatialColourSegmenter seg = new KMSpatialColourSegmenter(ColourSpace.CIE_Lab, new float[] { 1, 1, 1, weight, weight }, k, FloatFVComparison.EUCLIDEAN); final List<? extends PixelSet> result = seg.segment(oimage); return SegmentationUtilities.renderSegments(oimage.getWidth(), oimage.getHeight(), result); } @Override public void close() { // do nothing } public static void main(String[] args) throws IOException {
new SlideshowApplication(new KMeansSpatialSegmentationDemo(), 1024, 768, Utils.BACKGROUND_IMAGE);
jonhare/COMP3204
app/src/main/java/uk/ac/soton/ecs/comp3204/l7/Lecture7.java
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // }
import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.openimaj.content.slideshow.PictureSlide; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.JvmArgs; import uk.ac.soton.ecs.comp3204.utils.annotations.Lecture;
package uk.ac.soton.ecs.comp3204.l7; @Lecture(title = "L7: Local features and matching", handoutsURL = "http://jonhare.github.io/COMP3204/handouts/pdf/L7-matching.pdf", slidesURL = "http://jonhare.github.io/COMP3204/lectures/pdf/L7-matching.pdf") @JvmArgs(vmArguments = "-Xmx1G") public class Lecture7 { public static void main(String[] args) throws IOException { final List<Slide> slides = new ArrayList<Slide>(); for (int i = 1; i <= 24; i++) slides.add(new PictureSlide(Lecture7.class.getResource(String.format("l7.%03d.jpg", i)))); slides.add(new NarrowBaselineTemplatesDemo()); for (int i = 25; i <= 31; i++) slides.add(new PictureSlide(Lecture7.class.getResource(String.format("l7.%03d.jpg", i)))); slides.add(new LocalisationSensitivityDemo()); for (int i = 32; i <= 35; i++) slides.add(new PictureSlide(Lecture7.class.getResource(String.format("l7.%03d.jpg", i)))); slides.add(new GradOriDemo()); for (int i = 36; i <= 46; i++) slides.add(new PictureSlide(Lecture7.class.getResource(String.format("l7.%03d.jpg", i)))); slides.add(new EucMatchingDemo()); for (int i = 47; i <= 48; i++) slides.add(new PictureSlide(Lecture7.class.getResource(String.format("l7.%03d.jpg", i)))); slides.add(new MatchingDemo()); for (int i = 49; i <= 49; i++) slides.add(new PictureSlide(Lecture7.class.getResource(String.format("l7.%03d.jpg", i))));
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // } // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l7/Lecture7.java import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.openimaj.content.slideshow.PictureSlide; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.JvmArgs; import uk.ac.soton.ecs.comp3204.utils.annotations.Lecture; package uk.ac.soton.ecs.comp3204.l7; @Lecture(title = "L7: Local features and matching", handoutsURL = "http://jonhare.github.io/COMP3204/handouts/pdf/L7-matching.pdf", slidesURL = "http://jonhare.github.io/COMP3204/lectures/pdf/L7-matching.pdf") @JvmArgs(vmArguments = "-Xmx1G") public class Lecture7 { public static void main(String[] args) throws IOException { final List<Slide> slides = new ArrayList<Slide>(); for (int i = 1; i <= 24; i++) slides.add(new PictureSlide(Lecture7.class.getResource(String.format("l7.%03d.jpg", i)))); slides.add(new NarrowBaselineTemplatesDemo()); for (int i = 25; i <= 31; i++) slides.add(new PictureSlide(Lecture7.class.getResource(String.format("l7.%03d.jpg", i)))); slides.add(new LocalisationSensitivityDemo()); for (int i = 32; i <= 35; i++) slides.add(new PictureSlide(Lecture7.class.getResource(String.format("l7.%03d.jpg", i)))); slides.add(new GradOriDemo()); for (int i = 36; i <= 46; i++) slides.add(new PictureSlide(Lecture7.class.getResource(String.format("l7.%03d.jpg", i)))); slides.add(new EucMatchingDemo()); for (int i = 47; i <= 48; i++) slides.add(new PictureSlide(Lecture7.class.getResource(String.format("l7.%03d.jpg", i)))); slides.add(new MatchingDemo()); for (int i = 49; i <= 49; i++) slides.add(new PictureSlide(Lecture7.class.getResource(String.format("l7.%03d.jpg", i))));
new SlideshowApplication(slides, 1024, 768, Utils.BACKGROUND_IMAGE);
jonhare/COMP3204
app/src/main/java/uk/ac/soton/ecs/comp3204/l3/MeanFaceDemo.java
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l3/FaceDatasetDemo.java // public static class FaceDatasetProvider { // static File tmpFile; // static { // try { // tmpFile = File.createTempFile("faces", ".zip"); // FileUtils.copyURLToFile(FaceDatasetDemo.class.getResource("att_faces.zip"), tmpFile); // tmpFile.deleteOnExit(); // } catch (final Exception e) { // e.printStackTrace(); // } // } // // public static VFSGroupDataset<FImage> getDataset() throws FileSystemException { // return new VFSGroupDataset<FImage>("zip:" + tmpFile.toURI(), ImageUtilities.FIMAGE_READER); // } // } // // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // }
import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagLayout; import java.io.IOException; import javax.swing.JPanel; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.data.dataset.VFSGroupDataset; import org.openimaj.image.DisplayUtilities.ImageComponent; import org.openimaj.image.FImage; import org.openimaj.image.ImageUtilities; import org.openimaj.image.processing.resize.ResizeProcessor; import uk.ac.soton.ecs.comp3204.l3.FaceDatasetDemo.FaceDatasetProvider; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration;
package uk.ac.soton.ecs.comp3204.l3; /** * Visualise the mean face * * @author Jonathon Hare ([email protected]) * */ @Demonstration(title = "Mean face demo") public class MeanFaceDemo implements Slide { @Override public Component getComponent(int width, int height) throws IOException {
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l3/FaceDatasetDemo.java // public static class FaceDatasetProvider { // static File tmpFile; // static { // try { // tmpFile = File.createTempFile("faces", ".zip"); // FileUtils.copyURLToFile(FaceDatasetDemo.class.getResource("att_faces.zip"), tmpFile); // tmpFile.deleteOnExit(); // } catch (final Exception e) { // e.printStackTrace(); // } // } // // public static VFSGroupDataset<FImage> getDataset() throws FileSystemException { // return new VFSGroupDataset<FImage>("zip:" + tmpFile.toURI(), ImageUtilities.FIMAGE_READER); // } // } // // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // } // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l3/MeanFaceDemo.java import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagLayout; import java.io.IOException; import javax.swing.JPanel; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.data.dataset.VFSGroupDataset; import org.openimaj.image.DisplayUtilities.ImageComponent; import org.openimaj.image.FImage; import org.openimaj.image.ImageUtilities; import org.openimaj.image.processing.resize.ResizeProcessor; import uk.ac.soton.ecs.comp3204.l3.FaceDatasetDemo.FaceDatasetProvider; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration; package uk.ac.soton.ecs.comp3204.l3; /** * Visualise the mean face * * @author Jonathon Hare ([email protected]) * */ @Demonstration(title = "Mean face demo") public class MeanFaceDemo implements Slide { @Override public Component getComponent(int width, int height) throws IOException {
final VFSGroupDataset<FImage> dataset = FaceDatasetProvider.getDataset();
jonhare/COMP3204
app/src/main/java/uk/ac/soton/ecs/comp3204/l3/MeanFaceDemo.java
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l3/FaceDatasetDemo.java // public static class FaceDatasetProvider { // static File tmpFile; // static { // try { // tmpFile = File.createTempFile("faces", ".zip"); // FileUtils.copyURLToFile(FaceDatasetDemo.class.getResource("att_faces.zip"), tmpFile); // tmpFile.deleteOnExit(); // } catch (final Exception e) { // e.printStackTrace(); // } // } // // public static VFSGroupDataset<FImage> getDataset() throws FileSystemException { // return new VFSGroupDataset<FImage>("zip:" + tmpFile.toURI(), ImageUtilities.FIMAGE_READER); // } // } // // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // }
import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagLayout; import java.io.IOException; import javax.swing.JPanel; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.data.dataset.VFSGroupDataset; import org.openimaj.image.DisplayUtilities.ImageComponent; import org.openimaj.image.FImage; import org.openimaj.image.ImageUtilities; import org.openimaj.image.processing.resize.ResizeProcessor; import uk.ac.soton.ecs.comp3204.l3.FaceDatasetDemo.FaceDatasetProvider; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration;
package uk.ac.soton.ecs.comp3204.l3; /** * Visualise the mean face * * @author Jonathon Hare ([email protected]) * */ @Demonstration(title = "Mean face demo") public class MeanFaceDemo implements Slide { @Override public Component getComponent(int width, int height) throws IOException { final VFSGroupDataset<FImage> dataset = FaceDatasetProvider.getDataset(); final FImage img = dataset.getRandomInstance().fill(0f); for (final FImage i : dataset) { img.addInplace(i); } img.divideInplace(dataset.numInstances()).processInplace(new ResizeProcessor(6.0f)); final JPanel outer = new JPanel(); outer.setOpaque(false); outer.setPreferredSize(new Dimension(width, height)); outer.setLayout(new GridBagLayout()); final ImageComponent ic = new ImageComponent(true, false); ic.setAllowPanning(false); ic.setAllowZoom(false); ic.setShowPixelColours(false); ic.setShowXYPosition(false); ic.setImage(ImageUtilities.createBufferedImageForDisplay(img)); outer.add(ic); return outer; } @Override public void close() { // do nothing } public static void main(String[] args) throws IOException {
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l3/FaceDatasetDemo.java // public static class FaceDatasetProvider { // static File tmpFile; // static { // try { // tmpFile = File.createTempFile("faces", ".zip"); // FileUtils.copyURLToFile(FaceDatasetDemo.class.getResource("att_faces.zip"), tmpFile); // tmpFile.deleteOnExit(); // } catch (final Exception e) { // e.printStackTrace(); // } // } // // public static VFSGroupDataset<FImage> getDataset() throws FileSystemException { // return new VFSGroupDataset<FImage>("zip:" + tmpFile.toURI(), ImageUtilities.FIMAGE_READER); // } // } // // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // } // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l3/MeanFaceDemo.java import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagLayout; import java.io.IOException; import javax.swing.JPanel; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.data.dataset.VFSGroupDataset; import org.openimaj.image.DisplayUtilities.ImageComponent; import org.openimaj.image.FImage; import org.openimaj.image.ImageUtilities; import org.openimaj.image.processing.resize.ResizeProcessor; import uk.ac.soton.ecs.comp3204.l3.FaceDatasetDemo.FaceDatasetProvider; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration; package uk.ac.soton.ecs.comp3204.l3; /** * Visualise the mean face * * @author Jonathon Hare ([email protected]) * */ @Demonstration(title = "Mean face demo") public class MeanFaceDemo implements Slide { @Override public Component getComponent(int width, int height) throws IOException { final VFSGroupDataset<FImage> dataset = FaceDatasetProvider.getDataset(); final FImage img = dataset.getRandomInstance().fill(0f); for (final FImage i : dataset) { img.addInplace(i); } img.divideInplace(dataset.numInstances()).processInplace(new ResizeProcessor(6.0f)); final JPanel outer = new JPanel(); outer.setOpaque(false); outer.setPreferredSize(new Dimension(width, height)); outer.setLayout(new GridBagLayout()); final ImageComponent ic = new ImageComponent(true, false); ic.setAllowPanning(false); ic.setAllowZoom(false); ic.setShowPixelColours(false); ic.setShowXYPosition(false); ic.setImage(ImageUtilities.createBufferedImageForDisplay(img)); outer.add(ic); return outer; } @Override public void close() { // do nothing } public static void main(String[] args) throws IOException {
new SlideshowApplication(new MeanFaceDemo(), 1024, 768, Utils.BACKGROUND_IMAGE);
jonhare/COMP3204
app/src/main/java/uk/ac/soton/ecs/comp3204/l5/AlignmentDemo.java
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // }
import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagLayout; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.swing.JPanel; import javax.swing.JTabbedPane; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.image.DisplayUtilities.ImageComponent; import org.openimaj.image.ImageUtilities; import org.openimaj.image.MBFImage; import org.openimaj.image.colour.ColourSpace; import org.openimaj.image.colour.RGBColour; import org.openimaj.image.model.asm.datasets.AMToolsSampleDataset; import org.openimaj.image.model.asm.datasets.ShapeModelDataset; import org.openimaj.math.geometry.line.Line2d; import org.openimaj.math.geometry.point.PointList; import org.openimaj.math.geometry.point.PointListConnections; import org.openimaj.math.geometry.shape.algorithm.GeneralisedProcrustesAnalysis; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration;
Float[][] colours) { final MBFImage image = new MBFImage(width, height - 20, ColourSpace.RGB).fill(RGBColour.BLACK); int i = 0; for (final PointList p : points) { final PointList pts = p.clone(); pts.scale(1.5f); final Float[] c = colours[i++]; image.drawPoints(pts, c, 5); for (final Line2d line : pts.getLines(connections)) { image.drawLine(line, 3, c); } } final ImageComponent ic = new ImageComponent(true, true); ic.setAllowPanning(false); ic.setAllowZoom(false); ic.setShowPixelColours(false); ic.setShowXYPosition(false); ic.setImage(ImageUtilities.createBufferedImageForDisplay(image)); return ic; } @Override public void close() { // do nothing } public static void main(String[] args) throws IOException {
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // } // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l5/AlignmentDemo.java import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagLayout; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.swing.JPanel; import javax.swing.JTabbedPane; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.image.DisplayUtilities.ImageComponent; import org.openimaj.image.ImageUtilities; import org.openimaj.image.MBFImage; import org.openimaj.image.colour.ColourSpace; import org.openimaj.image.colour.RGBColour; import org.openimaj.image.model.asm.datasets.AMToolsSampleDataset; import org.openimaj.image.model.asm.datasets.ShapeModelDataset; import org.openimaj.math.geometry.line.Line2d; import org.openimaj.math.geometry.point.PointList; import org.openimaj.math.geometry.point.PointListConnections; import org.openimaj.math.geometry.shape.algorithm.GeneralisedProcrustesAnalysis; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration; Float[][] colours) { final MBFImage image = new MBFImage(width, height - 20, ColourSpace.RGB).fill(RGBColour.BLACK); int i = 0; for (final PointList p : points) { final PointList pts = p.clone(); pts.scale(1.5f); final Float[] c = colours[i++]; image.drawPoints(pts, c, 5); for (final Line2d line : pts.getLines(connections)) { image.drawLine(line, 3, c); } } final ImageComponent ic = new ImageComponent(true, true); ic.setAllowPanning(false); ic.setAllowZoom(false); ic.setShowPixelColours(false); ic.setShowXYPosition(false); ic.setImage(ImageUtilities.createBufferedImageForDisplay(image)); return ic; } @Override public void close() { // do nothing } public static void main(String[] args) throws IOException {
new SlideshowApplication(new AlignmentDemo(), 1024, 768, Utils.BACKGROUND_IMAGE);
jonhare/COMP3204
app/src/main/java/uk/ac/soton/ecs/comp3204/l3/EigenFaceReconstructionDemo.java
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l3/FaceDatasetDemo.java // public static class FaceDatasetProvider { // static File tmpFile; // static { // try { // tmpFile = File.createTempFile("faces", ".zip"); // FileUtils.copyURLToFile(FaceDatasetDemo.class.getResource("att_faces.zip"), tmpFile); // tmpFile.deleteOnExit(); // } catch (final Exception e) { // e.printStackTrace(); // } // } // // public static VFSGroupDataset<FImage> getDataset() throws FileSystemException { // return new VFSGroupDataset<FImage>("zip:" + tmpFile.toURI(), ImageUtilities.FIMAGE_READER); // } // } // // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // }
import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSeparator; import javax.swing.JSlider; import javax.swing.JTextField; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.data.dataset.VFSGroupDataset; import org.openimaj.image.DisplayUtilities.ImageComponent; import org.openimaj.image.FImage; import org.openimaj.image.ImageUtilities; import org.openimaj.image.model.EigenImages; import org.openimaj.image.processing.resize.ResizeProcessor; import uk.ac.soton.ecs.comp3204.l3.FaceDatasetDemo.FaceDatasetProvider; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration;
package uk.ac.soton.ecs.comp3204.l3; /** * Demonstration of the effect of changing weights on principal components. * * @author Jonathon Hare ([email protected]) * */ @Demonstration(title = "Eigenface reconstruction demo") public class EigenFaceReconstructionDemo implements Slide { private static final Font FONT = Font.decode("Monaco-28"); private BufferedImage bimg; private double[] vector; @Override public Component getComponent(int width, int height) throws IOException {
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l3/FaceDatasetDemo.java // public static class FaceDatasetProvider { // static File tmpFile; // static { // try { // tmpFile = File.createTempFile("faces", ".zip"); // FileUtils.copyURLToFile(FaceDatasetDemo.class.getResource("att_faces.zip"), tmpFile); // tmpFile.deleteOnExit(); // } catch (final Exception e) { // e.printStackTrace(); // } // } // // public static VFSGroupDataset<FImage> getDataset() throws FileSystemException { // return new VFSGroupDataset<FImage>("zip:" + tmpFile.toURI(), ImageUtilities.FIMAGE_READER); // } // } // // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // } // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l3/EigenFaceReconstructionDemo.java import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSeparator; import javax.swing.JSlider; import javax.swing.JTextField; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.data.dataset.VFSGroupDataset; import org.openimaj.image.DisplayUtilities.ImageComponent; import org.openimaj.image.FImage; import org.openimaj.image.ImageUtilities; import org.openimaj.image.model.EigenImages; import org.openimaj.image.processing.resize.ResizeProcessor; import uk.ac.soton.ecs.comp3204.l3.FaceDatasetDemo.FaceDatasetProvider; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration; package uk.ac.soton.ecs.comp3204.l3; /** * Demonstration of the effect of changing weights on principal components. * * @author Jonathon Hare ([email protected]) * */ @Demonstration(title = "Eigenface reconstruction demo") public class EigenFaceReconstructionDemo implements Slide { private static final Font FONT = Font.decode("Monaco-28"); private BufferedImage bimg; private double[] vector; @Override public Component getComponent(int width, int height) throws IOException {
final VFSGroupDataset<FImage> dataset = FaceDatasetProvider.getDataset();
jonhare/COMP3204
app/src/main/java/uk/ac/soton/ecs/comp3204/l3/EigenFaceReconstructionDemo.java
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l3/FaceDatasetDemo.java // public static class FaceDatasetProvider { // static File tmpFile; // static { // try { // tmpFile = File.createTempFile("faces", ".zip"); // FileUtils.copyURLToFile(FaceDatasetDemo.class.getResource("att_faces.zip"), tmpFile); // tmpFile.deleteOnExit(); // } catch (final Exception e) { // e.printStackTrace(); // } // } // // public static VFSGroupDataset<FImage> getDataset() throws FileSystemException { // return new VFSGroupDataset<FImage>("zip:" + tmpFile.toURI(), ImageUtilities.FIMAGE_READER); // } // } // // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // }
import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSeparator; import javax.swing.JSlider; import javax.swing.JTextField; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.data.dataset.VFSGroupDataset; import org.openimaj.image.DisplayUtilities.ImageComponent; import org.openimaj.image.FImage; import org.openimaj.image.ImageUtilities; import org.openimaj.image.model.EigenImages; import org.openimaj.image.processing.resize.ResizeProcessor; import uk.ac.soton.ecs.comp3204.l3.FaceDatasetDemo.FaceDatasetProvider; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration;
valField.setText(String.format("%2.2f", slider.getValue() / 10.0)); ic.setImage(bimg = ImageUtilities.createBufferedImageForDisplay(image, bimg)); } }); container.add(slider); container.add(valField); controls.add(container); } controls.add(new JSeparator(JSeparator.HORIZONTAL)); final JButton reset = new JButton("Reset"); reset.setFont(FONT); reset.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { for (final JSlider s : sliders) s.setValue(0); } }); controls.add(reset); outer.add(controls); return outer; } @Override public void close() { // do nothing } public static void main(String[] args) throws IOException {
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l3/FaceDatasetDemo.java // public static class FaceDatasetProvider { // static File tmpFile; // static { // try { // tmpFile = File.createTempFile("faces", ".zip"); // FileUtils.copyURLToFile(FaceDatasetDemo.class.getResource("att_faces.zip"), tmpFile); // tmpFile.deleteOnExit(); // } catch (final Exception e) { // e.printStackTrace(); // } // } // // public static VFSGroupDataset<FImage> getDataset() throws FileSystemException { // return new VFSGroupDataset<FImage>("zip:" + tmpFile.toURI(), ImageUtilities.FIMAGE_READER); // } // } // // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // } // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l3/EigenFaceReconstructionDemo.java import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSeparator; import javax.swing.JSlider; import javax.swing.JTextField; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.data.dataset.VFSGroupDataset; import org.openimaj.image.DisplayUtilities.ImageComponent; import org.openimaj.image.FImage; import org.openimaj.image.ImageUtilities; import org.openimaj.image.model.EigenImages; import org.openimaj.image.processing.resize.ResizeProcessor; import uk.ac.soton.ecs.comp3204.l3.FaceDatasetDemo.FaceDatasetProvider; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration; valField.setText(String.format("%2.2f", slider.getValue() / 10.0)); ic.setImage(bimg = ImageUtilities.createBufferedImageForDisplay(image, bimg)); } }); container.add(slider); container.add(valField); controls.add(container); } controls.add(new JSeparator(JSeparator.HORIZONTAL)); final JButton reset = new JButton("Reset"); reset.setFont(FONT); reset.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { for (final JSlider s : sliders) s.setValue(0); } }); controls.add(reset); outer.add(controls); return outer; } @Override public void close() { // do nothing } public static void main(String[] args) throws IOException {
new SlideshowApplication(new EigenFaceReconstructionDemo(), 1024, 768, Utils.BACKGROUND_IMAGE);
jonhare/COMP3204
app/src/main/java/uk/ac/soton/ecs/comp3204/l9/Lecture9.java
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // }
import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.openimaj.content.slideshow.PictureSlide; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.content.slideshow.VideoSlide; import org.openimaj.video.VideoDisplay.EndAction; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.JvmArgs; import uk.ac.soton.ecs.comp3204.utils.annotations.Lecture;
package uk.ac.soton.ecs.comp3204.l9; @Lecture(title = "L9: Image Search and Bags of Visual Words", handoutsURL = "http://jonhare.github.io/COMP3204/handouts/pdf/L9-imagesearch.pdf", slidesURL = "http://jonhare.github.io/COMP3204/lectures/pdf/L9-imagesearch.pdf") @JvmArgs(vmArguments = "-Xmx1G") public class Lecture9 { public static void main(String[] args) throws IOException { final List<Slide> slides = new ArrayList<Slide>(); slides.add(new PictureSlide(Lecture9.class.getResource(String.format("l9.%03d.jpg", 1)))); slides.add(new ArtARDemo()); for (int i = 2; i <= 28; i++) slides.add(new PictureSlide(Lecture9.class.getResource(String.format("l9.%03d.jpg", i)))); slides.add(new BoVWHistogramDemo()); for (int i = 29; i <= 37; i++) slides.add(new PictureSlide(Lecture9.class.getResource(String.format("l9.%03d.jpg", i))));
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // } // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l9/Lecture9.java import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.openimaj.content.slideshow.PictureSlide; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.content.slideshow.VideoSlide; import org.openimaj.video.VideoDisplay.EndAction; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.JvmArgs; import uk.ac.soton.ecs.comp3204.utils.annotations.Lecture; package uk.ac.soton.ecs.comp3204.l9; @Lecture(title = "L9: Image Search and Bags of Visual Words", handoutsURL = "http://jonhare.github.io/COMP3204/handouts/pdf/L9-imagesearch.pdf", slidesURL = "http://jonhare.github.io/COMP3204/lectures/pdf/L9-imagesearch.pdf") @JvmArgs(vmArguments = "-Xmx1G") public class Lecture9 { public static void main(String[] args) throws IOException { final List<Slide> slides = new ArrayList<Slide>(); slides.add(new PictureSlide(Lecture9.class.getResource(String.format("l9.%03d.jpg", 1)))); slides.add(new ArtARDemo()); for (int i = 2; i <= 28; i++) slides.add(new PictureSlide(Lecture9.class.getResource(String.format("l9.%03d.jpg", i)))); slides.add(new BoVWHistogramDemo()); for (int i = 29; i <= 37; i++) slides.add(new PictureSlide(Lecture9.class.getResource(String.format("l9.%03d.jpg", i))));
slides.add(new VideoSlide(Lecture9.class.getResource("TrentoDuomo.mov"), Utils.BACKGROUND_IMAGE_URL,
jonhare/COMP3204
app/src/main/java/uk/ac/soton/ecs/comp3204/l2/KMeansDemo.java
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // }
import java.awt.Component; import java.awt.Dimension; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSeparator; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import javax.swing.SwingConstants; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.image.DisplayUtilities; import org.openimaj.image.DisplayUtilities.ImageComponent; import org.openimaj.image.ImageUtilities; import org.openimaj.image.MBFImage; import org.openimaj.image.colour.ColourMap; import org.openimaj.image.colour.ColourSpace; import org.openimaj.image.colour.RGBColour; import org.openimaj.image.renderer.MBFImageRenderer; import org.openimaj.image.renderer.RenderHints; import org.openimaj.math.geometry.line.Line2d; import org.openimaj.math.geometry.point.Point2d; import org.openimaj.math.geometry.point.Point2dImpl; import org.openimaj.math.geometry.shape.Circle; import org.openimaj.math.geometry.triangulation.Voronoi; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration;
initKMeans(); for (int i = 0; i < 30 && isRunning; i++) { if (isRunning) kmeansAssignmentStep(true); if (isRunning && kmeansUpdateStep()) { break; } } if (isRunning) kmeansAssignmentStep(false); if (isRunning) drawVoronoi(); runBtn.setEnabled(true); clearBtn.setEnabled(true); kSpn.setEnabled(true); cnclBtn.setEnabled(false); isRunning = false; } }).start(); } else if (e.getActionCommand().equals("button.cancel")) { isRunning = false; cnclBtn.setEnabled(false); } } public static void main(String[] args) throws IOException {
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // } // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l2/KMeansDemo.java import java.awt.Component; import java.awt.Dimension; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSeparator; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import javax.swing.SwingConstants; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.image.DisplayUtilities; import org.openimaj.image.DisplayUtilities.ImageComponent; import org.openimaj.image.ImageUtilities; import org.openimaj.image.MBFImage; import org.openimaj.image.colour.ColourMap; import org.openimaj.image.colour.ColourSpace; import org.openimaj.image.colour.RGBColour; import org.openimaj.image.renderer.MBFImageRenderer; import org.openimaj.image.renderer.RenderHints; import org.openimaj.math.geometry.line.Line2d; import org.openimaj.math.geometry.point.Point2d; import org.openimaj.math.geometry.point.Point2dImpl; import org.openimaj.math.geometry.shape.Circle; import org.openimaj.math.geometry.triangulation.Voronoi; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration; initKMeans(); for (int i = 0; i < 30 && isRunning; i++) { if (isRunning) kmeansAssignmentStep(true); if (isRunning && kmeansUpdateStep()) { break; } } if (isRunning) kmeansAssignmentStep(false); if (isRunning) drawVoronoi(); runBtn.setEnabled(true); clearBtn.setEnabled(true); kSpn.setEnabled(true); cnclBtn.setEnabled(false); isRunning = false; } }).start(); } else if (e.getActionCommand().equals("button.cancel")) { isRunning = false; cnclBtn.setEnabled(false); } } public static void main(String[] args) throws IOException {
new SlideshowApplication(new KMeansDemo(), 1024, 768, Utils.BACKGROUND_IMAGE);
jonhare/COMP3204
app/src/main/java/uk/ac/soton/ecs/comp3204/l3/EigenDecompositionDemo.java
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // }
import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.io.IOException; import java.util.Random; import javax.swing.BoxLayout; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.image.ImageUtilities; import org.openimaj.image.colour.RGBColour; import org.openimaj.image.renderer.MBFImageRenderer; import org.openimaj.image.renderer.RenderHints; import org.openimaj.math.geometry.point.Point2dImpl; import org.openimaj.math.geometry.shape.Ellipse; import org.openimaj.math.geometry.shape.EllipseUtilities; import org.openimaj.math.geometry.transforms.TransformUtilities; import org.openimaj.math.matrix.MatrixUtils; import org.openimaj.math.statistics.distribution.CachingMultivariateGaussian; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration; import Jama.EigenvalueDecomposition; import Jama.Matrix;
} final MBFImageRenderer renderer = image.createRenderer(RenderHints.ANTI_ALIASED); if (drawEllipse) renderer.drawShape(e, 3, RGBColour.RED); int x = (int) (100 * decomp.getV().get(0, 0) * Math.sqrt(decomp.getRealEigenvalues()[0])); int y = (int) (100 * decomp.getV().get(1, 0) * Math.sqrt(decomp.getRealEigenvalues()[0])); renderer.drawLine(image.getWidth() / 2, image.getHeight() / 2, x + image.getWidth() / 2, image.getHeight() / 2 - y, 3, RGBColour.GREEN); x = (int) (100 * decomp.getV().get(0, 1) * Math.sqrt(decomp.getRealEigenvalues()[1])); y = (int) (100 * decomp.getV().get(1, 1) * Math.sqrt(decomp.getRealEigenvalues()[1])); renderer.drawLine(image.getWidth() / 2, image.getHeight() / 2, x + image.getWidth() / 2, image.getHeight() / 2 - y, 3, RGBColour.GREEN); } else { evec00.setText(""); evec01.setText(""); evec10.setText(""); evec11.setText(""); eval00.setText(""); eval01.setText(""); eval10.setText(""); eval11.setText(""); } this.imageComp.setImage(bimg = ImageUtilities.createBufferedImageForDisplay(image, bimg)); } public static void main(String[] args) throws IOException {
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // } // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l3/EigenDecompositionDemo.java import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.io.IOException; import java.util.Random; import javax.swing.BoxLayout; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.image.ImageUtilities; import org.openimaj.image.colour.RGBColour; import org.openimaj.image.renderer.MBFImageRenderer; import org.openimaj.image.renderer.RenderHints; import org.openimaj.math.geometry.point.Point2dImpl; import org.openimaj.math.geometry.shape.Ellipse; import org.openimaj.math.geometry.shape.EllipseUtilities; import org.openimaj.math.geometry.transforms.TransformUtilities; import org.openimaj.math.matrix.MatrixUtils; import org.openimaj.math.statistics.distribution.CachingMultivariateGaussian; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration; import Jama.EigenvalueDecomposition; import Jama.Matrix; } final MBFImageRenderer renderer = image.createRenderer(RenderHints.ANTI_ALIASED); if (drawEllipse) renderer.drawShape(e, 3, RGBColour.RED); int x = (int) (100 * decomp.getV().get(0, 0) * Math.sqrt(decomp.getRealEigenvalues()[0])); int y = (int) (100 * decomp.getV().get(1, 0) * Math.sqrt(decomp.getRealEigenvalues()[0])); renderer.drawLine(image.getWidth() / 2, image.getHeight() / 2, x + image.getWidth() / 2, image.getHeight() / 2 - y, 3, RGBColour.GREEN); x = (int) (100 * decomp.getV().get(0, 1) * Math.sqrt(decomp.getRealEigenvalues()[1])); y = (int) (100 * decomp.getV().get(1, 1) * Math.sqrt(decomp.getRealEigenvalues()[1])); renderer.drawLine(image.getWidth() / 2, image.getHeight() / 2, x + image.getWidth() / 2, image.getHeight() / 2 - y, 3, RGBColour.GREEN); } else { evec00.setText(""); evec01.setText(""); evec10.setText(""); evec11.setText(""); eval00.setText(""); eval01.setText(""); eval10.setText(""); eval11.setText(""); } this.imageComp.setImage(bimg = ImageUtilities.createBufferedImageForDisplay(image, bimg)); } public static void main(String[] args) throws IOException {
new SlideshowApplication(new EigenDecompositionDemo(), 1024, 768, Utils.BACKGROUND_IMAGE);
jonhare/COMP3204
app/src/main/java/uk/ac/soton/ecs/comp3204/l1/ColourSpacesDemo.java
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // }
import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import javax.swing.ButtonGroup; import javax.swing.JPanel; import javax.swing.JRadioButton; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.image.FImage; import org.openimaj.image.MBFImage; import org.openimaj.image.colour.ColourSpace; import org.openimaj.video.VideoDisplay; import org.openimaj.video.VideoDisplayListener; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration;
* @param colourSpace */ public static void convertColours(MBFImage frame, ColourSpace colourSpace) { // update the frame from the camera by converting to the selected colour // space before display final MBFImage cvt = colourSpace.convert(frame); // if the converted image has fewer than 3 bands, add more so it can be // displayed as RGB. if (cvt.numBands() == 1) { // this makes a three-band grey-level image, where all the bands are // the same cvt.bands.add(cvt.getBand(0).clone()); cvt.bands.add(cvt.getBand(0).clone()); } else if (cvt.numBands() == 2) { // this adds a third zero band to a two-band image cvt.bands.add(new FImage(cvt.getWidth(), cvt.getHeight())); } // this sets the frame to the colour converted version frame.internalAssign(cvt); } @Override public void actionPerformed(ActionEvent e) { // change the colour space to the one selected this.colourSpace = ColourSpace.valueOf(e.getActionCommand()); } public static void main(String[] args) throws IOException {
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // } // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l1/ColourSpacesDemo.java import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import javax.swing.ButtonGroup; import javax.swing.JPanel; import javax.swing.JRadioButton; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.image.FImage; import org.openimaj.image.MBFImage; import org.openimaj.image.colour.ColourSpace; import org.openimaj.video.VideoDisplay; import org.openimaj.video.VideoDisplayListener; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration; * @param colourSpace */ public static void convertColours(MBFImage frame, ColourSpace colourSpace) { // update the frame from the camera by converting to the selected colour // space before display final MBFImage cvt = colourSpace.convert(frame); // if the converted image has fewer than 3 bands, add more so it can be // displayed as RGB. if (cvt.numBands() == 1) { // this makes a three-band grey-level image, where all the bands are // the same cvt.bands.add(cvt.getBand(0).clone()); cvt.bands.add(cvt.getBand(0).clone()); } else if (cvt.numBands() == 2) { // this adds a third zero band to a two-band image cvt.bands.add(new FImage(cvt.getWidth(), cvt.getHeight())); } // this sets the frame to the colour converted version frame.internalAssign(cvt); } @Override public void actionPerformed(ActionEvent e) { // change the colour space to the one selected this.colourSpace = ColourSpace.valueOf(e.getActionCommand()); } public static void main(String[] args) throws IOException {
new SlideshowApplication(new ColourSpacesDemo(), 1024, 768, Utils.BACKGROUND_IMAGE);
jonhare/COMP3204
app/src/main/java/uk/ac/soton/ecs/comp3204/l4/KMeansSegmentationDemo.java
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // }
import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.List; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.image.DisplayUtilities.ImageComponent; import org.openimaj.image.ImageUtilities; import org.openimaj.image.MBFImage; import org.openimaj.image.colour.ColourSpace; import org.openimaj.image.pixel.PixelSet; import org.openimaj.image.segmentation.KMColourSegmenter; import org.openimaj.image.segmentation.SegmentationUtilities; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration;
@Override public void run() { ic.setImage(bimg = ImageUtilities.createBufferedImageForDisplay( segmentImage(oimage, (Integer) kSpinner.getValue()), bimg)); segmentBtn.setEnabled(true); kSpinner.setEnabled(true); } }).start(); } }); return base; } protected MBFImage segmentImage(MBFImage oimage, int k) { final KMColourSegmenter seg = new KMColourSegmenter(ColourSpace.CIE_Lab, k); final List<? extends PixelSet> result = seg.segment(oimage); return SegmentationUtilities.renderSegments(oimage.getWidth(), oimage.getHeight(), result); } @Override public void close() { // do nothing } public static void main(String[] args) throws IOException {
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // } // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l4/KMeansSegmentationDemo.java import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.List; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.image.DisplayUtilities.ImageComponent; import org.openimaj.image.ImageUtilities; import org.openimaj.image.MBFImage; import org.openimaj.image.colour.ColourSpace; import org.openimaj.image.pixel.PixelSet; import org.openimaj.image.segmentation.KMColourSegmenter; import org.openimaj.image.segmentation.SegmentationUtilities; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration; @Override public void run() { ic.setImage(bimg = ImageUtilities.createBufferedImageForDisplay( segmentImage(oimage, (Integer) kSpinner.getValue()), bimg)); segmentBtn.setEnabled(true); kSpinner.setEnabled(true); } }).start(); } }); return base; } protected MBFImage segmentImage(MBFImage oimage, int k) { final KMColourSegmenter seg = new KMColourSegmenter(ColourSpace.CIE_Lab, k); final List<? extends PixelSet> result = seg.segment(oimage); return SegmentationUtilities.renderSegments(oimage.getWidth(), oimage.getHeight(), result); } @Override public void close() { // do nothing } public static void main(String[] args) throws IOException {
new SlideshowApplication(new KMeansSegmentationDemo(), 1024, 768, Utils.BACKGROUND_IMAGE);
jonhare/COMP3204
app/src/main/java/uk/ac/soton/ecs/comp3204/l4/ConnectedComponentsDemo.java
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // }
import gnu.trove.map.hash.TIntIntHashMap; import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JPanel; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.image.DisplayUtilities.ImageComponent; import org.openimaj.image.FImage; import org.openimaj.image.ImageUtilities; import org.openimaj.image.MBFImage; import org.openimaj.image.colour.ColourSpace; import org.openimaj.image.colour.RGBColour; import org.openimaj.image.pixel.ConnectedComponent.ConnectMode; import org.openimaj.image.pixel.Pixel; import org.openimaj.image.processing.threshold.AdaptiveLocalThresholdMean; import org.openimaj.util.function.Function; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration;
if (!callback.apply(labels)) return labels; } } } return labels; } private void merge(TIntIntHashMap linked, int start, int target) { if (start == target) return; final int old = linked.get(start); if (old > target) { linked.put(start, target); merge(linked, old, target); } else { merge(linked, target, old); } } @Override public void close() { // do nothing } public static void main(String[] args) throws IOException {
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // } // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l4/ConnectedComponentsDemo.java import gnu.trove.map.hash.TIntIntHashMap; import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JPanel; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.image.DisplayUtilities.ImageComponent; import org.openimaj.image.FImage; import org.openimaj.image.ImageUtilities; import org.openimaj.image.MBFImage; import org.openimaj.image.colour.ColourSpace; import org.openimaj.image.colour.RGBColour; import org.openimaj.image.pixel.ConnectedComponent.ConnectMode; import org.openimaj.image.pixel.Pixel; import org.openimaj.image.processing.threshold.AdaptiveLocalThresholdMean; import org.openimaj.util.function.Function; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration; if (!callback.apply(labels)) return labels; } } } return labels; } private void merge(TIntIntHashMap linked, int start, int target) { if (start == target) return; final int old = linked.get(start); if (old > target) { linked.put(start, target); merge(linked, old, target); } else { merge(linked, target, old); } } @Override public void close() { // do nothing } public static void main(String[] args) throws IOException {
new SlideshowApplication(new ConnectedComponentsDemo(), 1024, 768, Utils.BACKGROUND_IMAGE);
jonhare/COMP3204
app/src/main/java/uk/ac/soton/ecs/comp3204/l6/MultiscaleHarrisPointsDemo.java
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l1/SimpleCameraDemo.java // @Demonstration(title = "Simple Camera Demo") // public class SimpleCameraDemo implements Slide { // protected VideoCaptureComponent vc; // // @Override // public JPanel getComponent(int width, int height) throws IOException { // // the main panel // final JPanel base = new JPanel(); // base.setOpaque(false); // base.setPreferredSize(new Dimension(width, height)); // base.setLayout(new GridBagLayout()); // vc = new VideoCaptureComponent(640, 480); // base.add(vc); // // return base; // } // // @Override // public void close() { // vc.close(); // } // // public static void main(String[] args) throws IOException { // new SlideshowApplication(new SimpleCameraDemo(), 1024, 768, Utils.BACKGROUND_IMAGE); // } // } // // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // }
import java.awt.Font; import java.io.IOException; import javax.swing.JPanel; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.image.FImage; import org.openimaj.image.MBFImage; import org.openimaj.image.colour.RGBColour; import org.openimaj.image.feature.local.interest.HarrisIPD; import org.openimaj.image.feature.local.interest.InterestPointData; import org.openimaj.image.processing.convolution.FGaussianConvolve; import org.openimaj.image.processing.resize.ResizeProcessor; import org.openimaj.math.geometry.shape.Circle; import org.openimaj.video.VideoDisplay; import org.openimaj.video.VideoDisplayListener; import uk.ac.soton.ecs.comp3204.l1.SimpleCameraDemo; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration;
public void beforeUpdate(MBFImage frame) { FImage gimg = frame.flatten(); // bring to sigma = 1.0 gimg.processInplace(new FGaussianConvolve(1f)); for (int i = 0; i < 3; i++) { final int t = (int) Math.pow(2, i); final double sigma = Math.sqrt(t); final float sf = t; harris.setDetectionScale((float) sigma); harris.setImageBlurred(true); harris.findInterestPoints(gimg); final float iscale = harris.getIntegrationScale(); final float samplesize = 4 * iscale + 1; for (final InterestPointData ipd : harris.getInterestPoints((float) (1e-5))) { ipd.x *= sf; ipd.y *= sf; frame.drawShape(new Circle(ipd, sf * samplesize), RGBColour.RED); } gimg.processInplace(new FGaussianConvolve((float) Math.sqrt((Math.pow(2, i + 1) - t)))); gimg = ResizeProcessor.halfSize(gimg); } } public static void main(String[] args) throws IOException {
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l1/SimpleCameraDemo.java // @Demonstration(title = "Simple Camera Demo") // public class SimpleCameraDemo implements Slide { // protected VideoCaptureComponent vc; // // @Override // public JPanel getComponent(int width, int height) throws IOException { // // the main panel // final JPanel base = new JPanel(); // base.setOpaque(false); // base.setPreferredSize(new Dimension(width, height)); // base.setLayout(new GridBagLayout()); // vc = new VideoCaptureComponent(640, 480); // base.add(vc); // // return base; // } // // @Override // public void close() { // vc.close(); // } // // public static void main(String[] args) throws IOException { // new SlideshowApplication(new SimpleCameraDemo(), 1024, 768, Utils.BACKGROUND_IMAGE); // } // } // // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // } // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l6/MultiscaleHarrisPointsDemo.java import java.awt.Font; import java.io.IOException; import javax.swing.JPanel; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.image.FImage; import org.openimaj.image.MBFImage; import org.openimaj.image.colour.RGBColour; import org.openimaj.image.feature.local.interest.HarrisIPD; import org.openimaj.image.feature.local.interest.InterestPointData; import org.openimaj.image.processing.convolution.FGaussianConvolve; import org.openimaj.image.processing.resize.ResizeProcessor; import org.openimaj.math.geometry.shape.Circle; import org.openimaj.video.VideoDisplay; import org.openimaj.video.VideoDisplayListener; import uk.ac.soton.ecs.comp3204.l1.SimpleCameraDemo; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration; public void beforeUpdate(MBFImage frame) { FImage gimg = frame.flatten(); // bring to sigma = 1.0 gimg.processInplace(new FGaussianConvolve(1f)); for (int i = 0; i < 3; i++) { final int t = (int) Math.pow(2, i); final double sigma = Math.sqrt(t); final float sf = t; harris.setDetectionScale((float) sigma); harris.setImageBlurred(true); harris.findInterestPoints(gimg); final float iscale = harris.getIntegrationScale(); final float samplesize = 4 * iscale + 1; for (final InterestPointData ipd : harris.getInterestPoints((float) (1e-5))) { ipd.x *= sf; ipd.y *= sf; frame.drawShape(new Circle(ipd, sf * samplesize), RGBColour.RED); } gimg.processInplace(new FGaussianConvolve((float) Math.sqrt((Math.pow(2, i + 1) - t)))); gimg = ResizeProcessor.halfSize(gimg); } } public static void main(String[] args) throws IOException {
new SlideshowApplication(new MultiscaleHarrisPointsDemo(), 1024, 768, Utils.BACKGROUND_IMAGE);
jonhare/COMP3204
app/src/main/java/uk/ac/soton/ecs/comp3204/l11/KinectDemo.java
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // }
import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import javax.swing.ButtonGroup; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.hardware.kinect.KinectController; import org.openimaj.image.FImage; import org.openimaj.image.Image; import org.openimaj.image.MBFImage; import org.openimaj.image.colour.RGBColour; import org.openimaj.video.Video; import org.openimaj.video.VideoDisplay; import uk.ac.soton.ecs.comp3204.utils.Utils;
return base; } return base; } @Override public void close() { if (display != null) { final VideoDisplay<MBFImage> tmp = display; display = null; tmp.close(); controller.close(); } } @Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand() == RGB) { depth = false; controller.setIRMode(false); } else if (e.getActionCommand() == IR) { depth = false; controller.setIRMode(true); } else if (e.getActionCommand() == DEPTH) { depth = true; } } public static void main(String[] args) throws IOException {
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // } // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l11/KinectDemo.java import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import javax.swing.ButtonGroup; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.hardware.kinect.KinectController; import org.openimaj.image.FImage; import org.openimaj.image.Image; import org.openimaj.image.MBFImage; import org.openimaj.image.colour.RGBColour; import org.openimaj.video.Video; import org.openimaj.video.VideoDisplay; import uk.ac.soton.ecs.comp3204.utils.Utils; return base; } return base; } @Override public void close() { if (display != null) { final VideoDisplay<MBFImage> tmp = display; display = null; tmp.close(); controller.close(); } } @Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand() == RGB) { depth = false; controller.setIRMode(false); } else if (e.getActionCommand() == IR) { depth = false; controller.setIRMode(true); } else if (e.getActionCommand() == DEPTH) { depth = true; } } public static void main(String[] args) throws IOException {
new SlideshowApplication(new KinectDemo(), 1024, 768, Utils.BACKGROUND_IMAGE);
jonhare/COMP3204
app/src/main/java/uk/ac/soton/ecs/comp3204/l5/PuppeteerDemo.java
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l1/SimpleCameraDemo.java // @Demonstration(title = "Simple Camera Demo") // public class SimpleCameraDemo implements Slide { // protected VideoCaptureComponent vc; // // @Override // public JPanel getComponent(int width, int height) throws IOException { // // the main panel // final JPanel base = new JPanel(); // base.setOpaque(false); // base.setPreferredSize(new Dimension(width, height)); // base.setLayout(new GridBagLayout()); // vc = new VideoCaptureComponent(640, 480); // base.add(vc); // // return base; // } // // @Override // public void close() { // vc.close(); // } // // public static void main(String[] args) throws IOException { // new SlideshowApplication(new SimpleCameraDemo(), 1024, 768, Utils.BACKGROUND_IMAGE); // } // } // // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // }
import gnu.trove.map.hash.TObjectIntHashMap; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.swing.JPanel; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.image.FImage; import org.openimaj.image.ImageUtilities; import org.openimaj.image.MBFImage; import org.openimaj.image.processing.face.tracking.clm.CLMFaceTracker; import org.openimaj.image.processing.face.tracking.clm.MultiTracker.TrackedFace; import org.openimaj.image.processing.transform.PiecewiseMeshWarp; import org.openimaj.math.geometry.shape.Rectangle; import org.openimaj.math.geometry.shape.Shape; import org.openimaj.math.geometry.shape.Triangle; import org.openimaj.util.pair.IndependentPair; import org.openimaj.util.pair.Pair; import org.openimaj.video.VideoDisplay; import org.openimaj.video.VideoDisplayListener; import uk.ac.soton.ecs.comp3204.l1.SimpleCameraDemo; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration;
final int ymin = (int) Math.max(0, bounds.y); final int ymax = (int) Math.min(Math.min(fore.getHeight(), back.getHeight()), bounds.y + bounds.height); final int xmax = (int) Math.min(Math.min(fore.getWidth(), back.getWidth()), bounds.x + bounds.width); for (int y = ymin; y < ymax; y++) { for (int x = xmin; x < xmax; x++) { if (rin[y][x] != 0 && gin[y][x] != 0 && bin[y][x] != 0) { rout[y][x] = rin[y][x]; gout[y][x] = gin[y][x]; bout[y][x] = bin[y][x]; } } } } @Override public JPanel getComponent(int width, int height) throws IOException { final JPanel c = super.getComponent(width, height); this.vc.getDisplay().addVideoListener(this); return c; } /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException {
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l1/SimpleCameraDemo.java // @Demonstration(title = "Simple Camera Demo") // public class SimpleCameraDemo implements Slide { // protected VideoCaptureComponent vc; // // @Override // public JPanel getComponent(int width, int height) throws IOException { // // the main panel // final JPanel base = new JPanel(); // base.setOpaque(false); // base.setPreferredSize(new Dimension(width, height)); // base.setLayout(new GridBagLayout()); // vc = new VideoCaptureComponent(640, 480); // base.add(vc); // // return base; // } // // @Override // public void close() { // vc.close(); // } // // public static void main(String[] args) throws IOException { // new SlideshowApplication(new SimpleCameraDemo(), 1024, 768, Utils.BACKGROUND_IMAGE); // } // } // // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // } // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l5/PuppeteerDemo.java import gnu.trove.map.hash.TObjectIntHashMap; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.swing.JPanel; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.image.FImage; import org.openimaj.image.ImageUtilities; import org.openimaj.image.MBFImage; import org.openimaj.image.processing.face.tracking.clm.CLMFaceTracker; import org.openimaj.image.processing.face.tracking.clm.MultiTracker.TrackedFace; import org.openimaj.image.processing.transform.PiecewiseMeshWarp; import org.openimaj.math.geometry.shape.Rectangle; import org.openimaj.math.geometry.shape.Shape; import org.openimaj.math.geometry.shape.Triangle; import org.openimaj.util.pair.IndependentPair; import org.openimaj.util.pair.Pair; import org.openimaj.video.VideoDisplay; import org.openimaj.video.VideoDisplayListener; import uk.ac.soton.ecs.comp3204.l1.SimpleCameraDemo; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration; final int ymin = (int) Math.max(0, bounds.y); final int ymax = (int) Math.min(Math.min(fore.getHeight(), back.getHeight()), bounds.y + bounds.height); final int xmax = (int) Math.min(Math.min(fore.getWidth(), back.getWidth()), bounds.x + bounds.width); for (int y = ymin; y < ymax; y++) { for (int x = xmin; x < xmax; x++) { if (rin[y][x] != 0 && gin[y][x] != 0 && bin[y][x] != 0) { rout[y][x] = rin[y][x]; gout[y][x] = gin[y][x]; bout[y][x] = bin[y][x]; } } } } @Override public JPanel getComponent(int width, int height) throws IOException { final JPanel c = super.getComponent(width, height); this.vc.getDisplay().addVideoListener(this); return c; } /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException {
new SlideshowApplication(new PuppeteerDemo(), 1024, 768, Utils.BACKGROUND_IMAGE);
jonhare/COMP3204
app/src/main/java/uk/ac/soton/ecs/comp3204/l6/ThresholdedHarrisResponseDemo.java
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l1/SimpleCameraDemo.java // @Demonstration(title = "Simple Camera Demo") // public class SimpleCameraDemo implements Slide { // protected VideoCaptureComponent vc; // // @Override // public JPanel getComponent(int width, int height) throws IOException { // // the main panel // final JPanel base = new JPanel(); // base.setOpaque(false); // base.setPreferredSize(new Dimension(width, height)); // base.setLayout(new GridBagLayout()); // vc = new VideoCaptureComponent(640, 480); // base.add(vc); // // return base; // } // // @Override // public void close() { // vc.close(); // } // // public static void main(String[] args) throws IOException { // new SlideshowApplication(new SimpleCameraDemo(), 1024, 768, Utils.BACKGROUND_IMAGE); // } // } // // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // }
import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.io.IOException; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.image.FImage; import org.openimaj.image.MBFImage; import org.openimaj.image.feature.local.interest.HarrisIPD; import org.openimaj.video.VideoDisplay; import org.openimaj.video.VideoDisplayListener; import uk.ac.soton.ecs.comp3204.l1.SimpleCameraDemo; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration;
c.add(controls, gbc); return c; } @Override public void afterUpdate(VideoDisplay<MBFImage> display) { // do nothing } @Override public void beforeUpdate(MBFImage frame) { harris.setDetectionScale(0); harris.setImageBlurred(true); harris.setIntegrationScale(computeScale()); harris.findInterestPoints(frame.flatten()); final FImage out = harris.createInterestPointMap(); out.threshold(thresholdSpinner.getValue() / 100000f); frame.internalAssign(out.toRGB()); } private float computeScale() { final int size = (Integer) windowSizeSpinner.getValue(); return (size - 1f) / 8f; } public static void main(String[] args) throws IOException {
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l1/SimpleCameraDemo.java // @Demonstration(title = "Simple Camera Demo") // public class SimpleCameraDemo implements Slide { // protected VideoCaptureComponent vc; // // @Override // public JPanel getComponent(int width, int height) throws IOException { // // the main panel // final JPanel base = new JPanel(); // base.setOpaque(false); // base.setPreferredSize(new Dimension(width, height)); // base.setLayout(new GridBagLayout()); // vc = new VideoCaptureComponent(640, 480); // base.add(vc); // // return base; // } // // @Override // public void close() { // vc.close(); // } // // public static void main(String[] args) throws IOException { // new SlideshowApplication(new SimpleCameraDemo(), 1024, 768, Utils.BACKGROUND_IMAGE); // } // } // // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // } // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l6/ThresholdedHarrisResponseDemo.java import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.io.IOException; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.image.FImage; import org.openimaj.image.MBFImage; import org.openimaj.image.feature.local.interest.HarrisIPD; import org.openimaj.video.VideoDisplay; import org.openimaj.video.VideoDisplayListener; import uk.ac.soton.ecs.comp3204.l1.SimpleCameraDemo; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration; c.add(controls, gbc); return c; } @Override public void afterUpdate(VideoDisplay<MBFImage> display) { // do nothing } @Override public void beforeUpdate(MBFImage frame) { harris.setDetectionScale(0); harris.setImageBlurred(true); harris.setIntegrationScale(computeScale()); harris.findInterestPoints(frame.flatten()); final FImage out = harris.createInterestPointMap(); out.threshold(thresholdSpinner.getValue() / 100000f); frame.internalAssign(out.toRGB()); } private float computeScale() { final int size = (Integer) windowSizeSpinner.getValue(); return (size - 1f) / 8f; } public static void main(String[] args) throws IOException {
new SlideshowApplication(new ThresholdedHarrisResponseDemo(), 1024, 768, Utils.BACKGROUND_IMAGE);
jonhare/COMP3204
app/src/main/java/uk/ac/soton/ecs/comp3204/l6/DoGResponseDemo.java
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l1/SimpleCameraDemo.java // @Demonstration(title = "Simple Camera Demo") // public class SimpleCameraDemo implements Slide { // protected VideoCaptureComponent vc; // // @Override // public JPanel getComponent(int width, int height) throws IOException { // // the main panel // final JPanel base = new JPanel(); // base.setOpaque(false); // base.setPreferredSize(new Dimension(width, height)); // base.setLayout(new GridBagLayout()); // vc = new VideoCaptureComponent(640, 480); // base.add(vc); // // return base; // } // // @Override // public void close() { // vc.close(); // } // // public static void main(String[] args) throws IOException { // new SlideshowApplication(new SimpleCameraDemo(), 1024, 768, Utils.BACKGROUND_IMAGE); // } // } // // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // }
import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.io.IOException; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.JTextField; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.image.FImage; import org.openimaj.image.MBFImage; import org.openimaj.image.processing.convolution.FGaussianConvolve; import org.openimaj.video.VideoDisplay; import org.openimaj.video.VideoDisplayListener; import uk.ac.soton.ecs.comp3204.l1.SimpleCameraDemo; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration;
} @Override public void beforeUpdate(MBFImage frame) { final float k = this.kSlider.getValue() / 10f; final float sigma2 = this.scaleSlider.getValue(); final float ksigma2 = sigma2 * (k * k - 1); final FImage gimg = frame.flatten(); final FImage blur1 = gimg.processInplace(new FGaussianConvolve((float) Math.sqrt(sigma2))); final FImage blur2 = gimg.process(new FGaussianConvolve((float) Math.sqrt(ksigma2))); blur1.subtractInplace(blur2); blur1.normalise(); frame.internalAssign(blur1.toRGB()); } @Override public void stateChanged(ChangeEvent e) { final float k = this.kSlider.getValue() / 10f; final float sigma2 = this.scaleSlider.getValue(); this.kField.setText(String.format("%2.2f", k)); this.scaleField.setText(String.format("%2.2f", sigma2)); } public static void main(String[] args) throws IOException {
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l1/SimpleCameraDemo.java // @Demonstration(title = "Simple Camera Demo") // public class SimpleCameraDemo implements Slide { // protected VideoCaptureComponent vc; // // @Override // public JPanel getComponent(int width, int height) throws IOException { // // the main panel // final JPanel base = new JPanel(); // base.setOpaque(false); // base.setPreferredSize(new Dimension(width, height)); // base.setLayout(new GridBagLayout()); // vc = new VideoCaptureComponent(640, 480); // base.add(vc); // // return base; // } // // @Override // public void close() { // vc.close(); // } // // public static void main(String[] args) throws IOException { // new SlideshowApplication(new SimpleCameraDemo(), 1024, 768, Utils.BACKGROUND_IMAGE); // } // } // // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // } // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l6/DoGResponseDemo.java import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.io.IOException; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.JTextField; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.image.FImage; import org.openimaj.image.MBFImage; import org.openimaj.image.processing.convolution.FGaussianConvolve; import org.openimaj.video.VideoDisplay; import org.openimaj.video.VideoDisplayListener; import uk.ac.soton.ecs.comp3204.l1.SimpleCameraDemo; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration; } @Override public void beforeUpdate(MBFImage frame) { final float k = this.kSlider.getValue() / 10f; final float sigma2 = this.scaleSlider.getValue(); final float ksigma2 = sigma2 * (k * k - 1); final FImage gimg = frame.flatten(); final FImage blur1 = gimg.processInplace(new FGaussianConvolve((float) Math.sqrt(sigma2))); final FImage blur2 = gimg.process(new FGaussianConvolve((float) Math.sqrt(ksigma2))); blur1.subtractInplace(blur2); blur1.normalise(); frame.internalAssign(blur1.toRGB()); } @Override public void stateChanged(ChangeEvent e) { final float k = this.kSlider.getValue() / 10f; final float sigma2 = this.scaleSlider.getValue(); this.kField.setText(String.format("%2.2f", k)); this.scaleField.setText(String.format("%2.2f", sigma2)); } public static void main(String[] args) throws IOException {
new SlideshowApplication(new DoGResponseDemo(), 1024, 768, Utils.BACKGROUND_IMAGE);
jonhare/COMP3204
app/src/main/java/uk/ac/soton/ecs/comp3204/l4/Lecture4.java
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // }
import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.openimaj.content.slideshow.PictureSlide; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.JvmArgs; import uk.ac.soton.ecs.comp3204.utils.annotations.Lecture;
slides.add(new AdaptiveThresholdDemo()); for (int i = 23; i <= 24; i++) slides.add(new PictureSlide(Lecture4.class.getResource(String.format("l4.%03d.jpg", i)))); slides.add(new AdaptiveThresholdVideoDemo()); for (int i = 25; i <= 26; i++) slides.add(new PictureSlide(Lecture4.class.getResource(String.format("l4.%03d.jpg", i)))); slides.add(new KMeansSegmentationDemo()); for (int i = 27; i <= 28; i++) slides.add(new PictureSlide(Lecture4.class.getResource(String.format("l4.%03d.jpg", i)))); slides.add(new KMeansSpatialSegmentationDemo()); for (int i = 29; i <= 30; i++) slides.add(new PictureSlide(Lecture4.class.getResource(String.format("l4.%03d.jpg", i)))); slides.add(new FHSegmentationDemo()); for (int i = 31; i <= 36; i++) slides.add(new PictureSlide(Lecture4.class.getResource(String.format("l4.%03d.jpg", i)))); slides.add(new ConnectedComponentsDemo()); slides.add(new PictureSlide(Lecture4.class.getResource("l4.037.jpg")));
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // } // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l4/Lecture4.java import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.openimaj.content.slideshow.PictureSlide; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.JvmArgs; import uk.ac.soton.ecs.comp3204.utils.annotations.Lecture; slides.add(new AdaptiveThresholdDemo()); for (int i = 23; i <= 24; i++) slides.add(new PictureSlide(Lecture4.class.getResource(String.format("l4.%03d.jpg", i)))); slides.add(new AdaptiveThresholdVideoDemo()); for (int i = 25; i <= 26; i++) slides.add(new PictureSlide(Lecture4.class.getResource(String.format("l4.%03d.jpg", i)))); slides.add(new KMeansSegmentationDemo()); for (int i = 27; i <= 28; i++) slides.add(new PictureSlide(Lecture4.class.getResource(String.format("l4.%03d.jpg", i)))); slides.add(new KMeansSpatialSegmentationDemo()); for (int i = 29; i <= 30; i++) slides.add(new PictureSlide(Lecture4.class.getResource(String.format("l4.%03d.jpg", i)))); slides.add(new FHSegmentationDemo()); for (int i = 31; i <= 36; i++) slides.add(new PictureSlide(Lecture4.class.getResource(String.format("l4.%03d.jpg", i)))); slides.add(new ConnectedComponentsDemo()); slides.add(new PictureSlide(Lecture4.class.getResource("l4.037.jpg")));
new SlideshowApplication(slides, 1024, 768, Utils.BACKGROUND_IMAGE);
jonhare/COMP3204
app/src/main/java/uk/ac/soton/ecs/comp3204/l6/HarrisPointsDemo.java
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l1/SimpleCameraDemo.java // @Demonstration(title = "Simple Camera Demo") // public class SimpleCameraDemo implements Slide { // protected VideoCaptureComponent vc; // // @Override // public JPanel getComponent(int width, int height) throws IOException { // // the main panel // final JPanel base = new JPanel(); // base.setOpaque(false); // base.setPreferredSize(new Dimension(width, height)); // base.setLayout(new GridBagLayout()); // vc = new VideoCaptureComponent(640, 480); // base.add(vc); // // return base; // } // // @Override // public void close() { // vc.close(); // } // // public static void main(String[] args) throws IOException { // new SlideshowApplication(new SimpleCameraDemo(), 1024, 768, Utils.BACKGROUND_IMAGE); // } // } // // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // }
import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.io.IOException; import java.util.List; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.image.MBFImage; import org.openimaj.image.colour.RGBColour; import org.openimaj.image.feature.local.interest.HarrisIPD; import org.openimaj.image.feature.local.interest.InterestPointData; import org.openimaj.video.VideoDisplay; import org.openimaj.video.VideoDisplayListener; import uk.ac.soton.ecs.comp3204.l1.SimpleCameraDemo; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration;
return c; } @Override public void afterUpdate(VideoDisplay<MBFImage> display) { // do nothing } @Override public void beforeUpdate(MBFImage frame) { harris.setDetectionScale(0); harris.setImageBlurred(true); harris.setIntegrationScale(computeScale()); harris.findInterestPoints(frame.flatten()); final List<InterestPointData> pts = harris.getInterestPoints(thresholdSpinner.getValue() / 100000f); for (final InterestPointData pt : pts) { frame.drawPoint(pt, RGBColour.RED, 5); } } private float computeScale() { final int size = (Integer) windowSizeSpinner.getValue(); return (size - 1f) / 8f; } public static void main(String[] args) throws IOException {
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l1/SimpleCameraDemo.java // @Demonstration(title = "Simple Camera Demo") // public class SimpleCameraDemo implements Slide { // protected VideoCaptureComponent vc; // // @Override // public JPanel getComponent(int width, int height) throws IOException { // // the main panel // final JPanel base = new JPanel(); // base.setOpaque(false); // base.setPreferredSize(new Dimension(width, height)); // base.setLayout(new GridBagLayout()); // vc = new VideoCaptureComponent(640, 480); // base.add(vc); // // return base; // } // // @Override // public void close() { // vc.close(); // } // // public static void main(String[] args) throws IOException { // new SlideshowApplication(new SimpleCameraDemo(), 1024, 768, Utils.BACKGROUND_IMAGE); // } // } // // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // } // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l6/HarrisPointsDemo.java import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.io.IOException; import java.util.List; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.image.MBFImage; import org.openimaj.image.colour.RGBColour; import org.openimaj.image.feature.local.interest.HarrisIPD; import org.openimaj.image.feature.local.interest.InterestPointData; import org.openimaj.video.VideoDisplay; import org.openimaj.video.VideoDisplayListener; import uk.ac.soton.ecs.comp3204.l1.SimpleCameraDemo; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration; return c; } @Override public void afterUpdate(VideoDisplay<MBFImage> display) { // do nothing } @Override public void beforeUpdate(MBFImage frame) { harris.setDetectionScale(0); harris.setImageBlurred(true); harris.setIntegrationScale(computeScale()); harris.findInterestPoints(frame.flatten()); final List<InterestPointData> pts = harris.getInterestPoints(thresholdSpinner.getValue() / 100000f); for (final InterestPointData pt : pts) { frame.drawPoint(pt, RGBColour.RED, 5); } } private float computeScale() { final int size = (Integer) windowSizeSpinner.getValue(); return (size - 1f) / 8f; } public static void main(String[] args) throws IOException {
new SlideshowApplication(new HarrisPointsDemo(), 1024, 768, Utils.BACKGROUND_IMAGE);
jonhare/COMP3204
app/src/main/java/uk/ac/soton/ecs/comp3204/l1/Lecture1.java
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // }
import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.openimaj.content.slideshow.PictureSlide; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.content.slideshow.VideoSlide; import org.openimaj.video.VideoDisplay.EndAction; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.JvmArgs; import uk.ac.soton.ecs.comp3204.utils.annotations.Lecture;
package uk.ac.soton.ecs.comp3204.l1; @Lecture(title = "L1: Building machines that see", handoutsURL = "http://jonhare.github.io/COMP3204/handouts/pdf/L1-machines-that-see.pdf", slidesURL = "http://jonhare.github.io/COMP3204/lectures/pdf/L1-machines-that-see.pdf") @JvmArgs(vmArguments = "-Xmx1G") public class Lecture1 { public static void main(String[] args) throws IOException { final List<Slide> slides = new ArrayList<Slide>(); for (int i = 1; i <= 25; i++) slides.add(new PictureSlide(Lecture1.class.getResource(String.format("l1.%03d.jpg", i)))); slides.add(new ColourSpacesDemo()); for (int i = 26; i <= 27; i++) slides.add(new PictureSlide(Lecture1.class.getResource(String.format("l1.%03d.jpg", i)))); slides.add(new SimpleCameraDemo()); for (int i = 28; i <= 28; i++) slides.add(new PictureSlide(Lecture1.class.getResource(String.format("l1.%03d.jpg", i))));
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // } // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l1/Lecture1.java import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.openimaj.content.slideshow.PictureSlide; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.content.slideshow.VideoSlide; import org.openimaj.video.VideoDisplay.EndAction; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.JvmArgs; import uk.ac.soton.ecs.comp3204.utils.annotations.Lecture; package uk.ac.soton.ecs.comp3204.l1; @Lecture(title = "L1: Building machines that see", handoutsURL = "http://jonhare.github.io/COMP3204/handouts/pdf/L1-machines-that-see.pdf", slidesURL = "http://jonhare.github.io/COMP3204/lectures/pdf/L1-machines-that-see.pdf") @JvmArgs(vmArguments = "-Xmx1G") public class Lecture1 { public static void main(String[] args) throws IOException { final List<Slide> slides = new ArrayList<Slide>(); for (int i = 1; i <= 25; i++) slides.add(new PictureSlide(Lecture1.class.getResource(String.format("l1.%03d.jpg", i)))); slides.add(new ColourSpacesDemo()); for (int i = 26; i <= 27; i++) slides.add(new PictureSlide(Lecture1.class.getResource(String.format("l1.%03d.jpg", i)))); slides.add(new SimpleCameraDemo()); for (int i = 28; i <= 28; i++) slides.add(new PictureSlide(Lecture1.class.getResource(String.format("l1.%03d.jpg", i))));
slides.add(new VideoSlide(Lecture1.class.getResource("grader.mp4"), Utils.BACKGROUND_IMAGE_URL,
jonhare/COMP3204
app/src/main/java/uk/ac/soton/ecs/comp3204/l3/FaceDatasetDemo.java
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // }
import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridBagLayout; import java.io.File; import java.io.IOException; import javax.swing.JPanel; import org.apache.commons.io.FileUtils; import org.apache.commons.vfs2.FileSystemException; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.data.dataset.VFSGroupDataset; import org.openimaj.image.DisplayUtilities.ImageComponent; import org.openimaj.image.FImage; import org.openimaj.image.ImageUtilities; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration;
outer.setOpaque(false); outer.setPreferredSize(new Dimension(width, height)); outer.setLayout(new GridBagLayout()); final JPanel base = new JPanel(); base.setOpaque(false); base.setPreferredSize(new Dimension(width, height - 50)); base.setLayout(new FlowLayout()); for (int i = 0; i < 60; i++) { final FImage img = dataset.getRandomInstance(); final ImageComponent ic = new ImageComponent(true, false); ic.setAllowPanning(false); ic.setAllowZoom(false); ic.setShowPixelColours(false); ic.setShowXYPosition(false); ic.setImage(ImageUtilities.createBufferedImageForDisplay(img)); base.add(ic); } outer.add(base); return outer; } @Override public void close() { // do nothing } public static void main(String[] args) throws IOException {
// Path: app/src/main/java/uk/ac/soton/ecs/comp3204/utils/Utils.java // public class Utils { // public static URL BACKGROUND_IMAGE_URL = Utils.class.getResource("/uk/ac/soton/ecs/comp3204/background.png"); // public static BufferedImage BACKGROUND_IMAGE = null; // static { // try { // BACKGROUND_IMAGE = ImageIO.read(BACKGROUND_IMAGE_URL); // } catch (final IOException e) { // } // } // // private Utils() { // } // // public static JLabel linkify(final String text, String URL, String toolTip) // { // URI temp = null; // try // { // temp = new URI(URL); // } catch (final Exception e) // { // e.printStackTrace(); // } // final URI uri = temp; // final JLabel link = new JLabel(); // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // if (!toolTip.equals("")) // link.setToolTipText(toolTip); // link.setCursor(new Cursor(Cursor.HAND_CURSOR)); // link.addMouseListener(new MouseListener() // { // @Override // public void mouseExited(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>"); // } // // @Override // public void mouseEntered(MouseEvent arg0) // { // link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>"); // } // // @Override // public void mouseClicked(MouseEvent arg0) // { // if (Desktop.isDesktopSupported()) // { // try // { // Desktop.getDesktop().browse(uri); // } // catch (final Exception e) // { // e.printStackTrace(); // } // } // else // { // final JOptionPane pane = new JOptionPane("Could not open link."); // final JDialog dialog = pane.createDialog(new JFrame(), ""); // dialog.setVisible(true); // } // } // // @Override // public void mousePressed(MouseEvent e) // { // } // // @Override // public void mouseReleased(MouseEvent e) // { // } // }); // return link; // } // } // Path: app/src/main/java/uk/ac/soton/ecs/comp3204/l3/FaceDatasetDemo.java import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridBagLayout; import java.io.File; import java.io.IOException; import javax.swing.JPanel; import org.apache.commons.io.FileUtils; import org.apache.commons.vfs2.FileSystemException; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.data.dataset.VFSGroupDataset; import org.openimaj.image.DisplayUtilities.ImageComponent; import org.openimaj.image.FImage; import org.openimaj.image.ImageUtilities; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration; outer.setOpaque(false); outer.setPreferredSize(new Dimension(width, height)); outer.setLayout(new GridBagLayout()); final JPanel base = new JPanel(); base.setOpaque(false); base.setPreferredSize(new Dimension(width, height - 50)); base.setLayout(new FlowLayout()); for (int i = 0; i < 60; i++) { final FImage img = dataset.getRandomInstance(); final ImageComponent ic = new ImageComponent(true, false); ic.setAllowPanning(false); ic.setAllowZoom(false); ic.setShowPixelColours(false); ic.setShowXYPosition(false); ic.setImage(ImageUtilities.createBufferedImageForDisplay(img)); base.add(ic); } outer.add(base); return outer; } @Override public void close() { // do nothing } public static void main(String[] args) throws IOException {
new SlideshowApplication(new FaceDatasetDemo(), 1024, 768, Utils.BACKGROUND_IMAGE);