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
ptitfred/magrit
server/sshd/src/main/java/org/kercoin/magrit/sshd/commands/MonitorCommand.java
// Path: server/core/src/main/java/org/kercoin/magrit/core/Context.java // @Singleton // public class Context { // // private final Configuration configuration = new Configuration(); // // private Injector injector; // // private final GitUtils gitUtils; // // private final ExecutorService commandRunnerPool; // // public Context() { // gitUtils = null; // commandRunnerPool = null; // } // // public Context(GitUtils gitUtils) { // this(gitUtils, null); // } // // @Inject // public Context(GitUtils gitUtils, // @Named("commandRunnerPool") ExecutorService commandRunnerPool) { // this.gitUtils = gitUtils; // this.commandRunnerPool = commandRunnerPool; // } // // public Configuration configuration() { // return configuration; // } // // public Injector getInjector() { // return injector; // } // // public ExecutorService getCommandRunnerPool() { // return commandRunnerPool; // } // // public void setInjector(Injector injector) { // this.injector = injector; // } // // public GitUtils getGitUtils() { // return gitUtils; // } // // } // // Path: server/core/src/main/java/org/kercoin/magrit/core/Pair.java // public class Pair<T, U> { // private T t; // private U u; // // public Pair(T t, U u) { // super(); // this.t = t; // this.u = u; // } // // public T getT() { // return t; // } // // public U getU() { // return u; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((t == null) ? 0 : t.hashCode()); // result = prime * result + ((u == null) ? 0 : u.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // @SuppressWarnings("unchecked") // Pair<T, U> other = (Pair<T, U>) obj; // if (t == null) { // if (other.t != null) // return false; // } else if (!t.equals(other.t)) // return false; // if (u == null) { // if (other.u != null) // return false; // } else if (!u.equals(other.u)) // return false; // return true; // } // // } // // Path: server/core/src/main/java/org/kercoin/magrit/core/build/BuildLifeCycleListener.java // public interface BuildLifeCycleListener { // // void buildScheduled(Repository repo, String sha1); // // void buildStarted(Repository repo, String sha1); // // void buildEnded(Repository repo, String sha1, Status status); // } // // Path: server/core/src/main/java/org/kercoin/magrit/core/build/QueueService.java // @ImplementedBy(QueueServiceImpl.class) // public interface QueueService { // Future<BuildResult> enqueueBuild(UserIdentity committer, Repository repository, // String sha1, String command, boolean force) throws Exception; // // void addCallback(BuildLifeCycleListener callback); // // void removeCallback(BuildLifeCycleListener callback); // // Collection<Pair<Repository, String>> getScheduledTasks(); // Collection<Pair<Repository, String>> getCurrentTasks(); // // } // // Path: server/core/src/main/java/org/kercoin/magrit/core/build/Status.java // public enum Status { // RUNNING('R'), // PENDING('P'), // ERROR('E'), // OK('O'), // INTERRUPTED('I'), // LOCAL('L'), // NEW('N'), // UNKNOWN('?'); // // private char code; // // private Status(char code) { this.code = code; } // // public char getCode() { // return code; // } // }
import com.google.inject.Inject; import com.google.inject.Singleton; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.Date; import org.eclipse.jgit.lib.Repository; import org.kercoin.magrit.core.Context; import org.kercoin.magrit.core.Pair; import org.kercoin.magrit.core.build.BuildLifeCycleListener; import org.kercoin.magrit.core.build.QueueService; import org.kercoin.magrit.core.build.Status;
@Override public boolean accept(String command) { return "magrit monitor".equals(command); } } @Override protected String getName() { return "MonitorCommand"; } @Override protected Class<MonitorCommand> getType() { return MonitorCommand.class; } private final QueueService buildQueueService; public MonitorCommand(Context ctx, QueueService buildQueueService) { super(ctx); this.buildQueueService = buildQueueService; } @Override public void run() { printOut.println("-- In Progress builds --"); // TODO read previous statuses and log them if (buildQueueService.getCurrentTasks().size() > 0) {
// Path: server/core/src/main/java/org/kercoin/magrit/core/Context.java // @Singleton // public class Context { // // private final Configuration configuration = new Configuration(); // // private Injector injector; // // private final GitUtils gitUtils; // // private final ExecutorService commandRunnerPool; // // public Context() { // gitUtils = null; // commandRunnerPool = null; // } // // public Context(GitUtils gitUtils) { // this(gitUtils, null); // } // // @Inject // public Context(GitUtils gitUtils, // @Named("commandRunnerPool") ExecutorService commandRunnerPool) { // this.gitUtils = gitUtils; // this.commandRunnerPool = commandRunnerPool; // } // // public Configuration configuration() { // return configuration; // } // // public Injector getInjector() { // return injector; // } // // public ExecutorService getCommandRunnerPool() { // return commandRunnerPool; // } // // public void setInjector(Injector injector) { // this.injector = injector; // } // // public GitUtils getGitUtils() { // return gitUtils; // } // // } // // Path: server/core/src/main/java/org/kercoin/magrit/core/Pair.java // public class Pair<T, U> { // private T t; // private U u; // // public Pair(T t, U u) { // super(); // this.t = t; // this.u = u; // } // // public T getT() { // return t; // } // // public U getU() { // return u; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((t == null) ? 0 : t.hashCode()); // result = prime * result + ((u == null) ? 0 : u.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // @SuppressWarnings("unchecked") // Pair<T, U> other = (Pair<T, U>) obj; // if (t == null) { // if (other.t != null) // return false; // } else if (!t.equals(other.t)) // return false; // if (u == null) { // if (other.u != null) // return false; // } else if (!u.equals(other.u)) // return false; // return true; // } // // } // // Path: server/core/src/main/java/org/kercoin/magrit/core/build/BuildLifeCycleListener.java // public interface BuildLifeCycleListener { // // void buildScheduled(Repository repo, String sha1); // // void buildStarted(Repository repo, String sha1); // // void buildEnded(Repository repo, String sha1, Status status); // } // // Path: server/core/src/main/java/org/kercoin/magrit/core/build/QueueService.java // @ImplementedBy(QueueServiceImpl.class) // public interface QueueService { // Future<BuildResult> enqueueBuild(UserIdentity committer, Repository repository, // String sha1, String command, boolean force) throws Exception; // // void addCallback(BuildLifeCycleListener callback); // // void removeCallback(BuildLifeCycleListener callback); // // Collection<Pair<Repository, String>> getScheduledTasks(); // Collection<Pair<Repository, String>> getCurrentTasks(); // // } // // Path: server/core/src/main/java/org/kercoin/magrit/core/build/Status.java // public enum Status { // RUNNING('R'), // PENDING('P'), // ERROR('E'), // OK('O'), // INTERRUPTED('I'), // LOCAL('L'), // NEW('N'), // UNKNOWN('?'); // // private char code; // // private Status(char code) { this.code = code; } // // public char getCode() { // return code; // } // } // Path: server/sshd/src/main/java/org/kercoin/magrit/sshd/commands/MonitorCommand.java import com.google.inject.Inject; import com.google.inject.Singleton; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.Date; import org.eclipse.jgit.lib.Repository; import org.kercoin.magrit.core.Context; import org.kercoin.magrit.core.Pair; import org.kercoin.magrit.core.build.BuildLifeCycleListener; import org.kercoin.magrit.core.build.QueueService; import org.kercoin.magrit.core.build.Status; @Override public boolean accept(String command) { return "magrit monitor".equals(command); } } @Override protected String getName() { return "MonitorCommand"; } @Override protected Class<MonitorCommand> getType() { return MonitorCommand.class; } private final QueueService buildQueueService; public MonitorCommand(Context ctx, QueueService buildQueueService) { super(ctx); this.buildQueueService = buildQueueService; } @Override public void run() { printOut.println("-- In Progress builds --"); // TODO read previous statuses and log them if (buildQueueService.getCurrentTasks().size() > 0) {
for (Pair<Repository, String> build : buildQueueService.getCurrentTasks()) {
ptitfred/magrit
server/sshd/src/main/java/org/kercoin/magrit/sshd/commands/MonitorCommand.java
// Path: server/core/src/main/java/org/kercoin/magrit/core/Context.java // @Singleton // public class Context { // // private final Configuration configuration = new Configuration(); // // private Injector injector; // // private final GitUtils gitUtils; // // private final ExecutorService commandRunnerPool; // // public Context() { // gitUtils = null; // commandRunnerPool = null; // } // // public Context(GitUtils gitUtils) { // this(gitUtils, null); // } // // @Inject // public Context(GitUtils gitUtils, // @Named("commandRunnerPool") ExecutorService commandRunnerPool) { // this.gitUtils = gitUtils; // this.commandRunnerPool = commandRunnerPool; // } // // public Configuration configuration() { // return configuration; // } // // public Injector getInjector() { // return injector; // } // // public ExecutorService getCommandRunnerPool() { // return commandRunnerPool; // } // // public void setInjector(Injector injector) { // this.injector = injector; // } // // public GitUtils getGitUtils() { // return gitUtils; // } // // } // // Path: server/core/src/main/java/org/kercoin/magrit/core/Pair.java // public class Pair<T, U> { // private T t; // private U u; // // public Pair(T t, U u) { // super(); // this.t = t; // this.u = u; // } // // public T getT() { // return t; // } // // public U getU() { // return u; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((t == null) ? 0 : t.hashCode()); // result = prime * result + ((u == null) ? 0 : u.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // @SuppressWarnings("unchecked") // Pair<T, U> other = (Pair<T, U>) obj; // if (t == null) { // if (other.t != null) // return false; // } else if (!t.equals(other.t)) // return false; // if (u == null) { // if (other.u != null) // return false; // } else if (!u.equals(other.u)) // return false; // return true; // } // // } // // Path: server/core/src/main/java/org/kercoin/magrit/core/build/BuildLifeCycleListener.java // public interface BuildLifeCycleListener { // // void buildScheduled(Repository repo, String sha1); // // void buildStarted(Repository repo, String sha1); // // void buildEnded(Repository repo, String sha1, Status status); // } // // Path: server/core/src/main/java/org/kercoin/magrit/core/build/QueueService.java // @ImplementedBy(QueueServiceImpl.class) // public interface QueueService { // Future<BuildResult> enqueueBuild(UserIdentity committer, Repository repository, // String sha1, String command, boolean force) throws Exception; // // void addCallback(BuildLifeCycleListener callback); // // void removeCallback(BuildLifeCycleListener callback); // // Collection<Pair<Repository, String>> getScheduledTasks(); // Collection<Pair<Repository, String>> getCurrentTasks(); // // } // // Path: server/core/src/main/java/org/kercoin/magrit/core/build/Status.java // public enum Status { // RUNNING('R'), // PENDING('P'), // ERROR('E'), // OK('O'), // INTERRUPTED('I'), // LOCAL('L'), // NEW('N'), // UNKNOWN('?'); // // private char code; // // private Status(char code) { this.code = code; } // // public char getCode() { // return code; // } // }
import com.google.inject.Inject; import com.google.inject.Singleton; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.Date; import org.eclipse.jgit.lib.Repository; import org.kercoin.magrit.core.Context; import org.kercoin.magrit.core.Pair; import org.kercoin.magrit.core.build.BuildLifeCycleListener; import org.kercoin.magrit.core.build.QueueService; import org.kercoin.magrit.core.build.Status;
private PrintStream printOut; @Override public void setOutputStream(OutputStream out) { super.setOutputStream(out); printOut = new PrintStream(out); } private String now() { return new Date().toString(); } @Override public void buildScheduled(Repository repo, String sha1) { synchronized(out) { printOut.println(String.format("%s - Build scheduled on %s @ %s", now(), repo, sha1)); printOut.flush(); } } @Override public void buildStarted(Repository repo, String sha1) { synchronized(out) { printOut.println(String.format("%s - Build started on %s @ %s", now(), repo, sha1)); printOut.flush(); } } @Override
// Path: server/core/src/main/java/org/kercoin/magrit/core/Context.java // @Singleton // public class Context { // // private final Configuration configuration = new Configuration(); // // private Injector injector; // // private final GitUtils gitUtils; // // private final ExecutorService commandRunnerPool; // // public Context() { // gitUtils = null; // commandRunnerPool = null; // } // // public Context(GitUtils gitUtils) { // this(gitUtils, null); // } // // @Inject // public Context(GitUtils gitUtils, // @Named("commandRunnerPool") ExecutorService commandRunnerPool) { // this.gitUtils = gitUtils; // this.commandRunnerPool = commandRunnerPool; // } // // public Configuration configuration() { // return configuration; // } // // public Injector getInjector() { // return injector; // } // // public ExecutorService getCommandRunnerPool() { // return commandRunnerPool; // } // // public void setInjector(Injector injector) { // this.injector = injector; // } // // public GitUtils getGitUtils() { // return gitUtils; // } // // } // // Path: server/core/src/main/java/org/kercoin/magrit/core/Pair.java // public class Pair<T, U> { // private T t; // private U u; // // public Pair(T t, U u) { // super(); // this.t = t; // this.u = u; // } // // public T getT() { // return t; // } // // public U getU() { // return u; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((t == null) ? 0 : t.hashCode()); // result = prime * result + ((u == null) ? 0 : u.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // @SuppressWarnings("unchecked") // Pair<T, U> other = (Pair<T, U>) obj; // if (t == null) { // if (other.t != null) // return false; // } else if (!t.equals(other.t)) // return false; // if (u == null) { // if (other.u != null) // return false; // } else if (!u.equals(other.u)) // return false; // return true; // } // // } // // Path: server/core/src/main/java/org/kercoin/magrit/core/build/BuildLifeCycleListener.java // public interface BuildLifeCycleListener { // // void buildScheduled(Repository repo, String sha1); // // void buildStarted(Repository repo, String sha1); // // void buildEnded(Repository repo, String sha1, Status status); // } // // Path: server/core/src/main/java/org/kercoin/magrit/core/build/QueueService.java // @ImplementedBy(QueueServiceImpl.class) // public interface QueueService { // Future<BuildResult> enqueueBuild(UserIdentity committer, Repository repository, // String sha1, String command, boolean force) throws Exception; // // void addCallback(BuildLifeCycleListener callback); // // void removeCallback(BuildLifeCycleListener callback); // // Collection<Pair<Repository, String>> getScheduledTasks(); // Collection<Pair<Repository, String>> getCurrentTasks(); // // } // // Path: server/core/src/main/java/org/kercoin/magrit/core/build/Status.java // public enum Status { // RUNNING('R'), // PENDING('P'), // ERROR('E'), // OK('O'), // INTERRUPTED('I'), // LOCAL('L'), // NEW('N'), // UNKNOWN('?'); // // private char code; // // private Status(char code) { this.code = code; } // // public char getCode() { // return code; // } // } // Path: server/sshd/src/main/java/org/kercoin/magrit/sshd/commands/MonitorCommand.java import com.google.inject.Inject; import com.google.inject.Singleton; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.Date; import org.eclipse.jgit.lib.Repository; import org.kercoin.magrit.core.Context; import org.kercoin.magrit.core.Pair; import org.kercoin.magrit.core.build.BuildLifeCycleListener; import org.kercoin.magrit.core.build.QueueService; import org.kercoin.magrit.core.build.Status; private PrintStream printOut; @Override public void setOutputStream(OutputStream out) { super.setOutputStream(out); printOut = new PrintStream(out); } private String now() { return new Date().toString(); } @Override public void buildScheduled(Repository repo, String sha1) { synchronized(out) { printOut.println(String.format("%s - Build scheduled on %s @ %s", now(), repo, sha1)); printOut.flush(); } } @Override public void buildStarted(Repository repo, String sha1) { synchronized(out) { printOut.println(String.format("%s - Build started on %s @ %s", now(), repo, sha1)); printOut.flush(); } } @Override
public void buildEnded(Repository repo, String sha1, Status status) {
ptitfred/magrit
server/core/src/test/java/tests/GuiceModulesHolder.java
// Path: server/core/src/main/java/org/kercoin/magrit/core/CoreModule.java // public class CoreModule extends AbstractModule { // // @Override // protected void configure() { // bind(BuildDAO.class).to(BuildDAOImpl.class); // bind(ExecutorService.class).annotatedWith(Names.named("commandRunnerPool")).toInstance(Executors.newCachedThreadPool()); // } // // }
import com.google.inject.Injector; import org.kercoin.magrit.core.CoreModule; import com.google.inject.Guice;
/* Copyright 2011-2012 Frederic Menou and others referred in AUTHORS file. This file is part of Magrit. Magrit 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. Magrit 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 Magrit. If not, see <http://www.gnu.org/licenses/>. */ package tests; public class GuiceModulesHolder { public static final Injector MAGRIT_MODULE; static {
// Path: server/core/src/main/java/org/kercoin/magrit/core/CoreModule.java // public class CoreModule extends AbstractModule { // // @Override // protected void configure() { // bind(BuildDAO.class).to(BuildDAOImpl.class); // bind(ExecutorService.class).annotatedWith(Names.named("commandRunnerPool")).toInstance(Executors.newCachedThreadPool()); // } // // } // Path: server/core/src/test/java/tests/GuiceModulesHolder.java import com.google.inject.Injector; import org.kercoin.magrit.core.CoreModule; import com.google.inject.Guice; /* Copyright 2011-2012 Frederic Menou and others referred in AUTHORS file. This file is part of Magrit. Magrit 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. Magrit 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 Magrit. If not, see <http://www.gnu.org/licenses/>. */ package tests; public class GuiceModulesHolder { public static final Injector MAGRIT_MODULE; static {
MAGRIT_MODULE = Guice.createInjector(new CoreModule());
ptitfred/magrit
server/core/src/main/java/org/kercoin/magrit/core/utils/SimpleTimeService.java
// Path: server/core/src/main/java/org/kercoin/magrit/core/Pair.java // public class Pair<T, U> { // private T t; // private U u; // // public Pair(T t, U u) { // super(); // this.t = t; // this.u = u; // } // // public T getT() { // return t; // } // // public U getU() { // return u; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((t == null) ? 0 : t.hashCode()); // result = prime * result + ((u == null) ? 0 : u.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // @SuppressWarnings("unchecked") // Pair<T, U> other = (Pair<T, U>) obj; // if (t == null) { // if (other.t != null) // return false; // } else if (!t.equals(other.t)) // return false; // if (u == null) { // if (other.u != null) // return false; // } else if (!u.equals(other.u)) // return false; // return true; // } // // }
import org.kercoin.magrit.core.Pair; import java.util.Calendar; import java.util.TimeZone;
/* Copyright 2011-2012 Frederic Menou and others referred in AUTHORS file. This file is part of Magrit. Magrit 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. Magrit 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 Magrit. If not, see <http://www.gnu.org/licenses/>. */ package org.kercoin.magrit.core.utils; public class SimpleTimeService implements TimeService { @Override
// Path: server/core/src/main/java/org/kercoin/magrit/core/Pair.java // public class Pair<T, U> { // private T t; // private U u; // // public Pair(T t, U u) { // super(); // this.t = t; // this.u = u; // } // // public T getT() { // return t; // } // // public U getU() { // return u; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((t == null) ? 0 : t.hashCode()); // result = prime * result + ((u == null) ? 0 : u.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // @SuppressWarnings("unchecked") // Pair<T, U> other = (Pair<T, U>) obj; // if (t == null) { // if (other.t != null) // return false; // } else if (!t.equals(other.t)) // return false; // if (u == null) { // if (other.u != null) // return false; // } else if (!u.equals(other.u)) // return false; // return true; // } // // } // Path: server/core/src/main/java/org/kercoin/magrit/core/utils/SimpleTimeService.java import org.kercoin.magrit.core.Pair; import java.util.Calendar; import java.util.TimeZone; /* Copyright 2011-2012 Frederic Menou and others referred in AUTHORS file. This file is part of Magrit. Magrit 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. Magrit 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 Magrit. If not, see <http://www.gnu.org/licenses/>. */ package org.kercoin.magrit.core.utils; public class SimpleTimeService implements TimeService { @Override
public Pair<Long, Integer> now() {
ptitfred/magrit
server/main/src/main/java/org/kercoin/magrit/ArgumentsParser.java
// Path: server/core/src/main/java/org/kercoin/magrit/core/Configuration.java // public class Configuration { // // private static final String DEFAULT_BASE_DIR = System.getProperty("java.io.tmpdir") + "/magrit"; // // private int sshPort = 2022; // // private File repositoriesHomeDir = new File(DEFAULT_BASE_DIR, "repos"); // // private File publickeysRepositoryDir = new File(DEFAULT_BASE_DIR, "keys"); // // private File workHomeDir = new File(DEFAULT_BASE_DIR, "builds"); // // private Authentication authentication = Authentication.SSH_PUBLIC_KEYS; // // private boolean remoteAllowed; // // public static enum Authentication { // SSH_PUBLIC_KEYS { public String external() { return "ssh-public-keys"; } }, // NONE { public String external() { return "none"; } }; // // public abstract String external(); // // /** // * @param authValue // * @return // */ // public static Authentication fromExternalValue(String authValue) { // for (Authentication auth : Authentication.values()) { // if (auth.external().equals(authValue)) { // return auth; // } // } // return Authentication.NONE; // } // } // // public int getSshPort() { // return sshPort; // } // // public void setSshPort(int sshPort) { // this.sshPort = sshPort; // } // // public Authentication getAuthentication() { // return authentication; // } // // public void setAuthentication(Authentication authentication) { // this.authentication = authentication; // } // // public File getRepositoriesHomeDir() { // return repositoriesHomeDir; // } // // public void setRepositoriesHomeDir(File repositoriesHomeDir) { // this.repositoriesHomeDir = repositoriesHomeDir; // } // // public File getWorkHomeDir() { // return workHomeDir; // } // // public void setWorkHomeDir(File workHomeDir) { // this.workHomeDir = workHomeDir; // } // // public File getPublickeyRepositoryDir() { // return publickeysRepositoryDir; // } // // public void setPublickeysRepositoryDir(File publickeysRepositoryDir) { // this.publickeysRepositoryDir = publickeysRepositoryDir; // } // // public void applyStandardLayout(String dir) { // repositoriesHomeDir = new File(dir, "bares"); // workHomeDir = new File(dir, "builds"); // publickeysRepositoryDir = new File(dir, "keys"); // } // // public boolean isRemoteAllowed() { // return remoteAllowed; // } // // public void setRemoteAllowed(boolean remoteAllowed) { // this.remoteAllowed = remoteAllowed; // } // // public int getSlots() { // return Runtime.getRuntime().availableProcessors(); // } // // } // // Path: server/core/src/main/java/org/kercoin/magrit/core/Configuration.java // public static enum Authentication { // SSH_PUBLIC_KEYS { public String external() { return "ssh-public-keys"; } }, // NONE { public String external() { return "none"; } }; // // public abstract String external(); // // /** // * @param authValue // * @return // */ // public static Authentication fromExternalValue(String authValue) { // for (Authentication auth : Authentication.values()) { // if (auth.external().equals(authValue)) { // return auth; // } // } // return Authentication.NONE; // } // }
import java.io.File; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.kercoin.magrit.core.Configuration; import org.kercoin.magrit.core.Configuration.Authentication;
/* Copyright 2011-2012 Frederic Menou and others referred in AUTHORS file. This file is part of Magrit. Magrit 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. Magrit 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 Magrit. If not, see <http://www.gnu.org/licenses/>. */ package org.kercoin.magrit; /** * @author ptitfred * */ class ArgumentsParser { private final CommandLine cmdLine; ArgumentsParser(String[] args) throws ParseException { CommandLineParser parser = new PosixParser(); Options options = createCmdLineOptions(); this.cmdLine = parser.parse(options, args, true); }
// Path: server/core/src/main/java/org/kercoin/magrit/core/Configuration.java // public class Configuration { // // private static final String DEFAULT_BASE_DIR = System.getProperty("java.io.tmpdir") + "/magrit"; // // private int sshPort = 2022; // // private File repositoriesHomeDir = new File(DEFAULT_BASE_DIR, "repos"); // // private File publickeysRepositoryDir = new File(DEFAULT_BASE_DIR, "keys"); // // private File workHomeDir = new File(DEFAULT_BASE_DIR, "builds"); // // private Authentication authentication = Authentication.SSH_PUBLIC_KEYS; // // private boolean remoteAllowed; // // public static enum Authentication { // SSH_PUBLIC_KEYS { public String external() { return "ssh-public-keys"; } }, // NONE { public String external() { return "none"; } }; // // public abstract String external(); // // /** // * @param authValue // * @return // */ // public static Authentication fromExternalValue(String authValue) { // for (Authentication auth : Authentication.values()) { // if (auth.external().equals(authValue)) { // return auth; // } // } // return Authentication.NONE; // } // } // // public int getSshPort() { // return sshPort; // } // // public void setSshPort(int sshPort) { // this.sshPort = sshPort; // } // // public Authentication getAuthentication() { // return authentication; // } // // public void setAuthentication(Authentication authentication) { // this.authentication = authentication; // } // // public File getRepositoriesHomeDir() { // return repositoriesHomeDir; // } // // public void setRepositoriesHomeDir(File repositoriesHomeDir) { // this.repositoriesHomeDir = repositoriesHomeDir; // } // // public File getWorkHomeDir() { // return workHomeDir; // } // // public void setWorkHomeDir(File workHomeDir) { // this.workHomeDir = workHomeDir; // } // // public File getPublickeyRepositoryDir() { // return publickeysRepositoryDir; // } // // public void setPublickeysRepositoryDir(File publickeysRepositoryDir) { // this.publickeysRepositoryDir = publickeysRepositoryDir; // } // // public void applyStandardLayout(String dir) { // repositoriesHomeDir = new File(dir, "bares"); // workHomeDir = new File(dir, "builds"); // publickeysRepositoryDir = new File(dir, "keys"); // } // // public boolean isRemoteAllowed() { // return remoteAllowed; // } // // public void setRemoteAllowed(boolean remoteAllowed) { // this.remoteAllowed = remoteAllowed; // } // // public int getSlots() { // return Runtime.getRuntime().availableProcessors(); // } // // } // // Path: server/core/src/main/java/org/kercoin/magrit/core/Configuration.java // public static enum Authentication { // SSH_PUBLIC_KEYS { public String external() { return "ssh-public-keys"; } }, // NONE { public String external() { return "none"; } }; // // public abstract String external(); // // /** // * @param authValue // * @return // */ // public static Authentication fromExternalValue(String authValue) { // for (Authentication auth : Authentication.values()) { // if (auth.external().equals(authValue)) { // return auth; // } // } // return Authentication.NONE; // } // } // Path: server/main/src/main/java/org/kercoin/magrit/ArgumentsParser.java import java.io.File; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.kercoin.magrit.core.Configuration; import org.kercoin.magrit.core.Configuration.Authentication; /* Copyright 2011-2012 Frederic Menou and others referred in AUTHORS file. This file is part of Magrit. Magrit 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. Magrit 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 Magrit. If not, see <http://www.gnu.org/licenses/>. */ package org.kercoin.magrit; /** * @author ptitfred * */ class ArgumentsParser { private final CommandLine cmdLine; ArgumentsParser(String[] args) throws ParseException { CommandLineParser parser = new PosixParser(); Options options = createCmdLineOptions(); this.cmdLine = parser.parse(options, args, true); }
void configure(Configuration configuration) throws ParseException {
ptitfred/magrit
server/main/src/main/java/org/kercoin/magrit/ArgumentsParser.java
// Path: server/core/src/main/java/org/kercoin/magrit/core/Configuration.java // public class Configuration { // // private static final String DEFAULT_BASE_DIR = System.getProperty("java.io.tmpdir") + "/magrit"; // // private int sshPort = 2022; // // private File repositoriesHomeDir = new File(DEFAULT_BASE_DIR, "repos"); // // private File publickeysRepositoryDir = new File(DEFAULT_BASE_DIR, "keys"); // // private File workHomeDir = new File(DEFAULT_BASE_DIR, "builds"); // // private Authentication authentication = Authentication.SSH_PUBLIC_KEYS; // // private boolean remoteAllowed; // // public static enum Authentication { // SSH_PUBLIC_KEYS { public String external() { return "ssh-public-keys"; } }, // NONE { public String external() { return "none"; } }; // // public abstract String external(); // // /** // * @param authValue // * @return // */ // public static Authentication fromExternalValue(String authValue) { // for (Authentication auth : Authentication.values()) { // if (auth.external().equals(authValue)) { // return auth; // } // } // return Authentication.NONE; // } // } // // public int getSshPort() { // return sshPort; // } // // public void setSshPort(int sshPort) { // this.sshPort = sshPort; // } // // public Authentication getAuthentication() { // return authentication; // } // // public void setAuthentication(Authentication authentication) { // this.authentication = authentication; // } // // public File getRepositoriesHomeDir() { // return repositoriesHomeDir; // } // // public void setRepositoriesHomeDir(File repositoriesHomeDir) { // this.repositoriesHomeDir = repositoriesHomeDir; // } // // public File getWorkHomeDir() { // return workHomeDir; // } // // public void setWorkHomeDir(File workHomeDir) { // this.workHomeDir = workHomeDir; // } // // public File getPublickeyRepositoryDir() { // return publickeysRepositoryDir; // } // // public void setPublickeysRepositoryDir(File publickeysRepositoryDir) { // this.publickeysRepositoryDir = publickeysRepositoryDir; // } // // public void applyStandardLayout(String dir) { // repositoriesHomeDir = new File(dir, "bares"); // workHomeDir = new File(dir, "builds"); // publickeysRepositoryDir = new File(dir, "keys"); // } // // public boolean isRemoteAllowed() { // return remoteAllowed; // } // // public void setRemoteAllowed(boolean remoteAllowed) { // this.remoteAllowed = remoteAllowed; // } // // public int getSlots() { // return Runtime.getRuntime().availableProcessors(); // } // // } // // Path: server/core/src/main/java/org/kercoin/magrit/core/Configuration.java // public static enum Authentication { // SSH_PUBLIC_KEYS { public String external() { return "ssh-public-keys"; } }, // NONE { public String external() { return "none"; } }; // // public abstract String external(); // // /** // * @param authValue // * @return // */ // public static Authentication fromExternalValue(String authValue) { // for (Authentication auth : Authentication.values()) { // if (auth.external().equals(authValue)) { // return auth; // } // } // return Authentication.NONE; // } // }
import java.io.File; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.kercoin.magrit.core.Configuration; import org.kercoin.magrit.core.Configuration.Authentication;
/* Copyright 2011-2012 Frederic Menou and others referred in AUTHORS file. This file is part of Magrit. Magrit 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. Magrit 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 Magrit. If not, see <http://www.gnu.org/licenses/>. */ package org.kercoin.magrit; /** * @author ptitfred * */ class ArgumentsParser { private final CommandLine cmdLine; ArgumentsParser(String[] args) throws ParseException { CommandLineParser parser = new PosixParser(); Options options = createCmdLineOptions(); this.cmdLine = parser.parse(options, args, true); } void configure(Configuration configuration) throws ParseException { if (has("standard")) { configuration.applyStandardLayout(get("standard")); } if (has("port")) { configuration.setSshPort(getPort("port", "SSH")); } if (has("bares")) { configuration.setRepositoriesHomeDir(getFile("bares")); } if (has("work")) { configuration.setWorkHomeDir(getFile("work")); } if (has("keys")) { configuration.setPublickeysRepositoryDir(getFile("keys")); } if (has("authentication")) {
// Path: server/core/src/main/java/org/kercoin/magrit/core/Configuration.java // public class Configuration { // // private static final String DEFAULT_BASE_DIR = System.getProperty("java.io.tmpdir") + "/magrit"; // // private int sshPort = 2022; // // private File repositoriesHomeDir = new File(DEFAULT_BASE_DIR, "repos"); // // private File publickeysRepositoryDir = new File(DEFAULT_BASE_DIR, "keys"); // // private File workHomeDir = new File(DEFAULT_BASE_DIR, "builds"); // // private Authentication authentication = Authentication.SSH_PUBLIC_KEYS; // // private boolean remoteAllowed; // // public static enum Authentication { // SSH_PUBLIC_KEYS { public String external() { return "ssh-public-keys"; } }, // NONE { public String external() { return "none"; } }; // // public abstract String external(); // // /** // * @param authValue // * @return // */ // public static Authentication fromExternalValue(String authValue) { // for (Authentication auth : Authentication.values()) { // if (auth.external().equals(authValue)) { // return auth; // } // } // return Authentication.NONE; // } // } // // public int getSshPort() { // return sshPort; // } // // public void setSshPort(int sshPort) { // this.sshPort = sshPort; // } // // public Authentication getAuthentication() { // return authentication; // } // // public void setAuthentication(Authentication authentication) { // this.authentication = authentication; // } // // public File getRepositoriesHomeDir() { // return repositoriesHomeDir; // } // // public void setRepositoriesHomeDir(File repositoriesHomeDir) { // this.repositoriesHomeDir = repositoriesHomeDir; // } // // public File getWorkHomeDir() { // return workHomeDir; // } // // public void setWorkHomeDir(File workHomeDir) { // this.workHomeDir = workHomeDir; // } // // public File getPublickeyRepositoryDir() { // return publickeysRepositoryDir; // } // // public void setPublickeysRepositoryDir(File publickeysRepositoryDir) { // this.publickeysRepositoryDir = publickeysRepositoryDir; // } // // public void applyStandardLayout(String dir) { // repositoriesHomeDir = new File(dir, "bares"); // workHomeDir = new File(dir, "builds"); // publickeysRepositoryDir = new File(dir, "keys"); // } // // public boolean isRemoteAllowed() { // return remoteAllowed; // } // // public void setRemoteAllowed(boolean remoteAllowed) { // this.remoteAllowed = remoteAllowed; // } // // public int getSlots() { // return Runtime.getRuntime().availableProcessors(); // } // // } // // Path: server/core/src/main/java/org/kercoin/magrit/core/Configuration.java // public static enum Authentication { // SSH_PUBLIC_KEYS { public String external() { return "ssh-public-keys"; } }, // NONE { public String external() { return "none"; } }; // // public abstract String external(); // // /** // * @param authValue // * @return // */ // public static Authentication fromExternalValue(String authValue) { // for (Authentication auth : Authentication.values()) { // if (auth.external().equals(authValue)) { // return auth; // } // } // return Authentication.NONE; // } // } // Path: server/main/src/main/java/org/kercoin/magrit/ArgumentsParser.java import java.io.File; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.kercoin.magrit.core.Configuration; import org.kercoin.magrit.core.Configuration.Authentication; /* Copyright 2011-2012 Frederic Menou and others referred in AUTHORS file. This file is part of Magrit. Magrit 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. Magrit 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 Magrit. If not, see <http://www.gnu.org/licenses/>. */ package org.kercoin.magrit; /** * @author ptitfred * */ class ArgumentsParser { private final CommandLine cmdLine; ArgumentsParser(String[] args) throws ParseException { CommandLineParser parser = new PosixParser(); Options options = createCmdLineOptions(); this.cmdLine = parser.parse(options, args, true); } void configure(Configuration configuration) throws ParseException { if (has("standard")) { configuration.applyStandardLayout(get("standard")); } if (has("port")) { configuration.setSshPort(getPort("port", "SSH")); } if (has("bares")) { configuration.setRepositoriesHomeDir(getFile("bares")); } if (has("work")) { configuration.setWorkHomeDir(getFile("work")); } if (has("keys")) { configuration.setPublickeysRepositoryDir(getFile("keys")); } if (has("authentication")) {
Authentication authentication = Authentication.NONE;
1gravity/Android-ContactPicker
library/src/main/java/com/onegravity/contactpicker/core/ContactElementImpl.java
// Path: library/src/main/java/com/onegravity/contactpicker/ContactElement.java // public interface ContactElement extends Serializable { // // long getId(); // // String getDisplayName(); // // boolean isChecked(); // // void setChecked(boolean checked, boolean suppressListenerCall); // // void addOnContactCheckedListener(OnContactCheckedListener listener); // // boolean matchesQuery(String[] queryStrings); // // } // // Path: library/src/main/java/com/onegravity/contactpicker/Helper.java // public class Helper { // // public static boolean isNullOrEmpty(CharSequence string){ // return string == null || string.length() == 0; // } // // public static DisplayMetrics getDisplayMetrics(Context context) { // Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); // DisplayMetrics metrics = new DisplayMetrics(); // display.getMetrics( metrics ); // return metrics; // } // // public static void closeQuietly(Cursor cursor) { // try { // cursor.close(); // } // catch (Exception ignore) {} // } // // public static void closeQuietly(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (IOException ignore) {} // } // // } // // Path: library/src/main/java/com/onegravity/contactpicker/OnContactCheckedListener.java // public interface OnContactCheckedListener<E extends ContactElement> { // // void onContactChecked(E contact, boolean wasChecked, boolean isChecked); // // }
import com.onegravity.contactpicker.ContactElement; import com.onegravity.contactpicker.Helper; import com.onegravity.contactpicker.OnContactCheckedListener; import java.util.ArrayList; import java.util.List; import java.util.Locale;
/* * Copyright (C) 2015-2017 Emanuel Moecklin * * 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.onegravity.contactpicker.core; /** * The concrete but abstract implementation of ContactElement. */ abstract class ContactElementImpl implements ContactElement { final private long mId; private String mDisplayName;
// Path: library/src/main/java/com/onegravity/contactpicker/ContactElement.java // public interface ContactElement extends Serializable { // // long getId(); // // String getDisplayName(); // // boolean isChecked(); // // void setChecked(boolean checked, boolean suppressListenerCall); // // void addOnContactCheckedListener(OnContactCheckedListener listener); // // boolean matchesQuery(String[] queryStrings); // // } // // Path: library/src/main/java/com/onegravity/contactpicker/Helper.java // public class Helper { // // public static boolean isNullOrEmpty(CharSequence string){ // return string == null || string.length() == 0; // } // // public static DisplayMetrics getDisplayMetrics(Context context) { // Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); // DisplayMetrics metrics = new DisplayMetrics(); // display.getMetrics( metrics ); // return metrics; // } // // public static void closeQuietly(Cursor cursor) { // try { // cursor.close(); // } // catch (Exception ignore) {} // } // // public static void closeQuietly(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (IOException ignore) {} // } // // } // // Path: library/src/main/java/com/onegravity/contactpicker/OnContactCheckedListener.java // public interface OnContactCheckedListener<E extends ContactElement> { // // void onContactChecked(E contact, boolean wasChecked, boolean isChecked); // // } // Path: library/src/main/java/com/onegravity/contactpicker/core/ContactElementImpl.java import com.onegravity.contactpicker.ContactElement; import com.onegravity.contactpicker.Helper; import com.onegravity.contactpicker.OnContactCheckedListener; import java.util.ArrayList; import java.util.List; import java.util.Locale; /* * Copyright (C) 2015-2017 Emanuel Moecklin * * 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.onegravity.contactpicker.core; /** * The concrete but abstract implementation of ContactElement. */ abstract class ContactElementImpl implements ContactElement { final private long mId; private String mDisplayName;
transient private List<OnContactCheckedListener> mListeners = new ArrayList<>();
1gravity/Android-ContactPicker
library/src/main/java/com/onegravity/contactpicker/core/ContactElementImpl.java
// Path: library/src/main/java/com/onegravity/contactpicker/ContactElement.java // public interface ContactElement extends Serializable { // // long getId(); // // String getDisplayName(); // // boolean isChecked(); // // void setChecked(boolean checked, boolean suppressListenerCall); // // void addOnContactCheckedListener(OnContactCheckedListener listener); // // boolean matchesQuery(String[] queryStrings); // // } // // Path: library/src/main/java/com/onegravity/contactpicker/Helper.java // public class Helper { // // public static boolean isNullOrEmpty(CharSequence string){ // return string == null || string.length() == 0; // } // // public static DisplayMetrics getDisplayMetrics(Context context) { // Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); // DisplayMetrics metrics = new DisplayMetrics(); // display.getMetrics( metrics ); // return metrics; // } // // public static void closeQuietly(Cursor cursor) { // try { // cursor.close(); // } // catch (Exception ignore) {} // } // // public static void closeQuietly(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (IOException ignore) {} // } // // } // // Path: library/src/main/java/com/onegravity/contactpicker/OnContactCheckedListener.java // public interface OnContactCheckedListener<E extends ContactElement> { // // void onContactChecked(E contact, boolean wasChecked, boolean isChecked); // // }
import com.onegravity.contactpicker.ContactElement; import com.onegravity.contactpicker.Helper; import com.onegravity.contactpicker.OnContactCheckedListener; import java.util.ArrayList; import java.util.List; import java.util.Locale;
/* * Copyright (C) 2015-2017 Emanuel Moecklin * * 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.onegravity.contactpicker.core; /** * The concrete but abstract implementation of ContactElement. */ abstract class ContactElementImpl implements ContactElement { final private long mId; private String mDisplayName; transient private List<OnContactCheckedListener> mListeners = new ArrayList<>(); transient private boolean mChecked = false; ContactElementImpl(long id, String displayName) { mId = id;
// Path: library/src/main/java/com/onegravity/contactpicker/ContactElement.java // public interface ContactElement extends Serializable { // // long getId(); // // String getDisplayName(); // // boolean isChecked(); // // void setChecked(boolean checked, boolean suppressListenerCall); // // void addOnContactCheckedListener(OnContactCheckedListener listener); // // boolean matchesQuery(String[] queryStrings); // // } // // Path: library/src/main/java/com/onegravity/contactpicker/Helper.java // public class Helper { // // public static boolean isNullOrEmpty(CharSequence string){ // return string == null || string.length() == 0; // } // // public static DisplayMetrics getDisplayMetrics(Context context) { // Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); // DisplayMetrics metrics = new DisplayMetrics(); // display.getMetrics( metrics ); // return metrics; // } // // public static void closeQuietly(Cursor cursor) { // try { // cursor.close(); // } // catch (Exception ignore) {} // } // // public static void closeQuietly(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (IOException ignore) {} // } // // } // // Path: library/src/main/java/com/onegravity/contactpicker/OnContactCheckedListener.java // public interface OnContactCheckedListener<E extends ContactElement> { // // void onContactChecked(E contact, boolean wasChecked, boolean isChecked); // // } // Path: library/src/main/java/com/onegravity/contactpicker/core/ContactElementImpl.java import com.onegravity.contactpicker.ContactElement; import com.onegravity.contactpicker.Helper; import com.onegravity.contactpicker.OnContactCheckedListener; import java.util.ArrayList; import java.util.List; import java.util.Locale; /* * Copyright (C) 2015-2017 Emanuel Moecklin * * 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.onegravity.contactpicker.core; /** * The concrete but abstract implementation of ContactElement. */ abstract class ContactElementImpl implements ContactElement { final private long mId; private String mDisplayName; transient private List<OnContactCheckedListener> mListeners = new ArrayList<>(); transient private boolean mChecked = false; ContactElementImpl(long id, String displayName) { mId = id;
mDisplayName = Helper.isNullOrEmpty(displayName) ? "---" : displayName;
1gravity/Android-ContactPicker
library/src/main/java/com/onegravity/contactpicker/core/ContactImpl.java
// Path: library/src/main/java/com/onegravity/contactpicker/Helper.java // public class Helper { // // public static boolean isNullOrEmpty(CharSequence string){ // return string == null || string.length() == 0; // } // // public static DisplayMetrics getDisplayMetrics(Context context) { // Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); // DisplayMetrics metrics = new DisplayMetrics(); // display.getMetrics( metrics ); // return metrics; // } // // public static void closeQuietly(Cursor cursor) { // try { // cursor.close(); // } // catch (Exception ignore) {} // } // // public static void closeQuietly(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (IOException ignore) {} // } // // } // // Path: library/src/main/java/com/onegravity/contactpicker/contact/Contact.java // public interface Contact extends ContactElement { // // String getFirstName(); // // String getLastName(); // // /** // * ContactsContract.CommonDataKinds.Email.TYPE values: // * // * - TYPE_CUSTOM // * - TYPE_HOME // * - TYPE_WORK // * - TYPE_OTHER // * - TYPE_MOBILE // * // * @param type the type // * @return a String with the Email. // */ // String getEmail(int type); // // /** // * @see com.onegravity.contactpicker.contact.Contact#getEmail(int) // * @return the map type to email. // */ // Map<Integer, String> getMapEmail(); // // /** // * ContactsContract.CommonDataKinds.Email.ContactsContract.CommonDataKinds.Phone.TYPE values: // * // * - TYPE_CUSTOM, TYPE_HOME, TYPE_MOBILE, TYPE_WORK, TYPE_FAX_WORK, TYPE_FAX_HOME, TYPE_PAGER // * - TYPE_OTHER, TYPE_CALLBACK, TYPE_CAR, TYPE_COMPANY_MAIN, TYPE_ISDN, TYPE_MAIN // * - TYPE_OTHER_FAX, TYPE_RADIO, TYPE_TELEX, TYPE_TTY_TDD, TYPE_WORK_MOBILE, TYPE_WORK_PAGER // * - TYPE_ASSISTANT, TYPE_MMS // * // * @param type the type // * @return a String with the phone. // */ // String getPhone(int type); // // /** // * @see com.onegravity.contactpicker.contact.Contact#getPhone(int) // * @return the map type to phone. // */ // Map<Integer, String> getMapPhone(); // // /** // * * ContactsContract.CommonDataKinds.StructuredPostal.TYPE values: // * // * - TYPE_CUSTOM // * - TYPE_HOME // * - TYPE_WORK // * - TYPE_OTHER // * // * @param type the type // * @return A String with the address // */ // String getAddress(int type); // // /** // * @see com.onegravity.contactpicker.contact.Contact#getAddress(int) // * @return the map type to address. // */ // Map<Integer, String> getMapAddress(); // // /** // * The contact letter is used in the ContactBadge (if no contact picture can be found). // */ // char getContactLetter(); // // /** // * The contact letter according to the sort order is used in the SectionIndexer for the fast // * scroll indicator. // */ // char getContactLetter(ContactSortOrder sortOrder); // // /** // * The contact color is used in the ContactBadge (if no contact picture can be found) as // * background color. // */ // int getContactColor(); // // /** // * Unique key across all contacts that won't change even if the column id changes. // */ // String getLookupKey(); // // Uri getPhotoUri(); // // Set<Long> getGroupIds(); // } // // Path: library/src/main/java/com/onegravity/contactpicker/contact/ContactSortOrder.java // public enum ContactSortOrder { // FIRST_NAME, // sort by first name // LAST_NAME, // sort by last name // AUTOMATIC; // sort by display name (device specific) // // public static ContactSortOrder lookup(String name) { // try { // return ContactSortOrder.valueOf(name); // } // catch (IllegalArgumentException ignore) { // Log.e(ContactSortOrder.class.getSimpleName(), ignore.getMessage()); // return AUTOMATIC; // } // } // // }
import java.util.regex.Pattern; import android.database.Cursor; import android.net.Uri; import android.provider.ContactsContract; import com.onegravity.contactpicker.Helper; import com.onegravity.contactpicker.contact.Contact; import com.onegravity.contactpicker.contact.ContactSortOrder; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.regex.Matcher;
public Map<Integer, String> getMapPhone() { return mPhone; } @Override public String getAddress(int type) { String address = mAddress.get(type); if (address == null && !mAddress.isEmpty()) { address = ""; } return address; } @Override public Map<Integer, String> getMapAddress() { return mAddress; } @Override public char getContactLetter() { if (mContactLetterBadge == 0) { Matcher m = CONTACT_LETTER.matcher(getDisplayName()); String letter = m.matches() ? m.group(1).toUpperCase(Locale.US) : "?"; mContactLetterBadge = Helper.isNullOrEmpty(letter) ? '?' : letter.charAt(0); } return mContactLetterBadge; } @Override
// Path: library/src/main/java/com/onegravity/contactpicker/Helper.java // public class Helper { // // public static boolean isNullOrEmpty(CharSequence string){ // return string == null || string.length() == 0; // } // // public static DisplayMetrics getDisplayMetrics(Context context) { // Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); // DisplayMetrics metrics = new DisplayMetrics(); // display.getMetrics( metrics ); // return metrics; // } // // public static void closeQuietly(Cursor cursor) { // try { // cursor.close(); // } // catch (Exception ignore) {} // } // // public static void closeQuietly(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (IOException ignore) {} // } // // } // // Path: library/src/main/java/com/onegravity/contactpicker/contact/Contact.java // public interface Contact extends ContactElement { // // String getFirstName(); // // String getLastName(); // // /** // * ContactsContract.CommonDataKinds.Email.TYPE values: // * // * - TYPE_CUSTOM // * - TYPE_HOME // * - TYPE_WORK // * - TYPE_OTHER // * - TYPE_MOBILE // * // * @param type the type // * @return a String with the Email. // */ // String getEmail(int type); // // /** // * @see com.onegravity.contactpicker.contact.Contact#getEmail(int) // * @return the map type to email. // */ // Map<Integer, String> getMapEmail(); // // /** // * ContactsContract.CommonDataKinds.Email.ContactsContract.CommonDataKinds.Phone.TYPE values: // * // * - TYPE_CUSTOM, TYPE_HOME, TYPE_MOBILE, TYPE_WORK, TYPE_FAX_WORK, TYPE_FAX_HOME, TYPE_PAGER // * - TYPE_OTHER, TYPE_CALLBACK, TYPE_CAR, TYPE_COMPANY_MAIN, TYPE_ISDN, TYPE_MAIN // * - TYPE_OTHER_FAX, TYPE_RADIO, TYPE_TELEX, TYPE_TTY_TDD, TYPE_WORK_MOBILE, TYPE_WORK_PAGER // * - TYPE_ASSISTANT, TYPE_MMS // * // * @param type the type // * @return a String with the phone. // */ // String getPhone(int type); // // /** // * @see com.onegravity.contactpicker.contact.Contact#getPhone(int) // * @return the map type to phone. // */ // Map<Integer, String> getMapPhone(); // // /** // * * ContactsContract.CommonDataKinds.StructuredPostal.TYPE values: // * // * - TYPE_CUSTOM // * - TYPE_HOME // * - TYPE_WORK // * - TYPE_OTHER // * // * @param type the type // * @return A String with the address // */ // String getAddress(int type); // // /** // * @see com.onegravity.contactpicker.contact.Contact#getAddress(int) // * @return the map type to address. // */ // Map<Integer, String> getMapAddress(); // // /** // * The contact letter is used in the ContactBadge (if no contact picture can be found). // */ // char getContactLetter(); // // /** // * The contact letter according to the sort order is used in the SectionIndexer for the fast // * scroll indicator. // */ // char getContactLetter(ContactSortOrder sortOrder); // // /** // * The contact color is used in the ContactBadge (if no contact picture can be found) as // * background color. // */ // int getContactColor(); // // /** // * Unique key across all contacts that won't change even if the column id changes. // */ // String getLookupKey(); // // Uri getPhotoUri(); // // Set<Long> getGroupIds(); // } // // Path: library/src/main/java/com/onegravity/contactpicker/contact/ContactSortOrder.java // public enum ContactSortOrder { // FIRST_NAME, // sort by first name // LAST_NAME, // sort by last name // AUTOMATIC; // sort by display name (device specific) // // public static ContactSortOrder lookup(String name) { // try { // return ContactSortOrder.valueOf(name); // } // catch (IllegalArgumentException ignore) { // Log.e(ContactSortOrder.class.getSimpleName(), ignore.getMessage()); // return AUTOMATIC; // } // } // // } // Path: library/src/main/java/com/onegravity/contactpicker/core/ContactImpl.java import java.util.regex.Pattern; import android.database.Cursor; import android.net.Uri; import android.provider.ContactsContract; import com.onegravity.contactpicker.Helper; import com.onegravity.contactpicker.contact.Contact; import com.onegravity.contactpicker.contact.ContactSortOrder; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; public Map<Integer, String> getMapPhone() { return mPhone; } @Override public String getAddress(int type) { String address = mAddress.get(type); if (address == null && !mAddress.isEmpty()) { address = ""; } return address; } @Override public Map<Integer, String> getMapAddress() { return mAddress; } @Override public char getContactLetter() { if (mContactLetterBadge == 0) { Matcher m = CONTACT_LETTER.matcher(getDisplayName()); String letter = m.matches() ? m.group(1).toUpperCase(Locale.US) : "?"; mContactLetterBadge = Helper.isNullOrEmpty(letter) ? '?' : letter.charAt(0); } return mContactLetterBadge; } @Override
public char getContactLetter(ContactSortOrder sortOrder) {
1gravity/Android-ContactPicker
library/src/main/java/com/onegravity/contactpicker/group/GroupViewHolder.java
// Path: library/src/main/java/com/onegravity/contactpicker/contact/Contact.java // public interface Contact extends ContactElement { // // String getFirstName(); // // String getLastName(); // // /** // * ContactsContract.CommonDataKinds.Email.TYPE values: // * // * - TYPE_CUSTOM // * - TYPE_HOME // * - TYPE_WORK // * - TYPE_OTHER // * - TYPE_MOBILE // * // * @param type the type // * @return a String with the Email. // */ // String getEmail(int type); // // /** // * @see com.onegravity.contactpicker.contact.Contact#getEmail(int) // * @return the map type to email. // */ // Map<Integer, String> getMapEmail(); // // /** // * ContactsContract.CommonDataKinds.Email.ContactsContract.CommonDataKinds.Phone.TYPE values: // * // * - TYPE_CUSTOM, TYPE_HOME, TYPE_MOBILE, TYPE_WORK, TYPE_FAX_WORK, TYPE_FAX_HOME, TYPE_PAGER // * - TYPE_OTHER, TYPE_CALLBACK, TYPE_CAR, TYPE_COMPANY_MAIN, TYPE_ISDN, TYPE_MAIN // * - TYPE_OTHER_FAX, TYPE_RADIO, TYPE_TELEX, TYPE_TTY_TDD, TYPE_WORK_MOBILE, TYPE_WORK_PAGER // * - TYPE_ASSISTANT, TYPE_MMS // * // * @param type the type // * @return a String with the phone. // */ // String getPhone(int type); // // /** // * @see com.onegravity.contactpicker.contact.Contact#getPhone(int) // * @return the map type to phone. // */ // Map<Integer, String> getMapPhone(); // // /** // * * ContactsContract.CommonDataKinds.StructuredPostal.TYPE values: // * // * - TYPE_CUSTOM // * - TYPE_HOME // * - TYPE_WORK // * - TYPE_OTHER // * // * @param type the type // * @return A String with the address // */ // String getAddress(int type); // // /** // * @see com.onegravity.contactpicker.contact.Contact#getAddress(int) // * @return the map type to address. // */ // Map<Integer, String> getMapAddress(); // // /** // * The contact letter is used in the ContactBadge (if no contact picture can be found). // */ // char getContactLetter(); // // /** // * The contact letter according to the sort order is used in the SectionIndexer for the fast // * scroll indicator. // */ // char getContactLetter(ContactSortOrder sortOrder); // // /** // * The contact color is used in the ContactBadge (if no contact picture can be found) as // * background color. // */ // int getContactColor(); // // /** // * Unique key across all contacts that won't change even if the column id changes. // */ // String getLookupKey(); // // Uri getPhotoUri(); // // Set<Long> getGroupIds(); // }
import android.content.res.Resources; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.TextView; import com.onegravity.contactpicker.R; import com.onegravity.contactpicker.contact.Contact; import java.util.Collection;
/* * Copyright (C) 2015-2017 Emanuel Moecklin * * 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.onegravity.contactpicker.group; public class GroupViewHolder extends RecyclerView.ViewHolder { private View mRoot; private CheckBox mSelect; private TextView mName; private TextView mDescription; GroupViewHolder(View root) { super(root); mRoot = root; mSelect = (CheckBox) root.findViewById(R.id.select); mName = (TextView) root.findViewById(R.id.name); mDescription = (TextView) root.findViewById(R.id.description); } void bind(final Group group) { mRoot.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mSelect.toggle(); } }); // main text / title mName.setText(group.getDisplayName()); // description
// Path: library/src/main/java/com/onegravity/contactpicker/contact/Contact.java // public interface Contact extends ContactElement { // // String getFirstName(); // // String getLastName(); // // /** // * ContactsContract.CommonDataKinds.Email.TYPE values: // * // * - TYPE_CUSTOM // * - TYPE_HOME // * - TYPE_WORK // * - TYPE_OTHER // * - TYPE_MOBILE // * // * @param type the type // * @return a String with the Email. // */ // String getEmail(int type); // // /** // * @see com.onegravity.contactpicker.contact.Contact#getEmail(int) // * @return the map type to email. // */ // Map<Integer, String> getMapEmail(); // // /** // * ContactsContract.CommonDataKinds.Email.ContactsContract.CommonDataKinds.Phone.TYPE values: // * // * - TYPE_CUSTOM, TYPE_HOME, TYPE_MOBILE, TYPE_WORK, TYPE_FAX_WORK, TYPE_FAX_HOME, TYPE_PAGER // * - TYPE_OTHER, TYPE_CALLBACK, TYPE_CAR, TYPE_COMPANY_MAIN, TYPE_ISDN, TYPE_MAIN // * - TYPE_OTHER_FAX, TYPE_RADIO, TYPE_TELEX, TYPE_TTY_TDD, TYPE_WORK_MOBILE, TYPE_WORK_PAGER // * - TYPE_ASSISTANT, TYPE_MMS // * // * @param type the type // * @return a String with the phone. // */ // String getPhone(int type); // // /** // * @see com.onegravity.contactpicker.contact.Contact#getPhone(int) // * @return the map type to phone. // */ // Map<Integer, String> getMapPhone(); // // /** // * * ContactsContract.CommonDataKinds.StructuredPostal.TYPE values: // * // * - TYPE_CUSTOM // * - TYPE_HOME // * - TYPE_WORK // * - TYPE_OTHER // * // * @param type the type // * @return A String with the address // */ // String getAddress(int type); // // /** // * @see com.onegravity.contactpicker.contact.Contact#getAddress(int) // * @return the map type to address. // */ // Map<Integer, String> getMapAddress(); // // /** // * The contact letter is used in the ContactBadge (if no contact picture can be found). // */ // char getContactLetter(); // // /** // * The contact letter according to the sort order is used in the SectionIndexer for the fast // * scroll indicator. // */ // char getContactLetter(ContactSortOrder sortOrder); // // /** // * The contact color is used in the ContactBadge (if no contact picture can be found) as // * background color. // */ // int getContactColor(); // // /** // * Unique key across all contacts that won't change even if the column id changes. // */ // String getLookupKey(); // // Uri getPhotoUri(); // // Set<Long> getGroupIds(); // } // Path: library/src/main/java/com/onegravity/contactpicker/group/GroupViewHolder.java import android.content.res.Resources; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.TextView; import com.onegravity.contactpicker.R; import com.onegravity.contactpicker.contact.Contact; import java.util.Collection; /* * Copyright (C) 2015-2017 Emanuel Moecklin * * 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.onegravity.contactpicker.group; public class GroupViewHolder extends RecyclerView.ViewHolder { private View mRoot; private CheckBox mSelect; private TextView mName; private TextView mDescription; GroupViewHolder(View root) { super(root); mRoot = root; mSelect = (CheckBox) root.findViewById(R.id.select); mName = (TextView) root.findViewById(R.id.name); mDescription = (TextView) root.findViewById(R.id.description); } void bind(final Group group) { mRoot.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mSelect.toggle(); } }); // main text / title mName.setText(group.getDisplayName()); // description
Collection<Contact> contacts = group.getContacts();
1gravity/Android-ContactPicker
library/src/main/java/com/onegravity/contactpicker/picture/ContactQueryHandler.java
// Path: library/src/main/java/com/onegravity/contactpicker/Helper.java // public class Helper { // // public static boolean isNullOrEmpty(CharSequence string){ // return string == null || string.length() == 0; // } // // public static DisplayMetrics getDisplayMetrics(Context context) { // Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); // DisplayMetrics metrics = new DisplayMetrics(); // display.getMetrics( metrics ); // return metrics; // } // // public static void closeQuietly(Cursor cursor) { // try { // cursor.close(); // } // catch (Exception ignore) {} // } // // public static void closeQuietly(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (IOException ignore) {} // } // // }
import android.content.AsyncQueryHandler; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.ContactsContract; import android.util.Log; import com.onegravity.contactpicker.Helper;
case Constants.TOKEN_PHONE_LOOKUP: { if (cursor != null && cursor.moveToFirst()) { long contactId = cursor.getLong(Constants.PHONE_ID_COLUMN_INDEX); String lookupKey = cursor.getString(Constants.PHONE_LOOKUP_STRING_COLUMN_INDEX); lookupUri = ContactsContract.Contacts.getLookupUri(contactId, lookupKey); } break; } case Constants.TOKEN_EMAIL_LOOKUP_AND_TRIGGER: trigger = true; createUri = Uri.fromParts("mailto", extras.getString(Constants.EXTRA_URI_CONTENT), null); // $FALL-THROUGH$ case Constants.TOKEN_EMAIL_LOOKUP: { if (cursor != null && cursor.moveToFirst()) { long contactId = cursor.getLong(Constants.EMAIL_ID_COLUMN_INDEX); String lookupKey = cursor.getString(Constants.EMAIL_LOOKUP_STRING_COLUMN_INDEX); lookupUri = ContactsContract.Contacts.getLookupUri(contactId, lookupKey); } break; } } } catch (Exception e) { Log.w(getClass().getSimpleName(), "Failed to get data: " + e.getMessage()); } finally {
// Path: library/src/main/java/com/onegravity/contactpicker/Helper.java // public class Helper { // // public static boolean isNullOrEmpty(CharSequence string){ // return string == null || string.length() == 0; // } // // public static DisplayMetrics getDisplayMetrics(Context context) { // Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); // DisplayMetrics metrics = new DisplayMetrics(); // display.getMetrics( metrics ); // return metrics; // } // // public static void closeQuietly(Cursor cursor) { // try { // cursor.close(); // } // catch (Exception ignore) {} // } // // public static void closeQuietly(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (IOException ignore) {} // } // // } // Path: library/src/main/java/com/onegravity/contactpicker/picture/ContactQueryHandler.java import android.content.AsyncQueryHandler; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.ContactsContract; import android.util.Log; import com.onegravity.contactpicker.Helper; case Constants.TOKEN_PHONE_LOOKUP: { if (cursor != null && cursor.moveToFirst()) { long contactId = cursor.getLong(Constants.PHONE_ID_COLUMN_INDEX); String lookupKey = cursor.getString(Constants.PHONE_LOOKUP_STRING_COLUMN_INDEX); lookupUri = ContactsContract.Contacts.getLookupUri(contactId, lookupKey); } break; } case Constants.TOKEN_EMAIL_LOOKUP_AND_TRIGGER: trigger = true; createUri = Uri.fromParts("mailto", extras.getString(Constants.EXTRA_URI_CONTENT), null); // $FALL-THROUGH$ case Constants.TOKEN_EMAIL_LOOKUP: { if (cursor != null && cursor.moveToFirst()) { long contactId = cursor.getLong(Constants.EMAIL_ID_COLUMN_INDEX); String lookupKey = cursor.getString(Constants.EMAIL_LOOKUP_STRING_COLUMN_INDEX); lookupUri = ContactsContract.Contacts.getLookupUri(contactId, lookupKey); } break; } } } catch (Exception e) { Log.w(getClass().getSimpleName(), "Failed to get data: " + e.getMessage()); } finally {
Helper.closeQuietly(cursor);
1gravity/Android-ContactPicker
library/src/main/java/com/onegravity/contactpicker/contact/ContactAdapter.java
// Path: library/src/main/java/com/onegravity/contactpicker/picture/ContactPictureManager.java // public class ContactPictureManager { // private static Bitmap sDummyBitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.RGB_565); // // private static final ExecutorService sExecutor = Executors.newFixedThreadPool(2); // // private final ContactPictureCache sPhotoCache; // // private final boolean mRoundContactPictures; // // public ContactPictureManager(Context context, boolean roundContactPictures) { // sPhotoCache = ContactPictureCache.getInstance( context ); // mRoundContactPictures = roundContactPictures; // EventBus.getDefault().register(this); // } // // /** // * Load a contact picture and display it using the supplied {@link ContactBadge} instance. // * // * <p> // * If a picture is found in the cache, it is displayed in the {@code ContactBadge} // * immediately. Otherwise a {@link ContactPictureLoader} is started to try to load the // * contact picture in a background thread. // * Depending on the result the contact picture or a fallback picture is shown (letter). // * </p> // */ // public void loadContactPicture(Contact contact, ContactBadge badge) { // String key = contact.getLookupKey(); // // // retrieve or create uri for the contact picture // Uri photoUri = contact.getPhotoUri(); // if (photoUri == null) { // photoUri = ContactUriCache.getUriFromCache(key); // if (photoUri == Uri.EMPTY) { // // pseudo uri used as key to retrieve Uris from the cache // photoUri = Uri.parse("picture://1gravity.com/" + Uri.encode(key)); // ContactUriCache.getInstance().put(key, photoUri); // } // } // // // retrieve contact picture from cache // Bitmap bitmap = sPhotoCache.get(photoUri, sDummyBitmap); // can handle Null keys // // if (bitmap != null && bitmap != sDummyBitmap) { // // 1) picture found --> update the contact badge // badge.setBitmap( bitmap ); // } // // else if (photoUri == Uri.EMPTY || bitmap == sDummyBitmap) { // // 2) we already tried to retrieve the contact picture before (unsuccessfully) // // --> "letter" contact image // badge.setCharacter(contact.getContactLetter(), contact.getContactColor()); // } // // else { // synchronized (badge) { // boolean hasLoaderAssociated = hasLoaderAssociated(key, badge); // // if (! hasLoaderAssociated) { // // 3a) temporary "letter" contact image till the contact picture is loaded (if there's any) // badge.setCharacter(contact.getContactLetter(), contact.getContactColor()); // // // 3b) load the contact picture // ContactPictureLoader loader = new ContactPictureLoader(key, badge, contact.getPhotoUri(), mRoundContactPictures); // badge.setKey(key); // try { // sExecutor.execute(loader); // } // catch (Exception ignore) {} // } // } // } // } // // /** // * @return {@code true}, if a loader with the same key has already been started for this // * ContactBadge, {@code false} otherwise. // */ // private boolean hasLoaderAssociated(String loaderKey, ContactBadge badge) { // String badgeKey = badge.getKey(); // // if (badgeKey == null || loaderKey == null) { // // no loader associated with the ContactBadge // return false; // } // // return badgeKey.equals(loaderKey); // } // // /** // * A ContactPictureLoader has loaded a contact picture and wants to update the ContactBadge. // * We use EventBus because it's a convenient way to run this on the UI thread and because it's // * very little boilerplate code. // */ // @Subscribe(threadMode = ThreadMode.MAIN) // public void onEventMainThread(ContactPictureLoaded event) { // ContactBadge badge = event.getBadge(); // String badgeKey = badge.getKey(); // String loaderKey = event.getKey(); // // if (badgeKey != null && loaderKey != null && badgeKey.equals(loaderKey)) { // badge.setBitmap( event.getBitmap() ); // } // } // // } // // Path: library/src/main/java/com/onegravity/contactpicker/picture/ContactPictureType.java // public enum ContactPictureType { // NONE, // ROUND, // SQUARE; // // public static ContactPictureType lookup(String name) { // try { // return ContactPictureType.valueOf(name); // } // catch (IllegalArgumentException ignore) { // Log.e(ContactPictureType.class.getSimpleName(), ignore.getMessage()); // return ROUND; // } // } // // }
import java.util.Map; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.SectionIndexer; import com.onegravity.contactpicker.R; import com.onegravity.contactpicker.picture.ContactPictureManager; import com.onegravity.contactpicker.picture.ContactPictureType; import java.util.ArrayList; import java.util.HashMap; import java.util.List;
/* * Copyright (C) 2015-2017 Emanuel Moecklin * * 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.onegravity.contactpicker.contact; public class ContactAdapter extends RecyclerView.Adapter<ContactViewHolder> implements SectionIndexer { private List<? extends Contact> mContacts; final private ContactSortOrder mSortOrder;
// Path: library/src/main/java/com/onegravity/contactpicker/picture/ContactPictureManager.java // public class ContactPictureManager { // private static Bitmap sDummyBitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.RGB_565); // // private static final ExecutorService sExecutor = Executors.newFixedThreadPool(2); // // private final ContactPictureCache sPhotoCache; // // private final boolean mRoundContactPictures; // // public ContactPictureManager(Context context, boolean roundContactPictures) { // sPhotoCache = ContactPictureCache.getInstance( context ); // mRoundContactPictures = roundContactPictures; // EventBus.getDefault().register(this); // } // // /** // * Load a contact picture and display it using the supplied {@link ContactBadge} instance. // * // * <p> // * If a picture is found in the cache, it is displayed in the {@code ContactBadge} // * immediately. Otherwise a {@link ContactPictureLoader} is started to try to load the // * contact picture in a background thread. // * Depending on the result the contact picture or a fallback picture is shown (letter). // * </p> // */ // public void loadContactPicture(Contact contact, ContactBadge badge) { // String key = contact.getLookupKey(); // // // retrieve or create uri for the contact picture // Uri photoUri = contact.getPhotoUri(); // if (photoUri == null) { // photoUri = ContactUriCache.getUriFromCache(key); // if (photoUri == Uri.EMPTY) { // // pseudo uri used as key to retrieve Uris from the cache // photoUri = Uri.parse("picture://1gravity.com/" + Uri.encode(key)); // ContactUriCache.getInstance().put(key, photoUri); // } // } // // // retrieve contact picture from cache // Bitmap bitmap = sPhotoCache.get(photoUri, sDummyBitmap); // can handle Null keys // // if (bitmap != null && bitmap != sDummyBitmap) { // // 1) picture found --> update the contact badge // badge.setBitmap( bitmap ); // } // // else if (photoUri == Uri.EMPTY || bitmap == sDummyBitmap) { // // 2) we already tried to retrieve the contact picture before (unsuccessfully) // // --> "letter" contact image // badge.setCharacter(contact.getContactLetter(), contact.getContactColor()); // } // // else { // synchronized (badge) { // boolean hasLoaderAssociated = hasLoaderAssociated(key, badge); // // if (! hasLoaderAssociated) { // // 3a) temporary "letter" contact image till the contact picture is loaded (if there's any) // badge.setCharacter(contact.getContactLetter(), contact.getContactColor()); // // // 3b) load the contact picture // ContactPictureLoader loader = new ContactPictureLoader(key, badge, contact.getPhotoUri(), mRoundContactPictures); // badge.setKey(key); // try { // sExecutor.execute(loader); // } // catch (Exception ignore) {} // } // } // } // } // // /** // * @return {@code true}, if a loader with the same key has already been started for this // * ContactBadge, {@code false} otherwise. // */ // private boolean hasLoaderAssociated(String loaderKey, ContactBadge badge) { // String badgeKey = badge.getKey(); // // if (badgeKey == null || loaderKey == null) { // // no loader associated with the ContactBadge // return false; // } // // return badgeKey.equals(loaderKey); // } // // /** // * A ContactPictureLoader has loaded a contact picture and wants to update the ContactBadge. // * We use EventBus because it's a convenient way to run this on the UI thread and because it's // * very little boilerplate code. // */ // @Subscribe(threadMode = ThreadMode.MAIN) // public void onEventMainThread(ContactPictureLoaded event) { // ContactBadge badge = event.getBadge(); // String badgeKey = badge.getKey(); // String loaderKey = event.getKey(); // // if (badgeKey != null && loaderKey != null && badgeKey.equals(loaderKey)) { // badge.setBitmap( event.getBitmap() ); // } // } // // } // // Path: library/src/main/java/com/onegravity/contactpicker/picture/ContactPictureType.java // public enum ContactPictureType { // NONE, // ROUND, // SQUARE; // // public static ContactPictureType lookup(String name) { // try { // return ContactPictureType.valueOf(name); // } // catch (IllegalArgumentException ignore) { // Log.e(ContactPictureType.class.getSimpleName(), ignore.getMessage()); // return ROUND; // } // } // // } // Path: library/src/main/java/com/onegravity/contactpicker/contact/ContactAdapter.java import java.util.Map; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.SectionIndexer; import com.onegravity.contactpicker.R; import com.onegravity.contactpicker.picture.ContactPictureManager; import com.onegravity.contactpicker.picture.ContactPictureType; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /* * Copyright (C) 2015-2017 Emanuel Moecklin * * 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.onegravity.contactpicker.contact; public class ContactAdapter extends RecyclerView.Adapter<ContactViewHolder> implements SectionIndexer { private List<? extends Contact> mContacts; final private ContactSortOrder mSortOrder;
final private ContactPictureType mContactPictureType;
1gravity/Android-ContactPicker
library/src/main/java/com/onegravity/contactpicker/contact/ContactAdapter.java
// Path: library/src/main/java/com/onegravity/contactpicker/picture/ContactPictureManager.java // public class ContactPictureManager { // private static Bitmap sDummyBitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.RGB_565); // // private static final ExecutorService sExecutor = Executors.newFixedThreadPool(2); // // private final ContactPictureCache sPhotoCache; // // private final boolean mRoundContactPictures; // // public ContactPictureManager(Context context, boolean roundContactPictures) { // sPhotoCache = ContactPictureCache.getInstance( context ); // mRoundContactPictures = roundContactPictures; // EventBus.getDefault().register(this); // } // // /** // * Load a contact picture and display it using the supplied {@link ContactBadge} instance. // * // * <p> // * If a picture is found in the cache, it is displayed in the {@code ContactBadge} // * immediately. Otherwise a {@link ContactPictureLoader} is started to try to load the // * contact picture in a background thread. // * Depending on the result the contact picture or a fallback picture is shown (letter). // * </p> // */ // public void loadContactPicture(Contact contact, ContactBadge badge) { // String key = contact.getLookupKey(); // // // retrieve or create uri for the contact picture // Uri photoUri = contact.getPhotoUri(); // if (photoUri == null) { // photoUri = ContactUriCache.getUriFromCache(key); // if (photoUri == Uri.EMPTY) { // // pseudo uri used as key to retrieve Uris from the cache // photoUri = Uri.parse("picture://1gravity.com/" + Uri.encode(key)); // ContactUriCache.getInstance().put(key, photoUri); // } // } // // // retrieve contact picture from cache // Bitmap bitmap = sPhotoCache.get(photoUri, sDummyBitmap); // can handle Null keys // // if (bitmap != null && bitmap != sDummyBitmap) { // // 1) picture found --> update the contact badge // badge.setBitmap( bitmap ); // } // // else if (photoUri == Uri.EMPTY || bitmap == sDummyBitmap) { // // 2) we already tried to retrieve the contact picture before (unsuccessfully) // // --> "letter" contact image // badge.setCharacter(contact.getContactLetter(), contact.getContactColor()); // } // // else { // synchronized (badge) { // boolean hasLoaderAssociated = hasLoaderAssociated(key, badge); // // if (! hasLoaderAssociated) { // // 3a) temporary "letter" contact image till the contact picture is loaded (if there's any) // badge.setCharacter(contact.getContactLetter(), contact.getContactColor()); // // // 3b) load the contact picture // ContactPictureLoader loader = new ContactPictureLoader(key, badge, contact.getPhotoUri(), mRoundContactPictures); // badge.setKey(key); // try { // sExecutor.execute(loader); // } // catch (Exception ignore) {} // } // } // } // } // // /** // * @return {@code true}, if a loader with the same key has already been started for this // * ContactBadge, {@code false} otherwise. // */ // private boolean hasLoaderAssociated(String loaderKey, ContactBadge badge) { // String badgeKey = badge.getKey(); // // if (badgeKey == null || loaderKey == null) { // // no loader associated with the ContactBadge // return false; // } // // return badgeKey.equals(loaderKey); // } // // /** // * A ContactPictureLoader has loaded a contact picture and wants to update the ContactBadge. // * We use EventBus because it's a convenient way to run this on the UI thread and because it's // * very little boilerplate code. // */ // @Subscribe(threadMode = ThreadMode.MAIN) // public void onEventMainThread(ContactPictureLoaded event) { // ContactBadge badge = event.getBadge(); // String badgeKey = badge.getKey(); // String loaderKey = event.getKey(); // // if (badgeKey != null && loaderKey != null && badgeKey.equals(loaderKey)) { // badge.setBitmap( event.getBitmap() ); // } // } // // } // // Path: library/src/main/java/com/onegravity/contactpicker/picture/ContactPictureType.java // public enum ContactPictureType { // NONE, // ROUND, // SQUARE; // // public static ContactPictureType lookup(String name) { // try { // return ContactPictureType.valueOf(name); // } // catch (IllegalArgumentException ignore) { // Log.e(ContactPictureType.class.getSimpleName(), ignore.getMessage()); // return ROUND; // } // } // // }
import java.util.Map; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.SectionIndexer; import com.onegravity.contactpicker.R; import com.onegravity.contactpicker.picture.ContactPictureManager; import com.onegravity.contactpicker.picture.ContactPictureType; import java.util.ArrayList; import java.util.HashMap; import java.util.List;
/* * Copyright (C) 2015-2017 Emanuel Moecklin * * 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.onegravity.contactpicker.contact; public class ContactAdapter extends RecyclerView.Adapter<ContactViewHolder> implements SectionIndexer { private List<? extends Contact> mContacts; final private ContactSortOrder mSortOrder; final private ContactPictureType mContactPictureType; final private ContactDescription mContactDescription; final private int mContactDescriptionType;
// Path: library/src/main/java/com/onegravity/contactpicker/picture/ContactPictureManager.java // public class ContactPictureManager { // private static Bitmap sDummyBitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.RGB_565); // // private static final ExecutorService sExecutor = Executors.newFixedThreadPool(2); // // private final ContactPictureCache sPhotoCache; // // private final boolean mRoundContactPictures; // // public ContactPictureManager(Context context, boolean roundContactPictures) { // sPhotoCache = ContactPictureCache.getInstance( context ); // mRoundContactPictures = roundContactPictures; // EventBus.getDefault().register(this); // } // // /** // * Load a contact picture and display it using the supplied {@link ContactBadge} instance. // * // * <p> // * If a picture is found in the cache, it is displayed in the {@code ContactBadge} // * immediately. Otherwise a {@link ContactPictureLoader} is started to try to load the // * contact picture in a background thread. // * Depending on the result the contact picture or a fallback picture is shown (letter). // * </p> // */ // public void loadContactPicture(Contact contact, ContactBadge badge) { // String key = contact.getLookupKey(); // // // retrieve or create uri for the contact picture // Uri photoUri = contact.getPhotoUri(); // if (photoUri == null) { // photoUri = ContactUriCache.getUriFromCache(key); // if (photoUri == Uri.EMPTY) { // // pseudo uri used as key to retrieve Uris from the cache // photoUri = Uri.parse("picture://1gravity.com/" + Uri.encode(key)); // ContactUriCache.getInstance().put(key, photoUri); // } // } // // // retrieve contact picture from cache // Bitmap bitmap = sPhotoCache.get(photoUri, sDummyBitmap); // can handle Null keys // // if (bitmap != null && bitmap != sDummyBitmap) { // // 1) picture found --> update the contact badge // badge.setBitmap( bitmap ); // } // // else if (photoUri == Uri.EMPTY || bitmap == sDummyBitmap) { // // 2) we already tried to retrieve the contact picture before (unsuccessfully) // // --> "letter" contact image // badge.setCharacter(contact.getContactLetter(), contact.getContactColor()); // } // // else { // synchronized (badge) { // boolean hasLoaderAssociated = hasLoaderAssociated(key, badge); // // if (! hasLoaderAssociated) { // // 3a) temporary "letter" contact image till the contact picture is loaded (if there's any) // badge.setCharacter(contact.getContactLetter(), contact.getContactColor()); // // // 3b) load the contact picture // ContactPictureLoader loader = new ContactPictureLoader(key, badge, contact.getPhotoUri(), mRoundContactPictures); // badge.setKey(key); // try { // sExecutor.execute(loader); // } // catch (Exception ignore) {} // } // } // } // } // // /** // * @return {@code true}, if a loader with the same key has already been started for this // * ContactBadge, {@code false} otherwise. // */ // private boolean hasLoaderAssociated(String loaderKey, ContactBadge badge) { // String badgeKey = badge.getKey(); // // if (badgeKey == null || loaderKey == null) { // // no loader associated with the ContactBadge // return false; // } // // return badgeKey.equals(loaderKey); // } // // /** // * A ContactPictureLoader has loaded a contact picture and wants to update the ContactBadge. // * We use EventBus because it's a convenient way to run this on the UI thread and because it's // * very little boilerplate code. // */ // @Subscribe(threadMode = ThreadMode.MAIN) // public void onEventMainThread(ContactPictureLoaded event) { // ContactBadge badge = event.getBadge(); // String badgeKey = badge.getKey(); // String loaderKey = event.getKey(); // // if (badgeKey != null && loaderKey != null && badgeKey.equals(loaderKey)) { // badge.setBitmap( event.getBitmap() ); // } // } // // } // // Path: library/src/main/java/com/onegravity/contactpicker/picture/ContactPictureType.java // public enum ContactPictureType { // NONE, // ROUND, // SQUARE; // // public static ContactPictureType lookup(String name) { // try { // return ContactPictureType.valueOf(name); // } // catch (IllegalArgumentException ignore) { // Log.e(ContactPictureType.class.getSimpleName(), ignore.getMessage()); // return ROUND; // } // } // // } // Path: library/src/main/java/com/onegravity/contactpicker/contact/ContactAdapter.java import java.util.Map; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.SectionIndexer; import com.onegravity.contactpicker.R; import com.onegravity.contactpicker.picture.ContactPictureManager; import com.onegravity.contactpicker.picture.ContactPictureType; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /* * Copyright (C) 2015-2017 Emanuel Moecklin * * 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.onegravity.contactpicker.contact; public class ContactAdapter extends RecyclerView.Adapter<ContactViewHolder> implements SectionIndexer { private List<? extends Contact> mContacts; final private ContactSortOrder mSortOrder; final private ContactPictureType mContactPictureType; final private ContactDescription mContactDescription; final private int mContactDescriptionType;
final private ContactPictureManager mContactPictureLoader;
1gravity/Android-ContactPicker
library/src/main/java/com/onegravity/contactpicker/core/GroupImpl.java
// Path: library/src/main/java/com/onegravity/contactpicker/contact/Contact.java // public interface Contact extends ContactElement { // // String getFirstName(); // // String getLastName(); // // /** // * ContactsContract.CommonDataKinds.Email.TYPE values: // * // * - TYPE_CUSTOM // * - TYPE_HOME // * - TYPE_WORK // * - TYPE_OTHER // * - TYPE_MOBILE // * // * @param type the type // * @return a String with the Email. // */ // String getEmail(int type); // // /** // * @see com.onegravity.contactpicker.contact.Contact#getEmail(int) // * @return the map type to email. // */ // Map<Integer, String> getMapEmail(); // // /** // * ContactsContract.CommonDataKinds.Email.ContactsContract.CommonDataKinds.Phone.TYPE values: // * // * - TYPE_CUSTOM, TYPE_HOME, TYPE_MOBILE, TYPE_WORK, TYPE_FAX_WORK, TYPE_FAX_HOME, TYPE_PAGER // * - TYPE_OTHER, TYPE_CALLBACK, TYPE_CAR, TYPE_COMPANY_MAIN, TYPE_ISDN, TYPE_MAIN // * - TYPE_OTHER_FAX, TYPE_RADIO, TYPE_TELEX, TYPE_TTY_TDD, TYPE_WORK_MOBILE, TYPE_WORK_PAGER // * - TYPE_ASSISTANT, TYPE_MMS // * // * @param type the type // * @return a String with the phone. // */ // String getPhone(int type); // // /** // * @see com.onegravity.contactpicker.contact.Contact#getPhone(int) // * @return the map type to phone. // */ // Map<Integer, String> getMapPhone(); // // /** // * * ContactsContract.CommonDataKinds.StructuredPostal.TYPE values: // * // * - TYPE_CUSTOM // * - TYPE_HOME // * - TYPE_WORK // * - TYPE_OTHER // * // * @param type the type // * @return A String with the address // */ // String getAddress(int type); // // /** // * @see com.onegravity.contactpicker.contact.Contact#getAddress(int) // * @return the map type to address. // */ // Map<Integer, String> getMapAddress(); // // /** // * The contact letter is used in the ContactBadge (if no contact picture can be found). // */ // char getContactLetter(); // // /** // * The contact letter according to the sort order is used in the SectionIndexer for the fast // * scroll indicator. // */ // char getContactLetter(ContactSortOrder sortOrder); // // /** // * The contact color is used in the ContactBadge (if no contact picture can be found) as // * background color. // */ // int getContactColor(); // // /** // * Unique key across all contacts that won't change even if the column id changes. // */ // String getLookupKey(); // // Uri getPhotoUri(); // // Set<Long> getGroupIds(); // } // // Path: library/src/main/java/com/onegravity/contactpicker/group/Group.java // public interface Group extends ContactElement { // // Collection<Contact> getContacts(); // // }
import android.database.Cursor; import android.provider.ContactsContract; import com.onegravity.contactpicker.contact.Contact; import com.onegravity.contactpicker.group.Group; import java.util.Collection; import java.util.HashMap; import java.util.Map;
/* * Copyright (C) 2015-2017 Emanuel Moecklin * * 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.onegravity.contactpicker.core; /** * GroupImpl is the concrete Group implementation. * It can be instantiated and modified only within its own package to prevent modifications from * classes outside the package. */ class GroupImpl extends ContactElementImpl implements Group { static GroupImpl fromCursor(Cursor cursor) { long id = cursor.getLong(cursor.getColumnIndex(ContactsContract.Groups._ID)); String title = cursor.getString(cursor.getColumnIndex(ContactsContract.Groups.TITLE)); return new GroupImpl(id, title); }
// Path: library/src/main/java/com/onegravity/contactpicker/contact/Contact.java // public interface Contact extends ContactElement { // // String getFirstName(); // // String getLastName(); // // /** // * ContactsContract.CommonDataKinds.Email.TYPE values: // * // * - TYPE_CUSTOM // * - TYPE_HOME // * - TYPE_WORK // * - TYPE_OTHER // * - TYPE_MOBILE // * // * @param type the type // * @return a String with the Email. // */ // String getEmail(int type); // // /** // * @see com.onegravity.contactpicker.contact.Contact#getEmail(int) // * @return the map type to email. // */ // Map<Integer, String> getMapEmail(); // // /** // * ContactsContract.CommonDataKinds.Email.ContactsContract.CommonDataKinds.Phone.TYPE values: // * // * - TYPE_CUSTOM, TYPE_HOME, TYPE_MOBILE, TYPE_WORK, TYPE_FAX_WORK, TYPE_FAX_HOME, TYPE_PAGER // * - TYPE_OTHER, TYPE_CALLBACK, TYPE_CAR, TYPE_COMPANY_MAIN, TYPE_ISDN, TYPE_MAIN // * - TYPE_OTHER_FAX, TYPE_RADIO, TYPE_TELEX, TYPE_TTY_TDD, TYPE_WORK_MOBILE, TYPE_WORK_PAGER // * - TYPE_ASSISTANT, TYPE_MMS // * // * @param type the type // * @return a String with the phone. // */ // String getPhone(int type); // // /** // * @see com.onegravity.contactpicker.contact.Contact#getPhone(int) // * @return the map type to phone. // */ // Map<Integer, String> getMapPhone(); // // /** // * * ContactsContract.CommonDataKinds.StructuredPostal.TYPE values: // * // * - TYPE_CUSTOM // * - TYPE_HOME // * - TYPE_WORK // * - TYPE_OTHER // * // * @param type the type // * @return A String with the address // */ // String getAddress(int type); // // /** // * @see com.onegravity.contactpicker.contact.Contact#getAddress(int) // * @return the map type to address. // */ // Map<Integer, String> getMapAddress(); // // /** // * The contact letter is used in the ContactBadge (if no contact picture can be found). // */ // char getContactLetter(); // // /** // * The contact letter according to the sort order is used in the SectionIndexer for the fast // * scroll indicator. // */ // char getContactLetter(ContactSortOrder sortOrder); // // /** // * The contact color is used in the ContactBadge (if no contact picture can be found) as // * background color. // */ // int getContactColor(); // // /** // * Unique key across all contacts that won't change even if the column id changes. // */ // String getLookupKey(); // // Uri getPhotoUri(); // // Set<Long> getGroupIds(); // } // // Path: library/src/main/java/com/onegravity/contactpicker/group/Group.java // public interface Group extends ContactElement { // // Collection<Contact> getContacts(); // // } // Path: library/src/main/java/com/onegravity/contactpicker/core/GroupImpl.java import android.database.Cursor; import android.provider.ContactsContract; import com.onegravity.contactpicker.contact.Contact; import com.onegravity.contactpicker.group.Group; import java.util.Collection; import java.util.HashMap; import java.util.Map; /* * Copyright (C) 2015-2017 Emanuel Moecklin * * 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.onegravity.contactpicker.core; /** * GroupImpl is the concrete Group implementation. * It can be instantiated and modified only within its own package to prevent modifications from * classes outside the package. */ class GroupImpl extends ContactElementImpl implements Group { static GroupImpl fromCursor(Cursor cursor) { long id = cursor.getLong(cursor.getColumnIndex(ContactsContract.Groups._ID)); String title = cursor.getString(cursor.getColumnIndex(ContactsContract.Groups.TITLE)); return new GroupImpl(id, title); }
private Map<Long, Contact> mContacts = new HashMap<>();
1gravity/Android-ContactPicker
library/src/main/java/com/onegravity/contactpicker/picture/ContactBadge.java
// Path: library/src/main/java/com/onegravity/contactpicker/Helper.java // public class Helper { // // public static boolean isNullOrEmpty(CharSequence string){ // return string == null || string.length() == 0; // } // // public static DisplayMetrics getDisplayMetrics(Context context) { // Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); // DisplayMetrics metrics = new DisplayMetrics(); // display.getMetrics( metrics ); // return metrics; // } // // public static void closeQuietly(Cursor cursor) { // try { // cursor.close(); // } // catch (Exception ignore) {} // } // // public static void closeQuietly(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (IOException ignore) {} // } // // } // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final String[] EMAIL_LOOKUP_PROJECTION = new String[]{ // ContactsContract.RawContacts.CONTACT_ID, // ContactsContract.Contacts.LOOKUP_KEY, // }; // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final String[] PHONE_LOOKUP_PROJECTION = new String[]{ // ContactsContract.PhoneLookup._ID, // ContactsContract.PhoneLookup.LOOKUP_KEY, // }; // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final int TOKEN_EMAIL_LOOKUP = 0; // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final int TOKEN_PHONE_LOOKUP = 1;
import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.res.Resources.Theme; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.OvalShape; import android.graphics.drawable.shapes.PathShape; import android.graphics.drawable.shapes.RectShape; import android.graphics.drawable.shapes.Shape; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.PhoneLookup; import android.provider.ContactsContract.QuickContact; import android.text.TextUtils; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import android.view.View.OnClickListener; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import com.onegravity.contactpicker.Helper; import com.onegravity.contactpicker.R; import static com.onegravity.contactpicker.picture.Constants.EMAIL_LOOKUP_PROJECTION; import static com.onegravity.contactpicker.picture.Constants.PHONE_LOOKUP_PROJECTION; import static com.onegravity.contactpicker.picture.Constants.TOKEN_EMAIL_LOOKUP; import static com.onegravity.contactpicker.picture.Constants.TOKEN_PHONE_LOOKUP;
private ShapeDrawable mTriangle; private Paint mLinePaint; private float mOffset; // pressed overlay private boolean mIsPressed; private ShapeDrawable mPressedOverlay; private boolean mRoundContactPictures = true; private String mKey; private float mDensity; public ContactBadge(Context context) { this(context, null); } public ContactBadge(Context context, AttributeSet attrs) { this(context, attrs, 0); } public ContactBadge(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); if (!isInEditMode()) { mQueryHandler = new ContactQueryHandler(context, mExcludeMimes); } setOnClickListener(this);
// Path: library/src/main/java/com/onegravity/contactpicker/Helper.java // public class Helper { // // public static boolean isNullOrEmpty(CharSequence string){ // return string == null || string.length() == 0; // } // // public static DisplayMetrics getDisplayMetrics(Context context) { // Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); // DisplayMetrics metrics = new DisplayMetrics(); // display.getMetrics( metrics ); // return metrics; // } // // public static void closeQuietly(Cursor cursor) { // try { // cursor.close(); // } // catch (Exception ignore) {} // } // // public static void closeQuietly(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (IOException ignore) {} // } // // } // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final String[] EMAIL_LOOKUP_PROJECTION = new String[]{ // ContactsContract.RawContacts.CONTACT_ID, // ContactsContract.Contacts.LOOKUP_KEY, // }; // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final String[] PHONE_LOOKUP_PROJECTION = new String[]{ // ContactsContract.PhoneLookup._ID, // ContactsContract.PhoneLookup.LOOKUP_KEY, // }; // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final int TOKEN_EMAIL_LOOKUP = 0; // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final int TOKEN_PHONE_LOOKUP = 1; // Path: library/src/main/java/com/onegravity/contactpicker/picture/ContactBadge.java import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.res.Resources.Theme; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.OvalShape; import android.graphics.drawable.shapes.PathShape; import android.graphics.drawable.shapes.RectShape; import android.graphics.drawable.shapes.Shape; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.PhoneLookup; import android.provider.ContactsContract.QuickContact; import android.text.TextUtils; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import android.view.View.OnClickListener; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import com.onegravity.contactpicker.Helper; import com.onegravity.contactpicker.R; import static com.onegravity.contactpicker.picture.Constants.EMAIL_LOOKUP_PROJECTION; import static com.onegravity.contactpicker.picture.Constants.PHONE_LOOKUP_PROJECTION; import static com.onegravity.contactpicker.picture.Constants.TOKEN_EMAIL_LOOKUP; import static com.onegravity.contactpicker.picture.Constants.TOKEN_PHONE_LOOKUP; private ShapeDrawable mTriangle; private Paint mLinePaint; private float mOffset; // pressed overlay private boolean mIsPressed; private ShapeDrawable mPressedOverlay; private boolean mRoundContactPictures = true; private String mKey; private float mDensity; public ContactBadge(Context context) { this(context, null); } public ContactBadge(Context context, AttributeSet attrs) { this(context, attrs, 0); } public ContactBadge(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); if (!isInEditMode()) { mQueryHandler = new ContactQueryHandler(context, mExcludeMimes); } setOnClickListener(this);
mDensity = Helper.getDisplayMetrics(context).density;
1gravity/Android-ContactPicker
library/src/main/java/com/onegravity/contactpicker/picture/ContactBadge.java
// Path: library/src/main/java/com/onegravity/contactpicker/Helper.java // public class Helper { // // public static boolean isNullOrEmpty(CharSequence string){ // return string == null || string.length() == 0; // } // // public static DisplayMetrics getDisplayMetrics(Context context) { // Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); // DisplayMetrics metrics = new DisplayMetrics(); // display.getMetrics( metrics ); // return metrics; // } // // public static void closeQuietly(Cursor cursor) { // try { // cursor.close(); // } // catch (Exception ignore) {} // } // // public static void closeQuietly(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (IOException ignore) {} // } // // } // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final String[] EMAIL_LOOKUP_PROJECTION = new String[]{ // ContactsContract.RawContacts.CONTACT_ID, // ContactsContract.Contacts.LOOKUP_KEY, // }; // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final String[] PHONE_LOOKUP_PROJECTION = new String[]{ // ContactsContract.PhoneLookup._ID, // ContactsContract.PhoneLookup.LOOKUP_KEY, // }; // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final int TOKEN_EMAIL_LOOKUP = 0; // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final int TOKEN_PHONE_LOOKUP = 1;
import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.res.Resources.Theme; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.OvalShape; import android.graphics.drawable.shapes.PathShape; import android.graphics.drawable.shapes.RectShape; import android.graphics.drawable.shapes.Shape; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.PhoneLookup; import android.provider.ContactsContract.QuickContact; import android.text.TextUtils; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import android.view.View.OnClickListener; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import com.onegravity.contactpicker.Helper; import com.onegravity.contactpicker.R; import static com.onegravity.contactpicker.picture.Constants.EMAIL_LOOKUP_PROJECTION; import static com.onegravity.contactpicker.picture.Constants.PHONE_LOOKUP_PROJECTION; import static com.onegravity.contactpicker.picture.Constants.TOKEN_EMAIL_LOOKUP; import static com.onegravity.contactpicker.picture.Constants.TOKEN_PHONE_LOOKUP;
/** * Assign a contact based on an email address. This should only be used when * the contact's URI is not available, as an extra query will have to be * performed to lookup the URI based on the email. * * @param emailAddress The email address of the contact. * @param lazyLookup If this is true, the lookup query will not be performed * until this view is clicked. */ public void assignContactFromEmail(String emailAddress, boolean lazyLookup) { assignContactFromEmail(emailAddress, lazyLookup, null); } /** * Assign a contact based on an email address. This should only be used when * the contact's URI is not available, as an extra query will have to be * performed to lookup the URI based on the email. * * @param emailAddress The email address of the contact. * @param lazyLookup If this is true, the lookup query will not be performed until this view is * clicked. * @param extras A bundle of extras to populate the contact edit page with if the contact is not * found and the user chooses to add the email address to an existing contact or * create a new contact. Uses the same string constants as those found in * {@link android.provider.ContactsContract.Intents.Insert} */ public void assignContactFromEmail(String emailAddress, boolean lazyLookup, Bundle extras) { mContactEmail = emailAddress; mExtras = extras; if (!lazyLookup && mQueryHandler != null) {
// Path: library/src/main/java/com/onegravity/contactpicker/Helper.java // public class Helper { // // public static boolean isNullOrEmpty(CharSequence string){ // return string == null || string.length() == 0; // } // // public static DisplayMetrics getDisplayMetrics(Context context) { // Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); // DisplayMetrics metrics = new DisplayMetrics(); // display.getMetrics( metrics ); // return metrics; // } // // public static void closeQuietly(Cursor cursor) { // try { // cursor.close(); // } // catch (Exception ignore) {} // } // // public static void closeQuietly(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (IOException ignore) {} // } // // } // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final String[] EMAIL_LOOKUP_PROJECTION = new String[]{ // ContactsContract.RawContacts.CONTACT_ID, // ContactsContract.Contacts.LOOKUP_KEY, // }; // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final String[] PHONE_LOOKUP_PROJECTION = new String[]{ // ContactsContract.PhoneLookup._ID, // ContactsContract.PhoneLookup.LOOKUP_KEY, // }; // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final int TOKEN_EMAIL_LOOKUP = 0; // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final int TOKEN_PHONE_LOOKUP = 1; // Path: library/src/main/java/com/onegravity/contactpicker/picture/ContactBadge.java import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.res.Resources.Theme; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.OvalShape; import android.graphics.drawable.shapes.PathShape; import android.graphics.drawable.shapes.RectShape; import android.graphics.drawable.shapes.Shape; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.PhoneLookup; import android.provider.ContactsContract.QuickContact; import android.text.TextUtils; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import android.view.View.OnClickListener; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import com.onegravity.contactpicker.Helper; import com.onegravity.contactpicker.R; import static com.onegravity.contactpicker.picture.Constants.EMAIL_LOOKUP_PROJECTION; import static com.onegravity.contactpicker.picture.Constants.PHONE_LOOKUP_PROJECTION; import static com.onegravity.contactpicker.picture.Constants.TOKEN_EMAIL_LOOKUP; import static com.onegravity.contactpicker.picture.Constants.TOKEN_PHONE_LOOKUP; /** * Assign a contact based on an email address. This should only be used when * the contact's URI is not available, as an extra query will have to be * performed to lookup the URI based on the email. * * @param emailAddress The email address of the contact. * @param lazyLookup If this is true, the lookup query will not be performed * until this view is clicked. */ public void assignContactFromEmail(String emailAddress, boolean lazyLookup) { assignContactFromEmail(emailAddress, lazyLookup, null); } /** * Assign a contact based on an email address. This should only be used when * the contact's URI is not available, as an extra query will have to be * performed to lookup the URI based on the email. * * @param emailAddress The email address of the contact. * @param lazyLookup If this is true, the lookup query will not be performed until this view is * clicked. * @param extras A bundle of extras to populate the contact edit page with if the contact is not * found and the user chooses to add the email address to an existing contact or * create a new contact. Uses the same string constants as those found in * {@link android.provider.ContactsContract.Intents.Insert} */ public void assignContactFromEmail(String emailAddress, boolean lazyLookup, Bundle extras) { mContactEmail = emailAddress; mExtras = extras; if (!lazyLookup && mQueryHandler != null) {
mQueryHandler.startQuery(TOKEN_EMAIL_LOOKUP, null,
1gravity/Android-ContactPicker
library/src/main/java/com/onegravity/contactpicker/picture/ContactBadge.java
// Path: library/src/main/java/com/onegravity/contactpicker/Helper.java // public class Helper { // // public static boolean isNullOrEmpty(CharSequence string){ // return string == null || string.length() == 0; // } // // public static DisplayMetrics getDisplayMetrics(Context context) { // Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); // DisplayMetrics metrics = new DisplayMetrics(); // display.getMetrics( metrics ); // return metrics; // } // // public static void closeQuietly(Cursor cursor) { // try { // cursor.close(); // } // catch (Exception ignore) {} // } // // public static void closeQuietly(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (IOException ignore) {} // } // // } // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final String[] EMAIL_LOOKUP_PROJECTION = new String[]{ // ContactsContract.RawContacts.CONTACT_ID, // ContactsContract.Contacts.LOOKUP_KEY, // }; // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final String[] PHONE_LOOKUP_PROJECTION = new String[]{ // ContactsContract.PhoneLookup._ID, // ContactsContract.PhoneLookup.LOOKUP_KEY, // }; // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final int TOKEN_EMAIL_LOOKUP = 0; // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final int TOKEN_PHONE_LOOKUP = 1;
import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.res.Resources.Theme; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.OvalShape; import android.graphics.drawable.shapes.PathShape; import android.graphics.drawable.shapes.RectShape; import android.graphics.drawable.shapes.Shape; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.PhoneLookup; import android.provider.ContactsContract.QuickContact; import android.text.TextUtils; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import android.view.View.OnClickListener; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import com.onegravity.contactpicker.Helper; import com.onegravity.contactpicker.R; import static com.onegravity.contactpicker.picture.Constants.EMAIL_LOOKUP_PROJECTION; import static com.onegravity.contactpicker.picture.Constants.PHONE_LOOKUP_PROJECTION; import static com.onegravity.contactpicker.picture.Constants.TOKEN_EMAIL_LOOKUP; import static com.onegravity.contactpicker.picture.Constants.TOKEN_PHONE_LOOKUP;
* the contact's URI is not available, as an extra query will have to be * performed to lookup the URI based on the email. * * @param emailAddress The email address of the contact. * @param lazyLookup If this is true, the lookup query will not be performed * until this view is clicked. */ public void assignContactFromEmail(String emailAddress, boolean lazyLookup) { assignContactFromEmail(emailAddress, lazyLookup, null); } /** * Assign a contact based on an email address. This should only be used when * the contact's URI is not available, as an extra query will have to be * performed to lookup the URI based on the email. * * @param emailAddress The email address of the contact. * @param lazyLookup If this is true, the lookup query will not be performed until this view is * clicked. * @param extras A bundle of extras to populate the contact edit page with if the contact is not * found and the user chooses to add the email address to an existing contact or * create a new contact. Uses the same string constants as those found in * {@link android.provider.ContactsContract.Intents.Insert} */ public void assignContactFromEmail(String emailAddress, boolean lazyLookup, Bundle extras) { mContactEmail = emailAddress; mExtras = extras; if (!lazyLookup && mQueryHandler != null) { mQueryHandler.startQuery(TOKEN_EMAIL_LOOKUP, null, Uri.withAppendedPath(Email.CONTENT_LOOKUP_URI, Uri.encode(mContactEmail)),
// Path: library/src/main/java/com/onegravity/contactpicker/Helper.java // public class Helper { // // public static boolean isNullOrEmpty(CharSequence string){ // return string == null || string.length() == 0; // } // // public static DisplayMetrics getDisplayMetrics(Context context) { // Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); // DisplayMetrics metrics = new DisplayMetrics(); // display.getMetrics( metrics ); // return metrics; // } // // public static void closeQuietly(Cursor cursor) { // try { // cursor.close(); // } // catch (Exception ignore) {} // } // // public static void closeQuietly(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (IOException ignore) {} // } // // } // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final String[] EMAIL_LOOKUP_PROJECTION = new String[]{ // ContactsContract.RawContacts.CONTACT_ID, // ContactsContract.Contacts.LOOKUP_KEY, // }; // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final String[] PHONE_LOOKUP_PROJECTION = new String[]{ // ContactsContract.PhoneLookup._ID, // ContactsContract.PhoneLookup.LOOKUP_KEY, // }; // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final int TOKEN_EMAIL_LOOKUP = 0; // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final int TOKEN_PHONE_LOOKUP = 1; // Path: library/src/main/java/com/onegravity/contactpicker/picture/ContactBadge.java import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.res.Resources.Theme; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.OvalShape; import android.graphics.drawable.shapes.PathShape; import android.graphics.drawable.shapes.RectShape; import android.graphics.drawable.shapes.Shape; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.PhoneLookup; import android.provider.ContactsContract.QuickContact; import android.text.TextUtils; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import android.view.View.OnClickListener; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import com.onegravity.contactpicker.Helper; import com.onegravity.contactpicker.R; import static com.onegravity.contactpicker.picture.Constants.EMAIL_LOOKUP_PROJECTION; import static com.onegravity.contactpicker.picture.Constants.PHONE_LOOKUP_PROJECTION; import static com.onegravity.contactpicker.picture.Constants.TOKEN_EMAIL_LOOKUP; import static com.onegravity.contactpicker.picture.Constants.TOKEN_PHONE_LOOKUP; * the contact's URI is not available, as an extra query will have to be * performed to lookup the URI based on the email. * * @param emailAddress The email address of the contact. * @param lazyLookup If this is true, the lookup query will not be performed * until this view is clicked. */ public void assignContactFromEmail(String emailAddress, boolean lazyLookup) { assignContactFromEmail(emailAddress, lazyLookup, null); } /** * Assign a contact based on an email address. This should only be used when * the contact's URI is not available, as an extra query will have to be * performed to lookup the URI based on the email. * * @param emailAddress The email address of the contact. * @param lazyLookup If this is true, the lookup query will not be performed until this view is * clicked. * @param extras A bundle of extras to populate the contact edit page with if the contact is not * found and the user chooses to add the email address to an existing contact or * create a new contact. Uses the same string constants as those found in * {@link android.provider.ContactsContract.Intents.Insert} */ public void assignContactFromEmail(String emailAddress, boolean lazyLookup, Bundle extras) { mContactEmail = emailAddress; mExtras = extras; if (!lazyLookup && mQueryHandler != null) { mQueryHandler.startQuery(TOKEN_EMAIL_LOOKUP, null, Uri.withAppendedPath(Email.CONTENT_LOOKUP_URI, Uri.encode(mContactEmail)),
EMAIL_LOOKUP_PROJECTION, null, null, null, mContactQueryHandlerCallback);
1gravity/Android-ContactPicker
library/src/main/java/com/onegravity/contactpicker/picture/ContactBadge.java
// Path: library/src/main/java/com/onegravity/contactpicker/Helper.java // public class Helper { // // public static boolean isNullOrEmpty(CharSequence string){ // return string == null || string.length() == 0; // } // // public static DisplayMetrics getDisplayMetrics(Context context) { // Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); // DisplayMetrics metrics = new DisplayMetrics(); // display.getMetrics( metrics ); // return metrics; // } // // public static void closeQuietly(Cursor cursor) { // try { // cursor.close(); // } // catch (Exception ignore) {} // } // // public static void closeQuietly(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (IOException ignore) {} // } // // } // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final String[] EMAIL_LOOKUP_PROJECTION = new String[]{ // ContactsContract.RawContacts.CONTACT_ID, // ContactsContract.Contacts.LOOKUP_KEY, // }; // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final String[] PHONE_LOOKUP_PROJECTION = new String[]{ // ContactsContract.PhoneLookup._ID, // ContactsContract.PhoneLookup.LOOKUP_KEY, // }; // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final int TOKEN_EMAIL_LOOKUP = 0; // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final int TOKEN_PHONE_LOOKUP = 1;
import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.res.Resources.Theme; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.OvalShape; import android.graphics.drawable.shapes.PathShape; import android.graphics.drawable.shapes.RectShape; import android.graphics.drawable.shapes.Shape; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.PhoneLookup; import android.provider.ContactsContract.QuickContact; import android.text.TextUtils; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import android.view.View.OnClickListener; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import com.onegravity.contactpicker.Helper; import com.onegravity.contactpicker.R; import static com.onegravity.contactpicker.picture.Constants.EMAIL_LOOKUP_PROJECTION; import static com.onegravity.contactpicker.picture.Constants.PHONE_LOOKUP_PROJECTION; import static com.onegravity.contactpicker.picture.Constants.TOKEN_EMAIL_LOOKUP; import static com.onegravity.contactpicker.picture.Constants.TOKEN_PHONE_LOOKUP;
/** * Assign a contact based on a phone number. This should only be used when the contact's URI is * not available, as an extra query will have to be performed to lookup the URI based on the * phone number. * * @param phoneNumber The phone number of the contact. * @param lazyLookup If this is true, the lookup query will not be performed until this view is * clicked. */ public void assignContactFromPhone(String phoneNumber, boolean lazyLookup) { assignContactFromPhone(phoneNumber, lazyLookup, new Bundle()); } /** * Assign a contact based on a phone number. This should only be used when the contact's URI is * not available, as an extra query will have to be performed to lookup the URI based on the * phone number. * * @param phoneNumber The phone number of the contact. * @param lazyLookup If this is true, the lookup query will not be performed until this view is * clicked. * @param extras A bundle of extras to populate the contact edit page with if the contact is not * found and the user chooses to add the phone number to an existing contact or * create a new contact. Uses the same string constants as those found in * {@link android.provider.ContactsContract.Intents.Insert} */ public void assignContactFromPhone(String phoneNumber, boolean lazyLookup, Bundle extras) { mContactPhone = phoneNumber; mExtras = extras; if (!lazyLookup && mQueryHandler != null) {
// Path: library/src/main/java/com/onegravity/contactpicker/Helper.java // public class Helper { // // public static boolean isNullOrEmpty(CharSequence string){ // return string == null || string.length() == 0; // } // // public static DisplayMetrics getDisplayMetrics(Context context) { // Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); // DisplayMetrics metrics = new DisplayMetrics(); // display.getMetrics( metrics ); // return metrics; // } // // public static void closeQuietly(Cursor cursor) { // try { // cursor.close(); // } // catch (Exception ignore) {} // } // // public static void closeQuietly(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (IOException ignore) {} // } // // } // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final String[] EMAIL_LOOKUP_PROJECTION = new String[]{ // ContactsContract.RawContacts.CONTACT_ID, // ContactsContract.Contacts.LOOKUP_KEY, // }; // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final String[] PHONE_LOOKUP_PROJECTION = new String[]{ // ContactsContract.PhoneLookup._ID, // ContactsContract.PhoneLookup.LOOKUP_KEY, // }; // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final int TOKEN_EMAIL_LOOKUP = 0; // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final int TOKEN_PHONE_LOOKUP = 1; // Path: library/src/main/java/com/onegravity/contactpicker/picture/ContactBadge.java import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.res.Resources.Theme; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.OvalShape; import android.graphics.drawable.shapes.PathShape; import android.graphics.drawable.shapes.RectShape; import android.graphics.drawable.shapes.Shape; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.PhoneLookup; import android.provider.ContactsContract.QuickContact; import android.text.TextUtils; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import android.view.View.OnClickListener; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import com.onegravity.contactpicker.Helper; import com.onegravity.contactpicker.R; import static com.onegravity.contactpicker.picture.Constants.EMAIL_LOOKUP_PROJECTION; import static com.onegravity.contactpicker.picture.Constants.PHONE_LOOKUP_PROJECTION; import static com.onegravity.contactpicker.picture.Constants.TOKEN_EMAIL_LOOKUP; import static com.onegravity.contactpicker.picture.Constants.TOKEN_PHONE_LOOKUP; /** * Assign a contact based on a phone number. This should only be used when the contact's URI is * not available, as an extra query will have to be performed to lookup the URI based on the * phone number. * * @param phoneNumber The phone number of the contact. * @param lazyLookup If this is true, the lookup query will not be performed until this view is * clicked. */ public void assignContactFromPhone(String phoneNumber, boolean lazyLookup) { assignContactFromPhone(phoneNumber, lazyLookup, new Bundle()); } /** * Assign a contact based on a phone number. This should only be used when the contact's URI is * not available, as an extra query will have to be performed to lookup the URI based on the * phone number. * * @param phoneNumber The phone number of the contact. * @param lazyLookup If this is true, the lookup query will not be performed until this view is * clicked. * @param extras A bundle of extras to populate the contact edit page with if the contact is not * found and the user chooses to add the phone number to an existing contact or * create a new contact. Uses the same string constants as those found in * {@link android.provider.ContactsContract.Intents.Insert} */ public void assignContactFromPhone(String phoneNumber, boolean lazyLookup, Bundle extras) { mContactPhone = phoneNumber; mExtras = extras; if (!lazyLookup && mQueryHandler != null) {
mQueryHandler.startQuery(TOKEN_PHONE_LOOKUP, null,
1gravity/Android-ContactPicker
library/src/main/java/com/onegravity/contactpicker/picture/ContactBadge.java
// Path: library/src/main/java/com/onegravity/contactpicker/Helper.java // public class Helper { // // public static boolean isNullOrEmpty(CharSequence string){ // return string == null || string.length() == 0; // } // // public static DisplayMetrics getDisplayMetrics(Context context) { // Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); // DisplayMetrics metrics = new DisplayMetrics(); // display.getMetrics( metrics ); // return metrics; // } // // public static void closeQuietly(Cursor cursor) { // try { // cursor.close(); // } // catch (Exception ignore) {} // } // // public static void closeQuietly(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (IOException ignore) {} // } // // } // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final String[] EMAIL_LOOKUP_PROJECTION = new String[]{ // ContactsContract.RawContacts.CONTACT_ID, // ContactsContract.Contacts.LOOKUP_KEY, // }; // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final String[] PHONE_LOOKUP_PROJECTION = new String[]{ // ContactsContract.PhoneLookup._ID, // ContactsContract.PhoneLookup.LOOKUP_KEY, // }; // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final int TOKEN_EMAIL_LOOKUP = 0; // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final int TOKEN_PHONE_LOOKUP = 1;
import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.res.Resources.Theme; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.OvalShape; import android.graphics.drawable.shapes.PathShape; import android.graphics.drawable.shapes.RectShape; import android.graphics.drawable.shapes.Shape; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.PhoneLookup; import android.provider.ContactsContract.QuickContact; import android.text.TextUtils; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import android.view.View.OnClickListener; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import com.onegravity.contactpicker.Helper; import com.onegravity.contactpicker.R; import static com.onegravity.contactpicker.picture.Constants.EMAIL_LOOKUP_PROJECTION; import static com.onegravity.contactpicker.picture.Constants.PHONE_LOOKUP_PROJECTION; import static com.onegravity.contactpicker.picture.Constants.TOKEN_EMAIL_LOOKUP; import static com.onegravity.contactpicker.picture.Constants.TOKEN_PHONE_LOOKUP;
* not available, as an extra query will have to be performed to lookup the URI based on the * phone number. * * @param phoneNumber The phone number of the contact. * @param lazyLookup If this is true, the lookup query will not be performed until this view is * clicked. */ public void assignContactFromPhone(String phoneNumber, boolean lazyLookup) { assignContactFromPhone(phoneNumber, lazyLookup, new Bundle()); } /** * Assign a contact based on a phone number. This should only be used when the contact's URI is * not available, as an extra query will have to be performed to lookup the URI based on the * phone number. * * @param phoneNumber The phone number of the contact. * @param lazyLookup If this is true, the lookup query will not be performed until this view is * clicked. * @param extras A bundle of extras to populate the contact edit page with if the contact is not * found and the user chooses to add the phone number to an existing contact or * create a new contact. Uses the same string constants as those found in * {@link android.provider.ContactsContract.Intents.Insert} */ public void assignContactFromPhone(String phoneNumber, boolean lazyLookup, Bundle extras) { mContactPhone = phoneNumber; mExtras = extras; if (!lazyLookup && mQueryHandler != null) { mQueryHandler.startQuery(TOKEN_PHONE_LOOKUP, null, Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, mContactPhone),
// Path: library/src/main/java/com/onegravity/contactpicker/Helper.java // public class Helper { // // public static boolean isNullOrEmpty(CharSequence string){ // return string == null || string.length() == 0; // } // // public static DisplayMetrics getDisplayMetrics(Context context) { // Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); // DisplayMetrics metrics = new DisplayMetrics(); // display.getMetrics( metrics ); // return metrics; // } // // public static void closeQuietly(Cursor cursor) { // try { // cursor.close(); // } // catch (Exception ignore) {} // } // // public static void closeQuietly(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (IOException ignore) {} // } // // } // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final String[] EMAIL_LOOKUP_PROJECTION = new String[]{ // ContactsContract.RawContacts.CONTACT_ID, // ContactsContract.Contacts.LOOKUP_KEY, // }; // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final String[] PHONE_LOOKUP_PROJECTION = new String[]{ // ContactsContract.PhoneLookup._ID, // ContactsContract.PhoneLookup.LOOKUP_KEY, // }; // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final int TOKEN_EMAIL_LOOKUP = 0; // // Path: library/src/main/java/com/onegravity/contactpicker/picture/Constants.java // static final int TOKEN_PHONE_LOOKUP = 1; // Path: library/src/main/java/com/onegravity/contactpicker/picture/ContactBadge.java import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.res.Resources.Theme; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.OvalShape; import android.graphics.drawable.shapes.PathShape; import android.graphics.drawable.shapes.RectShape; import android.graphics.drawable.shapes.Shape; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.PhoneLookup; import android.provider.ContactsContract.QuickContact; import android.text.TextUtils; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import android.view.View.OnClickListener; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import com.onegravity.contactpicker.Helper; import com.onegravity.contactpicker.R; import static com.onegravity.contactpicker.picture.Constants.EMAIL_LOOKUP_PROJECTION; import static com.onegravity.contactpicker.picture.Constants.PHONE_LOOKUP_PROJECTION; import static com.onegravity.contactpicker.picture.Constants.TOKEN_EMAIL_LOOKUP; import static com.onegravity.contactpicker.picture.Constants.TOKEN_PHONE_LOOKUP; * not available, as an extra query will have to be performed to lookup the URI based on the * phone number. * * @param phoneNumber The phone number of the contact. * @param lazyLookup If this is true, the lookup query will not be performed until this view is * clicked. */ public void assignContactFromPhone(String phoneNumber, boolean lazyLookup) { assignContactFromPhone(phoneNumber, lazyLookup, new Bundle()); } /** * Assign a contact based on a phone number. This should only be used when the contact's URI is * not available, as an extra query will have to be performed to lookup the URI based on the * phone number. * * @param phoneNumber The phone number of the contact. * @param lazyLookup If this is true, the lookup query will not be performed until this view is * clicked. * @param extras A bundle of extras to populate the contact edit page with if the contact is not * found and the user chooses to add the phone number to an existing contact or * create a new contact. Uses the same string constants as those found in * {@link android.provider.ContactsContract.Intents.Insert} */ public void assignContactFromPhone(String phoneNumber, boolean lazyLookup, Bundle extras) { mContactPhone = phoneNumber; mExtras = extras; if (!lazyLookup && mQueryHandler != null) { mQueryHandler.startQuery(TOKEN_PHONE_LOOKUP, null, Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, mContactPhone),
PHONE_LOOKUP_PROJECTION, null, null, null, mContactQueryHandlerCallback);
1gravity/Android-ContactPicker
library/src/main/java/com/onegravity/contactpicker/picture/ContactPictureLoader.java
// Path: library/src/main/java/com/onegravity/contactpicker/Helper.java // public class Helper { // // public static boolean isNullOrEmpty(CharSequence string){ // return string == null || string.length() == 0; // } // // public static DisplayMetrics getDisplayMetrics(Context context) { // Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); // DisplayMetrics metrics = new DisplayMetrics(); // display.getMetrics( metrics ); // return metrics; // } // // public static void closeQuietly(Cursor cursor) { // try { // cursor.close(); // } // catch (Exception ignore) {} // } // // public static void closeQuietly(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (IOException ignore) {} // } // // } // // Path: library/src/main/java/com/onegravity/contactpicker/picture/cache/ContactPictureCache.java // public class ContactPictureCache extends InMemoryCache<Uri, Bitmap> { // // private static ContactPictureCache sInstance; // private static int sMemClass; // // // we need to synchronize this to make sure there's no race condition instantiating the cache // public synchronized static ContactPictureCache getInstance(Context context) { // if (sInstance == null) { // ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); // sMemClass = activityManager.getMemoryClass(); // sInstance = new ContactPictureCache(); // } // return sInstance; // } // // private ContactPictureCache() { // // purge after 5 minutes of being idle, the cacheCapacity parameter is ignored // super(1000 * 60 * 5, 50); // } // // @Override // protected HardLruCache createHardLruCache(int cacheCapacity) { // // Use 1/16th of the available memory for this memory cache. // final int cacheSize = 1024 * 1024 * sMemClass / 16; // return new PhotoHardLruCache(cacheSize); // } // // private class PhotoHardLruCache extends HardLruCache { // public PhotoHardLruCache(int initialCapacity) { // super(initialCapacity); // } // // @Override // protected int sizeOf(Uri key, Bitmap bitmap) { // // The cache size will be measured in bytes rather than number of items. // return bitmap.getByteCount(); // } // } // }
import java.io.InputStream; import java.lang.ref.SoftReference; import static android.graphics.Bitmap.createBitmap; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.Shader; import android.net.Uri; import com.onegravity.contactpicker.Helper; import com.onegravity.contactpicker.picture.cache.ContactPictureCache; import java.io.FileNotFoundException;
/* * Copyright (C) 2015-2017 Emanuel Moecklin * * 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.onegravity.contactpicker.picture; /** * Runnable to load a contact picture for a specific ContactBadge. */ public class ContactPictureLoader implements Runnable { private final String mKey; private final SoftReference<ContactBadge> mBadge; private final Uri mPhotoUri; private final boolean mRoundContactPictures; ContactPictureLoader(String key, ContactBadge badge, Uri photoUri, boolean roundContactPictures) { mKey = key; mBadge = new SoftReference<>(badge); mPhotoUri = photoUri; mRoundContactPictures = roundContactPictures; } @Override public void run() { ContactBadge badge = mBadge.get(); if (badge == null) return; // fail fast Bitmap bitmap = retrievePicture(badge.getContext(), mPhotoUri, mRoundContactPictures); if (bitmap != null) { ContactPictureLoaded.post(mKey, badge, bitmap); } } public static Bitmap retrievePicture(Context context, Uri photoUri, boolean roundContactPictures) {
// Path: library/src/main/java/com/onegravity/contactpicker/Helper.java // public class Helper { // // public static boolean isNullOrEmpty(CharSequence string){ // return string == null || string.length() == 0; // } // // public static DisplayMetrics getDisplayMetrics(Context context) { // Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); // DisplayMetrics metrics = new DisplayMetrics(); // display.getMetrics( metrics ); // return metrics; // } // // public static void closeQuietly(Cursor cursor) { // try { // cursor.close(); // } // catch (Exception ignore) {} // } // // public static void closeQuietly(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (IOException ignore) {} // } // // } // // Path: library/src/main/java/com/onegravity/contactpicker/picture/cache/ContactPictureCache.java // public class ContactPictureCache extends InMemoryCache<Uri, Bitmap> { // // private static ContactPictureCache sInstance; // private static int sMemClass; // // // we need to synchronize this to make sure there's no race condition instantiating the cache // public synchronized static ContactPictureCache getInstance(Context context) { // if (sInstance == null) { // ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); // sMemClass = activityManager.getMemoryClass(); // sInstance = new ContactPictureCache(); // } // return sInstance; // } // // private ContactPictureCache() { // // purge after 5 minutes of being idle, the cacheCapacity parameter is ignored // super(1000 * 60 * 5, 50); // } // // @Override // protected HardLruCache createHardLruCache(int cacheCapacity) { // // Use 1/16th of the available memory for this memory cache. // final int cacheSize = 1024 * 1024 * sMemClass / 16; // return new PhotoHardLruCache(cacheSize); // } // // private class PhotoHardLruCache extends HardLruCache { // public PhotoHardLruCache(int initialCapacity) { // super(initialCapacity); // } // // @Override // protected int sizeOf(Uri key, Bitmap bitmap) { // // The cache size will be measured in bytes rather than number of items. // return bitmap.getByteCount(); // } // } // } // Path: library/src/main/java/com/onegravity/contactpicker/picture/ContactPictureLoader.java import java.io.InputStream; import java.lang.ref.SoftReference; import static android.graphics.Bitmap.createBitmap; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.Shader; import android.net.Uri; import com.onegravity.contactpicker.Helper; import com.onegravity.contactpicker.picture.cache.ContactPictureCache; import java.io.FileNotFoundException; /* * Copyright (C) 2015-2017 Emanuel Moecklin * * 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.onegravity.contactpicker.picture; /** * Runnable to load a contact picture for a specific ContactBadge. */ public class ContactPictureLoader implements Runnable { private final String mKey; private final SoftReference<ContactBadge> mBadge; private final Uri mPhotoUri; private final boolean mRoundContactPictures; ContactPictureLoader(String key, ContactBadge badge, Uri photoUri, boolean roundContactPictures) { mKey = key; mBadge = new SoftReference<>(badge); mPhotoUri = photoUri; mRoundContactPictures = roundContactPictures; } @Override public void run() { ContactBadge badge = mBadge.get(); if (badge == null) return; // fail fast Bitmap bitmap = retrievePicture(badge.getContext(), mPhotoUri, mRoundContactPictures); if (bitmap != null) { ContactPictureLoaded.post(mKey, badge, bitmap); } } public static Bitmap retrievePicture(Context context, Uri photoUri, boolean roundContactPictures) {
if (context == null || photoUri == null || Helper.isNullOrEmpty(photoUri.toString())) {
1gravity/Android-ContactPicker
library/src/main/java/com/onegravity/contactpicker/picture/ContactPictureLoader.java
// Path: library/src/main/java/com/onegravity/contactpicker/Helper.java // public class Helper { // // public static boolean isNullOrEmpty(CharSequence string){ // return string == null || string.length() == 0; // } // // public static DisplayMetrics getDisplayMetrics(Context context) { // Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); // DisplayMetrics metrics = new DisplayMetrics(); // display.getMetrics( metrics ); // return metrics; // } // // public static void closeQuietly(Cursor cursor) { // try { // cursor.close(); // } // catch (Exception ignore) {} // } // // public static void closeQuietly(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (IOException ignore) {} // } // // } // // Path: library/src/main/java/com/onegravity/contactpicker/picture/cache/ContactPictureCache.java // public class ContactPictureCache extends InMemoryCache<Uri, Bitmap> { // // private static ContactPictureCache sInstance; // private static int sMemClass; // // // we need to synchronize this to make sure there's no race condition instantiating the cache // public synchronized static ContactPictureCache getInstance(Context context) { // if (sInstance == null) { // ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); // sMemClass = activityManager.getMemoryClass(); // sInstance = new ContactPictureCache(); // } // return sInstance; // } // // private ContactPictureCache() { // // purge after 5 minutes of being idle, the cacheCapacity parameter is ignored // super(1000 * 60 * 5, 50); // } // // @Override // protected HardLruCache createHardLruCache(int cacheCapacity) { // // Use 1/16th of the available memory for this memory cache. // final int cacheSize = 1024 * 1024 * sMemClass / 16; // return new PhotoHardLruCache(cacheSize); // } // // private class PhotoHardLruCache extends HardLruCache { // public PhotoHardLruCache(int initialCapacity) { // super(initialCapacity); // } // // @Override // protected int sizeOf(Uri key, Bitmap bitmap) { // // The cache size will be measured in bytes rather than number of items. // return bitmap.getByteCount(); // } // } // }
import java.io.InputStream; import java.lang.ref.SoftReference; import static android.graphics.Bitmap.createBitmap; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.Shader; import android.net.Uri; import com.onegravity.contactpicker.Helper; import com.onegravity.contactpicker.picture.cache.ContactPictureCache; import java.io.FileNotFoundException;
// read contact picture try { stream = context.getContentResolver().openInputStream(photoUri); bitmap = BitmapFactory.decodeStream(stream); if (bitmap != null) { // some contact pictures aren't square... if (bitmap.getWidth() != bitmap.getHeight()) { int w = bitmap.getWidth(); int h = bitmap.getHeight(); int indent = Math.abs(w - h) / 2; int x = w > h ? indent : 0; int y = w < h ? indent : 0; int size = Math.min(w, h); bitmap = createBitmap(bitmap, x, y, size, size); } if (roundContactPictures) { bitmap = getRoundedBitmap(bitmap); } } } catch (OutOfMemoryError | FileNotFoundException ignore) {} finally { Helper.closeQuietly(stream); } // cache contact picture if (bitmap != null) {
// Path: library/src/main/java/com/onegravity/contactpicker/Helper.java // public class Helper { // // public static boolean isNullOrEmpty(CharSequence string){ // return string == null || string.length() == 0; // } // // public static DisplayMetrics getDisplayMetrics(Context context) { // Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); // DisplayMetrics metrics = new DisplayMetrics(); // display.getMetrics( metrics ); // return metrics; // } // // public static void closeQuietly(Cursor cursor) { // try { // cursor.close(); // } // catch (Exception ignore) {} // } // // public static void closeQuietly(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (IOException ignore) {} // } // // } // // Path: library/src/main/java/com/onegravity/contactpicker/picture/cache/ContactPictureCache.java // public class ContactPictureCache extends InMemoryCache<Uri, Bitmap> { // // private static ContactPictureCache sInstance; // private static int sMemClass; // // // we need to synchronize this to make sure there's no race condition instantiating the cache // public synchronized static ContactPictureCache getInstance(Context context) { // if (sInstance == null) { // ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); // sMemClass = activityManager.getMemoryClass(); // sInstance = new ContactPictureCache(); // } // return sInstance; // } // // private ContactPictureCache() { // // purge after 5 minutes of being idle, the cacheCapacity parameter is ignored // super(1000 * 60 * 5, 50); // } // // @Override // protected HardLruCache createHardLruCache(int cacheCapacity) { // // Use 1/16th of the available memory for this memory cache. // final int cacheSize = 1024 * 1024 * sMemClass / 16; // return new PhotoHardLruCache(cacheSize); // } // // private class PhotoHardLruCache extends HardLruCache { // public PhotoHardLruCache(int initialCapacity) { // super(initialCapacity); // } // // @Override // protected int sizeOf(Uri key, Bitmap bitmap) { // // The cache size will be measured in bytes rather than number of items. // return bitmap.getByteCount(); // } // } // } // Path: library/src/main/java/com/onegravity/contactpicker/picture/ContactPictureLoader.java import java.io.InputStream; import java.lang.ref.SoftReference; import static android.graphics.Bitmap.createBitmap; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.Shader; import android.net.Uri; import com.onegravity.contactpicker.Helper; import com.onegravity.contactpicker.picture.cache.ContactPictureCache; import java.io.FileNotFoundException; // read contact picture try { stream = context.getContentResolver().openInputStream(photoUri); bitmap = BitmapFactory.decodeStream(stream); if (bitmap != null) { // some contact pictures aren't square... if (bitmap.getWidth() != bitmap.getHeight()) { int w = bitmap.getWidth(); int h = bitmap.getHeight(); int indent = Math.abs(w - h) / 2; int x = w > h ? indent : 0; int y = w < h ? indent : 0; int size = Math.min(w, h); bitmap = createBitmap(bitmap, x, y, size, size); } if (roundContactPictures) { bitmap = getRoundedBitmap(bitmap); } } } catch (OutOfMemoryError | FileNotFoundException ignore) {} finally { Helper.closeQuietly(stream); } // cache contact picture if (bitmap != null) {
ContactPictureCache.getInstance(context).put(photoUri, bitmap);
se-bastiaan/ButterRemote-Android
app/src/main/java/eu/se_bastiaan/popcorntimeremote/database/InstanceDbHelper.java
// Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/Constants.java // public final class Constants { // // public static final Boolean LOG_ENABLED = BuildConfig.IS_DEBUG; // public static final String PREFS_FILE = "PTRemote_Prefs"; // public static final String DATABASE_NAME = "PTRemote_DB.db"; // public static final Integer DATABASE_VERSION = 1; // public static final String YOUTUBE_KEY = "AIzaSyC4GRG3DH0HyYvDpmLHqwmpKEhgpCBjduo"; // // private Constants() throws InstantiationException { // throw new InstantiationException("This class is not created for instantiation"); // } // // }
import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import eu.se_bastiaan.popcorntimeremote.Constants;
package eu.se_bastiaan.popcorntimeremote.database; public class InstanceDbHelper extends SQLiteOpenHelper { private static final String TEXT_TYPE = " TEXT"; private static final String COMMA_SEP = ","; private static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + InstanceEntry.TABLE_NAME + " (" + InstanceEntry._ID + " INTEGER PRIMARY KEY," + InstanceEntry.COLUMN_NAME_IP + TEXT_TYPE + COMMA_SEP + InstanceEntry.COLUMN_NAME_PORT + TEXT_TYPE + COMMA_SEP + InstanceEntry.COLUMN_NAME_NAME + TEXT_TYPE + COMMA_SEP + InstanceEntry.COLUMN_NAME_USERNAME + TEXT_TYPE + COMMA_SEP + InstanceEntry.COLUMN_NAME_PASSWORD + TEXT_TYPE + " )"; public InstanceDbHelper(Context context) {
// Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/Constants.java // public final class Constants { // // public static final Boolean LOG_ENABLED = BuildConfig.IS_DEBUG; // public static final String PREFS_FILE = "PTRemote_Prefs"; // public static final String DATABASE_NAME = "PTRemote_DB.db"; // public static final Integer DATABASE_VERSION = 1; // public static final String YOUTUBE_KEY = "AIzaSyC4GRG3DH0HyYvDpmLHqwmpKEhgpCBjduo"; // // private Constants() throws InstantiationException { // throw new InstantiationException("This class is not created for instantiation"); // } // // } // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/database/InstanceDbHelper.java import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import eu.se_bastiaan.popcorntimeremote.Constants; package eu.se_bastiaan.popcorntimeremote.database; public class InstanceDbHelper extends SQLiteOpenHelper { private static final String TEXT_TYPE = " TEXT"; private static final String COMMA_SEP = ","; private static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + InstanceEntry.TABLE_NAME + " (" + InstanceEntry._ID + " INTEGER PRIMARY KEY," + InstanceEntry.COLUMN_NAME_IP + TEXT_TYPE + COMMA_SEP + InstanceEntry.COLUMN_NAME_PORT + TEXT_TYPE + COMMA_SEP + InstanceEntry.COLUMN_NAME_NAME + TEXT_TYPE + COMMA_SEP + InstanceEntry.COLUMN_NAME_USERNAME + TEXT_TYPE + COMMA_SEP + InstanceEntry.COLUMN_NAME_PASSWORD + TEXT_TYPE + " )"; public InstanceDbHelper(Context context) {
super(context, Constants.DATABASE_NAME, null, Constants.DATABASE_VERSION);
se-bastiaan/ButterRemote-Android
app/src/main/java/eu/se_bastiaan/popcorntimeremote/utils/LogUtils.java
// Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/Constants.java // public final class Constants { // // public static final Boolean LOG_ENABLED = BuildConfig.IS_DEBUG; // public static final String PREFS_FILE = "PTRemote_Prefs"; // public static final String DATABASE_NAME = "PTRemote_DB.db"; // public static final Integer DATABASE_VERSION = 1; // public static final String YOUTUBE_KEY = "AIzaSyC4GRG3DH0HyYvDpmLHqwmpKEhgpCBjduo"; // // private Constants() throws InstantiationException { // throw new InstantiationException("This class is not created for instantiation"); // } // // }
import android.util.Log; import eu.se_bastiaan.popcorntimeremote.Constants;
package eu.se_bastiaan.popcorntimeremote.utils; public final class LogUtils { private static final String LOG_UTILS = "LogUtils"; private LogUtils() throws InstantiationException { throw new InstantiationException("This class is not created for instantiation"); } public static void d(Object message) { d(LOG_UTILS, message); } public static void d(Object tag, Object message) {
// Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/Constants.java // public final class Constants { // // public static final Boolean LOG_ENABLED = BuildConfig.IS_DEBUG; // public static final String PREFS_FILE = "PTRemote_Prefs"; // public static final String DATABASE_NAME = "PTRemote_DB.db"; // public static final Integer DATABASE_VERSION = 1; // public static final String YOUTUBE_KEY = "AIzaSyC4GRG3DH0HyYvDpmLHqwmpKEhgpCBjduo"; // // private Constants() throws InstantiationException { // throw new InstantiationException("This class is not created for instantiation"); // } // // } // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/utils/LogUtils.java import android.util.Log; import eu.se_bastiaan.popcorntimeremote.Constants; package eu.se_bastiaan.popcorntimeremote.utils; public final class LogUtils { private static final String LOG_UTILS = "LogUtils"; private LogUtils() throws InstantiationException { throw new InstantiationException("This class is not created for instantiation"); } public static void d(Object message) { d(LOG_UTILS, message); } public static void d(Object tag, Object message) {
if (Constants.LOG_ENABLED) {
se-bastiaan/ButterRemote-Android
app/src/main/java/eu/se_bastiaan/popcorntimeremote/widget/JoystickView.java
// Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/utils/PixelUtils.java // public final class PixelUtils { // // private PixelUtils() throws InstantiationException { // throw new InstantiationException("This class is not created for instantiation"); // } // // public static int getPixelsFromDp(Context context, Integer dp) { // Resources r = context.getResources(); // return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()); // } // // public static int getPixelsFromSp(Context context, Integer sp) { // Resources r = context.getResources(); // return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, r.getDisplayMetrics()); // } // // public static Drawable changeDrawableColor(Context context, Integer resId, Integer color) { // Drawable drawable = context.getResources().getDrawable(resId).mutate(); // drawable.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY)); // return drawable; // } // // public static Integer getStatusBarHeight(Context context) { // int statusBarHeight = 0; // int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); // if (resourceId > 0) { // statusBarHeight = context.getResources().getDimensionPixelSize(resourceId); // } // return statusBarHeight; // } // // }
import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.Handler; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.view.MotionEvent; import android.view.View; import eu.se_bastiaan.popcorntimeremote.utils.PixelUtils;
private final Runnable mCallbackRunnable = new Runnable() { @Override public void run() { mCalledOnce = true; mOnJoystickMoveListener.onValueChanged(getAngle(), getPower(), getDirection()); mHandler.postDelayed(this, 500); } }; public JoystickView(Context context) { super(context); initJoystickView(context); } public JoystickView(Context context, AttributeSet attrs) { super(context, attrs); initJoystickView(context); } public JoystickView(Context context, AttributeSet attrs, int defaultStyle) { super(context, attrs, defaultStyle); initJoystickView(context); } protected void initJoystickView(Context context) { mContext = context; mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG); mCirclePaint.setColor(Color.parseColor("#444C53")); mCirclePaint.setStyle(Paint.Style.STROKE);
// Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/utils/PixelUtils.java // public final class PixelUtils { // // private PixelUtils() throws InstantiationException { // throw new InstantiationException("This class is not created for instantiation"); // } // // public static int getPixelsFromDp(Context context, Integer dp) { // Resources r = context.getResources(); // return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()); // } // // public static int getPixelsFromSp(Context context, Integer sp) { // Resources r = context.getResources(); // return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, r.getDisplayMetrics()); // } // // public static Drawable changeDrawableColor(Context context, Integer resId, Integer color) { // Drawable drawable = context.getResources().getDrawable(resId).mutate(); // drawable.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY)); // return drawable; // } // // public static Integer getStatusBarHeight(Context context) { // int statusBarHeight = 0; // int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); // if (resourceId > 0) { // statusBarHeight = context.getResources().getDimensionPixelSize(resourceId); // } // return statusBarHeight; // } // // } // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/widget/JoystickView.java import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.Handler; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.view.MotionEvent; import android.view.View; import eu.se_bastiaan.popcorntimeremote.utils.PixelUtils; private final Runnable mCallbackRunnable = new Runnable() { @Override public void run() { mCalledOnce = true; mOnJoystickMoveListener.onValueChanged(getAngle(), getPower(), getDirection()); mHandler.postDelayed(this, 500); } }; public JoystickView(Context context) { super(context); initJoystickView(context); } public JoystickView(Context context, AttributeSet attrs) { super(context, attrs); initJoystickView(context); } public JoystickView(Context context, AttributeSet attrs, int defaultStyle) { super(context, attrs, defaultStyle); initJoystickView(context); } protected void initJoystickView(Context context) { mContext = context; mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG); mCirclePaint.setColor(Color.parseColor("#444C53")); mCirclePaint.setStyle(Paint.Style.STROKE);
mCirclePaint.setStrokeWidth(PixelUtils.getPixelsFromDp(mContext, 2));
se-bastiaan/ButterRemote-Android
app/src/main/java/eu/se_bastiaan/popcorntimeremote/activities/PairingScannerActivity.java
// Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/models/ScanModel.java // public class ScanModel implements Parcelable { // public String ip; // public String port; // public String user; // public String pass; // // @SuppressWarnings("unused") // public static final Parcelable.Creator<ScanModel> CREATOR = new Parcelable.Creator<ScanModel>() { // @Override // public ScanModel createFromParcel(Parcel in) { // return new ScanModel(in); // } // // @Override // public ScanModel[] newArray(int size) { // return new ScanModel[size]; // } // }; // // protected ScanModel(Parcel in) { // ip = in.readString(); // port = in.readString(); // user = in.readString(); // pass = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(ip); // dest.writeString(port); // dest.writeString(user); // dest.writeString(pass); // } // // }
import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import com.google.gson.Gson; import com.google.zxing.BarcodeFormat; import com.google.zxing.Result; import java.util.Arrays; import eu.se_bastiaan.popcorntimeremote.R; import eu.se_bastiaan.popcorntimeremote.models.ScanModel; import me.dm7.barcodescanner.zxing.ZXingScannerView;
package eu.se_bastiaan.popcorntimeremote.activities; public class PairingScannerActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler { public static Integer SCAN = 1440, SUCCESS = 1441; private ZXingScannerView scannerView; @Override public void onCreate(Bundle state) { super.onCreate(state); scannerView = new ZXingScannerView(this); setContentView(scannerView); } @Override public void onResume() { super.onResume(); scannerView.setResultHandler(this); scannerView.startCamera(); } @Override public void onPause() { super.onPause(); scannerView.stopCamera(); } @Override public void handleResult(Result rawResult) { try { String json = rawResult.getText(); Gson gson = new Gson();
// Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/models/ScanModel.java // public class ScanModel implements Parcelable { // public String ip; // public String port; // public String user; // public String pass; // // @SuppressWarnings("unused") // public static final Parcelable.Creator<ScanModel> CREATOR = new Parcelable.Creator<ScanModel>() { // @Override // public ScanModel createFromParcel(Parcel in) { // return new ScanModel(in); // } // // @Override // public ScanModel[] newArray(int size) { // return new ScanModel[size]; // } // }; // // protected ScanModel(Parcel in) { // ip = in.readString(); // port = in.readString(); // user = in.readString(); // pass = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(ip); // dest.writeString(port); // dest.writeString(user); // dest.writeString(pass); // } // // } // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/activities/PairingScannerActivity.java import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import com.google.gson.Gson; import com.google.zxing.BarcodeFormat; import com.google.zxing.Result; import java.util.Arrays; import eu.se_bastiaan.popcorntimeremote.R; import eu.se_bastiaan.popcorntimeremote.models.ScanModel; import me.dm7.barcodescanner.zxing.ZXingScannerView; package eu.se_bastiaan.popcorntimeremote.activities; public class PairingScannerActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler { public static Integer SCAN = 1440, SUCCESS = 1441; private ZXingScannerView scannerView; @Override public void onCreate(Bundle state) { super.onCreate(state); scannerView = new ZXingScannerView(this); setContentView(scannerView); } @Override public void onResume() { super.onResume(); scannerView.setResultHandler(this); scannerView.startCamera(); } @Override public void onPause() { super.onPause(); scannerView.stopCamera(); } @Override public void handleResult(Result rawResult) { try { String json = rawResult.getText(); Gson gson = new Gson();
ScanModel model = gson.fromJson(json, ScanModel.class);
se-bastiaan/ButterRemote-Android
app/src/main/java/eu/se_bastiaan/popcorntimeremote/fragments/LoadingControllerFragment.java
// Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/utils/LogUtils.java // public final class LogUtils { // // private static final String LOG_UTILS = "LogUtils"; // // private LogUtils() throws InstantiationException { // throw new InstantiationException("This class is not created for instantiation"); // } // // public static void d(Object message) { // d(LOG_UTILS, message); // } // // public static void d(Object tag, Object message) { // if (Constants.LOG_ENABLED) { // Log.d(tag.toString(), message.toString()); // } // } // // public static void v(Object message) { // v(LOG_UTILS, message); // } // // public static void v(Object tag, Object message) { // if (Constants.LOG_ENABLED) { // Log.v(tag.toString(), message.toString()); // } // } // // public static void e(Object message) { // e(LOG_UTILS, message); // } // // public static void e(Object tag, Object message) { // if (Constants.LOG_ENABLED) { // Log.e(tag.toString(), message.toString()); // } // } // // public static void e(Object tag, Object message, Throwable t) { // if (Constants.LOG_ENABLED) { // Log.e(tag.toString(), message.toString(), t); // } // } // // public static void w(Object message) { // w(LOG_UTILS, message); // } // // public static void w(Object tag, Object message) { // if (Constants.LOG_ENABLED) { // Log.w(tag.toString(), message.toString()); // } // } // // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import eu.se_bastiaan.popcorntimeremote.R; import eu.se_bastiaan.popcorntimeremote.utils.LogUtils;
package eu.se_bastiaan.popcorntimeremote.fragments; public class LoadingControllerFragment extends BaseControlFragment { @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/utils/LogUtils.java // public final class LogUtils { // // private static final String LOG_UTILS = "LogUtils"; // // private LogUtils() throws InstantiationException { // throw new InstantiationException("This class is not created for instantiation"); // } // // public static void d(Object message) { // d(LOG_UTILS, message); // } // // public static void d(Object tag, Object message) { // if (Constants.LOG_ENABLED) { // Log.d(tag.toString(), message.toString()); // } // } // // public static void v(Object message) { // v(LOG_UTILS, message); // } // // public static void v(Object tag, Object message) { // if (Constants.LOG_ENABLED) { // Log.v(tag.toString(), message.toString()); // } // } // // public static void e(Object message) { // e(LOG_UTILS, message); // } // // public static void e(Object tag, Object message) { // if (Constants.LOG_ENABLED) { // Log.e(tag.toString(), message.toString()); // } // } // // public static void e(Object tag, Object message, Throwable t) { // if (Constants.LOG_ENABLED) { // Log.e(tag.toString(), message.toString(), t); // } // } // // public static void w(Object message) { // w(LOG_UTILS, message); // } // // public static void w(Object tag, Object message) { // if (Constants.LOG_ENABLED) { // Log.w(tag.toString(), message.toString()); // } // } // // } // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/fragments/LoadingControllerFragment.java import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import eu.se_bastiaan.popcorntimeremote.R; import eu.se_bastiaan.popcorntimeremote.utils.LogUtils; package eu.se_bastiaan.popcorntimeremote.fragments; public class LoadingControllerFragment extends BaseControlFragment { @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
LogUtils.d("JoyStickMainControllerFragment", "onCreateView");
se-bastiaan/ButterRemote-Android
app/src/main/java/eu/se_bastiaan/popcorntimeremote/activities/IntroActivity.java
// Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideFive.java // public class SlideFive extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_five, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideFour.java // public class SlideFour extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_four, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideOne.java // public class SlideOne extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_one, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideSix.java // public class SlideSix extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_six, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideThree.java // public class SlideThree extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_three, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideTwo.java // public class SlideTwo extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_two, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/utils/PrefUtils.java // public final class PrefUtils { // // private PrefUtils() throws InstantiationException { // throw new InstantiationException("This class is not created for instantiation"); // } // // // Main functions below // // public static void clear(Context context) { // getPrefs(context).edit().clear().apply(); // } // // public static void save(Context context, String key, String value) { // getPrefs(context).edit().putString(key, value).apply(); // } // // public static String get(Context context, String key, String defaultValue) { // return getPrefs(context).getString(key, defaultValue); // } // // public static void save(Context context, String key, Boolean value) { // getPrefs(context).edit().putBoolean(key, value).apply(); // } // // public static Boolean get(Context context, String key, Boolean defaultValue) { // return getPrefs(context).getBoolean(key, defaultValue); // } // // public static Boolean contains(Context context, String key) { // return getPrefs(context).contains(key); // } // // public static ObscuredSharedPreferences getPrefs(Context context) { // return new ObscuredSharedPreferences(context, context.getSharedPreferences(Constants.PREFS_FILE, Context.MODE_PRIVATE)); // } // // }
import android.content.Intent; import android.os.Bundle; import android.view.WindowManager; import com.github.paolorotolo.appintro.AppIntro2; import eu.se_bastiaan.popcorntimeremote.intro.SlideFive; import eu.se_bastiaan.popcorntimeremote.intro.SlideFour; import eu.se_bastiaan.popcorntimeremote.intro.SlideOne; import eu.se_bastiaan.popcorntimeremote.intro.SlideSix; import eu.se_bastiaan.popcorntimeremote.intro.SlideThree; import eu.se_bastiaan.popcorntimeremote.intro.SlideTwo; import eu.se_bastiaan.popcorntimeremote.utils.PrefUtils;
package eu.se_bastiaan.popcorntimeremote.activities; public class IntroActivity extends AppIntro2 { @Override public void init(Bundle savedInstanceState) { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
// Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideFive.java // public class SlideFive extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_five, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideFour.java // public class SlideFour extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_four, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideOne.java // public class SlideOne extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_one, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideSix.java // public class SlideSix extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_six, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideThree.java // public class SlideThree extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_three, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideTwo.java // public class SlideTwo extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_two, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/utils/PrefUtils.java // public final class PrefUtils { // // private PrefUtils() throws InstantiationException { // throw new InstantiationException("This class is not created for instantiation"); // } // // // Main functions below // // public static void clear(Context context) { // getPrefs(context).edit().clear().apply(); // } // // public static void save(Context context, String key, String value) { // getPrefs(context).edit().putString(key, value).apply(); // } // // public static String get(Context context, String key, String defaultValue) { // return getPrefs(context).getString(key, defaultValue); // } // // public static void save(Context context, String key, Boolean value) { // getPrefs(context).edit().putBoolean(key, value).apply(); // } // // public static Boolean get(Context context, String key, Boolean defaultValue) { // return getPrefs(context).getBoolean(key, defaultValue); // } // // public static Boolean contains(Context context, String key) { // return getPrefs(context).contains(key); // } // // public static ObscuredSharedPreferences getPrefs(Context context) { // return new ObscuredSharedPreferences(context, context.getSharedPreferences(Constants.PREFS_FILE, Context.MODE_PRIVATE)); // } // // } // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/activities/IntroActivity.java import android.content.Intent; import android.os.Bundle; import android.view.WindowManager; import com.github.paolorotolo.appintro.AppIntro2; import eu.se_bastiaan.popcorntimeremote.intro.SlideFive; import eu.se_bastiaan.popcorntimeremote.intro.SlideFour; import eu.se_bastiaan.popcorntimeremote.intro.SlideOne; import eu.se_bastiaan.popcorntimeremote.intro.SlideSix; import eu.se_bastiaan.popcorntimeremote.intro.SlideThree; import eu.se_bastiaan.popcorntimeremote.intro.SlideTwo; import eu.se_bastiaan.popcorntimeremote.utils.PrefUtils; package eu.se_bastiaan.popcorntimeremote.activities; public class IntroActivity extends AppIntro2 { @Override public void init(Bundle savedInstanceState) { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
addSlide(new SlideOne(), getApplicationContext());
se-bastiaan/ButterRemote-Android
app/src/main/java/eu/se_bastiaan/popcorntimeremote/activities/IntroActivity.java
// Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideFive.java // public class SlideFive extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_five, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideFour.java // public class SlideFour extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_four, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideOne.java // public class SlideOne extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_one, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideSix.java // public class SlideSix extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_six, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideThree.java // public class SlideThree extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_three, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideTwo.java // public class SlideTwo extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_two, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/utils/PrefUtils.java // public final class PrefUtils { // // private PrefUtils() throws InstantiationException { // throw new InstantiationException("This class is not created for instantiation"); // } // // // Main functions below // // public static void clear(Context context) { // getPrefs(context).edit().clear().apply(); // } // // public static void save(Context context, String key, String value) { // getPrefs(context).edit().putString(key, value).apply(); // } // // public static String get(Context context, String key, String defaultValue) { // return getPrefs(context).getString(key, defaultValue); // } // // public static void save(Context context, String key, Boolean value) { // getPrefs(context).edit().putBoolean(key, value).apply(); // } // // public static Boolean get(Context context, String key, Boolean defaultValue) { // return getPrefs(context).getBoolean(key, defaultValue); // } // // public static Boolean contains(Context context, String key) { // return getPrefs(context).contains(key); // } // // public static ObscuredSharedPreferences getPrefs(Context context) { // return new ObscuredSharedPreferences(context, context.getSharedPreferences(Constants.PREFS_FILE, Context.MODE_PRIVATE)); // } // // }
import android.content.Intent; import android.os.Bundle; import android.view.WindowManager; import com.github.paolorotolo.appintro.AppIntro2; import eu.se_bastiaan.popcorntimeremote.intro.SlideFive; import eu.se_bastiaan.popcorntimeremote.intro.SlideFour; import eu.se_bastiaan.popcorntimeremote.intro.SlideOne; import eu.se_bastiaan.popcorntimeremote.intro.SlideSix; import eu.se_bastiaan.popcorntimeremote.intro.SlideThree; import eu.se_bastiaan.popcorntimeremote.intro.SlideTwo; import eu.se_bastiaan.popcorntimeremote.utils.PrefUtils;
package eu.se_bastiaan.popcorntimeremote.activities; public class IntroActivity extends AppIntro2 { @Override public void init(Bundle savedInstanceState) { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); addSlide(new SlideOne(), getApplicationContext());
// Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideFive.java // public class SlideFive extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_five, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideFour.java // public class SlideFour extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_four, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideOne.java // public class SlideOne extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_one, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideSix.java // public class SlideSix extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_six, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideThree.java // public class SlideThree extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_three, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideTwo.java // public class SlideTwo extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_two, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/utils/PrefUtils.java // public final class PrefUtils { // // private PrefUtils() throws InstantiationException { // throw new InstantiationException("This class is not created for instantiation"); // } // // // Main functions below // // public static void clear(Context context) { // getPrefs(context).edit().clear().apply(); // } // // public static void save(Context context, String key, String value) { // getPrefs(context).edit().putString(key, value).apply(); // } // // public static String get(Context context, String key, String defaultValue) { // return getPrefs(context).getString(key, defaultValue); // } // // public static void save(Context context, String key, Boolean value) { // getPrefs(context).edit().putBoolean(key, value).apply(); // } // // public static Boolean get(Context context, String key, Boolean defaultValue) { // return getPrefs(context).getBoolean(key, defaultValue); // } // // public static Boolean contains(Context context, String key) { // return getPrefs(context).contains(key); // } // // public static ObscuredSharedPreferences getPrefs(Context context) { // return new ObscuredSharedPreferences(context, context.getSharedPreferences(Constants.PREFS_FILE, Context.MODE_PRIVATE)); // } // // } // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/activities/IntroActivity.java import android.content.Intent; import android.os.Bundle; import android.view.WindowManager; import com.github.paolorotolo.appintro.AppIntro2; import eu.se_bastiaan.popcorntimeremote.intro.SlideFive; import eu.se_bastiaan.popcorntimeremote.intro.SlideFour; import eu.se_bastiaan.popcorntimeremote.intro.SlideOne; import eu.se_bastiaan.popcorntimeremote.intro.SlideSix; import eu.se_bastiaan.popcorntimeremote.intro.SlideThree; import eu.se_bastiaan.popcorntimeremote.intro.SlideTwo; import eu.se_bastiaan.popcorntimeremote.utils.PrefUtils; package eu.se_bastiaan.popcorntimeremote.activities; public class IntroActivity extends AppIntro2 { @Override public void init(Bundle savedInstanceState) { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); addSlide(new SlideOne(), getApplicationContext());
addSlide(new SlideTwo(), getApplicationContext());
se-bastiaan/ButterRemote-Android
app/src/main/java/eu/se_bastiaan/popcorntimeremote/activities/IntroActivity.java
// Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideFive.java // public class SlideFive extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_five, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideFour.java // public class SlideFour extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_four, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideOne.java // public class SlideOne extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_one, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideSix.java // public class SlideSix extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_six, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideThree.java // public class SlideThree extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_three, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideTwo.java // public class SlideTwo extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_two, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/utils/PrefUtils.java // public final class PrefUtils { // // private PrefUtils() throws InstantiationException { // throw new InstantiationException("This class is not created for instantiation"); // } // // // Main functions below // // public static void clear(Context context) { // getPrefs(context).edit().clear().apply(); // } // // public static void save(Context context, String key, String value) { // getPrefs(context).edit().putString(key, value).apply(); // } // // public static String get(Context context, String key, String defaultValue) { // return getPrefs(context).getString(key, defaultValue); // } // // public static void save(Context context, String key, Boolean value) { // getPrefs(context).edit().putBoolean(key, value).apply(); // } // // public static Boolean get(Context context, String key, Boolean defaultValue) { // return getPrefs(context).getBoolean(key, defaultValue); // } // // public static Boolean contains(Context context, String key) { // return getPrefs(context).contains(key); // } // // public static ObscuredSharedPreferences getPrefs(Context context) { // return new ObscuredSharedPreferences(context, context.getSharedPreferences(Constants.PREFS_FILE, Context.MODE_PRIVATE)); // } // // }
import android.content.Intent; import android.os.Bundle; import android.view.WindowManager; import com.github.paolorotolo.appintro.AppIntro2; import eu.se_bastiaan.popcorntimeremote.intro.SlideFive; import eu.se_bastiaan.popcorntimeremote.intro.SlideFour; import eu.se_bastiaan.popcorntimeremote.intro.SlideOne; import eu.se_bastiaan.popcorntimeremote.intro.SlideSix; import eu.se_bastiaan.popcorntimeremote.intro.SlideThree; import eu.se_bastiaan.popcorntimeremote.intro.SlideTwo; import eu.se_bastiaan.popcorntimeremote.utils.PrefUtils;
package eu.se_bastiaan.popcorntimeremote.activities; public class IntroActivity extends AppIntro2 { @Override public void init(Bundle savedInstanceState) { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); addSlide(new SlideOne(), getApplicationContext()); addSlide(new SlideTwo(), getApplicationContext());
// Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideFive.java // public class SlideFive extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_five, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideFour.java // public class SlideFour extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_four, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideOne.java // public class SlideOne extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_one, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideSix.java // public class SlideSix extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_six, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideThree.java // public class SlideThree extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_three, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideTwo.java // public class SlideTwo extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_two, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/utils/PrefUtils.java // public final class PrefUtils { // // private PrefUtils() throws InstantiationException { // throw new InstantiationException("This class is not created for instantiation"); // } // // // Main functions below // // public static void clear(Context context) { // getPrefs(context).edit().clear().apply(); // } // // public static void save(Context context, String key, String value) { // getPrefs(context).edit().putString(key, value).apply(); // } // // public static String get(Context context, String key, String defaultValue) { // return getPrefs(context).getString(key, defaultValue); // } // // public static void save(Context context, String key, Boolean value) { // getPrefs(context).edit().putBoolean(key, value).apply(); // } // // public static Boolean get(Context context, String key, Boolean defaultValue) { // return getPrefs(context).getBoolean(key, defaultValue); // } // // public static Boolean contains(Context context, String key) { // return getPrefs(context).contains(key); // } // // public static ObscuredSharedPreferences getPrefs(Context context) { // return new ObscuredSharedPreferences(context, context.getSharedPreferences(Constants.PREFS_FILE, Context.MODE_PRIVATE)); // } // // } // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/activities/IntroActivity.java import android.content.Intent; import android.os.Bundle; import android.view.WindowManager; import com.github.paolorotolo.appintro.AppIntro2; import eu.se_bastiaan.popcorntimeremote.intro.SlideFive; import eu.se_bastiaan.popcorntimeremote.intro.SlideFour; import eu.se_bastiaan.popcorntimeremote.intro.SlideOne; import eu.se_bastiaan.popcorntimeremote.intro.SlideSix; import eu.se_bastiaan.popcorntimeremote.intro.SlideThree; import eu.se_bastiaan.popcorntimeremote.intro.SlideTwo; import eu.se_bastiaan.popcorntimeremote.utils.PrefUtils; package eu.se_bastiaan.popcorntimeremote.activities; public class IntroActivity extends AppIntro2 { @Override public void init(Bundle savedInstanceState) { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); addSlide(new SlideOne(), getApplicationContext()); addSlide(new SlideTwo(), getApplicationContext());
addSlide(new SlideThree(), getApplicationContext());
se-bastiaan/ButterRemote-Android
app/src/main/java/eu/se_bastiaan/popcorntimeremote/activities/IntroActivity.java
// Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideFive.java // public class SlideFive extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_five, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideFour.java // public class SlideFour extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_four, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideOne.java // public class SlideOne extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_one, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideSix.java // public class SlideSix extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_six, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideThree.java // public class SlideThree extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_three, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideTwo.java // public class SlideTwo extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_two, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/utils/PrefUtils.java // public final class PrefUtils { // // private PrefUtils() throws InstantiationException { // throw new InstantiationException("This class is not created for instantiation"); // } // // // Main functions below // // public static void clear(Context context) { // getPrefs(context).edit().clear().apply(); // } // // public static void save(Context context, String key, String value) { // getPrefs(context).edit().putString(key, value).apply(); // } // // public static String get(Context context, String key, String defaultValue) { // return getPrefs(context).getString(key, defaultValue); // } // // public static void save(Context context, String key, Boolean value) { // getPrefs(context).edit().putBoolean(key, value).apply(); // } // // public static Boolean get(Context context, String key, Boolean defaultValue) { // return getPrefs(context).getBoolean(key, defaultValue); // } // // public static Boolean contains(Context context, String key) { // return getPrefs(context).contains(key); // } // // public static ObscuredSharedPreferences getPrefs(Context context) { // return new ObscuredSharedPreferences(context, context.getSharedPreferences(Constants.PREFS_FILE, Context.MODE_PRIVATE)); // } // // }
import android.content.Intent; import android.os.Bundle; import android.view.WindowManager; import com.github.paolorotolo.appintro.AppIntro2; import eu.se_bastiaan.popcorntimeremote.intro.SlideFive; import eu.se_bastiaan.popcorntimeremote.intro.SlideFour; import eu.se_bastiaan.popcorntimeremote.intro.SlideOne; import eu.se_bastiaan.popcorntimeremote.intro.SlideSix; import eu.se_bastiaan.popcorntimeremote.intro.SlideThree; import eu.se_bastiaan.popcorntimeremote.intro.SlideTwo; import eu.se_bastiaan.popcorntimeremote.utils.PrefUtils;
package eu.se_bastiaan.popcorntimeremote.activities; public class IntroActivity extends AppIntro2 { @Override public void init(Bundle savedInstanceState) { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); addSlide(new SlideOne(), getApplicationContext()); addSlide(new SlideTwo(), getApplicationContext()); addSlide(new SlideThree(), getApplicationContext());
// Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideFive.java // public class SlideFive extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_five, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideFour.java // public class SlideFour extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_four, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideOne.java // public class SlideOne extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_one, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideSix.java // public class SlideSix extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_six, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideThree.java // public class SlideThree extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_three, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideTwo.java // public class SlideTwo extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_two, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/utils/PrefUtils.java // public final class PrefUtils { // // private PrefUtils() throws InstantiationException { // throw new InstantiationException("This class is not created for instantiation"); // } // // // Main functions below // // public static void clear(Context context) { // getPrefs(context).edit().clear().apply(); // } // // public static void save(Context context, String key, String value) { // getPrefs(context).edit().putString(key, value).apply(); // } // // public static String get(Context context, String key, String defaultValue) { // return getPrefs(context).getString(key, defaultValue); // } // // public static void save(Context context, String key, Boolean value) { // getPrefs(context).edit().putBoolean(key, value).apply(); // } // // public static Boolean get(Context context, String key, Boolean defaultValue) { // return getPrefs(context).getBoolean(key, defaultValue); // } // // public static Boolean contains(Context context, String key) { // return getPrefs(context).contains(key); // } // // public static ObscuredSharedPreferences getPrefs(Context context) { // return new ObscuredSharedPreferences(context, context.getSharedPreferences(Constants.PREFS_FILE, Context.MODE_PRIVATE)); // } // // } // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/activities/IntroActivity.java import android.content.Intent; import android.os.Bundle; import android.view.WindowManager; import com.github.paolorotolo.appintro.AppIntro2; import eu.se_bastiaan.popcorntimeremote.intro.SlideFive; import eu.se_bastiaan.popcorntimeremote.intro.SlideFour; import eu.se_bastiaan.popcorntimeremote.intro.SlideOne; import eu.se_bastiaan.popcorntimeremote.intro.SlideSix; import eu.se_bastiaan.popcorntimeremote.intro.SlideThree; import eu.se_bastiaan.popcorntimeremote.intro.SlideTwo; import eu.se_bastiaan.popcorntimeremote.utils.PrefUtils; package eu.se_bastiaan.popcorntimeremote.activities; public class IntroActivity extends AppIntro2 { @Override public void init(Bundle savedInstanceState) { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); addSlide(new SlideOne(), getApplicationContext()); addSlide(new SlideTwo(), getApplicationContext()); addSlide(new SlideThree(), getApplicationContext());
addSlide(new SlideFour(), getApplicationContext());
se-bastiaan/ButterRemote-Android
app/src/main/java/eu/se_bastiaan/popcorntimeremote/activities/IntroActivity.java
// Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideFive.java // public class SlideFive extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_five, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideFour.java // public class SlideFour extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_four, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideOne.java // public class SlideOne extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_one, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideSix.java // public class SlideSix extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_six, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideThree.java // public class SlideThree extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_three, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideTwo.java // public class SlideTwo extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_two, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/utils/PrefUtils.java // public final class PrefUtils { // // private PrefUtils() throws InstantiationException { // throw new InstantiationException("This class is not created for instantiation"); // } // // // Main functions below // // public static void clear(Context context) { // getPrefs(context).edit().clear().apply(); // } // // public static void save(Context context, String key, String value) { // getPrefs(context).edit().putString(key, value).apply(); // } // // public static String get(Context context, String key, String defaultValue) { // return getPrefs(context).getString(key, defaultValue); // } // // public static void save(Context context, String key, Boolean value) { // getPrefs(context).edit().putBoolean(key, value).apply(); // } // // public static Boolean get(Context context, String key, Boolean defaultValue) { // return getPrefs(context).getBoolean(key, defaultValue); // } // // public static Boolean contains(Context context, String key) { // return getPrefs(context).contains(key); // } // // public static ObscuredSharedPreferences getPrefs(Context context) { // return new ObscuredSharedPreferences(context, context.getSharedPreferences(Constants.PREFS_FILE, Context.MODE_PRIVATE)); // } // // }
import android.content.Intent; import android.os.Bundle; import android.view.WindowManager; import com.github.paolorotolo.appintro.AppIntro2; import eu.se_bastiaan.popcorntimeremote.intro.SlideFive; import eu.se_bastiaan.popcorntimeremote.intro.SlideFour; import eu.se_bastiaan.popcorntimeremote.intro.SlideOne; import eu.se_bastiaan.popcorntimeremote.intro.SlideSix; import eu.se_bastiaan.popcorntimeremote.intro.SlideThree; import eu.se_bastiaan.popcorntimeremote.intro.SlideTwo; import eu.se_bastiaan.popcorntimeremote.utils.PrefUtils;
package eu.se_bastiaan.popcorntimeremote.activities; public class IntroActivity extends AppIntro2 { @Override public void init(Bundle savedInstanceState) { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); addSlide(new SlideOne(), getApplicationContext()); addSlide(new SlideTwo(), getApplicationContext()); addSlide(new SlideThree(), getApplicationContext()); addSlide(new SlideFour(), getApplicationContext());
// Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideFive.java // public class SlideFive extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_five, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideFour.java // public class SlideFour extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_four, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideOne.java // public class SlideOne extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_one, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideSix.java // public class SlideSix extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_six, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideThree.java // public class SlideThree extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_three, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideTwo.java // public class SlideTwo extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_two, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/utils/PrefUtils.java // public final class PrefUtils { // // private PrefUtils() throws InstantiationException { // throw new InstantiationException("This class is not created for instantiation"); // } // // // Main functions below // // public static void clear(Context context) { // getPrefs(context).edit().clear().apply(); // } // // public static void save(Context context, String key, String value) { // getPrefs(context).edit().putString(key, value).apply(); // } // // public static String get(Context context, String key, String defaultValue) { // return getPrefs(context).getString(key, defaultValue); // } // // public static void save(Context context, String key, Boolean value) { // getPrefs(context).edit().putBoolean(key, value).apply(); // } // // public static Boolean get(Context context, String key, Boolean defaultValue) { // return getPrefs(context).getBoolean(key, defaultValue); // } // // public static Boolean contains(Context context, String key) { // return getPrefs(context).contains(key); // } // // public static ObscuredSharedPreferences getPrefs(Context context) { // return new ObscuredSharedPreferences(context, context.getSharedPreferences(Constants.PREFS_FILE, Context.MODE_PRIVATE)); // } // // } // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/activities/IntroActivity.java import android.content.Intent; import android.os.Bundle; import android.view.WindowManager; import com.github.paolorotolo.appintro.AppIntro2; import eu.se_bastiaan.popcorntimeremote.intro.SlideFive; import eu.se_bastiaan.popcorntimeremote.intro.SlideFour; import eu.se_bastiaan.popcorntimeremote.intro.SlideOne; import eu.se_bastiaan.popcorntimeremote.intro.SlideSix; import eu.se_bastiaan.popcorntimeremote.intro.SlideThree; import eu.se_bastiaan.popcorntimeremote.intro.SlideTwo; import eu.se_bastiaan.popcorntimeremote.utils.PrefUtils; package eu.se_bastiaan.popcorntimeremote.activities; public class IntroActivity extends AppIntro2 { @Override public void init(Bundle savedInstanceState) { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); addSlide(new SlideOne(), getApplicationContext()); addSlide(new SlideTwo(), getApplicationContext()); addSlide(new SlideThree(), getApplicationContext()); addSlide(new SlideFour(), getApplicationContext());
addSlide(new SlideFive(), getApplicationContext());
se-bastiaan/ButterRemote-Android
app/src/main/java/eu/se_bastiaan/popcorntimeremote/activities/IntroActivity.java
// Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideFive.java // public class SlideFive extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_five, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideFour.java // public class SlideFour extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_four, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideOne.java // public class SlideOne extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_one, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideSix.java // public class SlideSix extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_six, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideThree.java // public class SlideThree extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_three, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideTwo.java // public class SlideTwo extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_two, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/utils/PrefUtils.java // public final class PrefUtils { // // private PrefUtils() throws InstantiationException { // throw new InstantiationException("This class is not created for instantiation"); // } // // // Main functions below // // public static void clear(Context context) { // getPrefs(context).edit().clear().apply(); // } // // public static void save(Context context, String key, String value) { // getPrefs(context).edit().putString(key, value).apply(); // } // // public static String get(Context context, String key, String defaultValue) { // return getPrefs(context).getString(key, defaultValue); // } // // public static void save(Context context, String key, Boolean value) { // getPrefs(context).edit().putBoolean(key, value).apply(); // } // // public static Boolean get(Context context, String key, Boolean defaultValue) { // return getPrefs(context).getBoolean(key, defaultValue); // } // // public static Boolean contains(Context context, String key) { // return getPrefs(context).contains(key); // } // // public static ObscuredSharedPreferences getPrefs(Context context) { // return new ObscuredSharedPreferences(context, context.getSharedPreferences(Constants.PREFS_FILE, Context.MODE_PRIVATE)); // } // // }
import android.content.Intent; import android.os.Bundle; import android.view.WindowManager; import com.github.paolorotolo.appintro.AppIntro2; import eu.se_bastiaan.popcorntimeremote.intro.SlideFive; import eu.se_bastiaan.popcorntimeremote.intro.SlideFour; import eu.se_bastiaan.popcorntimeremote.intro.SlideOne; import eu.se_bastiaan.popcorntimeremote.intro.SlideSix; import eu.se_bastiaan.popcorntimeremote.intro.SlideThree; import eu.se_bastiaan.popcorntimeremote.intro.SlideTwo; import eu.se_bastiaan.popcorntimeremote.utils.PrefUtils;
package eu.se_bastiaan.popcorntimeremote.activities; public class IntroActivity extends AppIntro2 { @Override public void init(Bundle savedInstanceState) { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); addSlide(new SlideOne(), getApplicationContext()); addSlide(new SlideTwo(), getApplicationContext()); addSlide(new SlideThree(), getApplicationContext()); addSlide(new SlideFour(), getApplicationContext()); addSlide(new SlideFive(), getApplicationContext());
// Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideFive.java // public class SlideFive extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_five, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideFour.java // public class SlideFour extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_four, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideOne.java // public class SlideOne extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_one, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideSix.java // public class SlideSix extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_six, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideThree.java // public class SlideThree extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_three, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideTwo.java // public class SlideTwo extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_two, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/utils/PrefUtils.java // public final class PrefUtils { // // private PrefUtils() throws InstantiationException { // throw new InstantiationException("This class is not created for instantiation"); // } // // // Main functions below // // public static void clear(Context context) { // getPrefs(context).edit().clear().apply(); // } // // public static void save(Context context, String key, String value) { // getPrefs(context).edit().putString(key, value).apply(); // } // // public static String get(Context context, String key, String defaultValue) { // return getPrefs(context).getString(key, defaultValue); // } // // public static void save(Context context, String key, Boolean value) { // getPrefs(context).edit().putBoolean(key, value).apply(); // } // // public static Boolean get(Context context, String key, Boolean defaultValue) { // return getPrefs(context).getBoolean(key, defaultValue); // } // // public static Boolean contains(Context context, String key) { // return getPrefs(context).contains(key); // } // // public static ObscuredSharedPreferences getPrefs(Context context) { // return new ObscuredSharedPreferences(context, context.getSharedPreferences(Constants.PREFS_FILE, Context.MODE_PRIVATE)); // } // // } // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/activities/IntroActivity.java import android.content.Intent; import android.os.Bundle; import android.view.WindowManager; import com.github.paolorotolo.appintro.AppIntro2; import eu.se_bastiaan.popcorntimeremote.intro.SlideFive; import eu.se_bastiaan.popcorntimeremote.intro.SlideFour; import eu.se_bastiaan.popcorntimeremote.intro.SlideOne; import eu.se_bastiaan.popcorntimeremote.intro.SlideSix; import eu.se_bastiaan.popcorntimeremote.intro.SlideThree; import eu.se_bastiaan.popcorntimeremote.intro.SlideTwo; import eu.se_bastiaan.popcorntimeremote.utils.PrefUtils; package eu.se_bastiaan.popcorntimeremote.activities; public class IntroActivity extends AppIntro2 { @Override public void init(Bundle savedInstanceState) { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); addSlide(new SlideOne(), getApplicationContext()); addSlide(new SlideTwo(), getApplicationContext()); addSlide(new SlideThree(), getApplicationContext()); addSlide(new SlideFour(), getApplicationContext()); addSlide(new SlideFive(), getApplicationContext());
addSlide(new SlideSix(), getApplicationContext());
se-bastiaan/ButterRemote-Android
app/src/main/java/eu/se_bastiaan/popcorntimeremote/activities/IntroActivity.java
// Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideFive.java // public class SlideFive extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_five, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideFour.java // public class SlideFour extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_four, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideOne.java // public class SlideOne extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_one, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideSix.java // public class SlideSix extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_six, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideThree.java // public class SlideThree extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_three, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideTwo.java // public class SlideTwo extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_two, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/utils/PrefUtils.java // public final class PrefUtils { // // private PrefUtils() throws InstantiationException { // throw new InstantiationException("This class is not created for instantiation"); // } // // // Main functions below // // public static void clear(Context context) { // getPrefs(context).edit().clear().apply(); // } // // public static void save(Context context, String key, String value) { // getPrefs(context).edit().putString(key, value).apply(); // } // // public static String get(Context context, String key, String defaultValue) { // return getPrefs(context).getString(key, defaultValue); // } // // public static void save(Context context, String key, Boolean value) { // getPrefs(context).edit().putBoolean(key, value).apply(); // } // // public static Boolean get(Context context, String key, Boolean defaultValue) { // return getPrefs(context).getBoolean(key, defaultValue); // } // // public static Boolean contains(Context context, String key) { // return getPrefs(context).contains(key); // } // // public static ObscuredSharedPreferences getPrefs(Context context) { // return new ObscuredSharedPreferences(context, context.getSharedPreferences(Constants.PREFS_FILE, Context.MODE_PRIVATE)); // } // // }
import android.content.Intent; import android.os.Bundle; import android.view.WindowManager; import com.github.paolorotolo.appintro.AppIntro2; import eu.se_bastiaan.popcorntimeremote.intro.SlideFive; import eu.se_bastiaan.popcorntimeremote.intro.SlideFour; import eu.se_bastiaan.popcorntimeremote.intro.SlideOne; import eu.se_bastiaan.popcorntimeremote.intro.SlideSix; import eu.se_bastiaan.popcorntimeremote.intro.SlideThree; import eu.se_bastiaan.popcorntimeremote.intro.SlideTwo; import eu.se_bastiaan.popcorntimeremote.utils.PrefUtils;
package eu.se_bastiaan.popcorntimeremote.activities; public class IntroActivity extends AppIntro2 { @Override public void init(Bundle savedInstanceState) { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); addSlide(new SlideOne(), getApplicationContext()); addSlide(new SlideTwo(), getApplicationContext()); addSlide(new SlideThree(), getApplicationContext()); addSlide(new SlideFour(), getApplicationContext()); addSlide(new SlideFive(), getApplicationContext()); addSlide(new SlideSix(), getApplicationContext()); } @Override public void onDonePressed() {
// Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideFive.java // public class SlideFive extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_five, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideFour.java // public class SlideFour extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_four, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideOne.java // public class SlideOne extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_one, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideSix.java // public class SlideSix extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_six, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideThree.java // public class SlideThree extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_three, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/intro/SlideTwo.java // public class SlideTwo extends Fragment { // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_introslide_two, container, false); // } // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/utils/PrefUtils.java // public final class PrefUtils { // // private PrefUtils() throws InstantiationException { // throw new InstantiationException("This class is not created for instantiation"); // } // // // Main functions below // // public static void clear(Context context) { // getPrefs(context).edit().clear().apply(); // } // // public static void save(Context context, String key, String value) { // getPrefs(context).edit().putString(key, value).apply(); // } // // public static String get(Context context, String key, String defaultValue) { // return getPrefs(context).getString(key, defaultValue); // } // // public static void save(Context context, String key, Boolean value) { // getPrefs(context).edit().putBoolean(key, value).apply(); // } // // public static Boolean get(Context context, String key, Boolean defaultValue) { // return getPrefs(context).getBoolean(key, defaultValue); // } // // public static Boolean contains(Context context, String key) { // return getPrefs(context).contains(key); // } // // public static ObscuredSharedPreferences getPrefs(Context context) { // return new ObscuredSharedPreferences(context, context.getSharedPreferences(Constants.PREFS_FILE, Context.MODE_PRIVATE)); // } // // } // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/activities/IntroActivity.java import android.content.Intent; import android.os.Bundle; import android.view.WindowManager; import com.github.paolorotolo.appintro.AppIntro2; import eu.se_bastiaan.popcorntimeremote.intro.SlideFive; import eu.se_bastiaan.popcorntimeremote.intro.SlideFour; import eu.se_bastiaan.popcorntimeremote.intro.SlideOne; import eu.se_bastiaan.popcorntimeremote.intro.SlideSix; import eu.se_bastiaan.popcorntimeremote.intro.SlideThree; import eu.se_bastiaan.popcorntimeremote.intro.SlideTwo; import eu.se_bastiaan.popcorntimeremote.utils.PrefUtils; package eu.se_bastiaan.popcorntimeremote.activities; public class IntroActivity extends AppIntro2 { @Override public void init(Bundle savedInstanceState) { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); addSlide(new SlideOne(), getApplicationContext()); addSlide(new SlideTwo(), getApplicationContext()); addSlide(new SlideThree(), getApplicationContext()); addSlide(new SlideFour(), getApplicationContext()); addSlide(new SlideFive(), getApplicationContext()); addSlide(new SlideSix(), getApplicationContext()); } @Override public void onDonePressed() {
PrefUtils.save(this, "intro", true);
se-bastiaan/ButterRemote-Android
app/src/main/java/eu/se_bastiaan/popcorntimeremote/rpc/PopcornTimeRpcClient.java
// Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/utils/LogUtils.java // public final class LogUtils { // // private static final String LOG_UTILS = "LogUtils"; // // private LogUtils() throws InstantiationException { // throw new InstantiationException("This class is not created for instantiation"); // } // // public static void d(Object message) { // d(LOG_UTILS, message); // } // // public static void d(Object tag, Object message) { // if (Constants.LOG_ENABLED) { // Log.d(tag.toString(), message.toString()); // } // } // // public static void v(Object message) { // v(LOG_UTILS, message); // } // // public static void v(Object tag, Object message) { // if (Constants.LOG_ENABLED) { // Log.v(tag.toString(), message.toString()); // } // } // // public static void e(Object message) { // e(LOG_UTILS, message); // } // // public static void e(Object tag, Object message) { // if (Constants.LOG_ENABLED) { // Log.e(tag.toString(), message.toString()); // } // } // // public static void e(Object tag, Object message, Throwable t) { // if (Constants.LOG_ENABLED) { // Log.e(tag.toString(), message.toString(), t); // } // } // // public static void w(Object message) { // w(LOG_UTILS, message); // } // // public static void w(Object tag, Object message) { // if (Constants.LOG_ENABLED) { // Log.w(tag.toString(), message.toString()); // } // } // // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/utils/Version.java // public class Version implements Comparable<Version> { // // private final String version; // // public Version(String version) { // if(version == null) // throw new IllegalArgumentException("Version can not be null"); // if(!version.matches("[0-9]+(\\.[0-9]+)+(\\-[0-9]+)*")) // throw new IllegalArgumentException("Invalid version format"); // this.version = version; // } // // public final String get() { // return this.version; // } // // @Override // public int compareTo(Version that) { // if(that == null) // return 1; // String[] thisParts = this.get().split("\\.|\\-"); // String[] thatParts = that.get().split("\\.|\\-"); // int length = Math.max(thisParts.length, thatParts.length); // for(int i = 0; i < length; i++) { // int thisPart = i < thisParts.length ? // Integer.parseInt(thisParts[i]) : 0; // int thatPart = i < thatParts.length ? // Integer.parseInt(thatParts[i]) : 0; // if(thisPart < thatPart) // return -1; // if(thisPart > thatPart) // return 1; // } // return 0; // } // // @Override // public boolean equals(Object that) { // if(this == that) // return true; // if(that == null) // return false; // if(((Object) this).getClass() != that.getClass()) // return false; // return this.compareTo((Version) that) == 0; // } // // /** // * Test if version1 is higher than version2. // * @param version1 // * @param version2 // * @return {code: true} when version1 is higher than version2. // */ // public static boolean compare(String version1, String version2) { // Version v1 = new Version(version1); // Version v2 = new Version(version2); // if(v1.compareTo(v2) > 0) { // return true; // } // return false; // } // // }
import android.util.Log; import com.google.gson.Gson; import com.google.gson.internal.LinkedTreeMap; import com.squareup.okhttp.Authenticator; import com.squareup.okhttp.Call; import com.squareup.okhttp.Callback; import com.squareup.okhttp.Credentials; import com.squareup.okhttp.MediaType; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.Response; import java.io.IOException; import java.net.Proxy; import java.util.ArrayList; import java.util.Arrays; import eu.se_bastiaan.popcorntimeremote.utils.LogUtils; import eu.se_bastiaan.popcorntimeremote.utils.Version;
return request(request, callback); } public Call down(Callback callback) { RpcRequest request = new RpcRequest("down", RequestId.DOWN); return request(request, callback); } public Call left(Callback callback) { RpcRequest request = new RpcRequest("left", RequestId.LEFT); return request(request, callback); } public Call right(Callback callback) { RpcRequest request = new RpcRequest("right", RequestId.RIGHT); return request(request, callback); } public Call enter(Callback callback) { RpcRequest request = new RpcRequest("enter", RequestId.ENTER); return request(request, callback); } public Call back(Callback callback) { RpcRequest request = new RpcRequest("back", RequestId.BACK); return request(request, callback); } public Call toggleQuality(Callback callback) { RpcRequest request;
// Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/utils/LogUtils.java // public final class LogUtils { // // private static final String LOG_UTILS = "LogUtils"; // // private LogUtils() throws InstantiationException { // throw new InstantiationException("This class is not created for instantiation"); // } // // public static void d(Object message) { // d(LOG_UTILS, message); // } // // public static void d(Object tag, Object message) { // if (Constants.LOG_ENABLED) { // Log.d(tag.toString(), message.toString()); // } // } // // public static void v(Object message) { // v(LOG_UTILS, message); // } // // public static void v(Object tag, Object message) { // if (Constants.LOG_ENABLED) { // Log.v(tag.toString(), message.toString()); // } // } // // public static void e(Object message) { // e(LOG_UTILS, message); // } // // public static void e(Object tag, Object message) { // if (Constants.LOG_ENABLED) { // Log.e(tag.toString(), message.toString()); // } // } // // public static void e(Object tag, Object message, Throwable t) { // if (Constants.LOG_ENABLED) { // Log.e(tag.toString(), message.toString(), t); // } // } // // public static void w(Object message) { // w(LOG_UTILS, message); // } // // public static void w(Object tag, Object message) { // if (Constants.LOG_ENABLED) { // Log.w(tag.toString(), message.toString()); // } // } // // } // // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/utils/Version.java // public class Version implements Comparable<Version> { // // private final String version; // // public Version(String version) { // if(version == null) // throw new IllegalArgumentException("Version can not be null"); // if(!version.matches("[0-9]+(\\.[0-9]+)+(\\-[0-9]+)*")) // throw new IllegalArgumentException("Invalid version format"); // this.version = version; // } // // public final String get() { // return this.version; // } // // @Override // public int compareTo(Version that) { // if(that == null) // return 1; // String[] thisParts = this.get().split("\\.|\\-"); // String[] thatParts = that.get().split("\\.|\\-"); // int length = Math.max(thisParts.length, thatParts.length); // for(int i = 0; i < length; i++) { // int thisPart = i < thisParts.length ? // Integer.parseInt(thisParts[i]) : 0; // int thatPart = i < thatParts.length ? // Integer.parseInt(thatParts[i]) : 0; // if(thisPart < thatPart) // return -1; // if(thisPart > thatPart) // return 1; // } // return 0; // } // // @Override // public boolean equals(Object that) { // if(this == that) // return true; // if(that == null) // return false; // if(((Object) this).getClass() != that.getClass()) // return false; // return this.compareTo((Version) that) == 0; // } // // /** // * Test if version1 is higher than version2. // * @param version1 // * @param version2 // * @return {code: true} when version1 is higher than version2. // */ // public static boolean compare(String version1, String version2) { // Version v1 = new Version(version1); // Version v2 = new Version(version2); // if(v1.compareTo(v2) > 0) { // return true; // } // return false; // } // // } // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/rpc/PopcornTimeRpcClient.java import android.util.Log; import com.google.gson.Gson; import com.google.gson.internal.LinkedTreeMap; import com.squareup.okhttp.Authenticator; import com.squareup.okhttp.Call; import com.squareup.okhttp.Callback; import com.squareup.okhttp.Credentials; import com.squareup.okhttp.MediaType; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.Response; import java.io.IOException; import java.net.Proxy; import java.util.ArrayList; import java.util.Arrays; import eu.se_bastiaan.popcorntimeremote.utils.LogUtils; import eu.se_bastiaan.popcorntimeremote.utils.Version; return request(request, callback); } public Call down(Callback callback) { RpcRequest request = new RpcRequest("down", RequestId.DOWN); return request(request, callback); } public Call left(Callback callback) { RpcRequest request = new RpcRequest("left", RequestId.LEFT); return request(request, callback); } public Call right(Callback callback) { RpcRequest request = new RpcRequest("right", RequestId.RIGHT); return request(request, callback); } public Call enter(Callback callback) { RpcRequest request = new RpcRequest("enter", RequestId.ENTER); return request(request, callback); } public Call back(Callback callback) { RpcRequest request = new RpcRequest("back", RequestId.BACK); return request(request, callback); } public Call toggleQuality(Callback callback) { RpcRequest request;
if(Version.compare(mVersion, ZERO_VERSION)) {
se-bastiaan/ButterRemote-Android
app/src/main/java/eu/se_bastiaan/popcorntimeremote/widget/ImageButton.java
// Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/utils/CheatSheet.java // public final class CheatSheet { // /** // * The estimated height of a toast, in dips (density-independent pixels). This is used to // * determine whether or not the toast should appear above or below the UI element. // */ // private static final int ESTIMATED_TOAST_HEIGHT_DIPS = 48; // // private CheatSheet() throws InstantiationException { // throw new InstantiationException("This class is not created for instantiation"); // } // // /** // * Sets up a cheat sheet (tooltip) for the given view by setting its {@link // * android.view.View.OnLongClickListener}. When the view is long-pressed, a {@link Toast} with // * the view's {@link android.view.View#getContentDescription() content description} will be // * shown either above (default) or below the view (if there isn't room above it). // * // * @param view The view to add a cheat sheet for. // */ // public static void setup(View view) { // view.setOnLongClickListener(new View.OnLongClickListener() { // @Override // public boolean onLongClick(View view) { // return showCheatSheet(view, view.getContentDescription()); // } // }); // } // // /** // * Sets up a cheat sheet (tooltip) for the given view by setting its {@link // * android.view.View.OnLongClickListener}. When the view is long-pressed, a {@link Toast} with // * the given text will be shown either above (default) or below the view (if there isn't room // * above it). // * // * @param view The view to add a cheat sheet for. // * @param textResId The string resource containing the text to show on long-press. // */ // public static void setup(View view, final int textResId) { // view.setOnLongClickListener(new View.OnLongClickListener() { // @Override // public boolean onLongClick(View view) { // return showCheatSheet(view, view.getContext().getString(textResId)); // } // }); // } // // /** // * Sets up a cheat sheet (tooltip) for the given view by setting its {@link // * android.view.View.OnLongClickListener}. When the view is long-pressed, a {@link Toast} with // * the given text will be shown either above (default) or below the view (if there isn't room // * above it). // * // * @param view The view to add a cheat sheet for. // * @param text The text to show on long-press. // */ // public static void setup(View view, final CharSequence text) { // view.setOnLongClickListener(new View.OnLongClickListener() { // @Override // public boolean onLongClick(View view) { // return showCheatSheet(view, text); // } // }); // } // // /** // * Removes the cheat sheet for the given view by removing the view's {@link // * android.view.View.OnLongClickListener}. // * // * @param view The view whose cheat sheet should be removed. // */ // public static void remove(final View view) { // view.setOnLongClickListener(null); // } // // /** // * Internal helper method to show the cheat sheet toast. // */ // private static boolean showCheatSheet(View view, CharSequence text) { // if (TextUtils.isEmpty(text)) { // return false; // } // // final int[] screenPos = new int[2]; // origin is device display // final Rect displayFrame = new Rect(); // includes decorations (e.g. status bar) // view.getLocationOnScreen(screenPos); // view.getWindowVisibleDisplayFrame(displayFrame); // // final Context context = view.getContext(); // final int viewWidth = view.getWidth(); // final int viewHeight = view.getHeight(); // final int viewCenterX = screenPos[0] + viewWidth / 2; // final int screenWidth = context.getResources().getDisplayMetrics().widthPixels; // final int estimatedToastHeight = (int) (ESTIMATED_TOAST_HEIGHT_DIPS // * context.getResources().getDisplayMetrics().density); // // Toast cheatSheet = Toast.makeText(context, text, Toast.LENGTH_SHORT); // boolean showBelow = screenPos[1] < estimatedToastHeight; // if (showBelow) { // // Show below // // Offsets are after decorations (e.g. status bar) are factored in // cheatSheet.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, // viewCenterX - screenWidth / 2, // screenPos[1] - displayFrame.top + viewHeight); // } else { // // Show above // // Offsets are after decorations (e.g. status bar) are factored in // // NOTE: We can't use Gravity.BOTTOM because when the keyboard is up // // its height isn't factored in. // cheatSheet.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, // viewCenterX - screenWidth / 2, // screenPos[1] - displayFrame.top - estimatedToastHeight); // } // // cheatSheet.show(); // return true; // } // }
import android.content.Context; import android.util.AttributeSet; import android.view.View; import eu.se_bastiaan.popcorntimeremote.utils.CheatSheet;
package eu.se_bastiaan.popcorntimeremote.widget; /** * Created by Sebastiaan on 21-09-14. */ public class ImageButton extends android.widget.ImageButton { public ImageButton(Context context) { super(context); } public ImageButton(Context context, AttributeSet attrs) { super(context, attrs); } public ImageButton(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void setContentDescription(CharSequence contentDesc) { super.setContentDescription(contentDesc); if(contentDesc.length() > 0)
// Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/utils/CheatSheet.java // public final class CheatSheet { // /** // * The estimated height of a toast, in dips (density-independent pixels). This is used to // * determine whether or not the toast should appear above or below the UI element. // */ // private static final int ESTIMATED_TOAST_HEIGHT_DIPS = 48; // // private CheatSheet() throws InstantiationException { // throw new InstantiationException("This class is not created for instantiation"); // } // // /** // * Sets up a cheat sheet (tooltip) for the given view by setting its {@link // * android.view.View.OnLongClickListener}. When the view is long-pressed, a {@link Toast} with // * the view's {@link android.view.View#getContentDescription() content description} will be // * shown either above (default) or below the view (if there isn't room above it). // * // * @param view The view to add a cheat sheet for. // */ // public static void setup(View view) { // view.setOnLongClickListener(new View.OnLongClickListener() { // @Override // public boolean onLongClick(View view) { // return showCheatSheet(view, view.getContentDescription()); // } // }); // } // // /** // * Sets up a cheat sheet (tooltip) for the given view by setting its {@link // * android.view.View.OnLongClickListener}. When the view is long-pressed, a {@link Toast} with // * the given text will be shown either above (default) or below the view (if there isn't room // * above it). // * // * @param view The view to add a cheat sheet for. // * @param textResId The string resource containing the text to show on long-press. // */ // public static void setup(View view, final int textResId) { // view.setOnLongClickListener(new View.OnLongClickListener() { // @Override // public boolean onLongClick(View view) { // return showCheatSheet(view, view.getContext().getString(textResId)); // } // }); // } // // /** // * Sets up a cheat sheet (tooltip) for the given view by setting its {@link // * android.view.View.OnLongClickListener}. When the view is long-pressed, a {@link Toast} with // * the given text will be shown either above (default) or below the view (if there isn't room // * above it). // * // * @param view The view to add a cheat sheet for. // * @param text The text to show on long-press. // */ // public static void setup(View view, final CharSequence text) { // view.setOnLongClickListener(new View.OnLongClickListener() { // @Override // public boolean onLongClick(View view) { // return showCheatSheet(view, text); // } // }); // } // // /** // * Removes the cheat sheet for the given view by removing the view's {@link // * android.view.View.OnLongClickListener}. // * // * @param view The view whose cheat sheet should be removed. // */ // public static void remove(final View view) { // view.setOnLongClickListener(null); // } // // /** // * Internal helper method to show the cheat sheet toast. // */ // private static boolean showCheatSheet(View view, CharSequence text) { // if (TextUtils.isEmpty(text)) { // return false; // } // // final int[] screenPos = new int[2]; // origin is device display // final Rect displayFrame = new Rect(); // includes decorations (e.g. status bar) // view.getLocationOnScreen(screenPos); // view.getWindowVisibleDisplayFrame(displayFrame); // // final Context context = view.getContext(); // final int viewWidth = view.getWidth(); // final int viewHeight = view.getHeight(); // final int viewCenterX = screenPos[0] + viewWidth / 2; // final int screenWidth = context.getResources().getDisplayMetrics().widthPixels; // final int estimatedToastHeight = (int) (ESTIMATED_TOAST_HEIGHT_DIPS // * context.getResources().getDisplayMetrics().density); // // Toast cheatSheet = Toast.makeText(context, text, Toast.LENGTH_SHORT); // boolean showBelow = screenPos[1] < estimatedToastHeight; // if (showBelow) { // // Show below // // Offsets are after decorations (e.g. status bar) are factored in // cheatSheet.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, // viewCenterX - screenWidth / 2, // screenPos[1] - displayFrame.top + viewHeight); // } else { // // Show above // // Offsets are after decorations (e.g. status bar) are factored in // // NOTE: We can't use Gravity.BOTTOM because when the keyboard is up // // its height isn't factored in. // cheatSheet.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, // viewCenterX - screenWidth / 2, // screenPos[1] - displayFrame.top - estimatedToastHeight); // } // // cheatSheet.show(); // return true; // } // } // Path: app/src/main/java/eu/se_bastiaan/popcorntimeremote/widget/ImageButton.java import android.content.Context; import android.util.AttributeSet; import android.view.View; import eu.se_bastiaan.popcorntimeremote.utils.CheatSheet; package eu.se_bastiaan.popcorntimeremote.widget; /** * Created by Sebastiaan on 21-09-14. */ public class ImageButton extends android.widget.ImageButton { public ImageButton(Context context) { super(context); } public ImageButton(Context context, AttributeSet attrs) { super(context, attrs); } public ImageButton(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void setContentDescription(CharSequence contentDesc) { super.setContentDescription(contentDesc); if(contentDesc.length() > 0)
CheatSheet.setup(this, contentDesc);
bcw104/scada-oildata
src/main/java/com/ht/scada/oildata/service/WellInfoService.java
// Path: src/main/java/com/ht/scada/oildata/model/WellInfoWrapper.java // public class WellInfoWrapper { // private String beng_jing; // private String han_shui; // private String yymd; // // public String getBeng_jing() { // return beng_jing; // } // // public void setBeng_jing(String beng_jing) { // this.beng_jing = beng_jing; // } // // public String getHan_shui() { // return han_shui; // } // // public void setHan_shui(String han_shui) { // this.han_shui = han_shui; // } // // public String getYymd() { // return yymd; // } // // public void setYymd(String yymd) { // this.yymd = yymd; // } // }
import com.ht.scada.oildata.model.WellInfoWrapper; import java.util.Date; import java.util.List; import java.util.Map; import org.sql2o.Sql2o;
package com.ht.scada.oildata.service; /** * 功图Service * * @author 赵磊 */ public interface WellInfoService { Sql2o getSql2o(); void setSql2o(Sql2o sql2o);
// Path: src/main/java/com/ht/scada/oildata/model/WellInfoWrapper.java // public class WellInfoWrapper { // private String beng_jing; // private String han_shui; // private String yymd; // // public String getBeng_jing() { // return beng_jing; // } // // public void setBeng_jing(String beng_jing) { // this.beng_jing = beng_jing; // } // // public String getHan_shui() { // return han_shui; // } // // public void setHan_shui(String han_shui) { // this.han_shui = han_shui; // } // // public String getYymd() { // return yymd; // } // // public void setYymd(String yymd) { // this.yymd = yymd; // } // } // Path: src/main/java/com/ht/scada/oildata/service/WellInfoService.java import com.ht.scada.oildata.model.WellInfoWrapper; import java.util.Date; import java.util.List; import java.util.Map; import org.sql2o.Sql2o; package com.ht.scada.oildata.service; /** * 功图Service * * @author 赵磊 */ public interface WellInfoService { Sql2o getSql2o(); void setSql2o(Sql2o sql2o);
WellInfoWrapper findWellInfoByCode(String code);
bcw104/scada-oildata
src/main/java/com/ht/scada/oildata/service/impl/WellInfoServiceImpl.java
// Path: src/main/java/com/ht/scada/oildata/model/WellInfoWrapper.java // public class WellInfoWrapper { // private String beng_jing; // private String han_shui; // private String yymd; // // public String getBeng_jing() { // return beng_jing; // } // // public void setBeng_jing(String beng_jing) { // this.beng_jing = beng_jing; // } // // public String getHan_shui() { // return han_shui; // } // // public void setHan_shui(String han_shui) { // this.han_shui = han_shui; // } // // public String getYymd() { // return yymd; // } // // public void setYymd(String yymd) { // this.yymd = yymd; // } // } // // Path: src/main/java/com/ht/scada/oildata/service/WellInfoService.java // public interface WellInfoService { // // Sql2o getSql2o(); // // void setSql2o(Sql2o sql2o); // // WellInfoWrapper findWellInfoByCode(String code); // // /** // * 获得系统内所有井的井号(游梁式和高原机器) // * // * @return // */ // List<Map<String, Object>> findAllEndtagsCode(); // // /** // * 根据井号, 获得某口井的基础量油信息 目前包括: 泵径, 含水率, 原油密度, 水密度 // * // * @param 井号 // * @return [rq, hs, 1, bj, dmyymd] // */ // Map<String, Object> findBasicCalculateInforsByCode(String code); // // /** // * 插入一条self量油信息 // * // * @param id // * @param code // * @param bengJing // * @param hanShui // * @param SMD // * @param YYMD // * @param lrqi // */ // void addOneTWellInforRecord(String id, String code, float bengJing, // float hanShui, float SMD, float YYMD, Date lrqi); // }
import com.ht.scada.oildata.model.WellInfoWrapper; import com.ht.scada.oildata.service.WellInfoService; import java.util.Date; import java.util.List; import java.util.Map; import javax.inject.Inject; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.sql2o.Connection; import org.sql2o.Sql2o;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.ht.scada.oildata.service.impl; /** * * @author 赵磊 2014-8-3 15:03:50 */ @Transactional @Service("wellInfoService")
// Path: src/main/java/com/ht/scada/oildata/model/WellInfoWrapper.java // public class WellInfoWrapper { // private String beng_jing; // private String han_shui; // private String yymd; // // public String getBeng_jing() { // return beng_jing; // } // // public void setBeng_jing(String beng_jing) { // this.beng_jing = beng_jing; // } // // public String getHan_shui() { // return han_shui; // } // // public void setHan_shui(String han_shui) { // this.han_shui = han_shui; // } // // public String getYymd() { // return yymd; // } // // public void setYymd(String yymd) { // this.yymd = yymd; // } // } // // Path: src/main/java/com/ht/scada/oildata/service/WellInfoService.java // public interface WellInfoService { // // Sql2o getSql2o(); // // void setSql2o(Sql2o sql2o); // // WellInfoWrapper findWellInfoByCode(String code); // // /** // * 获得系统内所有井的井号(游梁式和高原机器) // * // * @return // */ // List<Map<String, Object>> findAllEndtagsCode(); // // /** // * 根据井号, 获得某口井的基础量油信息 目前包括: 泵径, 含水率, 原油密度, 水密度 // * // * @param 井号 // * @return [rq, hs, 1, bj, dmyymd] // */ // Map<String, Object> findBasicCalculateInforsByCode(String code); // // /** // * 插入一条self量油信息 // * // * @param id // * @param code // * @param bengJing // * @param hanShui // * @param SMD // * @param YYMD // * @param lrqi // */ // void addOneTWellInforRecord(String id, String code, float bengJing, // float hanShui, float SMD, float YYMD, Date lrqi); // } // Path: src/main/java/com/ht/scada/oildata/service/impl/WellInfoServiceImpl.java import com.ht.scada.oildata.model.WellInfoWrapper; import com.ht.scada.oildata.service.WellInfoService; import java.util.Date; import java.util.List; import java.util.Map; import javax.inject.Inject; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.sql2o.Connection; import org.sql2o.Sql2o; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.ht.scada.oildata.service.impl; /** * * @author 赵磊 2014-8-3 15:03:50 */ @Transactional @Service("wellInfoService")
public class WellInfoServiceImpl implements WellInfoService {
bcw104/scada-oildata
src/main/java/com/ht/scada/oildata/service/impl/WellInfoServiceImpl.java
// Path: src/main/java/com/ht/scada/oildata/model/WellInfoWrapper.java // public class WellInfoWrapper { // private String beng_jing; // private String han_shui; // private String yymd; // // public String getBeng_jing() { // return beng_jing; // } // // public void setBeng_jing(String beng_jing) { // this.beng_jing = beng_jing; // } // // public String getHan_shui() { // return han_shui; // } // // public void setHan_shui(String han_shui) { // this.han_shui = han_shui; // } // // public String getYymd() { // return yymd; // } // // public void setYymd(String yymd) { // this.yymd = yymd; // } // } // // Path: src/main/java/com/ht/scada/oildata/service/WellInfoService.java // public interface WellInfoService { // // Sql2o getSql2o(); // // void setSql2o(Sql2o sql2o); // // WellInfoWrapper findWellInfoByCode(String code); // // /** // * 获得系统内所有井的井号(游梁式和高原机器) // * // * @return // */ // List<Map<String, Object>> findAllEndtagsCode(); // // /** // * 根据井号, 获得某口井的基础量油信息 目前包括: 泵径, 含水率, 原油密度, 水密度 // * // * @param 井号 // * @return [rq, hs, 1, bj, dmyymd] // */ // Map<String, Object> findBasicCalculateInforsByCode(String code); // // /** // * 插入一条self量油信息 // * // * @param id // * @param code // * @param bengJing // * @param hanShui // * @param SMD // * @param YYMD // * @param lrqi // */ // void addOneTWellInforRecord(String id, String code, float bengJing, // float hanShui, float SMD, float YYMD, Date lrqi); // }
import com.ht.scada.oildata.model.WellInfoWrapper; import com.ht.scada.oildata.service.WellInfoService; import java.util.Date; import java.util.List; import java.util.Map; import javax.inject.Inject; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.sql2o.Connection; import org.sql2o.Sql2o;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.ht.scada.oildata.service.impl; /** * * @author 赵磊 2014-8-3 15:03:50 */ @Transactional @Service("wellInfoService") public class WellInfoServiceImpl implements WellInfoService { @Inject protected Sql2o sql2o; @Override public Sql2o getSql2o() { return sql2o; } @Override public void setSql2o(Sql2o sql2o) { this.sql2o = sql2o; } @Override
// Path: src/main/java/com/ht/scada/oildata/model/WellInfoWrapper.java // public class WellInfoWrapper { // private String beng_jing; // private String han_shui; // private String yymd; // // public String getBeng_jing() { // return beng_jing; // } // // public void setBeng_jing(String beng_jing) { // this.beng_jing = beng_jing; // } // // public String getHan_shui() { // return han_shui; // } // // public void setHan_shui(String han_shui) { // this.han_shui = han_shui; // } // // public String getYymd() { // return yymd; // } // // public void setYymd(String yymd) { // this.yymd = yymd; // } // } // // Path: src/main/java/com/ht/scada/oildata/service/WellInfoService.java // public interface WellInfoService { // // Sql2o getSql2o(); // // void setSql2o(Sql2o sql2o); // // WellInfoWrapper findWellInfoByCode(String code); // // /** // * 获得系统内所有井的井号(游梁式和高原机器) // * // * @return // */ // List<Map<String, Object>> findAllEndtagsCode(); // // /** // * 根据井号, 获得某口井的基础量油信息 目前包括: 泵径, 含水率, 原油密度, 水密度 // * // * @param 井号 // * @return [rq, hs, 1, bj, dmyymd] // */ // Map<String, Object> findBasicCalculateInforsByCode(String code); // // /** // * 插入一条self量油信息 // * // * @param id // * @param code // * @param bengJing // * @param hanShui // * @param SMD // * @param YYMD // * @param lrqi // */ // void addOneTWellInforRecord(String id, String code, float bengJing, // float hanShui, float SMD, float YYMD, Date lrqi); // } // Path: src/main/java/com/ht/scada/oildata/service/impl/WellInfoServiceImpl.java import com.ht.scada.oildata.model.WellInfoWrapper; import com.ht.scada.oildata.service.WellInfoService; import java.util.Date; import java.util.List; import java.util.Map; import javax.inject.Inject; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.sql2o.Connection; import org.sql2o.Sql2o; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.ht.scada.oildata.service.impl; /** * * @author 赵磊 2014-8-3 15:03:50 */ @Transactional @Service("wellInfoService") public class WellInfoServiceImpl implements WellInfoService { @Inject protected Sql2o sql2o; @Override public Sql2o getSql2o() { return sql2o; } @Override public void setSql2o(Sql2o sql2o) { this.sql2o = sql2o; } @Override
public WellInfoWrapper findWellInfoByCode(String code) {
bcw104/scada-oildata
src/main/java/com/ht/scada/oildata/OilDataMessageDelegate.java
// Path: src/main/java/com/ht/scada/oildata/entity/FaultDiagnoseRecord.java // public class FaultDiagnoseRecord { // // private String id; // 唯一主键 // private String code;// 计量点编号(回路号、井号等) // private String name;// 故障类型 // private String info;// 故障信息 // private Integer level; // 故障程度 // @Column(name = "action_time") // private Date actionTime; // @Column(name = "resume_time") // private Date resumeTime; // // private User user; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getCode() { // return code; // } // // public void setCode(String code) { // this.code = code; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getInfo() { // return info; // } // // public void setInfo(String info) { // this.info = info; // } // // public Integer getLevel() { // return level; // } // // public void setLevel(Integer level) { // this.level = level; // } // // public Date getActionTime() { // return actionTime; // } // // public void setActionTime(Date actionTime) { // this.actionTime = actionTime; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // // // public Date getResumeTime() { // return resumeTime; // } // // public void setResumeTime(Date resumeTime) { // this.resumeTime = resumeTime; // } // // /** // * 生成报警记录用 // * @return // */ // public String getReMark() { // return "故障类型为:" + name + (level==null?"":(";故障程度为:" + String.valueOf(level))); // } // // }
import com.alibaba.fastjson.JSON; import com.ht.scada.oildata.entity.FaultDiagnoseRecord; import java.io.IOException;
package com.ht.scada.oildata; /** * 实时数据推送代理, 用于触发故障报警、遥信变位、遥测越限,使用时请注册监听器 * * @author: "薄成文" 13-5-21 下午1:51 * To change this template use File | Settings | File Templates. */ public class OilDataMessageDelegate { private OilDataMessageListener listener; public void setListener(OilDataMessageListener listener) { this.listener = listener; } /** * 收到故障报警信息<br/> * 故障记录中的id为字符串类型,客户端收到报警信息时该记录的ID已自动生成,但不保证立即写入数据库。 * @param message */ public void handleMessage(String message) throws IOException { System.out.println("收到故障报警"); System.out.println(message); if (listener != null) {
// Path: src/main/java/com/ht/scada/oildata/entity/FaultDiagnoseRecord.java // public class FaultDiagnoseRecord { // // private String id; // 唯一主键 // private String code;// 计量点编号(回路号、井号等) // private String name;// 故障类型 // private String info;// 故障信息 // private Integer level; // 故障程度 // @Column(name = "action_time") // private Date actionTime; // @Column(name = "resume_time") // private Date resumeTime; // // private User user; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getCode() { // return code; // } // // public void setCode(String code) { // this.code = code; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getInfo() { // return info; // } // // public void setInfo(String info) { // this.info = info; // } // // public Integer getLevel() { // return level; // } // // public void setLevel(Integer level) { // this.level = level; // } // // public Date getActionTime() { // return actionTime; // } // // public void setActionTime(Date actionTime) { // this.actionTime = actionTime; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // // // public Date getResumeTime() { // return resumeTime; // } // // public void setResumeTime(Date resumeTime) { // this.resumeTime = resumeTime; // } // // /** // * 生成报警记录用 // * @return // */ // public String getReMark() { // return "故障类型为:" + name + (level==null?"":(";故障程度为:" + String.valueOf(level))); // } // // } // Path: src/main/java/com/ht/scada/oildata/OilDataMessageDelegate.java import com.alibaba.fastjson.JSON; import com.ht.scada.oildata.entity.FaultDiagnoseRecord; import java.io.IOException; package com.ht.scada.oildata; /** * 实时数据推送代理, 用于触发故障报警、遥信变位、遥测越限,使用时请注册监听器 * * @author: "薄成文" 13-5-21 下午1:51 * To change this template use File | Settings | File Templates. */ public class OilDataMessageDelegate { private OilDataMessageListener listener; public void setListener(OilDataMessageListener listener) { this.listener = listener; } /** * 收到故障报警信息<br/> * 故障记录中的id为字符串类型,客户端收到报警信息时该记录的ID已自动生成,但不保证立即写入数据库。 * @param message */ public void handleMessage(String message) throws IOException { System.out.println("收到故障报警"); System.out.println(message); if (listener != null) {
FaultDiagnoseRecord record = JSON.parseObject(message, FaultDiagnoseRecord.class);
TomasOchoa/Absolute-Java-5th-Edition-Solutions
Chapter9/PP1/Main.java
// Path: Chapter9/PP1/NegativeNumberException.java // public class NegativeNumberException extends Exception // { // // Default Constructor // public NegativeNumberException() // { // super("N must be positive."); // } // // 1 arg Constructor (string) // public NegativeNumberException(String message) // { // super(message); // } // }
import tomas.ochoa.NegativeNumberException; import java.util.Scanner;
package tomas.ochoa; /** * Created by Tom's Desktop on 3/24/2016. * * Program: * - Calculates the average of N integers * * -Prompt user for input: * - Prompt user: * - try * - get integer * - throw exception * - catch(negative exception) * - if negative * - show error * - get input * - keep trying until not negative * - calculate average * - show */ public class Main { public static void main(String[] args) { // Int for N int n = 0; // Scanner for keyboard Scanner keyboard = new Scanner(System.in); // First try block to check if N is positive try { System.out.print("Enter N: "); n = keyboard.nextInt(); if(n < 0)
// Path: Chapter9/PP1/NegativeNumberException.java // public class NegativeNumberException extends Exception // { // // Default Constructor // public NegativeNumberException() // { // super("N must be positive."); // } // // 1 arg Constructor (string) // public NegativeNumberException(String message) // { // super(message); // } // } // Path: Chapter9/PP1/Main.java import tomas.ochoa.NegativeNumberException; import java.util.Scanner; package tomas.ochoa; /** * Created by Tom's Desktop on 3/24/2016. * * Program: * - Calculates the average of N integers * * -Prompt user for input: * - Prompt user: * - try * - get integer * - throw exception * - catch(negative exception) * - if negative * - show error * - get input * - keep trying until not negative * - calculate average * - show */ public class Main { public static void main(String[] args) { // Int for N int n = 0; // Scanner for keyboard Scanner keyboard = new Scanner(System.in); // First try block to check if N is positive try { System.out.print("Enter N: "); n = keyboard.nextInt(); if(n < 0)
throw new NegativeNumberException();
meridor/stecker
stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/DefaultManifestReader.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginMetadata.java // public interface PluginMetadata { // // /** // * Returns unique plugin name // * // * @return free-form string with name // */ // String getName(); // // /** // * Returns plugin version // * // * @return free-form string with version // */ // String getVersion(); // // /** // * Returns {@link Path} object corresponding to plugin file // * // * @return plugin {@link Path} object // */ // Path getPath(); // // /** // * Returns {@link org.meridor.stecker.interfaces.Dependency} object corresponding to this plugin // * // * @return dependency object // */ // Dependency getDependency(); // // /** // * Returns date when plugin was released // * // * @return local date or empty if not set // */ // Optional<ZonedDateTime> getDate(); // // /** // * Returns detailed plugin description // * // * @return description or empty if not set // */ // Optional<String> getDescription(); // // /** // * Returns maintainer email and name // * // * @return email and name in the format: <b>John Smith &lt;[email protected]&gt;</b> or empty if not set // */ // Optional<String> getMaintainer(); // // /** // * Returns a list of plugins required to make this plugin work // * // * @return possibly empty list with dependencies // */ // List<Dependency> getRequiredDependencies(); // // /** // * Returns a list of plugins that should be never installed simultaneously with this plugin // * // * @return possibly empty list with conflicting dependencies // */ // List<Dependency> getConflictingDependencies(); // // /** // * Returns a meta dependency which is provided by this plugin // * // * @return meta dependency or empty if not set // */ // Optional<Dependency> getProvidedDependency(); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/Dependency.java // public interface Dependency { // // /** // * Returns dependency name // * // * @return dependency name // */ // String getName(); // // /** // * Returns dependency version if present // * // * @return dependency version if present and empty otherwise // */ // Optional<String> getVersion(); // // /** // * Forces to override {@link Object#equals(Object)} // * // * @param anotherDependency dependency to compare to // * @return true if equal and false otherwise // */ // boolean equals(Object anotherDependency); // // /** // * Forces to override {@link Object#hashCode()} // * // * @return instance hash code // */ // int hashCode(); // // /** // * Returns dependency string representation // * // * @return dependency string representation // */ // String toString(); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ManifestReader.java // public interface ManifestReader { // // /** // * Reads jar file manifest and returns plugin information stored there // * // * @param pluginFile plugin file to process // * @return plugin information in {@link org.meridor.stecker.PluginMetadata} format // * @throws org.meridor.stecker.PluginException when something goes wrong during manifest reading // */ // PluginMetadata read(Path pluginFile) throws PluginException; // // }
import org.meridor.stecker.PluginException; import org.meridor.stecker.PluginMetadata; import org.meridor.stecker.interfaces.Dependency; import org.meridor.stecker.interfaces.ManifestReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.jar.JarInputStream; import java.util.jar.Manifest;
package org.meridor.stecker.impl; public class DefaultManifestReader implements ManifestReader { public static final String DEPENDENCY_DELIMITER = ";"; public static final String VERSION_DELIMITER = "="; public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ISO_OFFSET_DATE_TIME; @Override
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginMetadata.java // public interface PluginMetadata { // // /** // * Returns unique plugin name // * // * @return free-form string with name // */ // String getName(); // // /** // * Returns plugin version // * // * @return free-form string with version // */ // String getVersion(); // // /** // * Returns {@link Path} object corresponding to plugin file // * // * @return plugin {@link Path} object // */ // Path getPath(); // // /** // * Returns {@link org.meridor.stecker.interfaces.Dependency} object corresponding to this plugin // * // * @return dependency object // */ // Dependency getDependency(); // // /** // * Returns date when plugin was released // * // * @return local date or empty if not set // */ // Optional<ZonedDateTime> getDate(); // // /** // * Returns detailed plugin description // * // * @return description or empty if not set // */ // Optional<String> getDescription(); // // /** // * Returns maintainer email and name // * // * @return email and name in the format: <b>John Smith &lt;[email protected]&gt;</b> or empty if not set // */ // Optional<String> getMaintainer(); // // /** // * Returns a list of plugins required to make this plugin work // * // * @return possibly empty list with dependencies // */ // List<Dependency> getRequiredDependencies(); // // /** // * Returns a list of plugins that should be never installed simultaneously with this plugin // * // * @return possibly empty list with conflicting dependencies // */ // List<Dependency> getConflictingDependencies(); // // /** // * Returns a meta dependency which is provided by this plugin // * // * @return meta dependency or empty if not set // */ // Optional<Dependency> getProvidedDependency(); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/Dependency.java // public interface Dependency { // // /** // * Returns dependency name // * // * @return dependency name // */ // String getName(); // // /** // * Returns dependency version if present // * // * @return dependency version if present and empty otherwise // */ // Optional<String> getVersion(); // // /** // * Forces to override {@link Object#equals(Object)} // * // * @param anotherDependency dependency to compare to // * @return true if equal and false otherwise // */ // boolean equals(Object anotherDependency); // // /** // * Forces to override {@link Object#hashCode()} // * // * @return instance hash code // */ // int hashCode(); // // /** // * Returns dependency string representation // * // * @return dependency string representation // */ // String toString(); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ManifestReader.java // public interface ManifestReader { // // /** // * Reads jar file manifest and returns plugin information stored there // * // * @param pluginFile plugin file to process // * @return plugin information in {@link org.meridor.stecker.PluginMetadata} format // * @throws org.meridor.stecker.PluginException when something goes wrong during manifest reading // */ // PluginMetadata read(Path pluginFile) throws PluginException; // // } // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/DefaultManifestReader.java import org.meridor.stecker.PluginException; import org.meridor.stecker.PluginMetadata; import org.meridor.stecker.interfaces.Dependency; import org.meridor.stecker.interfaces.ManifestReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.jar.JarInputStream; import java.util.jar.Manifest; package org.meridor.stecker.impl; public class DefaultManifestReader implements ManifestReader { public static final String DEPENDENCY_DELIMITER = ";"; public static final String VERSION_DELIMITER = "="; public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ISO_OFFSET_DATE_TIME; @Override
public PluginMetadata read(Path pluginFile) throws PluginException {
meridor/stecker
stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/DefaultManifestReader.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginMetadata.java // public interface PluginMetadata { // // /** // * Returns unique plugin name // * // * @return free-form string with name // */ // String getName(); // // /** // * Returns plugin version // * // * @return free-form string with version // */ // String getVersion(); // // /** // * Returns {@link Path} object corresponding to plugin file // * // * @return plugin {@link Path} object // */ // Path getPath(); // // /** // * Returns {@link org.meridor.stecker.interfaces.Dependency} object corresponding to this plugin // * // * @return dependency object // */ // Dependency getDependency(); // // /** // * Returns date when plugin was released // * // * @return local date or empty if not set // */ // Optional<ZonedDateTime> getDate(); // // /** // * Returns detailed plugin description // * // * @return description or empty if not set // */ // Optional<String> getDescription(); // // /** // * Returns maintainer email and name // * // * @return email and name in the format: <b>John Smith &lt;[email protected]&gt;</b> or empty if not set // */ // Optional<String> getMaintainer(); // // /** // * Returns a list of plugins required to make this plugin work // * // * @return possibly empty list with dependencies // */ // List<Dependency> getRequiredDependencies(); // // /** // * Returns a list of plugins that should be never installed simultaneously with this plugin // * // * @return possibly empty list with conflicting dependencies // */ // List<Dependency> getConflictingDependencies(); // // /** // * Returns a meta dependency which is provided by this plugin // * // * @return meta dependency or empty if not set // */ // Optional<Dependency> getProvidedDependency(); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/Dependency.java // public interface Dependency { // // /** // * Returns dependency name // * // * @return dependency name // */ // String getName(); // // /** // * Returns dependency version if present // * // * @return dependency version if present and empty otherwise // */ // Optional<String> getVersion(); // // /** // * Forces to override {@link Object#equals(Object)} // * // * @param anotherDependency dependency to compare to // * @return true if equal and false otherwise // */ // boolean equals(Object anotherDependency); // // /** // * Forces to override {@link Object#hashCode()} // * // * @return instance hash code // */ // int hashCode(); // // /** // * Returns dependency string representation // * // * @return dependency string representation // */ // String toString(); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ManifestReader.java // public interface ManifestReader { // // /** // * Reads jar file manifest and returns plugin information stored there // * // * @param pluginFile plugin file to process // * @return plugin information in {@link org.meridor.stecker.PluginMetadata} format // * @throws org.meridor.stecker.PluginException when something goes wrong during manifest reading // */ // PluginMetadata read(Path pluginFile) throws PluginException; // // }
import org.meridor.stecker.PluginException; import org.meridor.stecker.PluginMetadata; import org.meridor.stecker.interfaces.Dependency; import org.meridor.stecker.interfaces.ManifestReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.jar.JarInputStream; import java.util.jar.Manifest;
package org.meridor.stecker.impl; public class DefaultManifestReader implements ManifestReader { public static final String DEPENDENCY_DELIMITER = ";"; public static final String VERSION_DELIMITER = "="; public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ISO_OFFSET_DATE_TIME; @Override
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginMetadata.java // public interface PluginMetadata { // // /** // * Returns unique plugin name // * // * @return free-form string with name // */ // String getName(); // // /** // * Returns plugin version // * // * @return free-form string with version // */ // String getVersion(); // // /** // * Returns {@link Path} object corresponding to plugin file // * // * @return plugin {@link Path} object // */ // Path getPath(); // // /** // * Returns {@link org.meridor.stecker.interfaces.Dependency} object corresponding to this plugin // * // * @return dependency object // */ // Dependency getDependency(); // // /** // * Returns date when plugin was released // * // * @return local date or empty if not set // */ // Optional<ZonedDateTime> getDate(); // // /** // * Returns detailed plugin description // * // * @return description or empty if not set // */ // Optional<String> getDescription(); // // /** // * Returns maintainer email and name // * // * @return email and name in the format: <b>John Smith &lt;[email protected]&gt;</b> or empty if not set // */ // Optional<String> getMaintainer(); // // /** // * Returns a list of plugins required to make this plugin work // * // * @return possibly empty list with dependencies // */ // List<Dependency> getRequiredDependencies(); // // /** // * Returns a list of plugins that should be never installed simultaneously with this plugin // * // * @return possibly empty list with conflicting dependencies // */ // List<Dependency> getConflictingDependencies(); // // /** // * Returns a meta dependency which is provided by this plugin // * // * @return meta dependency or empty if not set // */ // Optional<Dependency> getProvidedDependency(); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/Dependency.java // public interface Dependency { // // /** // * Returns dependency name // * // * @return dependency name // */ // String getName(); // // /** // * Returns dependency version if present // * // * @return dependency version if present and empty otherwise // */ // Optional<String> getVersion(); // // /** // * Forces to override {@link Object#equals(Object)} // * // * @param anotherDependency dependency to compare to // * @return true if equal and false otherwise // */ // boolean equals(Object anotherDependency); // // /** // * Forces to override {@link Object#hashCode()} // * // * @return instance hash code // */ // int hashCode(); // // /** // * Returns dependency string representation // * // * @return dependency string representation // */ // String toString(); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ManifestReader.java // public interface ManifestReader { // // /** // * Reads jar file manifest and returns plugin information stored there // * // * @param pluginFile plugin file to process // * @return plugin information in {@link org.meridor.stecker.PluginMetadata} format // * @throws org.meridor.stecker.PluginException when something goes wrong during manifest reading // */ // PluginMetadata read(Path pluginFile) throws PluginException; // // } // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/DefaultManifestReader.java import org.meridor.stecker.PluginException; import org.meridor.stecker.PluginMetadata; import org.meridor.stecker.interfaces.Dependency; import org.meridor.stecker.interfaces.ManifestReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.jar.JarInputStream; import java.util.jar.Manifest; package org.meridor.stecker.impl; public class DefaultManifestReader implements ManifestReader { public static final String DEPENDENCY_DELIMITER = ";"; public static final String VERSION_DELIMITER = "="; public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ISO_OFFSET_DATE_TIME; @Override
public PluginMetadata read(Path pluginFile) throws PluginException {
meridor/stecker
stecker-plugin-generator/src/test/java/org/meridor/stecker/generator/CreateMojoTest.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/FileSystemHelper.java // public class FileSystemHelper { // // public static Path createTempDirectory() throws IOException { // return Files.createTempDirectory("test"); // } // // public static void removeDirectory(Path directory) throws IOException { // Files.walkFileTree(directory, new SimpleFileVisitor<Path>() { // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException { // Files.delete(file); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException { // Files.delete(dir); // return FileVisitResult.CONTINUE; // } // }); // } // // }
import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DefaultArtifact; import org.apache.maven.artifact.handler.DefaultArtifactHandler; import org.apache.maven.plugin.testing.MojoRule; import org.apache.maven.project.MavenProject; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.meridor.stecker.impl.FileSystemHelper; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Optional; import static com.marvinformatics.kiss.matchers.path.PathMatchers.exists; import static com.marvinformatics.kiss.matchers.path.PathMatchers.isDirectory; import static com.marvinformatics.kiss.matchers.path.PathMatchers.isRegularFile; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat;
Path generatedDataDir = targetDir.resolve("plugin-generator"); assertThat(generatedDataDir, exists()); assertThat(generatedDataDir, isDirectory()); Path pluginFile = generatedDataDir.resolve("plugin-test-1.0.jar"); assertThat(pluginFile, exists()); assertThat(pluginFile, isRegularFile()); Path pluginDataDir = generatedDataDir.resolve("data"); assertThat(pluginDataDir, exists()); assertThat(pluginDataDir, isDirectory()); Path libDir = pluginDataDir.resolve("lib"); assertThat(libDir, exists()); assertThat(libDir, isDirectory()); Path dependencyFile = libDir.resolve(ARTIFACT_FILE); assertThat(dependencyFile, exists()); assertThat(dependencyFile, isRegularFile()); } private Optional<Path> getResource(String resourceName) throws URISyntaxException { URL resource = getClass().getClassLoader().getResource(resourceName); return (resource != null) ? Optional.of(Paths.get(resource.toURI())) : Optional.empty(); } @After public void removeData() throws Exception { if (targetDir != null && Files.exists(targetDir)) {
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/FileSystemHelper.java // public class FileSystemHelper { // // public static Path createTempDirectory() throws IOException { // return Files.createTempDirectory("test"); // } // // public static void removeDirectory(Path directory) throws IOException { // Files.walkFileTree(directory, new SimpleFileVisitor<Path>() { // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException { // Files.delete(file); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException { // Files.delete(dir); // return FileVisitResult.CONTINUE; // } // }); // } // // } // Path: stecker-plugin-generator/src/test/java/org/meridor/stecker/generator/CreateMojoTest.java import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DefaultArtifact; import org.apache.maven.artifact.handler.DefaultArtifactHandler; import org.apache.maven.plugin.testing.MojoRule; import org.apache.maven.project.MavenProject; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.meridor.stecker.impl.FileSystemHelper; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Optional; import static com.marvinformatics.kiss.matchers.path.PathMatchers.exists; import static com.marvinformatics.kiss.matchers.path.PathMatchers.isDirectory; import static com.marvinformatics.kiss.matchers.path.PathMatchers.isRegularFile; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; Path generatedDataDir = targetDir.resolve("plugin-generator"); assertThat(generatedDataDir, exists()); assertThat(generatedDataDir, isDirectory()); Path pluginFile = generatedDataDir.resolve("plugin-test-1.0.jar"); assertThat(pluginFile, exists()); assertThat(pluginFile, isRegularFile()); Path pluginDataDir = generatedDataDir.resolve("data"); assertThat(pluginDataDir, exists()); assertThat(pluginDataDir, isDirectory()); Path libDir = pluginDataDir.resolve("lib"); assertThat(libDir, exists()); assertThat(libDir, isDirectory()); Path dependencyFile = libDir.resolve(ARTIFACT_FILE); assertThat(dependencyFile, exists()); assertThat(dependencyFile, isRegularFile()); } private Optional<Path> getResource(String resourceName) throws URISyntaxException { URL resource = getClass().getClassLoader().getResource(resourceName); return (resource != null) ? Optional.of(Paths.get(resource.toURI())) : Optional.empty(); } @After public void removeData() throws Exception { if (targetDir != null && Files.exists(targetDir)) {
FileSystemHelper.removeDirectory(targetDir);
meridor/stecker
stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/DefaultClassesScanner.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ClassesScanner.java // public interface ClassesScanner { // // /** // * Returns a mapping between extension point classes and plugin file classes. E.g. if extension point is // * an interface <b>A</b> and some plugin implements it in classes B and C then the mapping will be: A -&gt; (B, C). // * // * @param pluginFile plugin file to process // * @param extensionPoints a list of extension point classes // * @return mapping from extension point to implementations from a plugin // * @throws org.meridor.stecker.PluginException when something goes wrong during classes scanning // */ // ScanResult scan(Path pluginFile, List<Class> extensionPoints) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginImplementationsAware.java // public interface PluginImplementationsAware { // // /** // * Returns a list of present extension points // * // * @return a list of extension points // */ // List<Class> getExtensionPoints(); // // /** // * Returns classes implementing extension point // * // * @param extensionPoint extension point class // * @return a list of implementation classes // */ // List<Class> getImplementations(Class extensionPoint); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ScanResult.java // public interface ScanResult { // // ClassLoader getClassLoader(); // // PluginImplementationsAware getContents(); // // }
import org.meridor.stecker.PluginException; import org.meridor.stecker.interfaces.ClassesScanner; import org.meridor.stecker.interfaces.PluginImplementationsAware; import org.meridor.stecker.interfaces.ScanResult; import java.nio.file.Path; import java.util.List;
package org.meridor.stecker.impl; public class DefaultClassesScanner implements ClassesScanner { private final Path cacheDirectory; public DefaultClassesScanner(Path cacheDirectory) { this.cacheDirectory = cacheDirectory; } @Override
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ClassesScanner.java // public interface ClassesScanner { // // /** // * Returns a mapping between extension point classes and plugin file classes. E.g. if extension point is // * an interface <b>A</b> and some plugin implements it in classes B and C then the mapping will be: A -&gt; (B, C). // * // * @param pluginFile plugin file to process // * @param extensionPoints a list of extension point classes // * @return mapping from extension point to implementations from a plugin // * @throws org.meridor.stecker.PluginException when something goes wrong during classes scanning // */ // ScanResult scan(Path pluginFile, List<Class> extensionPoints) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginImplementationsAware.java // public interface PluginImplementationsAware { // // /** // * Returns a list of present extension points // * // * @return a list of extension points // */ // List<Class> getExtensionPoints(); // // /** // * Returns classes implementing extension point // * // * @param extensionPoint extension point class // * @return a list of implementation classes // */ // List<Class> getImplementations(Class extensionPoint); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ScanResult.java // public interface ScanResult { // // ClassLoader getClassLoader(); // // PluginImplementationsAware getContents(); // // } // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/DefaultClassesScanner.java import org.meridor.stecker.PluginException; import org.meridor.stecker.interfaces.ClassesScanner; import org.meridor.stecker.interfaces.PluginImplementationsAware; import org.meridor.stecker.interfaces.ScanResult; import java.nio.file.Path; import java.util.List; package org.meridor.stecker.impl; public class DefaultClassesScanner implements ClassesScanner { private final Path cacheDirectory; public DefaultClassesScanner(Path cacheDirectory) { this.cacheDirectory = cacheDirectory; } @Override
public ScanResult scan(Path pluginFile, List<Class> extensionPoints) throws PluginException {
meridor/stecker
stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/DefaultClassesScanner.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ClassesScanner.java // public interface ClassesScanner { // // /** // * Returns a mapping between extension point classes and plugin file classes. E.g. if extension point is // * an interface <b>A</b> and some plugin implements it in classes B and C then the mapping will be: A -&gt; (B, C). // * // * @param pluginFile plugin file to process // * @param extensionPoints a list of extension point classes // * @return mapping from extension point to implementations from a plugin // * @throws org.meridor.stecker.PluginException when something goes wrong during classes scanning // */ // ScanResult scan(Path pluginFile, List<Class> extensionPoints) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginImplementationsAware.java // public interface PluginImplementationsAware { // // /** // * Returns a list of present extension points // * // * @return a list of extension points // */ // List<Class> getExtensionPoints(); // // /** // * Returns classes implementing extension point // * // * @param extensionPoint extension point class // * @return a list of implementation classes // */ // List<Class> getImplementations(Class extensionPoint); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ScanResult.java // public interface ScanResult { // // ClassLoader getClassLoader(); // // PluginImplementationsAware getContents(); // // }
import org.meridor.stecker.PluginException; import org.meridor.stecker.interfaces.ClassesScanner; import org.meridor.stecker.interfaces.PluginImplementationsAware; import org.meridor.stecker.interfaces.ScanResult; import java.nio.file.Path; import java.util.List;
package org.meridor.stecker.impl; public class DefaultClassesScanner implements ClassesScanner { private final Path cacheDirectory; public DefaultClassesScanner(Path cacheDirectory) { this.cacheDirectory = cacheDirectory; } @Override
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ClassesScanner.java // public interface ClassesScanner { // // /** // * Returns a mapping between extension point classes and plugin file classes. E.g. if extension point is // * an interface <b>A</b> and some plugin implements it in classes B and C then the mapping will be: A -&gt; (B, C). // * // * @param pluginFile plugin file to process // * @param extensionPoints a list of extension point classes // * @return mapping from extension point to implementations from a plugin // * @throws org.meridor.stecker.PluginException when something goes wrong during classes scanning // */ // ScanResult scan(Path pluginFile, List<Class> extensionPoints) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginImplementationsAware.java // public interface PluginImplementationsAware { // // /** // * Returns a list of present extension points // * // * @return a list of extension points // */ // List<Class> getExtensionPoints(); // // /** // * Returns classes implementing extension point // * // * @param extensionPoint extension point class // * @return a list of implementation classes // */ // List<Class> getImplementations(Class extensionPoint); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ScanResult.java // public interface ScanResult { // // ClassLoader getClassLoader(); // // PluginImplementationsAware getContents(); // // } // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/DefaultClassesScanner.java import org.meridor.stecker.PluginException; import org.meridor.stecker.interfaces.ClassesScanner; import org.meridor.stecker.interfaces.PluginImplementationsAware; import org.meridor.stecker.interfaces.ScanResult; import java.nio.file.Path; import java.util.List; package org.meridor.stecker.impl; public class DefaultClassesScanner implements ClassesScanner { private final Path cacheDirectory; public DefaultClassesScanner(Path cacheDirectory) { this.cacheDirectory = cacheDirectory; } @Override
public ScanResult scan(Path pluginFile, List<Class> extensionPoints) throws PluginException {
meridor/stecker
stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/DefaultClassesScanner.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ClassesScanner.java // public interface ClassesScanner { // // /** // * Returns a mapping between extension point classes and plugin file classes. E.g. if extension point is // * an interface <b>A</b> and some plugin implements it in classes B and C then the mapping will be: A -&gt; (B, C). // * // * @param pluginFile plugin file to process // * @param extensionPoints a list of extension point classes // * @return mapping from extension point to implementations from a plugin // * @throws org.meridor.stecker.PluginException when something goes wrong during classes scanning // */ // ScanResult scan(Path pluginFile, List<Class> extensionPoints) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginImplementationsAware.java // public interface PluginImplementationsAware { // // /** // * Returns a list of present extension points // * // * @return a list of extension points // */ // List<Class> getExtensionPoints(); // // /** // * Returns classes implementing extension point // * // * @param extensionPoint extension point class // * @return a list of implementation classes // */ // List<Class> getImplementations(Class extensionPoint); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ScanResult.java // public interface ScanResult { // // ClassLoader getClassLoader(); // // PluginImplementationsAware getContents(); // // }
import org.meridor.stecker.PluginException; import org.meridor.stecker.interfaces.ClassesScanner; import org.meridor.stecker.interfaces.PluginImplementationsAware; import org.meridor.stecker.interfaces.ScanResult; import java.nio.file.Path; import java.util.List;
package org.meridor.stecker.impl; public class DefaultClassesScanner implements ClassesScanner { private final Path cacheDirectory; public DefaultClassesScanner(Path cacheDirectory) { this.cacheDirectory = cacheDirectory; } @Override public ScanResult scan(Path pluginFile, List<Class> extensionPoints) throws PluginException { try { Path unpackedPluginDirectory = PluginUtils.unpackPlugin(pluginFile, cacheDirectory); Path pluginImplementationDirectory = PluginUtils.getPluginImplementationDirectory(unpackedPluginDirectory); ClassLoader classLoader = getClassLoader(unpackedPluginDirectory, pluginImplementationDirectory);
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ClassesScanner.java // public interface ClassesScanner { // // /** // * Returns a mapping between extension point classes and plugin file classes. E.g. if extension point is // * an interface <b>A</b> and some plugin implements it in classes B and C then the mapping will be: A -&gt; (B, C). // * // * @param pluginFile plugin file to process // * @param extensionPoints a list of extension point classes // * @return mapping from extension point to implementations from a plugin // * @throws org.meridor.stecker.PluginException when something goes wrong during classes scanning // */ // ScanResult scan(Path pluginFile, List<Class> extensionPoints) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginImplementationsAware.java // public interface PluginImplementationsAware { // // /** // * Returns a list of present extension points // * // * @return a list of extension points // */ // List<Class> getExtensionPoints(); // // /** // * Returns classes implementing extension point // * // * @param extensionPoint extension point class // * @return a list of implementation classes // */ // List<Class> getImplementations(Class extensionPoint); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ScanResult.java // public interface ScanResult { // // ClassLoader getClassLoader(); // // PluginImplementationsAware getContents(); // // } // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/DefaultClassesScanner.java import org.meridor.stecker.PluginException; import org.meridor.stecker.interfaces.ClassesScanner; import org.meridor.stecker.interfaces.PluginImplementationsAware; import org.meridor.stecker.interfaces.ScanResult; import java.nio.file.Path; import java.util.List; package org.meridor.stecker.impl; public class DefaultClassesScanner implements ClassesScanner { private final Path cacheDirectory; public DefaultClassesScanner(Path cacheDirectory) { this.cacheDirectory = cacheDirectory; } @Override public ScanResult scan(Path pluginFile, List<Class> extensionPoints) throws PluginException { try { Path unpackedPluginDirectory = PluginUtils.unpackPlugin(pluginFile, cacheDirectory); Path pluginImplementationDirectory = PluginUtils.getPluginImplementationDirectory(unpackedPluginDirectory); ClassLoader classLoader = getClassLoader(unpackedPluginDirectory, pluginImplementationDirectory);
PluginImplementationsAware pluginImplementationsAware = PluginUtils.getMatchingClasses(extensionPoints, pluginImplementationDirectory, classLoader);
meridor/stecker
stecker-plugin-loader/src/test/java/org/meridor/stecker/dev/DevResourcesScannerTest.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/TemporaryDirectory.java // public class TemporaryDirectory extends ExternalResource { // // private Path directory; // // @Override // protected void before() throws Throwable { // super.before(); // create(); // } // // private void create() throws IOException { // directory = FileSystemHelper.createTempDirectory(); // } // // @Override // protected void after() { // super.after(); // remove(); // } // // private void remove() { // try { // FileSystemHelper.removeDirectory(directory); // } catch (IOException e) { // System.out.println("Can't remove temporary directory"); // e.printStackTrace(); // } // } // // public Path getDirectory() { // return directory; // } // // public Path createFile(String fileName, byte[] contents) throws IOException { // Path filePath = directory.resolve(fileName); // Files.write(filePath, contents); // return filePath; // } // }
import org.junit.Rule; import org.junit.Test; import org.meridor.stecker.PluginException; import org.meridor.stecker.TemporaryDirectory; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat;
package org.meridor.stecker.dev; public class DevResourcesScannerTest { @Rule
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/TemporaryDirectory.java // public class TemporaryDirectory extends ExternalResource { // // private Path directory; // // @Override // protected void before() throws Throwable { // super.before(); // create(); // } // // private void create() throws IOException { // directory = FileSystemHelper.createTempDirectory(); // } // // @Override // protected void after() { // super.after(); // remove(); // } // // private void remove() { // try { // FileSystemHelper.removeDirectory(directory); // } catch (IOException e) { // System.out.println("Can't remove temporary directory"); // e.printStackTrace(); // } // } // // public Path getDirectory() { // return directory; // } // // public Path createFile(String fileName, byte[] contents) throws IOException { // Path filePath = directory.resolve(fileName); // Files.write(filePath, contents); // return filePath; // } // } // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/dev/DevResourcesScannerTest.java import org.junit.Rule; import org.junit.Test; import org.meridor.stecker.PluginException; import org.meridor.stecker.TemporaryDirectory; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; package org.meridor.stecker.dev; public class DevResourcesScannerTest { @Rule
public TemporaryDirectory temporaryDirectory = new TemporaryDirectory();
meridor/stecker
stecker-plugin-loader/src/test/java/org/meridor/stecker/dev/DevResourcesScannerTest.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/TemporaryDirectory.java // public class TemporaryDirectory extends ExternalResource { // // private Path directory; // // @Override // protected void before() throws Throwable { // super.before(); // create(); // } // // private void create() throws IOException { // directory = FileSystemHelper.createTempDirectory(); // } // // @Override // protected void after() { // super.after(); // remove(); // } // // private void remove() { // try { // FileSystemHelper.removeDirectory(directory); // } catch (IOException e) { // System.out.println("Can't remove temporary directory"); // e.printStackTrace(); // } // } // // public Path getDirectory() { // return directory; // } // // public Path createFile(String fileName, byte[] contents) throws IOException { // Path filePath = directory.resolve(fileName); // Files.write(filePath, contents); // return filePath; // } // }
import org.junit.Rule; import org.junit.Test; import org.meridor.stecker.PluginException; import org.meridor.stecker.TemporaryDirectory; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat;
package org.meridor.stecker.dev; public class DevResourcesScannerTest { @Rule public TemporaryDirectory temporaryDirectory = new TemporaryDirectory(); private static final String[] GLOBS = new String[]{"glob:**/*.txt"}; private Path matchingFile; @Test public void testScan() throws Exception { createFiles(); Path pluginDirectory = temporaryDirectory.getDirectory(); DevResourcesScanner devResourcesScanner = new DevResourcesScanner(GLOBS); List<Path> matchingResources = devResourcesScanner.scan(pluginDirectory); assertThat(matchingResources, hasSize(1)); assertThat(matchingResources, hasItem(matchingFile)); } @Test
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/TemporaryDirectory.java // public class TemporaryDirectory extends ExternalResource { // // private Path directory; // // @Override // protected void before() throws Throwable { // super.before(); // create(); // } // // private void create() throws IOException { // directory = FileSystemHelper.createTempDirectory(); // } // // @Override // protected void after() { // super.after(); // remove(); // } // // private void remove() { // try { // FileSystemHelper.removeDirectory(directory); // } catch (IOException e) { // System.out.println("Can't remove temporary directory"); // e.printStackTrace(); // } // } // // public Path getDirectory() { // return directory; // } // // public Path createFile(String fileName, byte[] contents) throws IOException { // Path filePath = directory.resolve(fileName); // Files.write(filePath, contents); // return filePath; // } // } // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/dev/DevResourcesScannerTest.java import org.junit.Rule; import org.junit.Test; import org.meridor.stecker.PluginException; import org.meridor.stecker.TemporaryDirectory; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; package org.meridor.stecker.dev; public class DevResourcesScannerTest { @Rule public TemporaryDirectory temporaryDirectory = new TemporaryDirectory(); private static final String[] GLOBS = new String[]{"glob:**/*.txt"}; private Path matchingFile; @Test public void testScan() throws Exception { createFiles(); Path pluginDirectory = temporaryDirectory.getDirectory(); DevResourcesScanner devResourcesScanner = new DevResourcesScanner(GLOBS); List<Path> matchingResources = devResourcesScanner.scan(pluginDirectory); assertThat(matchingResources, hasSize(1)); assertThat(matchingResources, hasItem(matchingFile)); } @Test
public void testResourcesDirectoryMissing() throws PluginException {
meridor/stecker
stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/DependencyContainerTest.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/Dependency.java // public interface Dependency { // // /** // * Returns dependency name // * // * @return dependency name // */ // String getName(); // // /** // * Returns dependency version if present // * // * @return dependency version if present and empty otherwise // */ // Optional<String> getVersion(); // // /** // * Forces to override {@link Object#equals(Object)} // * // * @param anotherDependency dependency to compare to // * @return true if equal and false otherwise // */ // boolean equals(Object anotherDependency); // // /** // * Forces to override {@link Object#hashCode()} // * // * @return instance hash code // */ // int hashCode(); // // /** // * Returns dependency string representation // * // * @return dependency string representation // */ // String toString(); // // }
import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.meridor.stecker.interfaces.Dependency; import java.util.Arrays; import java.util.Collection; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat;
package org.meridor.stecker.impl; @RunWith(Parameterized.class) public class DependencyContainerTest { private static final String DEPENDENCY_NAME = "some-name";
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/Dependency.java // public interface Dependency { // // /** // * Returns dependency name // * // * @return dependency name // */ // String getName(); // // /** // * Returns dependency version if present // * // * @return dependency version if present and empty otherwise // */ // Optional<String> getVersion(); // // /** // * Forces to override {@link Object#equals(Object)} // * // * @param anotherDependency dependency to compare to // * @return true if equal and false otherwise // */ // boolean equals(Object anotherDependency); // // /** // * Forces to override {@link Object#hashCode()} // * // * @return instance hash code // */ // int hashCode(); // // /** // * Returns dependency string representation // * // * @return dependency string representation // */ // String toString(); // // } // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/DependencyContainerTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.meridor.stecker.interfaces.Dependency; import java.util.Arrays; import java.util.Collection; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; package org.meridor.stecker.impl; @RunWith(Parameterized.class) public class DependencyContainerTest { private static final String DEPENDENCY_NAME = "some-name";
private static final Dependency DEPENDENCY_WITHOUT_VERSION = new DependencyContainer(DEPENDENCY_NAME);
meridor/stecker
stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/DefaultResourcesScanner.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ResourcesScanner.java // public interface ResourcesScanner { // // /** // * Does the scanning // * // * @param path depending on context can be a file or directory path // * @return a list of matching resources // * @throws org.meridor.stecker.PluginException when something goes wrong during resources scanning // */ // List<Path> scan(Path path) throws PluginException; // // }
import org.meridor.stecker.PluginException; import org.meridor.stecker.interfaces.ResourcesScanner; import java.io.IOException; import java.nio.file.Path; import java.util.List;
package org.meridor.stecker.impl; public class DefaultResourcesScanner implements ResourcesScanner { private final Path cacheDirectory; private final String[] patterns; public DefaultResourcesScanner(Path cacheDirectory, String[] patterns) { this.cacheDirectory = cacheDirectory; this.patterns = patterns; } @Override
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ResourcesScanner.java // public interface ResourcesScanner { // // /** // * Does the scanning // * // * @param path depending on context can be a file or directory path // * @return a list of matching resources // * @throws org.meridor.stecker.PluginException when something goes wrong during resources scanning // */ // List<Path> scan(Path path) throws PluginException; // // } // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/DefaultResourcesScanner.java import org.meridor.stecker.PluginException; import org.meridor.stecker.interfaces.ResourcesScanner; import java.io.IOException; import java.nio.file.Path; import java.util.List; package org.meridor.stecker.impl; public class DefaultResourcesScanner implements ResourcesScanner { private final Path cacheDirectory; private final String[] patterns; public DefaultResourcesScanner(Path cacheDirectory, String[] patterns) { this.cacheDirectory = cacheDirectory; this.patterns = patterns; } @Override
public List<Path> scan(Path pluginFile) throws PluginException {
meridor/stecker
stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginMetadata.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/Dependency.java // public interface Dependency { // // /** // * Returns dependency name // * // * @return dependency name // */ // String getName(); // // /** // * Returns dependency version if present // * // * @return dependency version if present and empty otherwise // */ // Optional<String> getVersion(); // // /** // * Forces to override {@link Object#equals(Object)} // * // * @param anotherDependency dependency to compare to // * @return true if equal and false otherwise // */ // boolean equals(Object anotherDependency); // // /** // * Forces to override {@link Object#hashCode()} // * // * @return instance hash code // */ // int hashCode(); // // /** // * Returns dependency string representation // * // * @return dependency string representation // */ // String toString(); // // }
import org.meridor.stecker.interfaces.Dependency; import java.nio.file.Path; import java.time.ZonedDateTime; import java.util.List; import java.util.Optional;
package org.meridor.stecker; /** * Stores metadata of a single plugin */ public interface PluginMetadata { /** * Returns unique plugin name * * @return free-form string with name */ String getName(); /** * Returns plugin version * * @return free-form string with version */ String getVersion(); /** * Returns {@link Path} object corresponding to plugin file * * @return plugin {@link Path} object */ Path getPath(); /** * Returns {@link org.meridor.stecker.interfaces.Dependency} object corresponding to this plugin * * @return dependency object */
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/Dependency.java // public interface Dependency { // // /** // * Returns dependency name // * // * @return dependency name // */ // String getName(); // // /** // * Returns dependency version if present // * // * @return dependency version if present and empty otherwise // */ // Optional<String> getVersion(); // // /** // * Forces to override {@link Object#equals(Object)} // * // * @param anotherDependency dependency to compare to // * @return true if equal and false otherwise // */ // boolean equals(Object anotherDependency); // // /** // * Forces to override {@link Object#hashCode()} // * // * @return instance hash code // */ // int hashCode(); // // /** // * Returns dependency string representation // * // * @return dependency string representation // */ // String toString(); // // } // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginMetadata.java import org.meridor.stecker.interfaces.Dependency; import java.nio.file.Path; import java.time.ZonedDateTime; import java.util.List; import java.util.Optional; package org.meridor.stecker; /** * Stores metadata of a single plugin */ public interface PluginMetadata { /** * Returns unique plugin name * * @return free-form string with name */ String getName(); /** * Returns plugin version * * @return free-form string with version */ String getVersion(); /** * Returns {@link Path} object corresponding to plugin file * * @return plugin {@link Path} object */ Path getPath(); /** * Returns {@link org.meridor.stecker.interfaces.Dependency} object corresponding to this plugin * * @return dependency object */
Dependency getDependency();
meridor/stecker
stecker-plugin-loader/src/test/java/org/meridor/stecker/PluginLoaderTest.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/ManifestField.java // public enum ManifestField { // // NAME("Plugin-Name"), // VERSION("Plugin-Version"), // DATE("Plugin-Date"), // DESCRIPTION("Plugin-Description"), // MAINTAINER("Plugin-Maintainer"), // DEPENDS("Plugin-Depends"), // CONFLICTS("Plugin-Conflicts"), // PROVIDES("Plugin-Provides"); // // private final String fieldName; // // private ManifestField(String fieldName) { // this.fieldName = fieldName; // } // // public String getFieldName() { // return fieldName; // } // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/data/AnnotatedImpl.java // @TestAnnotation // public class AnnotatedImpl { // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/data/TestExtensionPoint.java // public interface TestExtensionPoint { // // void doSomething(); // // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/data/TestExtensionPointImpl.java // public class TestExtensionPointImpl implements TestExtensionPoint { // // @Override // public void doSomething() { // new LibraryClass().act(); // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ClassesScanner.java // public interface ClassesScanner { // // /** // * Returns a mapping between extension point classes and plugin file classes. E.g. if extension point is // * an interface <b>A</b> and some plugin implements it in classes B and C then the mapping will be: A -&gt; (B, C). // * // * @param pluginFile plugin file to process // * @param extensionPoints a list of extension point classes // * @return mapping from extension point to implementations from a plugin // * @throws org.meridor.stecker.PluginException when something goes wrong during classes scanning // */ // ScanResult scan(Path pluginFile, List<Class> extensionPoints) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/DependencyChecker.java // public interface DependencyChecker { // // /** // * Checks dependencies and throws {@link org.meridor.stecker.PluginException} with {@link DependencyProblem} in case of issues // * // * @param pluginRegistry plugin registry object filled with data about all plugins // * @param pluginMetadata checked plugin metadata // * @throws org.meridor.stecker.PluginException when dependency issues occur // */ // void check(PluginsAware pluginRegistry, PluginMetadata pluginMetadata) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ManifestReader.java // public interface ManifestReader { // // /** // * Reads jar file manifest and returns plugin information stored there // * // * @param pluginFile plugin file to process // * @return plugin information in {@link org.meridor.stecker.PluginMetadata} format // * @throws org.meridor.stecker.PluginException when something goes wrong during manifest reading // */ // PluginMetadata read(Path pluginFile) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginsProvider.java // public interface PluginsProvider { // // /** // * Provides a list of plugins paths // * // * @param baseDirectory root directory to scan for plugins // * @return list of paths that seems to be plugins // * @throws org.meridor.stecker.PluginException when something goes wrong during base directory scanning // */ // List<Path> provide(Path baseDirectory) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ResourcesScanner.java // public interface ResourcesScanner { // // /** // * Does the scanning // * // * @param path depending on context can be a file or directory path // * @return a list of matching resources // * @throws org.meridor.stecker.PluginException when something goes wrong during resources scanning // */ // List<Path> scan(Path path) throws PluginException; // // }
import org.junit.Rule; import org.junit.Test; import org.meridor.stecker.impl.ManifestField; import org.meridor.stecker.impl.data.AnnotatedImpl; import org.meridor.stecker.impl.data.TestAnnotation; import org.meridor.stecker.impl.data.TestExtensionPoint; import org.meridor.stecker.impl.data.TestExtensionPointImpl; import org.meridor.stecker.interfaces.ClassesScanner; import org.meridor.stecker.interfaces.DependencyChecker; import org.meridor.stecker.interfaces.ManifestReader; import org.meridor.stecker.interfaces.PluginsProvider; import org.meridor.stecker.interfaces.ResourcesScanner; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.jar.Manifest; import java.util.stream.Collectors; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock;
package org.meridor.stecker; public class PluginLoaderTest { @Rule public TemporaryDirectory temporaryDirectory = new TemporaryDirectory(); @Test public void testFluentApi() throws PluginException { Path pluginDirectory = Paths.get("plugin-directory"); String fileGlob = "some-glob";
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/ManifestField.java // public enum ManifestField { // // NAME("Plugin-Name"), // VERSION("Plugin-Version"), // DATE("Plugin-Date"), // DESCRIPTION("Plugin-Description"), // MAINTAINER("Plugin-Maintainer"), // DEPENDS("Plugin-Depends"), // CONFLICTS("Plugin-Conflicts"), // PROVIDES("Plugin-Provides"); // // private final String fieldName; // // private ManifestField(String fieldName) { // this.fieldName = fieldName; // } // // public String getFieldName() { // return fieldName; // } // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/data/AnnotatedImpl.java // @TestAnnotation // public class AnnotatedImpl { // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/data/TestExtensionPoint.java // public interface TestExtensionPoint { // // void doSomething(); // // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/data/TestExtensionPointImpl.java // public class TestExtensionPointImpl implements TestExtensionPoint { // // @Override // public void doSomething() { // new LibraryClass().act(); // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ClassesScanner.java // public interface ClassesScanner { // // /** // * Returns a mapping between extension point classes and plugin file classes. E.g. if extension point is // * an interface <b>A</b> and some plugin implements it in classes B and C then the mapping will be: A -&gt; (B, C). // * // * @param pluginFile plugin file to process // * @param extensionPoints a list of extension point classes // * @return mapping from extension point to implementations from a plugin // * @throws org.meridor.stecker.PluginException when something goes wrong during classes scanning // */ // ScanResult scan(Path pluginFile, List<Class> extensionPoints) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/DependencyChecker.java // public interface DependencyChecker { // // /** // * Checks dependencies and throws {@link org.meridor.stecker.PluginException} with {@link DependencyProblem} in case of issues // * // * @param pluginRegistry plugin registry object filled with data about all plugins // * @param pluginMetadata checked plugin metadata // * @throws org.meridor.stecker.PluginException when dependency issues occur // */ // void check(PluginsAware pluginRegistry, PluginMetadata pluginMetadata) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ManifestReader.java // public interface ManifestReader { // // /** // * Reads jar file manifest and returns plugin information stored there // * // * @param pluginFile plugin file to process // * @return plugin information in {@link org.meridor.stecker.PluginMetadata} format // * @throws org.meridor.stecker.PluginException when something goes wrong during manifest reading // */ // PluginMetadata read(Path pluginFile) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginsProvider.java // public interface PluginsProvider { // // /** // * Provides a list of plugins paths // * // * @param baseDirectory root directory to scan for plugins // * @return list of paths that seems to be plugins // * @throws org.meridor.stecker.PluginException when something goes wrong during base directory scanning // */ // List<Path> provide(Path baseDirectory) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ResourcesScanner.java // public interface ResourcesScanner { // // /** // * Does the scanning // * // * @param path depending on context can be a file or directory path // * @return a list of matching resources // * @throws org.meridor.stecker.PluginException when something goes wrong during resources scanning // */ // List<Path> scan(Path path) throws PluginException; // // } // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/PluginLoaderTest.java import org.junit.Rule; import org.junit.Test; import org.meridor.stecker.impl.ManifestField; import org.meridor.stecker.impl.data.AnnotatedImpl; import org.meridor.stecker.impl.data.TestAnnotation; import org.meridor.stecker.impl.data.TestExtensionPoint; import org.meridor.stecker.impl.data.TestExtensionPointImpl; import org.meridor.stecker.interfaces.ClassesScanner; import org.meridor.stecker.interfaces.DependencyChecker; import org.meridor.stecker.interfaces.ManifestReader; import org.meridor.stecker.interfaces.PluginsProvider; import org.meridor.stecker.interfaces.ResourcesScanner; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.jar.Manifest; import java.util.stream.Collectors; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; package org.meridor.stecker; public class PluginLoaderTest { @Rule public TemporaryDirectory temporaryDirectory = new TemporaryDirectory(); @Test public void testFluentApi() throws PluginException { Path pluginDirectory = Paths.get("plugin-directory"); String fileGlob = "some-glob";
PluginsProvider pluginsProvider = mock(PluginsProvider.class);
meridor/stecker
stecker-plugin-loader/src/test/java/org/meridor/stecker/PluginLoaderTest.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/ManifestField.java // public enum ManifestField { // // NAME("Plugin-Name"), // VERSION("Plugin-Version"), // DATE("Plugin-Date"), // DESCRIPTION("Plugin-Description"), // MAINTAINER("Plugin-Maintainer"), // DEPENDS("Plugin-Depends"), // CONFLICTS("Plugin-Conflicts"), // PROVIDES("Plugin-Provides"); // // private final String fieldName; // // private ManifestField(String fieldName) { // this.fieldName = fieldName; // } // // public String getFieldName() { // return fieldName; // } // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/data/AnnotatedImpl.java // @TestAnnotation // public class AnnotatedImpl { // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/data/TestExtensionPoint.java // public interface TestExtensionPoint { // // void doSomething(); // // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/data/TestExtensionPointImpl.java // public class TestExtensionPointImpl implements TestExtensionPoint { // // @Override // public void doSomething() { // new LibraryClass().act(); // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ClassesScanner.java // public interface ClassesScanner { // // /** // * Returns a mapping between extension point classes and plugin file classes. E.g. if extension point is // * an interface <b>A</b> and some plugin implements it in classes B and C then the mapping will be: A -&gt; (B, C). // * // * @param pluginFile plugin file to process // * @param extensionPoints a list of extension point classes // * @return mapping from extension point to implementations from a plugin // * @throws org.meridor.stecker.PluginException when something goes wrong during classes scanning // */ // ScanResult scan(Path pluginFile, List<Class> extensionPoints) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/DependencyChecker.java // public interface DependencyChecker { // // /** // * Checks dependencies and throws {@link org.meridor.stecker.PluginException} with {@link DependencyProblem} in case of issues // * // * @param pluginRegistry plugin registry object filled with data about all plugins // * @param pluginMetadata checked plugin metadata // * @throws org.meridor.stecker.PluginException when dependency issues occur // */ // void check(PluginsAware pluginRegistry, PluginMetadata pluginMetadata) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ManifestReader.java // public interface ManifestReader { // // /** // * Reads jar file manifest and returns plugin information stored there // * // * @param pluginFile plugin file to process // * @return plugin information in {@link org.meridor.stecker.PluginMetadata} format // * @throws org.meridor.stecker.PluginException when something goes wrong during manifest reading // */ // PluginMetadata read(Path pluginFile) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginsProvider.java // public interface PluginsProvider { // // /** // * Provides a list of plugins paths // * // * @param baseDirectory root directory to scan for plugins // * @return list of paths that seems to be plugins // * @throws org.meridor.stecker.PluginException when something goes wrong during base directory scanning // */ // List<Path> provide(Path baseDirectory) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ResourcesScanner.java // public interface ResourcesScanner { // // /** // * Does the scanning // * // * @param path depending on context can be a file or directory path // * @return a list of matching resources // * @throws org.meridor.stecker.PluginException when something goes wrong during resources scanning // */ // List<Path> scan(Path path) throws PluginException; // // }
import org.junit.Rule; import org.junit.Test; import org.meridor.stecker.impl.ManifestField; import org.meridor.stecker.impl.data.AnnotatedImpl; import org.meridor.stecker.impl.data.TestAnnotation; import org.meridor.stecker.impl.data.TestExtensionPoint; import org.meridor.stecker.impl.data.TestExtensionPointImpl; import org.meridor.stecker.interfaces.ClassesScanner; import org.meridor.stecker.interfaces.DependencyChecker; import org.meridor.stecker.interfaces.ManifestReader; import org.meridor.stecker.interfaces.PluginsProvider; import org.meridor.stecker.interfaces.ResourcesScanner; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.jar.Manifest; import java.util.stream.Collectors; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock;
package org.meridor.stecker; public class PluginLoaderTest { @Rule public TemporaryDirectory temporaryDirectory = new TemporaryDirectory(); @Test public void testFluentApi() throws PluginException { Path pluginDirectory = Paths.get("plugin-directory"); String fileGlob = "some-glob"; PluginsProvider pluginsProvider = mock(PluginsProvider.class); Path cacheDirectory = Paths.get("cache-directory");
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/ManifestField.java // public enum ManifestField { // // NAME("Plugin-Name"), // VERSION("Plugin-Version"), // DATE("Plugin-Date"), // DESCRIPTION("Plugin-Description"), // MAINTAINER("Plugin-Maintainer"), // DEPENDS("Plugin-Depends"), // CONFLICTS("Plugin-Conflicts"), // PROVIDES("Plugin-Provides"); // // private final String fieldName; // // private ManifestField(String fieldName) { // this.fieldName = fieldName; // } // // public String getFieldName() { // return fieldName; // } // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/data/AnnotatedImpl.java // @TestAnnotation // public class AnnotatedImpl { // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/data/TestExtensionPoint.java // public interface TestExtensionPoint { // // void doSomething(); // // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/data/TestExtensionPointImpl.java // public class TestExtensionPointImpl implements TestExtensionPoint { // // @Override // public void doSomething() { // new LibraryClass().act(); // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ClassesScanner.java // public interface ClassesScanner { // // /** // * Returns a mapping between extension point classes and plugin file classes. E.g. if extension point is // * an interface <b>A</b> and some plugin implements it in classes B and C then the mapping will be: A -&gt; (B, C). // * // * @param pluginFile plugin file to process // * @param extensionPoints a list of extension point classes // * @return mapping from extension point to implementations from a plugin // * @throws org.meridor.stecker.PluginException when something goes wrong during classes scanning // */ // ScanResult scan(Path pluginFile, List<Class> extensionPoints) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/DependencyChecker.java // public interface DependencyChecker { // // /** // * Checks dependencies and throws {@link org.meridor.stecker.PluginException} with {@link DependencyProblem} in case of issues // * // * @param pluginRegistry plugin registry object filled with data about all plugins // * @param pluginMetadata checked plugin metadata // * @throws org.meridor.stecker.PluginException when dependency issues occur // */ // void check(PluginsAware pluginRegistry, PluginMetadata pluginMetadata) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ManifestReader.java // public interface ManifestReader { // // /** // * Reads jar file manifest and returns plugin information stored there // * // * @param pluginFile plugin file to process // * @return plugin information in {@link org.meridor.stecker.PluginMetadata} format // * @throws org.meridor.stecker.PluginException when something goes wrong during manifest reading // */ // PluginMetadata read(Path pluginFile) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginsProvider.java // public interface PluginsProvider { // // /** // * Provides a list of plugins paths // * // * @param baseDirectory root directory to scan for plugins // * @return list of paths that seems to be plugins // * @throws org.meridor.stecker.PluginException when something goes wrong during base directory scanning // */ // List<Path> provide(Path baseDirectory) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ResourcesScanner.java // public interface ResourcesScanner { // // /** // * Does the scanning // * // * @param path depending on context can be a file or directory path // * @return a list of matching resources // * @throws org.meridor.stecker.PluginException when something goes wrong during resources scanning // */ // List<Path> scan(Path path) throws PluginException; // // } // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/PluginLoaderTest.java import org.junit.Rule; import org.junit.Test; import org.meridor.stecker.impl.ManifestField; import org.meridor.stecker.impl.data.AnnotatedImpl; import org.meridor.stecker.impl.data.TestAnnotation; import org.meridor.stecker.impl.data.TestExtensionPoint; import org.meridor.stecker.impl.data.TestExtensionPointImpl; import org.meridor.stecker.interfaces.ClassesScanner; import org.meridor.stecker.interfaces.DependencyChecker; import org.meridor.stecker.interfaces.ManifestReader; import org.meridor.stecker.interfaces.PluginsProvider; import org.meridor.stecker.interfaces.ResourcesScanner; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.jar.Manifest; import java.util.stream.Collectors; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; package org.meridor.stecker; public class PluginLoaderTest { @Rule public TemporaryDirectory temporaryDirectory = new TemporaryDirectory(); @Test public void testFluentApi() throws PluginException { Path pluginDirectory = Paths.get("plugin-directory"); String fileGlob = "some-glob"; PluginsProvider pluginsProvider = mock(PluginsProvider.class); Path cacheDirectory = Paths.get("cache-directory");
Class[] extensionPointsArray = new Class[]{TestExtensionPoint.class, TestExtensionPoint.class}; //We intentionally duplicate extension points
meridor/stecker
stecker-plugin-loader/src/test/java/org/meridor/stecker/PluginLoaderTest.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/ManifestField.java // public enum ManifestField { // // NAME("Plugin-Name"), // VERSION("Plugin-Version"), // DATE("Plugin-Date"), // DESCRIPTION("Plugin-Description"), // MAINTAINER("Plugin-Maintainer"), // DEPENDS("Plugin-Depends"), // CONFLICTS("Plugin-Conflicts"), // PROVIDES("Plugin-Provides"); // // private final String fieldName; // // private ManifestField(String fieldName) { // this.fieldName = fieldName; // } // // public String getFieldName() { // return fieldName; // } // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/data/AnnotatedImpl.java // @TestAnnotation // public class AnnotatedImpl { // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/data/TestExtensionPoint.java // public interface TestExtensionPoint { // // void doSomething(); // // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/data/TestExtensionPointImpl.java // public class TestExtensionPointImpl implements TestExtensionPoint { // // @Override // public void doSomething() { // new LibraryClass().act(); // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ClassesScanner.java // public interface ClassesScanner { // // /** // * Returns a mapping between extension point classes and plugin file classes. E.g. if extension point is // * an interface <b>A</b> and some plugin implements it in classes B and C then the mapping will be: A -&gt; (B, C). // * // * @param pluginFile plugin file to process // * @param extensionPoints a list of extension point classes // * @return mapping from extension point to implementations from a plugin // * @throws org.meridor.stecker.PluginException when something goes wrong during classes scanning // */ // ScanResult scan(Path pluginFile, List<Class> extensionPoints) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/DependencyChecker.java // public interface DependencyChecker { // // /** // * Checks dependencies and throws {@link org.meridor.stecker.PluginException} with {@link DependencyProblem} in case of issues // * // * @param pluginRegistry plugin registry object filled with data about all plugins // * @param pluginMetadata checked plugin metadata // * @throws org.meridor.stecker.PluginException when dependency issues occur // */ // void check(PluginsAware pluginRegistry, PluginMetadata pluginMetadata) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ManifestReader.java // public interface ManifestReader { // // /** // * Reads jar file manifest and returns plugin information stored there // * // * @param pluginFile plugin file to process // * @return plugin information in {@link org.meridor.stecker.PluginMetadata} format // * @throws org.meridor.stecker.PluginException when something goes wrong during manifest reading // */ // PluginMetadata read(Path pluginFile) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginsProvider.java // public interface PluginsProvider { // // /** // * Provides a list of plugins paths // * // * @param baseDirectory root directory to scan for plugins // * @return list of paths that seems to be plugins // * @throws org.meridor.stecker.PluginException when something goes wrong during base directory scanning // */ // List<Path> provide(Path baseDirectory) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ResourcesScanner.java // public interface ResourcesScanner { // // /** // * Does the scanning // * // * @param path depending on context can be a file or directory path // * @return a list of matching resources // * @throws org.meridor.stecker.PluginException when something goes wrong during resources scanning // */ // List<Path> scan(Path path) throws PluginException; // // }
import org.junit.Rule; import org.junit.Test; import org.meridor.stecker.impl.ManifestField; import org.meridor.stecker.impl.data.AnnotatedImpl; import org.meridor.stecker.impl.data.TestAnnotation; import org.meridor.stecker.impl.data.TestExtensionPoint; import org.meridor.stecker.impl.data.TestExtensionPointImpl; import org.meridor.stecker.interfaces.ClassesScanner; import org.meridor.stecker.interfaces.DependencyChecker; import org.meridor.stecker.interfaces.ManifestReader; import org.meridor.stecker.interfaces.PluginsProvider; import org.meridor.stecker.interfaces.ResourcesScanner; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.jar.Manifest; import java.util.stream.Collectors; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock;
package org.meridor.stecker; public class PluginLoaderTest { @Rule public TemporaryDirectory temporaryDirectory = new TemporaryDirectory(); @Test public void testFluentApi() throws PluginException { Path pluginDirectory = Paths.get("plugin-directory"); String fileGlob = "some-glob"; PluginsProvider pluginsProvider = mock(PluginsProvider.class); Path cacheDirectory = Paths.get("cache-directory"); Class[] extensionPointsArray = new Class[]{TestExtensionPoint.class, TestExtensionPoint.class}; //We intentionally duplicate extension points
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/ManifestField.java // public enum ManifestField { // // NAME("Plugin-Name"), // VERSION("Plugin-Version"), // DATE("Plugin-Date"), // DESCRIPTION("Plugin-Description"), // MAINTAINER("Plugin-Maintainer"), // DEPENDS("Plugin-Depends"), // CONFLICTS("Plugin-Conflicts"), // PROVIDES("Plugin-Provides"); // // private final String fieldName; // // private ManifestField(String fieldName) { // this.fieldName = fieldName; // } // // public String getFieldName() { // return fieldName; // } // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/data/AnnotatedImpl.java // @TestAnnotation // public class AnnotatedImpl { // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/data/TestExtensionPoint.java // public interface TestExtensionPoint { // // void doSomething(); // // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/data/TestExtensionPointImpl.java // public class TestExtensionPointImpl implements TestExtensionPoint { // // @Override // public void doSomething() { // new LibraryClass().act(); // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ClassesScanner.java // public interface ClassesScanner { // // /** // * Returns a mapping between extension point classes and plugin file classes. E.g. if extension point is // * an interface <b>A</b> and some plugin implements it in classes B and C then the mapping will be: A -&gt; (B, C). // * // * @param pluginFile plugin file to process // * @param extensionPoints a list of extension point classes // * @return mapping from extension point to implementations from a plugin // * @throws org.meridor.stecker.PluginException when something goes wrong during classes scanning // */ // ScanResult scan(Path pluginFile, List<Class> extensionPoints) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/DependencyChecker.java // public interface DependencyChecker { // // /** // * Checks dependencies and throws {@link org.meridor.stecker.PluginException} with {@link DependencyProblem} in case of issues // * // * @param pluginRegistry plugin registry object filled with data about all plugins // * @param pluginMetadata checked plugin metadata // * @throws org.meridor.stecker.PluginException when dependency issues occur // */ // void check(PluginsAware pluginRegistry, PluginMetadata pluginMetadata) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ManifestReader.java // public interface ManifestReader { // // /** // * Reads jar file manifest and returns plugin information stored there // * // * @param pluginFile plugin file to process // * @return plugin information in {@link org.meridor.stecker.PluginMetadata} format // * @throws org.meridor.stecker.PluginException when something goes wrong during manifest reading // */ // PluginMetadata read(Path pluginFile) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginsProvider.java // public interface PluginsProvider { // // /** // * Provides a list of plugins paths // * // * @param baseDirectory root directory to scan for plugins // * @return list of paths that seems to be plugins // * @throws org.meridor.stecker.PluginException when something goes wrong during base directory scanning // */ // List<Path> provide(Path baseDirectory) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ResourcesScanner.java // public interface ResourcesScanner { // // /** // * Does the scanning // * // * @param path depending on context can be a file or directory path // * @return a list of matching resources // * @throws org.meridor.stecker.PluginException when something goes wrong during resources scanning // */ // List<Path> scan(Path path) throws PluginException; // // } // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/PluginLoaderTest.java import org.junit.Rule; import org.junit.Test; import org.meridor.stecker.impl.ManifestField; import org.meridor.stecker.impl.data.AnnotatedImpl; import org.meridor.stecker.impl.data.TestAnnotation; import org.meridor.stecker.impl.data.TestExtensionPoint; import org.meridor.stecker.impl.data.TestExtensionPointImpl; import org.meridor.stecker.interfaces.ClassesScanner; import org.meridor.stecker.interfaces.DependencyChecker; import org.meridor.stecker.interfaces.ManifestReader; import org.meridor.stecker.interfaces.PluginsProvider; import org.meridor.stecker.interfaces.ResourcesScanner; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.jar.Manifest; import java.util.stream.Collectors; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; package org.meridor.stecker; public class PluginLoaderTest { @Rule public TemporaryDirectory temporaryDirectory = new TemporaryDirectory(); @Test public void testFluentApi() throws PluginException { Path pluginDirectory = Paths.get("plugin-directory"); String fileGlob = "some-glob"; PluginsProvider pluginsProvider = mock(PluginsProvider.class); Path cacheDirectory = Paths.get("cache-directory"); Class[] extensionPointsArray = new Class[]{TestExtensionPoint.class, TestExtensionPoint.class}; //We intentionally duplicate extension points
ManifestReader manifestReader = mock(ManifestReader.class);
meridor/stecker
stecker-plugin-loader/src/test/java/org/meridor/stecker/PluginLoaderTest.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/ManifestField.java // public enum ManifestField { // // NAME("Plugin-Name"), // VERSION("Plugin-Version"), // DATE("Plugin-Date"), // DESCRIPTION("Plugin-Description"), // MAINTAINER("Plugin-Maintainer"), // DEPENDS("Plugin-Depends"), // CONFLICTS("Plugin-Conflicts"), // PROVIDES("Plugin-Provides"); // // private final String fieldName; // // private ManifestField(String fieldName) { // this.fieldName = fieldName; // } // // public String getFieldName() { // return fieldName; // } // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/data/AnnotatedImpl.java // @TestAnnotation // public class AnnotatedImpl { // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/data/TestExtensionPoint.java // public interface TestExtensionPoint { // // void doSomething(); // // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/data/TestExtensionPointImpl.java // public class TestExtensionPointImpl implements TestExtensionPoint { // // @Override // public void doSomething() { // new LibraryClass().act(); // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ClassesScanner.java // public interface ClassesScanner { // // /** // * Returns a mapping between extension point classes and plugin file classes. E.g. if extension point is // * an interface <b>A</b> and some plugin implements it in classes B and C then the mapping will be: A -&gt; (B, C). // * // * @param pluginFile plugin file to process // * @param extensionPoints a list of extension point classes // * @return mapping from extension point to implementations from a plugin // * @throws org.meridor.stecker.PluginException when something goes wrong during classes scanning // */ // ScanResult scan(Path pluginFile, List<Class> extensionPoints) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/DependencyChecker.java // public interface DependencyChecker { // // /** // * Checks dependencies and throws {@link org.meridor.stecker.PluginException} with {@link DependencyProblem} in case of issues // * // * @param pluginRegistry plugin registry object filled with data about all plugins // * @param pluginMetadata checked plugin metadata // * @throws org.meridor.stecker.PluginException when dependency issues occur // */ // void check(PluginsAware pluginRegistry, PluginMetadata pluginMetadata) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ManifestReader.java // public interface ManifestReader { // // /** // * Reads jar file manifest and returns plugin information stored there // * // * @param pluginFile plugin file to process // * @return plugin information in {@link org.meridor.stecker.PluginMetadata} format // * @throws org.meridor.stecker.PluginException when something goes wrong during manifest reading // */ // PluginMetadata read(Path pluginFile) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginsProvider.java // public interface PluginsProvider { // // /** // * Provides a list of plugins paths // * // * @param baseDirectory root directory to scan for plugins // * @return list of paths that seems to be plugins // * @throws org.meridor.stecker.PluginException when something goes wrong during base directory scanning // */ // List<Path> provide(Path baseDirectory) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ResourcesScanner.java // public interface ResourcesScanner { // // /** // * Does the scanning // * // * @param path depending on context can be a file or directory path // * @return a list of matching resources // * @throws org.meridor.stecker.PluginException when something goes wrong during resources scanning // */ // List<Path> scan(Path path) throws PluginException; // // }
import org.junit.Rule; import org.junit.Test; import org.meridor.stecker.impl.ManifestField; import org.meridor.stecker.impl.data.AnnotatedImpl; import org.meridor.stecker.impl.data.TestAnnotation; import org.meridor.stecker.impl.data.TestExtensionPoint; import org.meridor.stecker.impl.data.TestExtensionPointImpl; import org.meridor.stecker.interfaces.ClassesScanner; import org.meridor.stecker.interfaces.DependencyChecker; import org.meridor.stecker.interfaces.ManifestReader; import org.meridor.stecker.interfaces.PluginsProvider; import org.meridor.stecker.interfaces.ResourcesScanner; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.jar.Manifest; import java.util.stream.Collectors; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock;
package org.meridor.stecker; public class PluginLoaderTest { @Rule public TemporaryDirectory temporaryDirectory = new TemporaryDirectory(); @Test public void testFluentApi() throws PluginException { Path pluginDirectory = Paths.get("plugin-directory"); String fileGlob = "some-glob"; PluginsProvider pluginsProvider = mock(PluginsProvider.class); Path cacheDirectory = Paths.get("cache-directory"); Class[] extensionPointsArray = new Class[]{TestExtensionPoint.class, TestExtensionPoint.class}; //We intentionally duplicate extension points ManifestReader manifestReader = mock(ManifestReader.class);
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/ManifestField.java // public enum ManifestField { // // NAME("Plugin-Name"), // VERSION("Plugin-Version"), // DATE("Plugin-Date"), // DESCRIPTION("Plugin-Description"), // MAINTAINER("Plugin-Maintainer"), // DEPENDS("Plugin-Depends"), // CONFLICTS("Plugin-Conflicts"), // PROVIDES("Plugin-Provides"); // // private final String fieldName; // // private ManifestField(String fieldName) { // this.fieldName = fieldName; // } // // public String getFieldName() { // return fieldName; // } // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/data/AnnotatedImpl.java // @TestAnnotation // public class AnnotatedImpl { // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/data/TestExtensionPoint.java // public interface TestExtensionPoint { // // void doSomething(); // // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/data/TestExtensionPointImpl.java // public class TestExtensionPointImpl implements TestExtensionPoint { // // @Override // public void doSomething() { // new LibraryClass().act(); // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ClassesScanner.java // public interface ClassesScanner { // // /** // * Returns a mapping between extension point classes and plugin file classes. E.g. if extension point is // * an interface <b>A</b> and some plugin implements it in classes B and C then the mapping will be: A -&gt; (B, C). // * // * @param pluginFile plugin file to process // * @param extensionPoints a list of extension point classes // * @return mapping from extension point to implementations from a plugin // * @throws org.meridor.stecker.PluginException when something goes wrong during classes scanning // */ // ScanResult scan(Path pluginFile, List<Class> extensionPoints) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/DependencyChecker.java // public interface DependencyChecker { // // /** // * Checks dependencies and throws {@link org.meridor.stecker.PluginException} with {@link DependencyProblem} in case of issues // * // * @param pluginRegistry plugin registry object filled with data about all plugins // * @param pluginMetadata checked plugin metadata // * @throws org.meridor.stecker.PluginException when dependency issues occur // */ // void check(PluginsAware pluginRegistry, PluginMetadata pluginMetadata) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ManifestReader.java // public interface ManifestReader { // // /** // * Reads jar file manifest and returns plugin information stored there // * // * @param pluginFile plugin file to process // * @return plugin information in {@link org.meridor.stecker.PluginMetadata} format // * @throws org.meridor.stecker.PluginException when something goes wrong during manifest reading // */ // PluginMetadata read(Path pluginFile) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginsProvider.java // public interface PluginsProvider { // // /** // * Provides a list of plugins paths // * // * @param baseDirectory root directory to scan for plugins // * @return list of paths that seems to be plugins // * @throws org.meridor.stecker.PluginException when something goes wrong during base directory scanning // */ // List<Path> provide(Path baseDirectory) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ResourcesScanner.java // public interface ResourcesScanner { // // /** // * Does the scanning // * // * @param path depending on context can be a file or directory path // * @return a list of matching resources // * @throws org.meridor.stecker.PluginException when something goes wrong during resources scanning // */ // List<Path> scan(Path path) throws PluginException; // // } // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/PluginLoaderTest.java import org.junit.Rule; import org.junit.Test; import org.meridor.stecker.impl.ManifestField; import org.meridor.stecker.impl.data.AnnotatedImpl; import org.meridor.stecker.impl.data.TestAnnotation; import org.meridor.stecker.impl.data.TestExtensionPoint; import org.meridor.stecker.impl.data.TestExtensionPointImpl; import org.meridor.stecker.interfaces.ClassesScanner; import org.meridor.stecker.interfaces.DependencyChecker; import org.meridor.stecker.interfaces.ManifestReader; import org.meridor.stecker.interfaces.PluginsProvider; import org.meridor.stecker.interfaces.ResourcesScanner; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.jar.Manifest; import java.util.stream.Collectors; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; package org.meridor.stecker; public class PluginLoaderTest { @Rule public TemporaryDirectory temporaryDirectory = new TemporaryDirectory(); @Test public void testFluentApi() throws PluginException { Path pluginDirectory = Paths.get("plugin-directory"); String fileGlob = "some-glob"; PluginsProvider pluginsProvider = mock(PluginsProvider.class); Path cacheDirectory = Paths.get("cache-directory"); Class[] extensionPointsArray = new Class[]{TestExtensionPoint.class, TestExtensionPoint.class}; //We intentionally duplicate extension points ManifestReader manifestReader = mock(ManifestReader.class);
DependencyChecker dependencyChecker = mock(DependencyChecker.class);
meridor/stecker
stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/DefaultPluginsProvider.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginsProvider.java // public interface PluginsProvider { // // /** // * Provides a list of plugins paths // * // * @param baseDirectory root directory to scan for plugins // * @return list of paths that seems to be plugins // * @throws org.meridor.stecker.PluginException when something goes wrong during base directory scanning // */ // List<Path> provide(Path baseDirectory) throws PluginException; // // }
import org.meridor.stecker.PluginException; import org.meridor.stecker.interfaces.PluginsProvider; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.util.List; import java.util.stream.Collectors;
package org.meridor.stecker.impl; public class DefaultPluginsProvider implements PluginsProvider { private final String fileGlob; public DefaultPluginsProvider(String fileGlob) { this.fileGlob = fileGlob; } @Override
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginsProvider.java // public interface PluginsProvider { // // /** // * Provides a list of plugins paths // * // * @param baseDirectory root directory to scan for plugins // * @return list of paths that seems to be plugins // * @throws org.meridor.stecker.PluginException when something goes wrong during base directory scanning // */ // List<Path> provide(Path baseDirectory) throws PluginException; // // } // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/DefaultPluginsProvider.java import org.meridor.stecker.PluginException; import org.meridor.stecker.interfaces.PluginsProvider; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.util.List; import java.util.stream.Collectors; package org.meridor.stecker.impl; public class DefaultPluginsProvider implements PluginsProvider { private final String fileGlob; public DefaultPluginsProvider(String fileGlob) { this.fileGlob = fileGlob; } @Override
public List<Path> provide(Path pluginsDirectory) throws PluginException {
meridor/stecker
stecker-plugin-loader/src/test/java/org/meridor/stecker/dev/DevManifestReaderTest.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginMetadata.java // public interface PluginMetadata { // // /** // * Returns unique plugin name // * // * @return free-form string with name // */ // String getName(); // // /** // * Returns plugin version // * // * @return free-form string with version // */ // String getVersion(); // // /** // * Returns {@link Path} object corresponding to plugin file // * // * @return plugin {@link Path} object // */ // Path getPath(); // // /** // * Returns {@link org.meridor.stecker.interfaces.Dependency} object corresponding to this plugin // * // * @return dependency object // */ // Dependency getDependency(); // // /** // * Returns date when plugin was released // * // * @return local date or empty if not set // */ // Optional<ZonedDateTime> getDate(); // // /** // * Returns detailed plugin description // * // * @return description or empty if not set // */ // Optional<String> getDescription(); // // /** // * Returns maintainer email and name // * // * @return email and name in the format: <b>John Smith &lt;[email protected]&gt;</b> or empty if not set // */ // Optional<String> getMaintainer(); // // /** // * Returns a list of plugins required to make this plugin work // * // * @return possibly empty list with dependencies // */ // List<Dependency> getRequiredDependencies(); // // /** // * Returns a list of plugins that should be never installed simultaneously with this plugin // * // * @return possibly empty list with conflicting dependencies // */ // List<Dependency> getConflictingDependencies(); // // /** // * Returns a meta dependency which is provided by this plugin // * // * @return meta dependency or empty if not set // */ // Optional<Dependency> getProvidedDependency(); // // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/TemporaryDirectory.java // public class TemporaryDirectory extends ExternalResource { // // private Path directory; // // @Override // protected void before() throws Throwable { // super.before(); // create(); // } // // private void create() throws IOException { // directory = FileSystemHelper.createTempDirectory(); // } // // @Override // protected void after() { // super.after(); // remove(); // } // // private void remove() { // try { // FileSystemHelper.removeDirectory(directory); // } catch (IOException e) { // System.out.println("Can't remove temporary directory"); // e.printStackTrace(); // } // } // // public Path getDirectory() { // return directory; // } // // public Path createFile(String fileName, byte[] contents) throws IOException { // Path filePath = directory.resolve(fileName); // Files.write(filePath, contents); // return filePath; // } // }
import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.meridor.stecker.PluginMetadata; import org.meridor.stecker.TemporaryDirectory; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat;
package org.meridor.stecker.dev; public class DevManifestReaderTest { @Rule
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginMetadata.java // public interface PluginMetadata { // // /** // * Returns unique plugin name // * // * @return free-form string with name // */ // String getName(); // // /** // * Returns plugin version // * // * @return free-form string with version // */ // String getVersion(); // // /** // * Returns {@link Path} object corresponding to plugin file // * // * @return plugin {@link Path} object // */ // Path getPath(); // // /** // * Returns {@link org.meridor.stecker.interfaces.Dependency} object corresponding to this plugin // * // * @return dependency object // */ // Dependency getDependency(); // // /** // * Returns date when plugin was released // * // * @return local date or empty if not set // */ // Optional<ZonedDateTime> getDate(); // // /** // * Returns detailed plugin description // * // * @return description or empty if not set // */ // Optional<String> getDescription(); // // /** // * Returns maintainer email and name // * // * @return email and name in the format: <b>John Smith &lt;[email protected]&gt;</b> or empty if not set // */ // Optional<String> getMaintainer(); // // /** // * Returns a list of plugins required to make this plugin work // * // * @return possibly empty list with dependencies // */ // List<Dependency> getRequiredDependencies(); // // /** // * Returns a list of plugins that should be never installed simultaneously with this plugin // * // * @return possibly empty list with conflicting dependencies // */ // List<Dependency> getConflictingDependencies(); // // /** // * Returns a meta dependency which is provided by this plugin // * // * @return meta dependency or empty if not set // */ // Optional<Dependency> getProvidedDependency(); // // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/TemporaryDirectory.java // public class TemporaryDirectory extends ExternalResource { // // private Path directory; // // @Override // protected void before() throws Throwable { // super.before(); // create(); // } // // private void create() throws IOException { // directory = FileSystemHelper.createTempDirectory(); // } // // @Override // protected void after() { // super.after(); // remove(); // } // // private void remove() { // try { // FileSystemHelper.removeDirectory(directory); // } catch (IOException e) { // System.out.println("Can't remove temporary directory"); // e.printStackTrace(); // } // } // // public Path getDirectory() { // return directory; // } // // public Path createFile(String fileName, byte[] contents) throws IOException { // Path filePath = directory.resolve(fileName); // Files.write(filePath, contents); // return filePath; // } // } // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/dev/DevManifestReaderTest.java import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.meridor.stecker.PluginMetadata; import org.meridor.stecker.TemporaryDirectory; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; package org.meridor.stecker.dev; public class DevManifestReaderTest { @Rule
public TemporaryDirectory temporaryDirectory = new TemporaryDirectory();
meridor/stecker
stecker-plugin-loader/src/test/java/org/meridor/stecker/dev/DevManifestReaderTest.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginMetadata.java // public interface PluginMetadata { // // /** // * Returns unique plugin name // * // * @return free-form string with name // */ // String getName(); // // /** // * Returns plugin version // * // * @return free-form string with version // */ // String getVersion(); // // /** // * Returns {@link Path} object corresponding to plugin file // * // * @return plugin {@link Path} object // */ // Path getPath(); // // /** // * Returns {@link org.meridor.stecker.interfaces.Dependency} object corresponding to this plugin // * // * @return dependency object // */ // Dependency getDependency(); // // /** // * Returns date when plugin was released // * // * @return local date or empty if not set // */ // Optional<ZonedDateTime> getDate(); // // /** // * Returns detailed plugin description // * // * @return description or empty if not set // */ // Optional<String> getDescription(); // // /** // * Returns maintainer email and name // * // * @return email and name in the format: <b>John Smith &lt;[email protected]&gt;</b> or empty if not set // */ // Optional<String> getMaintainer(); // // /** // * Returns a list of plugins required to make this plugin work // * // * @return possibly empty list with dependencies // */ // List<Dependency> getRequiredDependencies(); // // /** // * Returns a list of plugins that should be never installed simultaneously with this plugin // * // * @return possibly empty list with conflicting dependencies // */ // List<Dependency> getConflictingDependencies(); // // /** // * Returns a meta dependency which is provided by this plugin // * // * @return meta dependency or empty if not set // */ // Optional<Dependency> getProvidedDependency(); // // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/TemporaryDirectory.java // public class TemporaryDirectory extends ExternalResource { // // private Path directory; // // @Override // protected void before() throws Throwable { // super.before(); // create(); // } // // private void create() throws IOException { // directory = FileSystemHelper.createTempDirectory(); // } // // @Override // protected void after() { // super.after(); // remove(); // } // // private void remove() { // try { // FileSystemHelper.removeDirectory(directory); // } catch (IOException e) { // System.out.println("Can't remove temporary directory"); // e.printStackTrace(); // } // } // // public Path getDirectory() { // return directory; // } // // public Path createFile(String fileName, byte[] contents) throws IOException { // Path filePath = directory.resolve(fileName); // Files.write(filePath, contents); // return filePath; // } // }
import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.meridor.stecker.PluginMetadata; import org.meridor.stecker.TemporaryDirectory; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat;
package org.meridor.stecker.dev; public class DevManifestReaderTest { @Rule public TemporaryDirectory temporaryDirectory = new TemporaryDirectory(); private static final String DIRECTORY_NAME = "some-plugin"; private Path pluginDirectory; @Before public void createDirectory() throws IOException { pluginDirectory = temporaryDirectory.getDirectory().resolve(DIRECTORY_NAME); Files.createDirectories(pluginDirectory); } @Test public void testRead() throws Exception { DevManifestReader devManifestReader = new DevManifestReader();
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginMetadata.java // public interface PluginMetadata { // // /** // * Returns unique plugin name // * // * @return free-form string with name // */ // String getName(); // // /** // * Returns plugin version // * // * @return free-form string with version // */ // String getVersion(); // // /** // * Returns {@link Path} object corresponding to plugin file // * // * @return plugin {@link Path} object // */ // Path getPath(); // // /** // * Returns {@link org.meridor.stecker.interfaces.Dependency} object corresponding to this plugin // * // * @return dependency object // */ // Dependency getDependency(); // // /** // * Returns date when plugin was released // * // * @return local date or empty if not set // */ // Optional<ZonedDateTime> getDate(); // // /** // * Returns detailed plugin description // * // * @return description or empty if not set // */ // Optional<String> getDescription(); // // /** // * Returns maintainer email and name // * // * @return email and name in the format: <b>John Smith &lt;[email protected]&gt;</b> or empty if not set // */ // Optional<String> getMaintainer(); // // /** // * Returns a list of plugins required to make this plugin work // * // * @return possibly empty list with dependencies // */ // List<Dependency> getRequiredDependencies(); // // /** // * Returns a list of plugins that should be never installed simultaneously with this plugin // * // * @return possibly empty list with conflicting dependencies // */ // List<Dependency> getConflictingDependencies(); // // /** // * Returns a meta dependency which is provided by this plugin // * // * @return meta dependency or empty if not set // */ // Optional<Dependency> getProvidedDependency(); // // } // // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/TemporaryDirectory.java // public class TemporaryDirectory extends ExternalResource { // // private Path directory; // // @Override // protected void before() throws Throwable { // super.before(); // create(); // } // // private void create() throws IOException { // directory = FileSystemHelper.createTempDirectory(); // } // // @Override // protected void after() { // super.after(); // remove(); // } // // private void remove() { // try { // FileSystemHelper.removeDirectory(directory); // } catch (IOException e) { // System.out.println("Can't remove temporary directory"); // e.printStackTrace(); // } // } // // public Path getDirectory() { // return directory; // } // // public Path createFile(String fileName, byte[] contents) throws IOException { // Path filePath = directory.resolve(fileName); // Files.write(filePath, contents); // return filePath; // } // } // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/dev/DevManifestReaderTest.java import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.meridor.stecker.PluginMetadata; import org.meridor.stecker.TemporaryDirectory; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; package org.meridor.stecker.dev; public class DevManifestReaderTest { @Rule public TemporaryDirectory temporaryDirectory = new TemporaryDirectory(); private static final String DIRECTORY_NAME = "some-plugin"; private Path pluginDirectory; @Before public void createDirectory() throws IOException { pluginDirectory = temporaryDirectory.getDirectory().resolve(DIRECTORY_NAME); Files.createDirectories(pluginDirectory); } @Test public void testRead() throws Exception { DevManifestReader devManifestReader = new DevManifestReader();
PluginMetadata pluginMetadata = devManifestReader.read(pluginDirectory);
meridor/stecker
stecker-plugin-loader/src/test/java/org/meridor/stecker/ResourcesWatcherTest.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ResourceChangedHandler.java // public interface ResourceChangedHandler { // // void onResourceChanged(Path resource); // // }
import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.meridor.stecker.interfaces.ResourceChangedHandler; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Timer; import java.util.TimerTask; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat;
Thread.sleep(1500); assertThat(testHandler.getChangesCount(), equalTo(1)); //Event should occur only once } private void scheduleFileChange() { final long SCHEDULE_DELAY = 1000; new Timer().schedule(new TimerTask() { @Override public void run() { try { Files.write(temporaryFile, randomString().getBytes()); } catch (IOException e) { throw new RuntimeException(e); } } }, SCHEDULE_DELAY); } private String randomString() { return String.valueOf(1e6 * Math.random()); } @After public void after() { if (resourcesWatcher != null) { resourcesWatcher.stop(); } }
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ResourceChangedHandler.java // public interface ResourceChangedHandler { // // void onResourceChanged(Path resource); // // } // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/ResourcesWatcherTest.java import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.meridor.stecker.interfaces.ResourceChangedHandler; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Timer; import java.util.TimerTask; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; Thread.sleep(1500); assertThat(testHandler.getChangesCount(), equalTo(1)); //Event should occur only once } private void scheduleFileChange() { final long SCHEDULE_DELAY = 1000; new Timer().schedule(new TimerTask() { @Override public void run() { try { Files.write(temporaryFile, randomString().getBytes()); } catch (IOException e) { throw new RuntimeException(e); } } }, SCHEDULE_DELAY); } private String randomString() { return String.valueOf(1e6 * Math.random()); } @After public void after() { if (resourcesWatcher != null) { resourcesWatcher.stop(); } }
private static class TestHandler implements ResourceChangedHandler {
meridor/stecker
stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/DefaultScanResult.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginImplementationsAware.java // public interface PluginImplementationsAware { // // /** // * Returns a list of present extension points // * // * @return a list of extension points // */ // List<Class> getExtensionPoints(); // // /** // * Returns classes implementing extension point // * // * @param extensionPoint extension point class // * @return a list of implementation classes // */ // List<Class> getImplementations(Class extensionPoint); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ScanResult.java // public interface ScanResult { // // ClassLoader getClassLoader(); // // PluginImplementationsAware getContents(); // // }
import org.meridor.stecker.interfaces.PluginImplementationsAware; import org.meridor.stecker.interfaces.ScanResult;
package org.meridor.stecker.impl; public class DefaultScanResult implements ScanResult { private final ClassLoader classLoader;
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginImplementationsAware.java // public interface PluginImplementationsAware { // // /** // * Returns a list of present extension points // * // * @return a list of extension points // */ // List<Class> getExtensionPoints(); // // /** // * Returns classes implementing extension point // * // * @param extensionPoint extension point class // * @return a list of implementation classes // */ // List<Class> getImplementations(Class extensionPoint); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/ScanResult.java // public interface ScanResult { // // ClassLoader getClassLoader(); // // PluginImplementationsAware getContents(); // // } // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/DefaultScanResult.java import org.meridor.stecker.interfaces.PluginImplementationsAware; import org.meridor.stecker.interfaces.ScanResult; package org.meridor.stecker.impl; public class DefaultScanResult implements ScanResult { private final ClassLoader classLoader;
private final PluginImplementationsAware contents;
meridor/stecker
stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/DefaultVersionComparator.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/VersionRelation.java // public enum VersionRelation { // // GREATER_THAN, // LESS_THAN, // EQUAL, // NOT_EQUAL, // IN_RANGE, // NOT_IN_RANGE // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/VersionComparator.java // public interface VersionComparator { // // /** // * Returns how actual version is related to required, e.g. whether it's less or greater than required or in required // * version range. See {@link org.meridor.stecker.VersionRelation} values for details. // * // * @param required required version or version range or nothing // * @param actual actual version or nothing // * @return how actual version relates to required // */ // VersionRelation compare(Optional<String> required, Optional<String> actual); // // }
import org.meridor.stecker.VersionRelation; import org.meridor.stecker.interfaces.VersionComparator; import java.util.Optional; import static org.meridor.stecker.VersionRelation.EQUAL; import static org.meridor.stecker.VersionRelation.GREATER_THAN; import static org.meridor.stecker.VersionRelation.IN_RANGE; import static org.meridor.stecker.VersionRelation.LESS_THAN; import static org.meridor.stecker.VersionRelation.NOT_EQUAL; import static org.meridor.stecker.VersionRelation.NOT_IN_RANGE;
package org.meridor.stecker.impl; public class DefaultVersionComparator implements VersionComparator { @Override
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/VersionRelation.java // public enum VersionRelation { // // GREATER_THAN, // LESS_THAN, // EQUAL, // NOT_EQUAL, // IN_RANGE, // NOT_IN_RANGE // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/VersionComparator.java // public interface VersionComparator { // // /** // * Returns how actual version is related to required, e.g. whether it's less or greater than required or in required // * version range. See {@link org.meridor.stecker.VersionRelation} values for details. // * // * @param required required version or version range or nothing // * @param actual actual version or nothing // * @return how actual version relates to required // */ // VersionRelation compare(Optional<String> required, Optional<String> actual); // // } // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/DefaultVersionComparator.java import org.meridor.stecker.VersionRelation; import org.meridor.stecker.interfaces.VersionComparator; import java.util.Optional; import static org.meridor.stecker.VersionRelation.EQUAL; import static org.meridor.stecker.VersionRelation.GREATER_THAN; import static org.meridor.stecker.VersionRelation.IN_RANGE; import static org.meridor.stecker.VersionRelation.LESS_THAN; import static org.meridor.stecker.VersionRelation.NOT_EQUAL; import static org.meridor.stecker.VersionRelation.NOT_IN_RANGE; package org.meridor.stecker.impl; public class DefaultVersionComparator implements VersionComparator { @Override
public VersionRelation compare(Optional<String> required, Optional<String> actual) {
meridor/stecker
stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/PluginUtils.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginImplementationsAware.java // public interface PluginImplementationsAware { // // /** // * Returns a list of present extension points // * // * @return a list of extension points // */ // List<Class> getExtensionPoints(); // // /** // * Returns classes implementing extension point // * // * @param extensionPoint extension point class // * @return a list of implementation classes // */ // List<Class> getImplementations(Class extensionPoint); // // }
import org.meridor.stecker.PluginException; import org.meridor.stecker.interfaces.PluginImplementationsAware; import java.io.IOException; import java.lang.annotation.Annotation; import java.net.URI; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.stream.Collectors;
public static FileTime getLastModificationTime(Path path) throws IOException { return Files.readAttributes(path, BasicFileAttributes.class).lastModifiedTime(); } public static Path getPluginImplementationDirectory(Path unpackedPluginDirectory) { return unpackedPluginDirectory.resolve(PLUGIN_IMPLEMENTATION_UNPACK_DIRECTORY); } public static List<Path> getMatchingFiles(Path pluginImplementationDirectory, String[] patterns) throws IOException { List<Path> matchingFiles = new ArrayList<>(); List<PathMatcher> pathMatchers = Arrays.stream(patterns) .map(FileSystems.getDefault()::getPathMatcher) .collect(Collectors.toList()); Files.walkFileTree(pluginImplementationDirectory, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException { for (PathMatcher pathMatcher : pathMatchers) { if (pathMatcher.matches(file)) { matchingFiles.add(file); } } return FileVisitResult.CONTINUE; } }); return matchingFiles; }
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginImplementationsAware.java // public interface PluginImplementationsAware { // // /** // * Returns a list of present extension points // * // * @return a list of extension points // */ // List<Class> getExtensionPoints(); // // /** // * Returns classes implementing extension point // * // * @param extensionPoint extension point class // * @return a list of implementation classes // */ // List<Class> getImplementations(Class extensionPoint); // // } // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/PluginUtils.java import org.meridor.stecker.PluginException; import org.meridor.stecker.interfaces.PluginImplementationsAware; import java.io.IOException; import java.lang.annotation.Annotation; import java.net.URI; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.stream.Collectors; public static FileTime getLastModificationTime(Path path) throws IOException { return Files.readAttributes(path, BasicFileAttributes.class).lastModifiedTime(); } public static Path getPluginImplementationDirectory(Path unpackedPluginDirectory) { return unpackedPluginDirectory.resolve(PLUGIN_IMPLEMENTATION_UNPACK_DIRECTORY); } public static List<Path> getMatchingFiles(Path pluginImplementationDirectory, String[] patterns) throws IOException { List<Path> matchingFiles = new ArrayList<>(); List<PathMatcher> pathMatchers = Arrays.stream(patterns) .map(FileSystems.getDefault()::getPathMatcher) .collect(Collectors.toList()); Files.walkFileTree(pluginImplementationDirectory, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException { for (PathMatcher pathMatcher : pathMatchers) { if (pathMatcher.matches(file)) { matchingFiles.add(file); } } return FileVisitResult.CONTINUE; } }); return matchingFiles; }
public static PluginImplementationsAware getMatchingClasses(List<Class> extensionPoints, Path pluginImplementationDirectory, ClassLoader classLoader) throws Exception {
meridor/stecker
stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/PluginUtils.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginImplementationsAware.java // public interface PluginImplementationsAware { // // /** // * Returns a list of present extension points // * // * @return a list of extension points // */ // List<Class> getExtensionPoints(); // // /** // * Returns classes implementing extension point // * // * @param extensionPoint extension point class // * @return a list of implementation classes // */ // List<Class> getImplementations(Class extensionPoint); // // }
import org.meridor.stecker.PluginException; import org.meridor.stecker.interfaces.PluginImplementationsAware; import java.io.IOException; import java.lang.annotation.Annotation; import java.net.URI; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.stream.Collectors;
} } } return new ClassesRegistry(matchingClasses); } private static String getClassName(Path pluginImplementationDirectory, Path classFile) { String className = pluginImplementationDirectory .relativize(classFile) .toString() .replace(JAR_DIRECTORY_SEPARATOR, PACKAGE_SEPARATOR) .replace(CLASS_FILE_EXTENSION, ""); if (className.startsWith(PACKAGE_SEPARATOR) && className.length() > 1) { className = className.substring(1); } return className; } private static boolean isAnnotatedWith(Class<?> currentClass, Class<?> extensionPoint) { return extensionPoint.isAnnotation() && currentClass.isAnnotationPresent(extensionPoint.asSubclass(Annotation.class)); } private static boolean isSubclassOf(Class<?> currentClass, Class<?> extensionPoint) { return extensionPoint.isAssignableFrom(currentClass); }
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginImplementationsAware.java // public interface PluginImplementationsAware { // // /** // * Returns a list of present extension points // * // * @return a list of extension points // */ // List<Class> getExtensionPoints(); // // /** // * Returns classes implementing extension point // * // * @param extensionPoint extension point class // * @return a list of implementation classes // */ // List<Class> getImplementations(Class extensionPoint); // // } // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/PluginUtils.java import org.meridor.stecker.PluginException; import org.meridor.stecker.interfaces.PluginImplementationsAware; import java.io.IOException; import java.lang.annotation.Annotation; import java.net.URI; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.stream.Collectors; } } } return new ClassesRegistry(matchingClasses); } private static String getClassName(Path pluginImplementationDirectory, Path classFile) { String className = pluginImplementationDirectory .relativize(classFile) .toString() .replace(JAR_DIRECTORY_SEPARATOR, PACKAGE_SEPARATOR) .replace(CLASS_FILE_EXTENSION, ""); if (className.startsWith(PACKAGE_SEPARATOR) && className.length() > 1) { className = className.substring(1); } return className; } private static boolean isAnnotatedWith(Class<?> currentClass, Class<?> extensionPoint) { return extensionPoint.isAnnotation() && currentClass.isAnnotationPresent(extensionPoint.asSubclass(Annotation.class)); } private static boolean isSubclassOf(Class<?> currentClass, Class<?> extensionPoint) { return extensionPoint.isAssignableFrom(currentClass); }
public static ClassLoader getClassLoader(Path classesPath, Path dependenciesPath) throws PluginException {
meridor/stecker
stecker-plugin-loader/src/main/java/org/meridor/stecker/dev/DevPluginsProvider.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginsProvider.java // public interface PluginsProvider { // // /** // * Provides a list of plugins paths // * // * @param baseDirectory root directory to scan for plugins // * @return list of paths that seems to be plugins // * @throws org.meridor.stecker.PluginException when something goes wrong during base directory scanning // */ // List<Path> provide(Path baseDirectory) throws PluginException; // // }
import org.meridor.stecker.PluginException; import org.meridor.stecker.interfaces.PluginsProvider; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.stream.Collectors;
package org.meridor.stecker.dev; public class DevPluginsProvider implements PluginsProvider { @Override
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginsProvider.java // public interface PluginsProvider { // // /** // * Provides a list of plugins paths // * // * @param baseDirectory root directory to scan for plugins // * @return list of paths that seems to be plugins // * @throws org.meridor.stecker.PluginException when something goes wrong during base directory scanning // */ // List<Path> provide(Path baseDirectory) throws PluginException; // // } // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/dev/DevPluginsProvider.java import org.meridor.stecker.PluginException; import org.meridor.stecker.interfaces.PluginsProvider; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.stream.Collectors; package org.meridor.stecker.dev; public class DevPluginsProvider implements PluginsProvider { @Override
public List<Path> provide(Path baseDirectory) throws PluginException {
meridor/stecker
stecker-plugin-loader/src/test/java/org/meridor/stecker/TemporaryDirectory.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/FileSystemHelper.java // public class FileSystemHelper { // // public static Path createTempDirectory() throws IOException { // return Files.createTempDirectory("test"); // } // // public static void removeDirectory(Path directory) throws IOException { // Files.walkFileTree(directory, new SimpleFileVisitor<Path>() { // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException { // Files.delete(file); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException { // Files.delete(dir); // return FileVisitResult.CONTINUE; // } // }); // } // // }
import org.junit.rules.ExternalResource; import org.meridor.stecker.impl.FileSystemHelper; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path;
package org.meridor.stecker; public class TemporaryDirectory extends ExternalResource { private Path directory; @Override protected void before() throws Throwable { super.before(); create(); } private void create() throws IOException {
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/FileSystemHelper.java // public class FileSystemHelper { // // public static Path createTempDirectory() throws IOException { // return Files.createTempDirectory("test"); // } // // public static void removeDirectory(Path directory) throws IOException { // Files.walkFileTree(directory, new SimpleFileVisitor<Path>() { // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException { // Files.delete(file); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException { // Files.delete(dir); // return FileVisitResult.CONTINUE; // } // }); // } // // } // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/TemporaryDirectory.java import org.junit.rules.ExternalResource; import org.meridor.stecker.impl.FileSystemHelper; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; package org.meridor.stecker; public class TemporaryDirectory extends ExternalResource { private Path directory; @Override protected void before() throws Throwable { super.before(); create(); } private void create() throws IOException {
directory = FileSystemHelper.createTempDirectory();
meridor/stecker
stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/DefaultVersionComparatorTest.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/VersionRelation.java // public enum VersionRelation { // // GREATER_THAN, // LESS_THAN, // EQUAL, // NOT_EQUAL, // IN_RANGE, // NOT_IN_RANGE // // }
import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.meridor.stecker.VersionRelation; import java.util.Arrays; import java.util.Collection; import java.util.Optional; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat;
package org.meridor.stecker.impl; @RunWith(Parameterized.class) public class DefaultVersionComparatorTest { private final Optional<String> required; private final Optional<String> actual;
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/VersionRelation.java // public enum VersionRelation { // // GREATER_THAN, // LESS_THAN, // EQUAL, // NOT_EQUAL, // IN_RANGE, // NOT_IN_RANGE // // } // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/DefaultVersionComparatorTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.meridor.stecker.VersionRelation; import java.util.Arrays; import java.util.Collection; import java.util.Optional; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; package org.meridor.stecker.impl; @RunWith(Parameterized.class) public class DefaultVersionComparatorTest { private final Optional<String> required; private final Optional<String> actual;
private final VersionRelation relation;
meridor/stecker
stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/PluginMetadataContainer.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginMetadata.java // public interface PluginMetadata { // // /** // * Returns unique plugin name // * // * @return free-form string with name // */ // String getName(); // // /** // * Returns plugin version // * // * @return free-form string with version // */ // String getVersion(); // // /** // * Returns {@link Path} object corresponding to plugin file // * // * @return plugin {@link Path} object // */ // Path getPath(); // // /** // * Returns {@link org.meridor.stecker.interfaces.Dependency} object corresponding to this plugin // * // * @return dependency object // */ // Dependency getDependency(); // // /** // * Returns date when plugin was released // * // * @return local date or empty if not set // */ // Optional<ZonedDateTime> getDate(); // // /** // * Returns detailed plugin description // * // * @return description or empty if not set // */ // Optional<String> getDescription(); // // /** // * Returns maintainer email and name // * // * @return email and name in the format: <b>John Smith &lt;[email protected]&gt;</b> or empty if not set // */ // Optional<String> getMaintainer(); // // /** // * Returns a list of plugins required to make this plugin work // * // * @return possibly empty list with dependencies // */ // List<Dependency> getRequiredDependencies(); // // /** // * Returns a list of plugins that should be never installed simultaneously with this plugin // * // * @return possibly empty list with conflicting dependencies // */ // List<Dependency> getConflictingDependencies(); // // /** // * Returns a meta dependency which is provided by this plugin // * // * @return meta dependency or empty if not set // */ // Optional<Dependency> getProvidedDependency(); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/Dependency.java // public interface Dependency { // // /** // * Returns dependency name // * // * @return dependency name // */ // String getName(); // // /** // * Returns dependency version if present // * // * @return dependency version if present and empty otherwise // */ // Optional<String> getVersion(); // // /** // * Forces to override {@link Object#equals(Object)} // * // * @param anotherDependency dependency to compare to // * @return true if equal and false otherwise // */ // boolean equals(Object anotherDependency); // // /** // * Forces to override {@link Object#hashCode()} // * // * @return instance hash code // */ // int hashCode(); // // /** // * Returns dependency string representation // * // * @return dependency string representation // */ // String toString(); // // }
import org.meridor.stecker.PluginMetadata; import org.meridor.stecker.interfaces.Dependency; import java.nio.file.Path; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.List; import java.util.Optional;
package org.meridor.stecker.impl; public class PluginMetadataContainer implements PluginMetadata { private final String name; private final String version; private final Path filePath;
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginMetadata.java // public interface PluginMetadata { // // /** // * Returns unique plugin name // * // * @return free-form string with name // */ // String getName(); // // /** // * Returns plugin version // * // * @return free-form string with version // */ // String getVersion(); // // /** // * Returns {@link Path} object corresponding to plugin file // * // * @return plugin {@link Path} object // */ // Path getPath(); // // /** // * Returns {@link org.meridor.stecker.interfaces.Dependency} object corresponding to this plugin // * // * @return dependency object // */ // Dependency getDependency(); // // /** // * Returns date when plugin was released // * // * @return local date or empty if not set // */ // Optional<ZonedDateTime> getDate(); // // /** // * Returns detailed plugin description // * // * @return description or empty if not set // */ // Optional<String> getDescription(); // // /** // * Returns maintainer email and name // * // * @return email and name in the format: <b>John Smith &lt;[email protected]&gt;</b> or empty if not set // */ // Optional<String> getMaintainer(); // // /** // * Returns a list of plugins required to make this plugin work // * // * @return possibly empty list with dependencies // */ // List<Dependency> getRequiredDependencies(); // // /** // * Returns a list of plugins that should be never installed simultaneously with this plugin // * // * @return possibly empty list with conflicting dependencies // */ // List<Dependency> getConflictingDependencies(); // // /** // * Returns a meta dependency which is provided by this plugin // * // * @return meta dependency or empty if not set // */ // Optional<Dependency> getProvidedDependency(); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/Dependency.java // public interface Dependency { // // /** // * Returns dependency name // * // * @return dependency name // */ // String getName(); // // /** // * Returns dependency version if present // * // * @return dependency version if present and empty otherwise // */ // Optional<String> getVersion(); // // /** // * Forces to override {@link Object#equals(Object)} // * // * @param anotherDependency dependency to compare to // * @return true if equal and false otherwise // */ // boolean equals(Object anotherDependency); // // /** // * Forces to override {@link Object#hashCode()} // * // * @return instance hash code // */ // int hashCode(); // // /** // * Returns dependency string representation // * // * @return dependency string representation // */ // String toString(); // // } // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/PluginMetadataContainer.java import org.meridor.stecker.PluginMetadata; import org.meridor.stecker.interfaces.Dependency; import java.nio.file.Path; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.List; import java.util.Optional; package org.meridor.stecker.impl; public class PluginMetadataContainer implements PluginMetadata { private final String name; private final String version; private final Path filePath;
private final List<Dependency> depends = new ArrayList<>();
meridor/stecker
stecker-plugin-loader/src/test/java/org/meridor/stecker/dev/DevPluginsProviderTest.java
// Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/TemporaryDirectory.java // public class TemporaryDirectory extends ExternalResource { // // private Path directory; // // @Override // protected void before() throws Throwable { // super.before(); // create(); // } // // private void create() throws IOException { // directory = FileSystemHelper.createTempDirectory(); // } // // @Override // protected void after() { // super.after(); // remove(); // } // // private void remove() { // try { // FileSystemHelper.removeDirectory(directory); // } catch (IOException e) { // System.out.println("Can't remove temporary directory"); // e.printStackTrace(); // } // } // // public Path getDirectory() { // return directory; // } // // public Path createFile(String fileName, byte[] contents) throws IOException { // Path filePath = directory.resolve(fileName); // Files.write(filePath, contents); // return filePath; // } // }
import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.meridor.stecker.TemporaryDirectory; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat;
package org.meridor.stecker.dev; public class DevPluginsProviderTest { @Rule
// Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/TemporaryDirectory.java // public class TemporaryDirectory extends ExternalResource { // // private Path directory; // // @Override // protected void before() throws Throwable { // super.before(); // create(); // } // // private void create() throws IOException { // directory = FileSystemHelper.createTempDirectory(); // } // // @Override // protected void after() { // super.after(); // remove(); // } // // private void remove() { // try { // FileSystemHelper.removeDirectory(directory); // } catch (IOException e) { // System.out.println("Can't remove temporary directory"); // e.printStackTrace(); // } // } // // public Path getDirectory() { // return directory; // } // // public Path createFile(String fileName, byte[] contents) throws IOException { // Path filePath = directory.resolve(fileName); // Files.write(filePath, contents); // return filePath; // } // } // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/dev/DevPluginsProviderTest.java import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.meridor.stecker.TemporaryDirectory; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; package org.meridor.stecker.dev; public class DevPluginsProviderTest { @Rule
public TemporaryDirectory temporaryDirectory = new TemporaryDirectory();
meridor/stecker
stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/DefaultDependencyCheckerTest.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginMetadata.java // public interface PluginMetadata { // // /** // * Returns unique plugin name // * // * @return free-form string with name // */ // String getName(); // // /** // * Returns plugin version // * // * @return free-form string with version // */ // String getVersion(); // // /** // * Returns {@link Path} object corresponding to plugin file // * // * @return plugin {@link Path} object // */ // Path getPath(); // // /** // * Returns {@link org.meridor.stecker.interfaces.Dependency} object corresponding to this plugin // * // * @return dependency object // */ // Dependency getDependency(); // // /** // * Returns date when plugin was released // * // * @return local date or empty if not set // */ // Optional<ZonedDateTime> getDate(); // // /** // * Returns detailed plugin description // * // * @return description or empty if not set // */ // Optional<String> getDescription(); // // /** // * Returns maintainer email and name // * // * @return email and name in the format: <b>John Smith &lt;[email protected]&gt;</b> or empty if not set // */ // Optional<String> getMaintainer(); // // /** // * Returns a list of plugins required to make this plugin work // * // * @return possibly empty list with dependencies // */ // List<Dependency> getRequiredDependencies(); // // /** // * Returns a list of plugins that should be never installed simultaneously with this plugin // * // * @return possibly empty list with conflicting dependencies // */ // List<Dependency> getConflictingDependencies(); // // /** // * Returns a meta dependency which is provided by this plugin // * // * @return meta dependency or empty if not set // */ // Optional<Dependency> getProvidedDependency(); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/Dependency.java // public interface Dependency { // // /** // * Returns dependency name // * // * @return dependency name // */ // String getName(); // // /** // * Returns dependency version if present // * // * @return dependency version if present and empty otherwise // */ // Optional<String> getVersion(); // // /** // * Forces to override {@link Object#equals(Object)} // * // * @param anotherDependency dependency to compare to // * @return true if equal and false otherwise // */ // boolean equals(Object anotherDependency); // // /** // * Forces to override {@link Object#hashCode()} // * // * @return instance hash code // */ // int hashCode(); // // /** // * Returns dependency string representation // * // * @return dependency string representation // */ // String toString(); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginsAware.java // public interface PluginsAware { // // /** // * Returns information about plugin by its plugin name // * // * @param pluginName plugin name to process // * @return information about plugin or empty if not present // */ // Optional<PluginMetadata> getPlugin(String pluginName); // // /** // * Returns a list of dependencies in the registry // * // * @return a list of dependencies // */ // List<String> getPluginNames(); // // }
import org.junit.Test; import org.meridor.stecker.PluginException; import org.meridor.stecker.PluginMetadata; import org.meridor.stecker.interfaces.Dependency; import org.meridor.stecker.interfaces.PluginsAware; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package org.meridor.stecker.impl; public class DefaultDependencyCheckerTest { private static final String MISSING_NAME = "missing";
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginMetadata.java // public interface PluginMetadata { // // /** // * Returns unique plugin name // * // * @return free-form string with name // */ // String getName(); // // /** // * Returns plugin version // * // * @return free-form string with version // */ // String getVersion(); // // /** // * Returns {@link Path} object corresponding to plugin file // * // * @return plugin {@link Path} object // */ // Path getPath(); // // /** // * Returns {@link org.meridor.stecker.interfaces.Dependency} object corresponding to this plugin // * // * @return dependency object // */ // Dependency getDependency(); // // /** // * Returns date when plugin was released // * // * @return local date or empty if not set // */ // Optional<ZonedDateTime> getDate(); // // /** // * Returns detailed plugin description // * // * @return description or empty if not set // */ // Optional<String> getDescription(); // // /** // * Returns maintainer email and name // * // * @return email and name in the format: <b>John Smith &lt;[email protected]&gt;</b> or empty if not set // */ // Optional<String> getMaintainer(); // // /** // * Returns a list of plugins required to make this plugin work // * // * @return possibly empty list with dependencies // */ // List<Dependency> getRequiredDependencies(); // // /** // * Returns a list of plugins that should be never installed simultaneously with this plugin // * // * @return possibly empty list with conflicting dependencies // */ // List<Dependency> getConflictingDependencies(); // // /** // * Returns a meta dependency which is provided by this plugin // * // * @return meta dependency or empty if not set // */ // Optional<Dependency> getProvidedDependency(); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/Dependency.java // public interface Dependency { // // /** // * Returns dependency name // * // * @return dependency name // */ // String getName(); // // /** // * Returns dependency version if present // * // * @return dependency version if present and empty otherwise // */ // Optional<String> getVersion(); // // /** // * Forces to override {@link Object#equals(Object)} // * // * @param anotherDependency dependency to compare to // * @return true if equal and false otherwise // */ // boolean equals(Object anotherDependency); // // /** // * Forces to override {@link Object#hashCode()} // * // * @return instance hash code // */ // int hashCode(); // // /** // * Returns dependency string representation // * // * @return dependency string representation // */ // String toString(); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginsAware.java // public interface PluginsAware { // // /** // * Returns information about plugin by its plugin name // * // * @param pluginName plugin name to process // * @return information about plugin or empty if not present // */ // Optional<PluginMetadata> getPlugin(String pluginName); // // /** // * Returns a list of dependencies in the registry // * // * @return a list of dependencies // */ // List<String> getPluginNames(); // // } // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/DefaultDependencyCheckerTest.java import org.junit.Test; import org.meridor.stecker.PluginException; import org.meridor.stecker.PluginMetadata; import org.meridor.stecker.interfaces.Dependency; import org.meridor.stecker.interfaces.PluginsAware; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package org.meridor.stecker.impl; public class DefaultDependencyCheckerTest { private static final String MISSING_NAME = "missing";
private static final Dependency MISSING_DEPENDENCY = new DependencyContainer(MISSING_NAME);
meridor/stecker
stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/DefaultDependencyCheckerTest.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginMetadata.java // public interface PluginMetadata { // // /** // * Returns unique plugin name // * // * @return free-form string with name // */ // String getName(); // // /** // * Returns plugin version // * // * @return free-form string with version // */ // String getVersion(); // // /** // * Returns {@link Path} object corresponding to plugin file // * // * @return plugin {@link Path} object // */ // Path getPath(); // // /** // * Returns {@link org.meridor.stecker.interfaces.Dependency} object corresponding to this plugin // * // * @return dependency object // */ // Dependency getDependency(); // // /** // * Returns date when plugin was released // * // * @return local date or empty if not set // */ // Optional<ZonedDateTime> getDate(); // // /** // * Returns detailed plugin description // * // * @return description or empty if not set // */ // Optional<String> getDescription(); // // /** // * Returns maintainer email and name // * // * @return email and name in the format: <b>John Smith &lt;[email protected]&gt;</b> or empty if not set // */ // Optional<String> getMaintainer(); // // /** // * Returns a list of plugins required to make this plugin work // * // * @return possibly empty list with dependencies // */ // List<Dependency> getRequiredDependencies(); // // /** // * Returns a list of plugins that should be never installed simultaneously with this plugin // * // * @return possibly empty list with conflicting dependencies // */ // List<Dependency> getConflictingDependencies(); // // /** // * Returns a meta dependency which is provided by this plugin // * // * @return meta dependency or empty if not set // */ // Optional<Dependency> getProvidedDependency(); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/Dependency.java // public interface Dependency { // // /** // * Returns dependency name // * // * @return dependency name // */ // String getName(); // // /** // * Returns dependency version if present // * // * @return dependency version if present and empty otherwise // */ // Optional<String> getVersion(); // // /** // * Forces to override {@link Object#equals(Object)} // * // * @param anotherDependency dependency to compare to // * @return true if equal and false otherwise // */ // boolean equals(Object anotherDependency); // // /** // * Forces to override {@link Object#hashCode()} // * // * @return instance hash code // */ // int hashCode(); // // /** // * Returns dependency string representation // * // * @return dependency string representation // */ // String toString(); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginsAware.java // public interface PluginsAware { // // /** // * Returns information about plugin by its plugin name // * // * @param pluginName plugin name to process // * @return information about plugin or empty if not present // */ // Optional<PluginMetadata> getPlugin(String pluginName); // // /** // * Returns a list of dependencies in the registry // * // * @return a list of dependencies // */ // List<String> getPluginNames(); // // }
import org.junit.Test; import org.meridor.stecker.PluginException; import org.meridor.stecker.PluginMetadata; import org.meridor.stecker.interfaces.Dependency; import org.meridor.stecker.interfaces.PluginsAware; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package org.meridor.stecker.impl; public class DefaultDependencyCheckerTest { private static final String MISSING_NAME = "missing"; private static final Dependency MISSING_DEPENDENCY = new DependencyContainer(MISSING_NAME); private static final String FIXED_VERSION_NAME = "fixed"; private static final Dependency DEPENDENCY_WITH_FIXED_VERSION = new DependencyContainer(FIXED_VERSION_NAME, "1.0"); private static final String VERSION_RANGE_NAME = "range"; private static final Dependency DEPENDENCY_WITH_VERSION_RANGE = new DependencyContainer(VERSION_RANGE_NAME, "[1.0,1.1]");
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginMetadata.java // public interface PluginMetadata { // // /** // * Returns unique plugin name // * // * @return free-form string with name // */ // String getName(); // // /** // * Returns plugin version // * // * @return free-form string with version // */ // String getVersion(); // // /** // * Returns {@link Path} object corresponding to plugin file // * // * @return plugin {@link Path} object // */ // Path getPath(); // // /** // * Returns {@link org.meridor.stecker.interfaces.Dependency} object corresponding to this plugin // * // * @return dependency object // */ // Dependency getDependency(); // // /** // * Returns date when plugin was released // * // * @return local date or empty if not set // */ // Optional<ZonedDateTime> getDate(); // // /** // * Returns detailed plugin description // * // * @return description or empty if not set // */ // Optional<String> getDescription(); // // /** // * Returns maintainer email and name // * // * @return email and name in the format: <b>John Smith &lt;[email protected]&gt;</b> or empty if not set // */ // Optional<String> getMaintainer(); // // /** // * Returns a list of plugins required to make this plugin work // * // * @return possibly empty list with dependencies // */ // List<Dependency> getRequiredDependencies(); // // /** // * Returns a list of plugins that should be never installed simultaneously with this plugin // * // * @return possibly empty list with conflicting dependencies // */ // List<Dependency> getConflictingDependencies(); // // /** // * Returns a meta dependency which is provided by this plugin // * // * @return meta dependency or empty if not set // */ // Optional<Dependency> getProvidedDependency(); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/Dependency.java // public interface Dependency { // // /** // * Returns dependency name // * // * @return dependency name // */ // String getName(); // // /** // * Returns dependency version if present // * // * @return dependency version if present and empty otherwise // */ // Optional<String> getVersion(); // // /** // * Forces to override {@link Object#equals(Object)} // * // * @param anotherDependency dependency to compare to // * @return true if equal and false otherwise // */ // boolean equals(Object anotherDependency); // // /** // * Forces to override {@link Object#hashCode()} // * // * @return instance hash code // */ // int hashCode(); // // /** // * Returns dependency string representation // * // * @return dependency string representation // */ // String toString(); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginsAware.java // public interface PluginsAware { // // /** // * Returns information about plugin by its plugin name // * // * @param pluginName plugin name to process // * @return information about plugin or empty if not present // */ // Optional<PluginMetadata> getPlugin(String pluginName); // // /** // * Returns a list of dependencies in the registry // * // * @return a list of dependencies // */ // List<String> getPluginNames(); // // } // Path: stecker-plugin-loader/src/test/java/org/meridor/stecker/impl/DefaultDependencyCheckerTest.java import org.junit.Test; import org.meridor.stecker.PluginException; import org.meridor.stecker.PluginMetadata; import org.meridor.stecker.interfaces.Dependency; import org.meridor.stecker.interfaces.PluginsAware; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package org.meridor.stecker.impl; public class DefaultDependencyCheckerTest { private static final String MISSING_NAME = "missing"; private static final Dependency MISSING_DEPENDENCY = new DependencyContainer(MISSING_NAME); private static final String FIXED_VERSION_NAME = "fixed"; private static final Dependency DEPENDENCY_WITH_FIXED_VERSION = new DependencyContainer(FIXED_VERSION_NAME, "1.0"); private static final String VERSION_RANGE_NAME = "range"; private static final Dependency DEPENDENCY_WITH_VERSION_RANGE = new DependencyContainer(VERSION_RANGE_NAME, "[1.0,1.1]");
private static PluginMetadata getPluginDependenciesMetadata(final Dependency[] requiredDependencies, final Dependency[] conflictingDependencies) {
meridor/stecker
stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/PluginRegistryContainer.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginMetadata.java // public interface PluginMetadata { // // /** // * Returns unique plugin name // * // * @return free-form string with name // */ // String getName(); // // /** // * Returns plugin version // * // * @return free-form string with version // */ // String getVersion(); // // /** // * Returns {@link Path} object corresponding to plugin file // * // * @return plugin {@link Path} object // */ // Path getPath(); // // /** // * Returns {@link org.meridor.stecker.interfaces.Dependency} object corresponding to this plugin // * // * @return dependency object // */ // Dependency getDependency(); // // /** // * Returns date when plugin was released // * // * @return local date or empty if not set // */ // Optional<ZonedDateTime> getDate(); // // /** // * Returns detailed plugin description // * // * @return description or empty if not set // */ // Optional<String> getDescription(); // // /** // * Returns maintainer email and name // * // * @return email and name in the format: <b>John Smith &lt;[email protected]&gt;</b> or empty if not set // */ // Optional<String> getMaintainer(); // // /** // * Returns a list of plugins required to make this plugin work // * // * @return possibly empty list with dependencies // */ // List<Dependency> getRequiredDependencies(); // // /** // * Returns a list of plugins that should be never installed simultaneously with this plugin // * // * @return possibly empty list with conflicting dependencies // */ // List<Dependency> getConflictingDependencies(); // // /** // * Returns a meta dependency which is provided by this plugin // * // * @return meta dependency or empty if not set // */ // Optional<Dependency> getProvidedDependency(); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginRegistry.java // public interface PluginRegistry extends PluginsAware, ImplementationsAware, ResourcesAware, ClassLoaderAware { // // /** // * Add extension point implementations to registry // * // * @param pluginMetadata plugin metadata object // * @param extensionPoint extension point class // * @param implementationClasses a list of implementation classes // */ // void addImplementations(PluginMetadata pluginMetadata, Class extensionPoint, List<Class> implementationClasses); // // /** // * Adds information about new plugin // * // * @param pluginMetadata plugin metadata object // * @throws PluginException when another plugin provides the same virtual dependency // */ // void addPlugin(PluginMetadata pluginMetadata) throws PluginException; // // /** // * Add resources for specific plugin // * // * @param pluginMetadata plugin metadata object // * @param resources plugin resources // */ // void addResources(PluginMetadata pluginMetadata, List<Path> resources); // // /** // * Adds class loader instance for specific plugin // * // * @param pluginMetadata plugin metadata object // * @param classLoader class loader instance corresponding to current plugin // */ // void addClassLoader(PluginMetadata pluginMetadata, ClassLoader classLoader); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/Dependency.java // public interface Dependency { // // /** // * Returns dependency name // * // * @return dependency name // */ // String getName(); // // /** // * Returns dependency version if present // * // * @return dependency version if present and empty otherwise // */ // Optional<String> getVersion(); // // /** // * Forces to override {@link Object#equals(Object)} // * // * @param anotherDependency dependency to compare to // * @return true if equal and false otherwise // */ // boolean equals(Object anotherDependency); // // /** // * Forces to override {@link Object#hashCode()} // * // * @return instance hash code // */ // int hashCode(); // // /** // * Returns dependency string representation // * // * @return dependency string representation // */ // String toString(); // // }
import org.meridor.stecker.PluginException; import org.meridor.stecker.PluginMetadata; import org.meridor.stecker.PluginRegistry; import org.meridor.stecker.interfaces.Dependency; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors;
package org.meridor.stecker.impl; public class PluginRegistryContainer implements PluginRegistry { private final Map<String, ClassesRegistry> registry = new HashMap<>();
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginMetadata.java // public interface PluginMetadata { // // /** // * Returns unique plugin name // * // * @return free-form string with name // */ // String getName(); // // /** // * Returns plugin version // * // * @return free-form string with version // */ // String getVersion(); // // /** // * Returns {@link Path} object corresponding to plugin file // * // * @return plugin {@link Path} object // */ // Path getPath(); // // /** // * Returns {@link org.meridor.stecker.interfaces.Dependency} object corresponding to this plugin // * // * @return dependency object // */ // Dependency getDependency(); // // /** // * Returns date when plugin was released // * // * @return local date or empty if not set // */ // Optional<ZonedDateTime> getDate(); // // /** // * Returns detailed plugin description // * // * @return description or empty if not set // */ // Optional<String> getDescription(); // // /** // * Returns maintainer email and name // * // * @return email and name in the format: <b>John Smith &lt;[email protected]&gt;</b> or empty if not set // */ // Optional<String> getMaintainer(); // // /** // * Returns a list of plugins required to make this plugin work // * // * @return possibly empty list with dependencies // */ // List<Dependency> getRequiredDependencies(); // // /** // * Returns a list of plugins that should be never installed simultaneously with this plugin // * // * @return possibly empty list with conflicting dependencies // */ // List<Dependency> getConflictingDependencies(); // // /** // * Returns a meta dependency which is provided by this plugin // * // * @return meta dependency or empty if not set // */ // Optional<Dependency> getProvidedDependency(); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginRegistry.java // public interface PluginRegistry extends PluginsAware, ImplementationsAware, ResourcesAware, ClassLoaderAware { // // /** // * Add extension point implementations to registry // * // * @param pluginMetadata plugin metadata object // * @param extensionPoint extension point class // * @param implementationClasses a list of implementation classes // */ // void addImplementations(PluginMetadata pluginMetadata, Class extensionPoint, List<Class> implementationClasses); // // /** // * Adds information about new plugin // * // * @param pluginMetadata plugin metadata object // * @throws PluginException when another plugin provides the same virtual dependency // */ // void addPlugin(PluginMetadata pluginMetadata) throws PluginException; // // /** // * Add resources for specific plugin // * // * @param pluginMetadata plugin metadata object // * @param resources plugin resources // */ // void addResources(PluginMetadata pluginMetadata, List<Path> resources); // // /** // * Adds class loader instance for specific plugin // * // * @param pluginMetadata plugin metadata object // * @param classLoader class loader instance corresponding to current plugin // */ // void addClassLoader(PluginMetadata pluginMetadata, ClassLoader classLoader); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/Dependency.java // public interface Dependency { // // /** // * Returns dependency name // * // * @return dependency name // */ // String getName(); // // /** // * Returns dependency version if present // * // * @return dependency version if present and empty otherwise // */ // Optional<String> getVersion(); // // /** // * Forces to override {@link Object#equals(Object)} // * // * @param anotherDependency dependency to compare to // * @return true if equal and false otherwise // */ // boolean equals(Object anotherDependency); // // /** // * Forces to override {@link Object#hashCode()} // * // * @return instance hash code // */ // int hashCode(); // // /** // * Returns dependency string representation // * // * @return dependency string representation // */ // String toString(); // // } // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/PluginRegistryContainer.java import org.meridor.stecker.PluginException; import org.meridor.stecker.PluginMetadata; import org.meridor.stecker.PluginRegistry; import org.meridor.stecker.interfaces.Dependency; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; package org.meridor.stecker.impl; public class PluginRegistryContainer implements PluginRegistry { private final Map<String, ClassesRegistry> registry = new HashMap<>();
private final Map<String, PluginMetadata> plugins = new HashMap<>();
meridor/stecker
stecker-plugin-loader/src/main/java/org/meridor/stecker/dev/DevDependencyChecker.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginMetadata.java // public interface PluginMetadata { // // /** // * Returns unique plugin name // * // * @return free-form string with name // */ // String getName(); // // /** // * Returns plugin version // * // * @return free-form string with version // */ // String getVersion(); // // /** // * Returns {@link Path} object corresponding to plugin file // * // * @return plugin {@link Path} object // */ // Path getPath(); // // /** // * Returns {@link org.meridor.stecker.interfaces.Dependency} object corresponding to this plugin // * // * @return dependency object // */ // Dependency getDependency(); // // /** // * Returns date when plugin was released // * // * @return local date or empty if not set // */ // Optional<ZonedDateTime> getDate(); // // /** // * Returns detailed plugin description // * // * @return description or empty if not set // */ // Optional<String> getDescription(); // // /** // * Returns maintainer email and name // * // * @return email and name in the format: <b>John Smith &lt;[email protected]&gt;</b> or empty if not set // */ // Optional<String> getMaintainer(); // // /** // * Returns a list of plugins required to make this plugin work // * // * @return possibly empty list with dependencies // */ // List<Dependency> getRequiredDependencies(); // // /** // * Returns a list of plugins that should be never installed simultaneously with this plugin // * // * @return possibly empty list with conflicting dependencies // */ // List<Dependency> getConflictingDependencies(); // // /** // * Returns a meta dependency which is provided by this plugin // * // * @return meta dependency or empty if not set // */ // Optional<Dependency> getProvidedDependency(); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/DependencyChecker.java // public interface DependencyChecker { // // /** // * Checks dependencies and throws {@link org.meridor.stecker.PluginException} with {@link DependencyProblem} in case of issues // * // * @param pluginRegistry plugin registry object filled with data about all plugins // * @param pluginMetadata checked plugin metadata // * @throws org.meridor.stecker.PluginException when dependency issues occur // */ // void check(PluginsAware pluginRegistry, PluginMetadata pluginMetadata) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginsAware.java // public interface PluginsAware { // // /** // * Returns information about plugin by its plugin name // * // * @param pluginName plugin name to process // * @return information about plugin or empty if not present // */ // Optional<PluginMetadata> getPlugin(String pluginName); // // /** // * Returns a list of dependencies in the registry // * // * @return a list of dependencies // */ // List<String> getPluginNames(); // // }
import org.meridor.stecker.PluginException; import org.meridor.stecker.PluginMetadata; import org.meridor.stecker.interfaces.DependencyChecker; import org.meridor.stecker.interfaces.PluginsAware;
package org.meridor.stecker.dev; public class DevDependencyChecker implements DependencyChecker { @Override
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginMetadata.java // public interface PluginMetadata { // // /** // * Returns unique plugin name // * // * @return free-form string with name // */ // String getName(); // // /** // * Returns plugin version // * // * @return free-form string with version // */ // String getVersion(); // // /** // * Returns {@link Path} object corresponding to plugin file // * // * @return plugin {@link Path} object // */ // Path getPath(); // // /** // * Returns {@link org.meridor.stecker.interfaces.Dependency} object corresponding to this plugin // * // * @return dependency object // */ // Dependency getDependency(); // // /** // * Returns date when plugin was released // * // * @return local date or empty if not set // */ // Optional<ZonedDateTime> getDate(); // // /** // * Returns detailed plugin description // * // * @return description or empty if not set // */ // Optional<String> getDescription(); // // /** // * Returns maintainer email and name // * // * @return email and name in the format: <b>John Smith &lt;[email protected]&gt;</b> or empty if not set // */ // Optional<String> getMaintainer(); // // /** // * Returns a list of plugins required to make this plugin work // * // * @return possibly empty list with dependencies // */ // List<Dependency> getRequiredDependencies(); // // /** // * Returns a list of plugins that should be never installed simultaneously with this plugin // * // * @return possibly empty list with conflicting dependencies // */ // List<Dependency> getConflictingDependencies(); // // /** // * Returns a meta dependency which is provided by this plugin // * // * @return meta dependency or empty if not set // */ // Optional<Dependency> getProvidedDependency(); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/DependencyChecker.java // public interface DependencyChecker { // // /** // * Checks dependencies and throws {@link org.meridor.stecker.PluginException} with {@link DependencyProblem} in case of issues // * // * @param pluginRegistry plugin registry object filled with data about all plugins // * @param pluginMetadata checked plugin metadata // * @throws org.meridor.stecker.PluginException when dependency issues occur // */ // void check(PluginsAware pluginRegistry, PluginMetadata pluginMetadata) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginsAware.java // public interface PluginsAware { // // /** // * Returns information about plugin by its plugin name // * // * @param pluginName plugin name to process // * @return information about plugin or empty if not present // */ // Optional<PluginMetadata> getPlugin(String pluginName); // // /** // * Returns a list of dependencies in the registry // * // * @return a list of dependencies // */ // List<String> getPluginNames(); // // } // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/dev/DevDependencyChecker.java import org.meridor.stecker.PluginException; import org.meridor.stecker.PluginMetadata; import org.meridor.stecker.interfaces.DependencyChecker; import org.meridor.stecker.interfaces.PluginsAware; package org.meridor.stecker.dev; public class DevDependencyChecker implements DependencyChecker { @Override
public void check(PluginsAware pluginRegistry, PluginMetadata pluginMetadata) throws PluginException {
meridor/stecker
stecker-plugin-loader/src/main/java/org/meridor/stecker/dev/DevDependencyChecker.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginMetadata.java // public interface PluginMetadata { // // /** // * Returns unique plugin name // * // * @return free-form string with name // */ // String getName(); // // /** // * Returns plugin version // * // * @return free-form string with version // */ // String getVersion(); // // /** // * Returns {@link Path} object corresponding to plugin file // * // * @return plugin {@link Path} object // */ // Path getPath(); // // /** // * Returns {@link org.meridor.stecker.interfaces.Dependency} object corresponding to this plugin // * // * @return dependency object // */ // Dependency getDependency(); // // /** // * Returns date when plugin was released // * // * @return local date or empty if not set // */ // Optional<ZonedDateTime> getDate(); // // /** // * Returns detailed plugin description // * // * @return description or empty if not set // */ // Optional<String> getDescription(); // // /** // * Returns maintainer email and name // * // * @return email and name in the format: <b>John Smith &lt;[email protected]&gt;</b> or empty if not set // */ // Optional<String> getMaintainer(); // // /** // * Returns a list of plugins required to make this plugin work // * // * @return possibly empty list with dependencies // */ // List<Dependency> getRequiredDependencies(); // // /** // * Returns a list of plugins that should be never installed simultaneously with this plugin // * // * @return possibly empty list with conflicting dependencies // */ // List<Dependency> getConflictingDependencies(); // // /** // * Returns a meta dependency which is provided by this plugin // * // * @return meta dependency or empty if not set // */ // Optional<Dependency> getProvidedDependency(); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/DependencyChecker.java // public interface DependencyChecker { // // /** // * Checks dependencies and throws {@link org.meridor.stecker.PluginException} with {@link DependencyProblem} in case of issues // * // * @param pluginRegistry plugin registry object filled with data about all plugins // * @param pluginMetadata checked plugin metadata // * @throws org.meridor.stecker.PluginException when dependency issues occur // */ // void check(PluginsAware pluginRegistry, PluginMetadata pluginMetadata) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginsAware.java // public interface PluginsAware { // // /** // * Returns information about plugin by its plugin name // * // * @param pluginName plugin name to process // * @return information about plugin or empty if not present // */ // Optional<PluginMetadata> getPlugin(String pluginName); // // /** // * Returns a list of dependencies in the registry // * // * @return a list of dependencies // */ // List<String> getPluginNames(); // // }
import org.meridor.stecker.PluginException; import org.meridor.stecker.PluginMetadata; import org.meridor.stecker.interfaces.DependencyChecker; import org.meridor.stecker.interfaces.PluginsAware;
package org.meridor.stecker.dev; public class DevDependencyChecker implements DependencyChecker { @Override
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginMetadata.java // public interface PluginMetadata { // // /** // * Returns unique plugin name // * // * @return free-form string with name // */ // String getName(); // // /** // * Returns plugin version // * // * @return free-form string with version // */ // String getVersion(); // // /** // * Returns {@link Path} object corresponding to plugin file // * // * @return plugin {@link Path} object // */ // Path getPath(); // // /** // * Returns {@link org.meridor.stecker.interfaces.Dependency} object corresponding to this plugin // * // * @return dependency object // */ // Dependency getDependency(); // // /** // * Returns date when plugin was released // * // * @return local date or empty if not set // */ // Optional<ZonedDateTime> getDate(); // // /** // * Returns detailed plugin description // * // * @return description or empty if not set // */ // Optional<String> getDescription(); // // /** // * Returns maintainer email and name // * // * @return email and name in the format: <b>John Smith &lt;[email protected]&gt;</b> or empty if not set // */ // Optional<String> getMaintainer(); // // /** // * Returns a list of plugins required to make this plugin work // * // * @return possibly empty list with dependencies // */ // List<Dependency> getRequiredDependencies(); // // /** // * Returns a list of plugins that should be never installed simultaneously with this plugin // * // * @return possibly empty list with conflicting dependencies // */ // List<Dependency> getConflictingDependencies(); // // /** // * Returns a meta dependency which is provided by this plugin // * // * @return meta dependency or empty if not set // */ // Optional<Dependency> getProvidedDependency(); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/DependencyChecker.java // public interface DependencyChecker { // // /** // * Checks dependencies and throws {@link org.meridor.stecker.PluginException} with {@link DependencyProblem} in case of issues // * // * @param pluginRegistry plugin registry object filled with data about all plugins // * @param pluginMetadata checked plugin metadata // * @throws org.meridor.stecker.PluginException when dependency issues occur // */ // void check(PluginsAware pluginRegistry, PluginMetadata pluginMetadata) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginsAware.java // public interface PluginsAware { // // /** // * Returns information about plugin by its plugin name // * // * @param pluginName plugin name to process // * @return information about plugin or empty if not present // */ // Optional<PluginMetadata> getPlugin(String pluginName); // // /** // * Returns a list of dependencies in the registry // * // * @return a list of dependencies // */ // List<String> getPluginNames(); // // } // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/dev/DevDependencyChecker.java import org.meridor.stecker.PluginException; import org.meridor.stecker.PluginMetadata; import org.meridor.stecker.interfaces.DependencyChecker; import org.meridor.stecker.interfaces.PluginsAware; package org.meridor.stecker.dev; public class DevDependencyChecker implements DependencyChecker { @Override
public void check(PluginsAware pluginRegistry, PluginMetadata pluginMetadata) throws PluginException {
meridor/stecker
stecker-plugin-loader/src/main/java/org/meridor/stecker/dev/DevDependencyChecker.java
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginMetadata.java // public interface PluginMetadata { // // /** // * Returns unique plugin name // * // * @return free-form string with name // */ // String getName(); // // /** // * Returns plugin version // * // * @return free-form string with version // */ // String getVersion(); // // /** // * Returns {@link Path} object corresponding to plugin file // * // * @return plugin {@link Path} object // */ // Path getPath(); // // /** // * Returns {@link org.meridor.stecker.interfaces.Dependency} object corresponding to this plugin // * // * @return dependency object // */ // Dependency getDependency(); // // /** // * Returns date when plugin was released // * // * @return local date or empty if not set // */ // Optional<ZonedDateTime> getDate(); // // /** // * Returns detailed plugin description // * // * @return description or empty if not set // */ // Optional<String> getDescription(); // // /** // * Returns maintainer email and name // * // * @return email and name in the format: <b>John Smith &lt;[email protected]&gt;</b> or empty if not set // */ // Optional<String> getMaintainer(); // // /** // * Returns a list of plugins required to make this plugin work // * // * @return possibly empty list with dependencies // */ // List<Dependency> getRequiredDependencies(); // // /** // * Returns a list of plugins that should be never installed simultaneously with this plugin // * // * @return possibly empty list with conflicting dependencies // */ // List<Dependency> getConflictingDependencies(); // // /** // * Returns a meta dependency which is provided by this plugin // * // * @return meta dependency or empty if not set // */ // Optional<Dependency> getProvidedDependency(); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/DependencyChecker.java // public interface DependencyChecker { // // /** // * Checks dependencies and throws {@link org.meridor.stecker.PluginException} with {@link DependencyProblem} in case of issues // * // * @param pluginRegistry plugin registry object filled with data about all plugins // * @param pluginMetadata checked plugin metadata // * @throws org.meridor.stecker.PluginException when dependency issues occur // */ // void check(PluginsAware pluginRegistry, PluginMetadata pluginMetadata) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginsAware.java // public interface PluginsAware { // // /** // * Returns information about plugin by its plugin name // * // * @param pluginName plugin name to process // * @return information about plugin or empty if not present // */ // Optional<PluginMetadata> getPlugin(String pluginName); // // /** // * Returns a list of dependencies in the registry // * // * @return a list of dependencies // */ // List<String> getPluginNames(); // // }
import org.meridor.stecker.PluginException; import org.meridor.stecker.PluginMetadata; import org.meridor.stecker.interfaces.DependencyChecker; import org.meridor.stecker.interfaces.PluginsAware;
package org.meridor.stecker.dev; public class DevDependencyChecker implements DependencyChecker { @Override
// Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginException.java // public class PluginException extends Exception { // // private Optional<DependencyProblem> dependencyProblem = Optional.empty(); // // private Optional<PluginMetadata> pluginMetadata = Optional.empty(); // // public PluginException(Exception e) { // super(e); // } // // public PluginException(String message) { // super(message); // } // // public PluginException(String message, Exception e) { // super(message, e); // } // // public PluginException withDependencyProblem(DependencyProblem dependencyProblem) { // this.dependencyProblem = Optional.ofNullable(dependencyProblem); // return this; // } // // public PluginException withPlugin(PluginMetadata pluginMetadata) { // this.pluginMetadata = Optional.ofNullable(pluginMetadata); // return this; // } // // /** // * Returns dependency problem if any // * // * @return dependency problem // */ // public Optional<DependencyProblem> getDependencyProblem() { // return dependencyProblem; // } // // /** // * Returns plugin affected // * // * @return plugin metadata // */ // public Optional<PluginMetadata> getPluginMetadata() { // return pluginMetadata; // } // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/PluginMetadata.java // public interface PluginMetadata { // // /** // * Returns unique plugin name // * // * @return free-form string with name // */ // String getName(); // // /** // * Returns plugin version // * // * @return free-form string with version // */ // String getVersion(); // // /** // * Returns {@link Path} object corresponding to plugin file // * // * @return plugin {@link Path} object // */ // Path getPath(); // // /** // * Returns {@link org.meridor.stecker.interfaces.Dependency} object corresponding to this plugin // * // * @return dependency object // */ // Dependency getDependency(); // // /** // * Returns date when plugin was released // * // * @return local date or empty if not set // */ // Optional<ZonedDateTime> getDate(); // // /** // * Returns detailed plugin description // * // * @return description or empty if not set // */ // Optional<String> getDescription(); // // /** // * Returns maintainer email and name // * // * @return email and name in the format: <b>John Smith &lt;[email protected]&gt;</b> or empty if not set // */ // Optional<String> getMaintainer(); // // /** // * Returns a list of plugins required to make this plugin work // * // * @return possibly empty list with dependencies // */ // List<Dependency> getRequiredDependencies(); // // /** // * Returns a list of plugins that should be never installed simultaneously with this plugin // * // * @return possibly empty list with conflicting dependencies // */ // List<Dependency> getConflictingDependencies(); // // /** // * Returns a meta dependency which is provided by this plugin // * // * @return meta dependency or empty if not set // */ // Optional<Dependency> getProvidedDependency(); // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/DependencyChecker.java // public interface DependencyChecker { // // /** // * Checks dependencies and throws {@link org.meridor.stecker.PluginException} with {@link DependencyProblem} in case of issues // * // * @param pluginRegistry plugin registry object filled with data about all plugins // * @param pluginMetadata checked plugin metadata // * @throws org.meridor.stecker.PluginException when dependency issues occur // */ // void check(PluginsAware pluginRegistry, PluginMetadata pluginMetadata) throws PluginException; // // } // // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/interfaces/PluginsAware.java // public interface PluginsAware { // // /** // * Returns information about plugin by its plugin name // * // * @param pluginName plugin name to process // * @return information about plugin or empty if not present // */ // Optional<PluginMetadata> getPlugin(String pluginName); // // /** // * Returns a list of dependencies in the registry // * // * @return a list of dependencies // */ // List<String> getPluginNames(); // // } // Path: stecker-plugin-loader/src/main/java/org/meridor/stecker/dev/DevDependencyChecker.java import org.meridor.stecker.PluginException; import org.meridor.stecker.PluginMetadata; import org.meridor.stecker.interfaces.DependencyChecker; import org.meridor.stecker.interfaces.PluginsAware; package org.meridor.stecker.dev; public class DevDependencyChecker implements DependencyChecker { @Override
public void check(PluginsAware pluginRegistry, PluginMetadata pluginMetadata) throws PluginException {
alexvictoor/MarbleTest4J
src/main/java/io/reactivex/marble/junit/MarbleRule.java
// Path: src/main/java/org/reactivestreams/ISetupSubscriptionsTest.java // public interface ISetupSubscriptionsTest { // void toBe(String... marbles); // } // // Path: src/main/java/org/reactivestreams/ISetupTest.java // public interface ISetupTest { // // void toBe(String marble, // Map<String, ?> values, // Exception errorValue); // // void toBe(String marble, // Map<String, ?> values); // // void toBe(String marble); // // } // // Path: src/main/java/org/reactivestreams/SubscriptionLog.java // public class SubscriptionLog { // public final long subscribe; // public final long unsubscribe; // // public SubscriptionLog(long subscribe) { // this.subscribe = subscribe; // this.unsubscribe = Long.MAX_VALUE; // } // // public SubscriptionLog(long subscribe, long unsubscribe) { // this.subscribe = subscribe; // this.unsubscribe = unsubscribe; // } // // public boolean doesNeverEnd() { // return unsubscribe == Long.MAX_VALUE; // } // // @Override // public String toString() { // return "SubscriptionLog{" + // "subscribe=" + subscribe + // ", unsubscribe=" + unsubscribe + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // SubscriptionLog that = (SubscriptionLog) o; // // if (subscribe != that.subscribe) return false; // return unsubscribe == that.unsubscribe; // // } // // @Override // public int hashCode() { // int result = (int) (subscribe ^ (subscribe >>> 32)); // result = 31 * result + (int) (unsubscribe ^ (unsubscribe >>> 32)); // return result; // } // }
import io.reactivex.*; import io.reactivex.marble.*; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import org.reactivestreams.ISetupSubscriptionsTest; import org.reactivestreams.ISetupTest; import org.reactivestreams.SubscriptionLog; import java.util.List; import java.util.Map;
package io.reactivex.marble.junit; public class MarbleRule implements TestRule { private static ThreadLocal<MarbleScheduler> schedulerHolder = new ThreadLocal<>(); public final MarbleScheduler scheduler; public MarbleRule() { scheduler = new MarbleScheduler(); } public MarbleRule(long frameTimeFactor) { scheduler = new MarbleScheduler(frameTimeFactor); } public static <T> HotObservable<T> hot(String marbles, Map<String, T> values) { return schedulerHolder.get().createHotObservable(marbles, values); } public static HotObservable<String> hot(String marbles) { return schedulerHolder.get().createHotObservable(marbles); } public static <T> ColdObservable<T> cold(String marbles, Map<String, T> values) { return schedulerHolder.get().createColdObservable(marbles, values); } public static ColdObservable<String> cold(String marbles) { return schedulerHolder.get().createColdObservable(marbles); }
// Path: src/main/java/org/reactivestreams/ISetupSubscriptionsTest.java // public interface ISetupSubscriptionsTest { // void toBe(String... marbles); // } // // Path: src/main/java/org/reactivestreams/ISetupTest.java // public interface ISetupTest { // // void toBe(String marble, // Map<String, ?> values, // Exception errorValue); // // void toBe(String marble, // Map<String, ?> values); // // void toBe(String marble); // // } // // Path: src/main/java/org/reactivestreams/SubscriptionLog.java // public class SubscriptionLog { // public final long subscribe; // public final long unsubscribe; // // public SubscriptionLog(long subscribe) { // this.subscribe = subscribe; // this.unsubscribe = Long.MAX_VALUE; // } // // public SubscriptionLog(long subscribe, long unsubscribe) { // this.subscribe = subscribe; // this.unsubscribe = unsubscribe; // } // // public boolean doesNeverEnd() { // return unsubscribe == Long.MAX_VALUE; // } // // @Override // public String toString() { // return "SubscriptionLog{" + // "subscribe=" + subscribe + // ", unsubscribe=" + unsubscribe + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // SubscriptionLog that = (SubscriptionLog) o; // // if (subscribe != that.subscribe) return false; // return unsubscribe == that.unsubscribe; // // } // // @Override // public int hashCode() { // int result = (int) (subscribe ^ (subscribe >>> 32)); // result = 31 * result + (int) (unsubscribe ^ (unsubscribe >>> 32)); // return result; // } // } // Path: src/main/java/io/reactivex/marble/junit/MarbleRule.java import io.reactivex.*; import io.reactivex.marble.*; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import org.reactivestreams.ISetupSubscriptionsTest; import org.reactivestreams.ISetupTest; import org.reactivestreams.SubscriptionLog; import java.util.List; import java.util.Map; package io.reactivex.marble.junit; public class MarbleRule implements TestRule { private static ThreadLocal<MarbleScheduler> schedulerHolder = new ThreadLocal<>(); public final MarbleScheduler scheduler; public MarbleRule() { scheduler = new MarbleScheduler(); } public MarbleRule(long frameTimeFactor) { scheduler = new MarbleScheduler(frameTimeFactor); } public static <T> HotObservable<T> hot(String marbles, Map<String, T> values) { return schedulerHolder.get().createHotObservable(marbles, values); } public static HotObservable<String> hot(String marbles) { return schedulerHolder.get().createHotObservable(marbles); } public static <T> ColdObservable<T> cold(String marbles, Map<String, T> values) { return schedulerHolder.get().createColdObservable(marbles, values); } public static ColdObservable<String> cold(String marbles) { return schedulerHolder.get().createColdObservable(marbles); }
public static ISetupTest expectObservable(Observable<?> actual) {
alexvictoor/MarbleTest4J
src/main/java/io/reactivex/marble/junit/MarbleRule.java
// Path: src/main/java/org/reactivestreams/ISetupSubscriptionsTest.java // public interface ISetupSubscriptionsTest { // void toBe(String... marbles); // } // // Path: src/main/java/org/reactivestreams/ISetupTest.java // public interface ISetupTest { // // void toBe(String marble, // Map<String, ?> values, // Exception errorValue); // // void toBe(String marble, // Map<String, ?> values); // // void toBe(String marble); // // } // // Path: src/main/java/org/reactivestreams/SubscriptionLog.java // public class SubscriptionLog { // public final long subscribe; // public final long unsubscribe; // // public SubscriptionLog(long subscribe) { // this.subscribe = subscribe; // this.unsubscribe = Long.MAX_VALUE; // } // // public SubscriptionLog(long subscribe, long unsubscribe) { // this.subscribe = subscribe; // this.unsubscribe = unsubscribe; // } // // public boolean doesNeverEnd() { // return unsubscribe == Long.MAX_VALUE; // } // // @Override // public String toString() { // return "SubscriptionLog{" + // "subscribe=" + subscribe + // ", unsubscribe=" + unsubscribe + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // SubscriptionLog that = (SubscriptionLog) o; // // if (subscribe != that.subscribe) return false; // return unsubscribe == that.unsubscribe; // // } // // @Override // public int hashCode() { // int result = (int) (subscribe ^ (subscribe >>> 32)); // result = 31 * result + (int) (unsubscribe ^ (unsubscribe >>> 32)); // return result; // } // }
import io.reactivex.*; import io.reactivex.marble.*; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import org.reactivestreams.ISetupSubscriptionsTest; import org.reactivestreams.ISetupTest; import org.reactivestreams.SubscriptionLog; import java.util.List; import java.util.Map;
} public static ISetupTest expectFlowable(Flowable<?> actual, String unsubscriptionMarbles) { return schedulerHolder.get().expectFlowable(actual, unsubscriptionMarbles); } public static ISetupTest expectSingle(Single<?> actual) { return schedulerHolder.get().expectFlowable(actual.toFlowable()); } public static ISetupTest expectSingle(Single<?> actual, String unsubscriptionMarbles) { return schedulerHolder.get().expectFlowable(actual.toFlowable(), unsubscriptionMarbles); } public static ISetupTest expectMaybe(Maybe<?> actual) { return schedulerHolder.get().expectFlowable(actual.toFlowable()); } public static ISetupTest expectCompletable(Completable actual, String unsubscriptionMarbles) { return schedulerHolder.get().expectFlowable(actual.toFlowable(), unsubscriptionMarbles); } public static ISetupTest expectCompletable(Completable actual) { return schedulerHolder.get().expectFlowable(actual.toFlowable()); } public static ISetupTest expectMaybe(Maybe<?> actual, String unsubscriptionMarbles) { return schedulerHolder.get().expectObservable(actual.toObservable(), unsubscriptionMarbles); }
// Path: src/main/java/org/reactivestreams/ISetupSubscriptionsTest.java // public interface ISetupSubscriptionsTest { // void toBe(String... marbles); // } // // Path: src/main/java/org/reactivestreams/ISetupTest.java // public interface ISetupTest { // // void toBe(String marble, // Map<String, ?> values, // Exception errorValue); // // void toBe(String marble, // Map<String, ?> values); // // void toBe(String marble); // // } // // Path: src/main/java/org/reactivestreams/SubscriptionLog.java // public class SubscriptionLog { // public final long subscribe; // public final long unsubscribe; // // public SubscriptionLog(long subscribe) { // this.subscribe = subscribe; // this.unsubscribe = Long.MAX_VALUE; // } // // public SubscriptionLog(long subscribe, long unsubscribe) { // this.subscribe = subscribe; // this.unsubscribe = unsubscribe; // } // // public boolean doesNeverEnd() { // return unsubscribe == Long.MAX_VALUE; // } // // @Override // public String toString() { // return "SubscriptionLog{" + // "subscribe=" + subscribe + // ", unsubscribe=" + unsubscribe + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // SubscriptionLog that = (SubscriptionLog) o; // // if (subscribe != that.subscribe) return false; // return unsubscribe == that.unsubscribe; // // } // // @Override // public int hashCode() { // int result = (int) (subscribe ^ (subscribe >>> 32)); // result = 31 * result + (int) (unsubscribe ^ (unsubscribe >>> 32)); // return result; // } // } // Path: src/main/java/io/reactivex/marble/junit/MarbleRule.java import io.reactivex.*; import io.reactivex.marble.*; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import org.reactivestreams.ISetupSubscriptionsTest; import org.reactivestreams.ISetupTest; import org.reactivestreams.SubscriptionLog; import java.util.List; import java.util.Map; } public static ISetupTest expectFlowable(Flowable<?> actual, String unsubscriptionMarbles) { return schedulerHolder.get().expectFlowable(actual, unsubscriptionMarbles); } public static ISetupTest expectSingle(Single<?> actual) { return schedulerHolder.get().expectFlowable(actual.toFlowable()); } public static ISetupTest expectSingle(Single<?> actual, String unsubscriptionMarbles) { return schedulerHolder.get().expectFlowable(actual.toFlowable(), unsubscriptionMarbles); } public static ISetupTest expectMaybe(Maybe<?> actual) { return schedulerHolder.get().expectFlowable(actual.toFlowable()); } public static ISetupTest expectCompletable(Completable actual, String unsubscriptionMarbles) { return schedulerHolder.get().expectFlowable(actual.toFlowable(), unsubscriptionMarbles); } public static ISetupTest expectCompletable(Completable actual) { return schedulerHolder.get().expectFlowable(actual.toFlowable()); } public static ISetupTest expectMaybe(Maybe<?> actual, String unsubscriptionMarbles) { return schedulerHolder.get().expectObservable(actual.toObservable(), unsubscriptionMarbles); }
public static ISetupSubscriptionsTest expectSubscriptions(List<SubscriptionLog> subscriptions) {
alexvictoor/MarbleTest4J
src/main/java/io/reactivex/marble/junit/MarbleRule.java
// Path: src/main/java/org/reactivestreams/ISetupSubscriptionsTest.java // public interface ISetupSubscriptionsTest { // void toBe(String... marbles); // } // // Path: src/main/java/org/reactivestreams/ISetupTest.java // public interface ISetupTest { // // void toBe(String marble, // Map<String, ?> values, // Exception errorValue); // // void toBe(String marble, // Map<String, ?> values); // // void toBe(String marble); // // } // // Path: src/main/java/org/reactivestreams/SubscriptionLog.java // public class SubscriptionLog { // public final long subscribe; // public final long unsubscribe; // // public SubscriptionLog(long subscribe) { // this.subscribe = subscribe; // this.unsubscribe = Long.MAX_VALUE; // } // // public SubscriptionLog(long subscribe, long unsubscribe) { // this.subscribe = subscribe; // this.unsubscribe = unsubscribe; // } // // public boolean doesNeverEnd() { // return unsubscribe == Long.MAX_VALUE; // } // // @Override // public String toString() { // return "SubscriptionLog{" + // "subscribe=" + subscribe + // ", unsubscribe=" + unsubscribe + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // SubscriptionLog that = (SubscriptionLog) o; // // if (subscribe != that.subscribe) return false; // return unsubscribe == that.unsubscribe; // // } // // @Override // public int hashCode() { // int result = (int) (subscribe ^ (subscribe >>> 32)); // result = 31 * result + (int) (unsubscribe ^ (unsubscribe >>> 32)); // return result; // } // }
import io.reactivex.*; import io.reactivex.marble.*; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import org.reactivestreams.ISetupSubscriptionsTest; import org.reactivestreams.ISetupTest; import org.reactivestreams.SubscriptionLog; import java.util.List; import java.util.Map;
} public static ISetupTest expectFlowable(Flowable<?> actual, String unsubscriptionMarbles) { return schedulerHolder.get().expectFlowable(actual, unsubscriptionMarbles); } public static ISetupTest expectSingle(Single<?> actual) { return schedulerHolder.get().expectFlowable(actual.toFlowable()); } public static ISetupTest expectSingle(Single<?> actual, String unsubscriptionMarbles) { return schedulerHolder.get().expectFlowable(actual.toFlowable(), unsubscriptionMarbles); } public static ISetupTest expectMaybe(Maybe<?> actual) { return schedulerHolder.get().expectFlowable(actual.toFlowable()); } public static ISetupTest expectCompletable(Completable actual, String unsubscriptionMarbles) { return schedulerHolder.get().expectFlowable(actual.toFlowable(), unsubscriptionMarbles); } public static ISetupTest expectCompletable(Completable actual) { return schedulerHolder.get().expectFlowable(actual.toFlowable()); } public static ISetupTest expectMaybe(Maybe<?> actual, String unsubscriptionMarbles) { return schedulerHolder.get().expectObservable(actual.toObservable(), unsubscriptionMarbles); }
// Path: src/main/java/org/reactivestreams/ISetupSubscriptionsTest.java // public interface ISetupSubscriptionsTest { // void toBe(String... marbles); // } // // Path: src/main/java/org/reactivestreams/ISetupTest.java // public interface ISetupTest { // // void toBe(String marble, // Map<String, ?> values, // Exception errorValue); // // void toBe(String marble, // Map<String, ?> values); // // void toBe(String marble); // // } // // Path: src/main/java/org/reactivestreams/SubscriptionLog.java // public class SubscriptionLog { // public final long subscribe; // public final long unsubscribe; // // public SubscriptionLog(long subscribe) { // this.subscribe = subscribe; // this.unsubscribe = Long.MAX_VALUE; // } // // public SubscriptionLog(long subscribe, long unsubscribe) { // this.subscribe = subscribe; // this.unsubscribe = unsubscribe; // } // // public boolean doesNeverEnd() { // return unsubscribe == Long.MAX_VALUE; // } // // @Override // public String toString() { // return "SubscriptionLog{" + // "subscribe=" + subscribe + // ", unsubscribe=" + unsubscribe + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // SubscriptionLog that = (SubscriptionLog) o; // // if (subscribe != that.subscribe) return false; // return unsubscribe == that.unsubscribe; // // } // // @Override // public int hashCode() { // int result = (int) (subscribe ^ (subscribe >>> 32)); // result = 31 * result + (int) (unsubscribe ^ (unsubscribe >>> 32)); // return result; // } // } // Path: src/main/java/io/reactivex/marble/junit/MarbleRule.java import io.reactivex.*; import io.reactivex.marble.*; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import org.reactivestreams.ISetupSubscriptionsTest; import org.reactivestreams.ISetupTest; import org.reactivestreams.SubscriptionLog; import java.util.List; import java.util.Map; } public static ISetupTest expectFlowable(Flowable<?> actual, String unsubscriptionMarbles) { return schedulerHolder.get().expectFlowable(actual, unsubscriptionMarbles); } public static ISetupTest expectSingle(Single<?> actual) { return schedulerHolder.get().expectFlowable(actual.toFlowable()); } public static ISetupTest expectSingle(Single<?> actual, String unsubscriptionMarbles) { return schedulerHolder.get().expectFlowable(actual.toFlowable(), unsubscriptionMarbles); } public static ISetupTest expectMaybe(Maybe<?> actual) { return schedulerHolder.get().expectFlowable(actual.toFlowable()); } public static ISetupTest expectCompletable(Completable actual, String unsubscriptionMarbles) { return schedulerHolder.get().expectFlowable(actual.toFlowable(), unsubscriptionMarbles); } public static ISetupTest expectCompletable(Completable actual) { return schedulerHolder.get().expectFlowable(actual.toFlowable()); } public static ISetupTest expectMaybe(Maybe<?> actual, String unsubscriptionMarbles) { return schedulerHolder.get().expectObservable(actual.toObservable(), unsubscriptionMarbles); }
public static ISetupSubscriptionsTest expectSubscriptions(List<SubscriptionLog> subscriptions) {
alexvictoor/MarbleTest4J
src/test/java/org/reactivestreams/MarbleSchedulerTest.java
// Path: src/main/java/reactor/ColdFlux.java // public class ColdFlux<T> extends Flux<T> implements TestablePublisher<T> { // // private final TestablePublisher<T> publisher; // // protected ColdFlux(TestablePublisher<T> publisher) { // this.publisher = publisher; // } // // @Override // public void subscribe(Subscriber<? super T> s) { // publisher.subscribe(s); // } // // @Override // public List<SubscriptionLog> getSubscriptions() { // return publisher.getSubscriptions(); // } // // @Override // public List<Recorded<T>> getMessages() { // return publisher.getMessages(); // } // // public static <T> ColdFlux<T> create(Scheduler scheduler, Recorded<T>... notifications) { // return create(scheduler, Arrays.asList(notifications)); // } // // public static <T> ColdFlux<T> create(final Scheduler scheduler, List<Recorded<T>> notifications) { // // ColdPublisher<T> coldPublisher = new ColdPublisher<>(new SchedulerFactory() { // @Override // public org.reactivestreams.Scheduler create() { // return new SchedulerAdapter(scheduler); // } // }, notifications); // // return new ColdFlux<>(coldPublisher); // } // // } // // Path: src/main/java/reactor/HotFlux.java // public class HotFlux<T> extends Flux<T> implements TestablePublisher<T> { // // private final TestablePublisher<T> publisher; // // protected HotFlux(TestablePublisher<T> publisher) { // this.publisher = publisher; // } // // @Override // public void subscribe(Subscriber<? super T> s) { // publisher.subscribe(s); // } // // @Override // public List<SubscriptionLog> getSubscriptions() { // return publisher.getSubscriptions(); // } // // @Override // public List<Recorded<T>> getMessages() { // return publisher.getMessages(); // } // // public static <T> HotFlux<T> create(Scheduler scheduler, Recorded<T>... notifications) { // return create(scheduler, Arrays.asList(notifications)); // } // // public static <T> HotFlux<T> create(Scheduler scheduler, List<Recorded<T>> notifications) { // HotPublisher<T> hotPublisher = new HotPublisher<>(new SchedulerAdapter(scheduler), notifications); // return new HotFlux<>(hotPublisher); // } // // } // // Path: src/main/java/reactor/MarbleScheduler.java // public class MarbleScheduler extends VirtualTimeScheduler { // private final MarbleSchedulerState state; // private final long frameTimeFactor; // // public MarbleScheduler() { // this(10); // } // // public MarbleScheduler(long frameTimeFactor) { // this.frameTimeFactor = frameTimeFactor; // state = new MarbleSchedulerState(frameTimeFactor, new MarbleSchedulerState.ISchedule() { // @Override // public long now() { // return MarbleScheduler.this.now(TimeUnit.MILLISECONDS); // } // // @Override // public void schedule(Runnable runnable, long time) { // MarbleScheduler.this.schedule(runnable, time, TimeUnit.MILLISECONDS); // } // }, getClass()); // } // // // public <T> ColdFlux<T> createColdFlux(String marbles, Map<String, T> values) { // List<Recorded<T>> notifications = Parser.parseMarbles(marbles, values, null, frameTimeFactor); // return ColdFlux.create(this, notifications); // } // // public <T> ColdFlux<T> createColdFlux(String marbles) { // return createColdFlux(marbles, null); // } // // public <T> HotFlux<T> createHotFlux(String marbles, Map<String, T> values) { // List<Recorded<T>> notifications = Parser.parseMarbles(marbles, values, null, frameTimeFactor); // return HotFlux.create(this, notifications); // } // // public <T> HotFlux<T> createHotFlux(String marbles) { // return createHotFlux(marbles, null); // } // // // public long createTime(String marbles) { // int endIndex = marbles.indexOf("|"); // if (endIndex == -1) { // throw new RuntimeException("Marble diagram for time should have a completion marker '|'"); // } // // return endIndex * frameTimeFactor; // } // // // public void flush() { // advanceTimeTo(Instant.ofEpochMilli(Long.MAX_VALUE)); // state.flush(); // } // // public <T> ISetupTest expectFlux(Flux<T> flux) { // return expectFlux(flux, null); // } // // public <T> ISetupTest expectFlux(Flux<T> flux, String unsubscriptionMarbles) { // return state.expectPublisher(flux, unsubscriptionMarbles); // } // // public ISetupSubscriptionsTest expectSubscriptions(List<SubscriptionLog> subscriptions) { // return state.expectSubscriptions(subscriptions); // } // } // // Path: src/main/java/io/reactivex/marble/MapHelper.java // public static <V> Map<String, V> of(String k, V v) { // return Collections.singletonMap(k,v); // }
import io.reactivex.subscribers.TestSubscriber; import org.junit.After; import org.junit.Before; import org.junit.Test; import reactor.ColdFlux; import reactor.HotFlux; import reactor.MarbleScheduler; import reactor.core.publisher.Flux; import java.time.Duration; import java.util.Collections; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.function.Function; import static org.assertj.core.api.Assertions.assertThat; import static io.reactivex.marble.MapHelper.of;
package org.reactivestreams; public class MarbleSchedulerTest { private MarbleScheduler scheduler; @Before public void setupScheduler() { scheduler = new MarbleScheduler(); } @After public void flushScheduler() { if (scheduler != null) { scheduler.flush(); } } @Test public void should_create_a_cold_observable() {
// Path: src/main/java/reactor/ColdFlux.java // public class ColdFlux<T> extends Flux<T> implements TestablePublisher<T> { // // private final TestablePublisher<T> publisher; // // protected ColdFlux(TestablePublisher<T> publisher) { // this.publisher = publisher; // } // // @Override // public void subscribe(Subscriber<? super T> s) { // publisher.subscribe(s); // } // // @Override // public List<SubscriptionLog> getSubscriptions() { // return publisher.getSubscriptions(); // } // // @Override // public List<Recorded<T>> getMessages() { // return publisher.getMessages(); // } // // public static <T> ColdFlux<T> create(Scheduler scheduler, Recorded<T>... notifications) { // return create(scheduler, Arrays.asList(notifications)); // } // // public static <T> ColdFlux<T> create(final Scheduler scheduler, List<Recorded<T>> notifications) { // // ColdPublisher<T> coldPublisher = new ColdPublisher<>(new SchedulerFactory() { // @Override // public org.reactivestreams.Scheduler create() { // return new SchedulerAdapter(scheduler); // } // }, notifications); // // return new ColdFlux<>(coldPublisher); // } // // } // // Path: src/main/java/reactor/HotFlux.java // public class HotFlux<T> extends Flux<T> implements TestablePublisher<T> { // // private final TestablePublisher<T> publisher; // // protected HotFlux(TestablePublisher<T> publisher) { // this.publisher = publisher; // } // // @Override // public void subscribe(Subscriber<? super T> s) { // publisher.subscribe(s); // } // // @Override // public List<SubscriptionLog> getSubscriptions() { // return publisher.getSubscriptions(); // } // // @Override // public List<Recorded<T>> getMessages() { // return publisher.getMessages(); // } // // public static <T> HotFlux<T> create(Scheduler scheduler, Recorded<T>... notifications) { // return create(scheduler, Arrays.asList(notifications)); // } // // public static <T> HotFlux<T> create(Scheduler scheduler, List<Recorded<T>> notifications) { // HotPublisher<T> hotPublisher = new HotPublisher<>(new SchedulerAdapter(scheduler), notifications); // return new HotFlux<>(hotPublisher); // } // // } // // Path: src/main/java/reactor/MarbleScheduler.java // public class MarbleScheduler extends VirtualTimeScheduler { // private final MarbleSchedulerState state; // private final long frameTimeFactor; // // public MarbleScheduler() { // this(10); // } // // public MarbleScheduler(long frameTimeFactor) { // this.frameTimeFactor = frameTimeFactor; // state = new MarbleSchedulerState(frameTimeFactor, new MarbleSchedulerState.ISchedule() { // @Override // public long now() { // return MarbleScheduler.this.now(TimeUnit.MILLISECONDS); // } // // @Override // public void schedule(Runnable runnable, long time) { // MarbleScheduler.this.schedule(runnable, time, TimeUnit.MILLISECONDS); // } // }, getClass()); // } // // // public <T> ColdFlux<T> createColdFlux(String marbles, Map<String, T> values) { // List<Recorded<T>> notifications = Parser.parseMarbles(marbles, values, null, frameTimeFactor); // return ColdFlux.create(this, notifications); // } // // public <T> ColdFlux<T> createColdFlux(String marbles) { // return createColdFlux(marbles, null); // } // // public <T> HotFlux<T> createHotFlux(String marbles, Map<String, T> values) { // List<Recorded<T>> notifications = Parser.parseMarbles(marbles, values, null, frameTimeFactor); // return HotFlux.create(this, notifications); // } // // public <T> HotFlux<T> createHotFlux(String marbles) { // return createHotFlux(marbles, null); // } // // // public long createTime(String marbles) { // int endIndex = marbles.indexOf("|"); // if (endIndex == -1) { // throw new RuntimeException("Marble diagram for time should have a completion marker '|'"); // } // // return endIndex * frameTimeFactor; // } // // // public void flush() { // advanceTimeTo(Instant.ofEpochMilli(Long.MAX_VALUE)); // state.flush(); // } // // public <T> ISetupTest expectFlux(Flux<T> flux) { // return expectFlux(flux, null); // } // // public <T> ISetupTest expectFlux(Flux<T> flux, String unsubscriptionMarbles) { // return state.expectPublisher(flux, unsubscriptionMarbles); // } // // public ISetupSubscriptionsTest expectSubscriptions(List<SubscriptionLog> subscriptions) { // return state.expectSubscriptions(subscriptions); // } // } // // Path: src/main/java/io/reactivex/marble/MapHelper.java // public static <V> Map<String, V> of(String k, V v) { // return Collections.singletonMap(k,v); // } // Path: src/test/java/org/reactivestreams/MarbleSchedulerTest.java import io.reactivex.subscribers.TestSubscriber; import org.junit.After; import org.junit.Before; import org.junit.Test; import reactor.ColdFlux; import reactor.HotFlux; import reactor.MarbleScheduler; import reactor.core.publisher.Flux; import java.time.Duration; import java.util.Collections; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.function.Function; import static org.assertj.core.api.Assertions.assertThat; import static io.reactivex.marble.MapHelper.of; package org.reactivestreams; public class MarbleSchedulerTest { private MarbleScheduler scheduler; @Before public void setupScheduler() { scheduler = new MarbleScheduler(); } @After public void flushScheduler() { if (scheduler != null) { scheduler.flush(); } } @Test public void should_create_a_cold_observable() {
ColdFlux<String> source = scheduler.createColdFlux("--a---b--|", of("a", "A", "b", "B"));
alexvictoor/MarbleTest4J
src/test/java/org/reactivestreams/MarbleSchedulerTest.java
// Path: src/main/java/reactor/ColdFlux.java // public class ColdFlux<T> extends Flux<T> implements TestablePublisher<T> { // // private final TestablePublisher<T> publisher; // // protected ColdFlux(TestablePublisher<T> publisher) { // this.publisher = publisher; // } // // @Override // public void subscribe(Subscriber<? super T> s) { // publisher.subscribe(s); // } // // @Override // public List<SubscriptionLog> getSubscriptions() { // return publisher.getSubscriptions(); // } // // @Override // public List<Recorded<T>> getMessages() { // return publisher.getMessages(); // } // // public static <T> ColdFlux<T> create(Scheduler scheduler, Recorded<T>... notifications) { // return create(scheduler, Arrays.asList(notifications)); // } // // public static <T> ColdFlux<T> create(final Scheduler scheduler, List<Recorded<T>> notifications) { // // ColdPublisher<T> coldPublisher = new ColdPublisher<>(new SchedulerFactory() { // @Override // public org.reactivestreams.Scheduler create() { // return new SchedulerAdapter(scheduler); // } // }, notifications); // // return new ColdFlux<>(coldPublisher); // } // // } // // Path: src/main/java/reactor/HotFlux.java // public class HotFlux<T> extends Flux<T> implements TestablePublisher<T> { // // private final TestablePublisher<T> publisher; // // protected HotFlux(TestablePublisher<T> publisher) { // this.publisher = publisher; // } // // @Override // public void subscribe(Subscriber<? super T> s) { // publisher.subscribe(s); // } // // @Override // public List<SubscriptionLog> getSubscriptions() { // return publisher.getSubscriptions(); // } // // @Override // public List<Recorded<T>> getMessages() { // return publisher.getMessages(); // } // // public static <T> HotFlux<T> create(Scheduler scheduler, Recorded<T>... notifications) { // return create(scheduler, Arrays.asList(notifications)); // } // // public static <T> HotFlux<T> create(Scheduler scheduler, List<Recorded<T>> notifications) { // HotPublisher<T> hotPublisher = new HotPublisher<>(new SchedulerAdapter(scheduler), notifications); // return new HotFlux<>(hotPublisher); // } // // } // // Path: src/main/java/reactor/MarbleScheduler.java // public class MarbleScheduler extends VirtualTimeScheduler { // private final MarbleSchedulerState state; // private final long frameTimeFactor; // // public MarbleScheduler() { // this(10); // } // // public MarbleScheduler(long frameTimeFactor) { // this.frameTimeFactor = frameTimeFactor; // state = new MarbleSchedulerState(frameTimeFactor, new MarbleSchedulerState.ISchedule() { // @Override // public long now() { // return MarbleScheduler.this.now(TimeUnit.MILLISECONDS); // } // // @Override // public void schedule(Runnable runnable, long time) { // MarbleScheduler.this.schedule(runnable, time, TimeUnit.MILLISECONDS); // } // }, getClass()); // } // // // public <T> ColdFlux<T> createColdFlux(String marbles, Map<String, T> values) { // List<Recorded<T>> notifications = Parser.parseMarbles(marbles, values, null, frameTimeFactor); // return ColdFlux.create(this, notifications); // } // // public <T> ColdFlux<T> createColdFlux(String marbles) { // return createColdFlux(marbles, null); // } // // public <T> HotFlux<T> createHotFlux(String marbles, Map<String, T> values) { // List<Recorded<T>> notifications = Parser.parseMarbles(marbles, values, null, frameTimeFactor); // return HotFlux.create(this, notifications); // } // // public <T> HotFlux<T> createHotFlux(String marbles) { // return createHotFlux(marbles, null); // } // // // public long createTime(String marbles) { // int endIndex = marbles.indexOf("|"); // if (endIndex == -1) { // throw new RuntimeException("Marble diagram for time should have a completion marker '|'"); // } // // return endIndex * frameTimeFactor; // } // // // public void flush() { // advanceTimeTo(Instant.ofEpochMilli(Long.MAX_VALUE)); // state.flush(); // } // // public <T> ISetupTest expectFlux(Flux<T> flux) { // return expectFlux(flux, null); // } // // public <T> ISetupTest expectFlux(Flux<T> flux, String unsubscriptionMarbles) { // return state.expectPublisher(flux, unsubscriptionMarbles); // } // // public ISetupSubscriptionsTest expectSubscriptions(List<SubscriptionLog> subscriptions) { // return state.expectSubscriptions(subscriptions); // } // } // // Path: src/main/java/io/reactivex/marble/MapHelper.java // public static <V> Map<String, V> of(String k, V v) { // return Collections.singletonMap(k,v); // }
import io.reactivex.subscribers.TestSubscriber; import org.junit.After; import org.junit.Before; import org.junit.Test; import reactor.ColdFlux; import reactor.HotFlux; import reactor.MarbleScheduler; import reactor.core.publisher.Flux; import java.time.Duration; import java.util.Collections; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.function.Function; import static org.assertj.core.api.Assertions.assertThat; import static io.reactivex.marble.MapHelper.of;
package org.reactivestreams; public class MarbleSchedulerTest { private MarbleScheduler scheduler; @Before public void setupScheduler() { scheduler = new MarbleScheduler(); } @After public void flushScheduler() { if (scheduler != null) { scheduler.flush(); } } @Test public void should_create_a_cold_observable() {
// Path: src/main/java/reactor/ColdFlux.java // public class ColdFlux<T> extends Flux<T> implements TestablePublisher<T> { // // private final TestablePublisher<T> publisher; // // protected ColdFlux(TestablePublisher<T> publisher) { // this.publisher = publisher; // } // // @Override // public void subscribe(Subscriber<? super T> s) { // publisher.subscribe(s); // } // // @Override // public List<SubscriptionLog> getSubscriptions() { // return publisher.getSubscriptions(); // } // // @Override // public List<Recorded<T>> getMessages() { // return publisher.getMessages(); // } // // public static <T> ColdFlux<T> create(Scheduler scheduler, Recorded<T>... notifications) { // return create(scheduler, Arrays.asList(notifications)); // } // // public static <T> ColdFlux<T> create(final Scheduler scheduler, List<Recorded<T>> notifications) { // // ColdPublisher<T> coldPublisher = new ColdPublisher<>(new SchedulerFactory() { // @Override // public org.reactivestreams.Scheduler create() { // return new SchedulerAdapter(scheduler); // } // }, notifications); // // return new ColdFlux<>(coldPublisher); // } // // } // // Path: src/main/java/reactor/HotFlux.java // public class HotFlux<T> extends Flux<T> implements TestablePublisher<T> { // // private final TestablePublisher<T> publisher; // // protected HotFlux(TestablePublisher<T> publisher) { // this.publisher = publisher; // } // // @Override // public void subscribe(Subscriber<? super T> s) { // publisher.subscribe(s); // } // // @Override // public List<SubscriptionLog> getSubscriptions() { // return publisher.getSubscriptions(); // } // // @Override // public List<Recorded<T>> getMessages() { // return publisher.getMessages(); // } // // public static <T> HotFlux<T> create(Scheduler scheduler, Recorded<T>... notifications) { // return create(scheduler, Arrays.asList(notifications)); // } // // public static <T> HotFlux<T> create(Scheduler scheduler, List<Recorded<T>> notifications) { // HotPublisher<T> hotPublisher = new HotPublisher<>(new SchedulerAdapter(scheduler), notifications); // return new HotFlux<>(hotPublisher); // } // // } // // Path: src/main/java/reactor/MarbleScheduler.java // public class MarbleScheduler extends VirtualTimeScheduler { // private final MarbleSchedulerState state; // private final long frameTimeFactor; // // public MarbleScheduler() { // this(10); // } // // public MarbleScheduler(long frameTimeFactor) { // this.frameTimeFactor = frameTimeFactor; // state = new MarbleSchedulerState(frameTimeFactor, new MarbleSchedulerState.ISchedule() { // @Override // public long now() { // return MarbleScheduler.this.now(TimeUnit.MILLISECONDS); // } // // @Override // public void schedule(Runnable runnable, long time) { // MarbleScheduler.this.schedule(runnable, time, TimeUnit.MILLISECONDS); // } // }, getClass()); // } // // // public <T> ColdFlux<T> createColdFlux(String marbles, Map<String, T> values) { // List<Recorded<T>> notifications = Parser.parseMarbles(marbles, values, null, frameTimeFactor); // return ColdFlux.create(this, notifications); // } // // public <T> ColdFlux<T> createColdFlux(String marbles) { // return createColdFlux(marbles, null); // } // // public <T> HotFlux<T> createHotFlux(String marbles, Map<String, T> values) { // List<Recorded<T>> notifications = Parser.parseMarbles(marbles, values, null, frameTimeFactor); // return HotFlux.create(this, notifications); // } // // public <T> HotFlux<T> createHotFlux(String marbles) { // return createHotFlux(marbles, null); // } // // // public long createTime(String marbles) { // int endIndex = marbles.indexOf("|"); // if (endIndex == -1) { // throw new RuntimeException("Marble diagram for time should have a completion marker '|'"); // } // // return endIndex * frameTimeFactor; // } // // // public void flush() { // advanceTimeTo(Instant.ofEpochMilli(Long.MAX_VALUE)); // state.flush(); // } // // public <T> ISetupTest expectFlux(Flux<T> flux) { // return expectFlux(flux, null); // } // // public <T> ISetupTest expectFlux(Flux<T> flux, String unsubscriptionMarbles) { // return state.expectPublisher(flux, unsubscriptionMarbles); // } // // public ISetupSubscriptionsTest expectSubscriptions(List<SubscriptionLog> subscriptions) { // return state.expectSubscriptions(subscriptions); // } // } // // Path: src/main/java/io/reactivex/marble/MapHelper.java // public static <V> Map<String, V> of(String k, V v) { // return Collections.singletonMap(k,v); // } // Path: src/test/java/org/reactivestreams/MarbleSchedulerTest.java import io.reactivex.subscribers.TestSubscriber; import org.junit.After; import org.junit.Before; import org.junit.Test; import reactor.ColdFlux; import reactor.HotFlux; import reactor.MarbleScheduler; import reactor.core.publisher.Flux; import java.time.Duration; import java.util.Collections; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.function.Function; import static org.assertj.core.api.Assertions.assertThat; import static io.reactivex.marble.MapHelper.of; package org.reactivestreams; public class MarbleSchedulerTest { private MarbleScheduler scheduler; @Before public void setupScheduler() { scheduler = new MarbleScheduler(); } @After public void flushScheduler() { if (scheduler != null) { scheduler.flush(); } } @Test public void should_create_a_cold_observable() {
ColdFlux<String> source = scheduler.createColdFlux("--a---b--|", of("a", "A", "b", "B"));
alexvictoor/MarbleTest4J
src/main/java/io/reactivex/marble/MarbleScheduler.java
// Path: src/main/java/org/reactivestreams/ExpectSubscriptionsException.java // public class ExpectSubscriptionsException extends RuntimeException { // // public ExpectSubscriptionsException(String message, String caller) { // super(message + "\n\n from assertion at " + caller + "\n\n----------------------\n"); // } // // }
import io.reactivex.BackpressureStrategy; import io.reactivex.Flowable; import io.reactivex.Observable; import io.reactivex.Scheduler; import io.reactivex.annotations.NonNull; import io.reactivex.schedulers.TestScheduler; import org.reactivestreams.*; import org.reactivestreams.ExpectSubscriptionsException; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit;
public <T> ColdObservable<T> createColdObservable(String marbles) { return createColdObservable(marbles, null); } public <T> HotObservable<T> createHotObservable(String marbles, Map<String, T> values) { List<Recorded<T>> notifications = Parser.parseMarbles(marbles, values, null, frameTimeFactor); return HotObservable.create(this, notifications); } public <T> HotObservable<T> createHotObservable(String marbles) { return createHotObservable(marbles, null); } public long createTime(String marbles) { int endIndex = marbles.indexOf("|"); if (endIndex == -1) { throw new RuntimeException("Marble diagram for time should have a completion marker '|'"); } return endIndex * frameTimeFactor; } public void flush() { testScheduler.advanceTimeTo(Long.MAX_VALUE, TimeUnit.MILLISECONDS); try { state.flush(); } catch (ExpectPublisherException ex) { throw new ExpectFlowableException(ex.getMessage());
// Path: src/main/java/org/reactivestreams/ExpectSubscriptionsException.java // public class ExpectSubscriptionsException extends RuntimeException { // // public ExpectSubscriptionsException(String message, String caller) { // super(message + "\n\n from assertion at " + caller + "\n\n----------------------\n"); // } // // } // Path: src/main/java/io/reactivex/marble/MarbleScheduler.java import io.reactivex.BackpressureStrategy; import io.reactivex.Flowable; import io.reactivex.Observable; import io.reactivex.Scheduler; import io.reactivex.annotations.NonNull; import io.reactivex.schedulers.TestScheduler; import org.reactivestreams.*; import org.reactivestreams.ExpectSubscriptionsException; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; public <T> ColdObservable<T> createColdObservable(String marbles) { return createColdObservable(marbles, null); } public <T> HotObservable<T> createHotObservable(String marbles, Map<String, T> values) { List<Recorded<T>> notifications = Parser.parseMarbles(marbles, values, null, frameTimeFactor); return HotObservable.create(this, notifications); } public <T> HotObservable<T> createHotObservable(String marbles) { return createHotObservable(marbles, null); } public long createTime(String marbles) { int endIndex = marbles.indexOf("|"); if (endIndex == -1) { throw new RuntimeException("Marble diagram for time should have a completion marker '|'"); } return endIndex * frameTimeFactor; } public void flush() { testScheduler.advanceTimeTo(Long.MAX_VALUE, TimeUnit.MILLISECONDS); try { state.flush(); } catch (ExpectPublisherException ex) { throw new ExpectFlowableException(ex.getMessage());
} catch (ExpectSubscriptionsException ex) {
alexvictoor/MarbleTest4J
src/test/java/io/reactivex/marble/MarbleSchedulerTest.java
// Path: src/main/java/io/reactivex/marble/MapHelper.java // public static <V> Map<String, V> of(String k, V v) { // return Collections.singletonMap(k,v); // }
import io.reactivex.Observable; import io.reactivex.functions.Function; import io.reactivex.observers.TestObserver; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.Collections; import java.util.Map; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; import static io.reactivex.marble.MapHelper.of;
package io.reactivex.marble; public class MarbleSchedulerTest { private MarbleScheduler scheduler; @Before public void setupScheduler() { scheduler = new MarbleScheduler(); } @After public void flushScheduler() { if (scheduler != null) { scheduler.flush(); } } @Test public void should_create_a_cold_observable() {
// Path: src/main/java/io/reactivex/marble/MapHelper.java // public static <V> Map<String, V> of(String k, V v) { // return Collections.singletonMap(k,v); // } // Path: src/test/java/io/reactivex/marble/MarbleSchedulerTest.java import io.reactivex.Observable; import io.reactivex.functions.Function; import io.reactivex.observers.TestObserver; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.Collections; import java.util.Map; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; import static io.reactivex.marble.MapHelper.of; package io.reactivex.marble; public class MarbleSchedulerTest { private MarbleScheduler scheduler; @Before public void setupScheduler() { scheduler = new MarbleScheduler(); } @After public void flushScheduler() { if (scheduler != null) { scheduler.flush(); } } @Test public void should_create_a_cold_observable() {
ColdObservable<String> source = scheduler.createColdObservable("--a---b--|", of("a", "A", "b", "B"));
alexvictoor/MarbleTest4J
src/test/java/rx/marble/MarbleSchedulerTest.java
// Path: src/main/java/rx/marble/MapHelper.java // public static <V> Map<String, V> of(String k, V v) { // return Collections.singletonMap(k,v); // }
import org.junit.After; import org.junit.Before; import org.junit.Test; import rx.Observable; import rx.Subscription; import rx.functions.Action0; import rx.functions.Func1; import rx.observers.TestSubscriber; import rx.subjects.BehaviorSubject; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Collections; import java.util.Map; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; import static rx.marble.MapHelper.of;
package rx.marble; public class MarbleSchedulerTest { private MarbleScheduler scheduler; @Before public void setupScheduler() { scheduler = new MarbleScheduler(); } @After public void flushScheduler() { if (scheduler != null) { scheduler.flush(); } } @Test public void should_create_a_cold_observable() {
// Path: src/main/java/rx/marble/MapHelper.java // public static <V> Map<String, V> of(String k, V v) { // return Collections.singletonMap(k,v); // } // Path: src/test/java/rx/marble/MarbleSchedulerTest.java import org.junit.After; import org.junit.Before; import org.junit.Test; import rx.Observable; import rx.Subscription; import rx.functions.Action0; import rx.functions.Func1; import rx.observers.TestSubscriber; import rx.subjects.BehaviorSubject; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Collections; import java.util.Map; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; import static rx.marble.MapHelper.of; package rx.marble; public class MarbleSchedulerTest { private MarbleScheduler scheduler; @Before public void setupScheduler() { scheduler = new MarbleScheduler(); } @After public void flushScheduler() { if (scheduler != null) { scheduler.flush(); } } @Test public void should_create_a_cold_observable() {
ColdObservable<String> source = scheduler.createColdObservable("--a---b--|", of("a", "A", "b", "B"));
alexvictoor/MarbleTest4J
src/test/java/io/reactivex/marble/junit/DemoTest.java
// Path: src/main/java/io/reactivex/marble/ColdObservable.java // public class ColdObservable<T> extends Observable<T> implements TestablePublisher<T> { // // private final TestablePublisher<T> publisher; // // protected ColdObservable(TestablePublisher<T> publisher) { // this.publisher = publisher; // } // // @Override // public void subscribe(Subscriber<? super T> s) { // publisher.subscribe(s); // } // // @Override // protected void subscribeActual(Observer<? super T> observer) { // publisher.subscribe(new ObserverAdapter<>(observer)); // } // // @Override // public List<SubscriptionLog> getSubscriptions() { // return publisher.getSubscriptions(); // } // // @Override // public List<Recorded<T>> getMessages() { // return publisher.getMessages(); // } // // public static <T> ColdObservable<T> create(Scheduler scheduler, Recorded<T>... notifications) { // return create(scheduler, Arrays.asList(notifications)); // } // // public static <T> ColdObservable<T> create(final Scheduler scheduler, List<Recorded<T>> notifications) { // // ColdPublisher<T> coldPublisher = new ColdPublisher<>(new SchedulerFactory() { // @Override // public org.reactivestreams.Scheduler create() { // return new SchedulerAdapter(scheduler); // } // }, notifications); // // return new ColdObservable<>(coldPublisher); // } // // } // // Path: src/main/java/io/reactivex/marble/MapHelper.java // public static <V> Map<String, V> of(String k, V v) { // return Collections.singletonMap(k,v); // } // // Path: src/main/java/io/reactivex/marble/junit/MarbleRule.java // public class MarbleRule implements TestRule { // // private static ThreadLocal<MarbleScheduler> schedulerHolder = new ThreadLocal<>(); // // public final MarbleScheduler scheduler; // // public MarbleRule() { // scheduler = new MarbleScheduler(); // } // // public MarbleRule(long frameTimeFactor) { // scheduler = new MarbleScheduler(frameTimeFactor); // } // // public static <T> HotObservable<T> hot(String marbles, Map<String, T> values) { // return schedulerHolder.get().createHotObservable(marbles, values); // } // // public static HotObservable<String> hot(String marbles) { // return schedulerHolder.get().createHotObservable(marbles); // } // // public static <T> ColdObservable<T> cold(String marbles, Map<String, T> values) { // return schedulerHolder.get().createColdObservable(marbles, values); // } // // public static ColdObservable<String> cold(String marbles) { // return schedulerHolder.get().createColdObservable(marbles); // } // // public static ISetupTest expectObservable(Observable<?> actual) { // return schedulerHolder.get().expectObservable(actual); // } // // public static ISetupTest expectObservable(Observable<?> actual, String unsubscriptionMarbles) { // return schedulerHolder.get().expectObservable(actual, unsubscriptionMarbles); // } // // public static ISetupTest expectFlowable(Flowable<?> actual) { // return schedulerHolder.get().expectFlowable(actual); // } // // public static ISetupTest expectFlowable(Flowable<?> actual, String unsubscriptionMarbles) { // return schedulerHolder.get().expectFlowable(actual, unsubscriptionMarbles); // } // // public static ISetupTest expectSingle(Single<?> actual) { // return schedulerHolder.get().expectFlowable(actual.toFlowable()); // } // // public static ISetupTest expectSingle(Single<?> actual, String unsubscriptionMarbles) { // return schedulerHolder.get().expectFlowable(actual.toFlowable(), unsubscriptionMarbles); // } // // public static ISetupTest expectMaybe(Maybe<?> actual) { // return schedulerHolder.get().expectFlowable(actual.toFlowable()); // } // // public static ISetupTest expectCompletable(Completable actual, String unsubscriptionMarbles) { // return schedulerHolder.get().expectFlowable(actual.toFlowable(), unsubscriptionMarbles); // } // // public static ISetupTest expectCompletable(Completable actual) { // return schedulerHolder.get().expectFlowable(actual.toFlowable()); // } // // public static ISetupTest expectMaybe(Maybe<?> actual, String unsubscriptionMarbles) { // return schedulerHolder.get().expectObservable(actual.toObservable(), unsubscriptionMarbles); // } // // public static ISetupSubscriptionsTest expectSubscriptions(List<SubscriptionLog> subscriptions) { // return schedulerHolder.get().expectSubscriptions(subscriptions); // } // // @Override // public Statement apply(final Statement base, Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // schedulerHolder.set(scheduler); // try { // base.evaluate(); // scheduler.flush(); // } finally { // schedulerHolder.remove(); // } // // } // }; // } // }
import io.reactivex.*; import io.reactivex.annotations.NonNull; import io.reactivex.functions.BiFunction; import io.reactivex.functions.Consumer; import io.reactivex.functions.Function; import io.reactivex.marble.ColdObservable; import org.junit.Rule; import org.junit.Test; import java.util.Map; import java.util.concurrent.TimeUnit; import static io.reactivex.marble.MapHelper.of; import static io.reactivex.marble.junit.MarbleRule.*;
package io.reactivex.marble.junit; public class DemoTest { @Rule
// Path: src/main/java/io/reactivex/marble/ColdObservable.java // public class ColdObservable<T> extends Observable<T> implements TestablePublisher<T> { // // private final TestablePublisher<T> publisher; // // protected ColdObservable(TestablePublisher<T> publisher) { // this.publisher = publisher; // } // // @Override // public void subscribe(Subscriber<? super T> s) { // publisher.subscribe(s); // } // // @Override // protected void subscribeActual(Observer<? super T> observer) { // publisher.subscribe(new ObserverAdapter<>(observer)); // } // // @Override // public List<SubscriptionLog> getSubscriptions() { // return publisher.getSubscriptions(); // } // // @Override // public List<Recorded<T>> getMessages() { // return publisher.getMessages(); // } // // public static <T> ColdObservable<T> create(Scheduler scheduler, Recorded<T>... notifications) { // return create(scheduler, Arrays.asList(notifications)); // } // // public static <T> ColdObservable<T> create(final Scheduler scheduler, List<Recorded<T>> notifications) { // // ColdPublisher<T> coldPublisher = new ColdPublisher<>(new SchedulerFactory() { // @Override // public org.reactivestreams.Scheduler create() { // return new SchedulerAdapter(scheduler); // } // }, notifications); // // return new ColdObservable<>(coldPublisher); // } // // } // // Path: src/main/java/io/reactivex/marble/MapHelper.java // public static <V> Map<String, V> of(String k, V v) { // return Collections.singletonMap(k,v); // } // // Path: src/main/java/io/reactivex/marble/junit/MarbleRule.java // public class MarbleRule implements TestRule { // // private static ThreadLocal<MarbleScheduler> schedulerHolder = new ThreadLocal<>(); // // public final MarbleScheduler scheduler; // // public MarbleRule() { // scheduler = new MarbleScheduler(); // } // // public MarbleRule(long frameTimeFactor) { // scheduler = new MarbleScheduler(frameTimeFactor); // } // // public static <T> HotObservable<T> hot(String marbles, Map<String, T> values) { // return schedulerHolder.get().createHotObservable(marbles, values); // } // // public static HotObservable<String> hot(String marbles) { // return schedulerHolder.get().createHotObservable(marbles); // } // // public static <T> ColdObservable<T> cold(String marbles, Map<String, T> values) { // return schedulerHolder.get().createColdObservable(marbles, values); // } // // public static ColdObservable<String> cold(String marbles) { // return schedulerHolder.get().createColdObservable(marbles); // } // // public static ISetupTest expectObservable(Observable<?> actual) { // return schedulerHolder.get().expectObservable(actual); // } // // public static ISetupTest expectObservable(Observable<?> actual, String unsubscriptionMarbles) { // return schedulerHolder.get().expectObservable(actual, unsubscriptionMarbles); // } // // public static ISetupTest expectFlowable(Flowable<?> actual) { // return schedulerHolder.get().expectFlowable(actual); // } // // public static ISetupTest expectFlowable(Flowable<?> actual, String unsubscriptionMarbles) { // return schedulerHolder.get().expectFlowable(actual, unsubscriptionMarbles); // } // // public static ISetupTest expectSingle(Single<?> actual) { // return schedulerHolder.get().expectFlowable(actual.toFlowable()); // } // // public static ISetupTest expectSingle(Single<?> actual, String unsubscriptionMarbles) { // return schedulerHolder.get().expectFlowable(actual.toFlowable(), unsubscriptionMarbles); // } // // public static ISetupTest expectMaybe(Maybe<?> actual) { // return schedulerHolder.get().expectFlowable(actual.toFlowable()); // } // // public static ISetupTest expectCompletable(Completable actual, String unsubscriptionMarbles) { // return schedulerHolder.get().expectFlowable(actual.toFlowable(), unsubscriptionMarbles); // } // // public static ISetupTest expectCompletable(Completable actual) { // return schedulerHolder.get().expectFlowable(actual.toFlowable()); // } // // public static ISetupTest expectMaybe(Maybe<?> actual, String unsubscriptionMarbles) { // return schedulerHolder.get().expectObservable(actual.toObservable(), unsubscriptionMarbles); // } // // public static ISetupSubscriptionsTest expectSubscriptions(List<SubscriptionLog> subscriptions) { // return schedulerHolder.get().expectSubscriptions(subscriptions); // } // // @Override // public Statement apply(final Statement base, Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // schedulerHolder.set(scheduler); // try { // base.evaluate(); // scheduler.flush(); // } finally { // schedulerHolder.remove(); // } // // } // }; // } // } // Path: src/test/java/io/reactivex/marble/junit/DemoTest.java import io.reactivex.*; import io.reactivex.annotations.NonNull; import io.reactivex.functions.BiFunction; import io.reactivex.functions.Consumer; import io.reactivex.functions.Function; import io.reactivex.marble.ColdObservable; import org.junit.Rule; import org.junit.Test; import java.util.Map; import java.util.concurrent.TimeUnit; import static io.reactivex.marble.MapHelper.of; import static io.reactivex.marble.junit.MarbleRule.*; package io.reactivex.marble.junit; public class DemoTest { @Rule
public MarbleRule marble = new MarbleRule();
alexvictoor/MarbleTest4J
src/test/java/rx/marble/RecordedStreamComparatorTest.java
// Path: src/main/java/rx/marble/RecordedStreamComparator.java // public enum EventComparisonResult { EQUALS, ONLY_ON_ACTUAL, ONLY_ON_EXPECTED }
import org.junit.Test; import rx.Notification; import java.util.ArrayList; import java.util.List; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static rx.Notification.createOnError; import static rx.Notification.createOnNext; import static rx.marble.RecordedStreamComparator.EventComparisonResult.*;
package rx.marble; /** * Created by Alexandre Victoor on 26/10/2016. */ public class RecordedStreamComparatorTest { @Test public void should_detect_missing_event_in_actual_records() { // given Recorded<?> onCompletedEvent = new Recorded<>(10, Notification.createOnCompleted()); List<Recorded<?>> actualRecords = asList(); List<Recorded<?>> expectedRecords = new ArrayList<>(); expectedRecords.add(onCompletedEvent); // when RecordedStreamComparator.StreamComparison result = new RecordedStreamComparator().compare(actualRecords, expectedRecords); // then assertThat(result.streamEquals).isFalse(); assertThat(result.unitComparisons).hasSize(1); assertThat(result.unitComparisons.get(0)).isEqualToComparingFieldByField(
// Path: src/main/java/rx/marble/RecordedStreamComparator.java // public enum EventComparisonResult { EQUALS, ONLY_ON_ACTUAL, ONLY_ON_EXPECTED } // Path: src/test/java/rx/marble/RecordedStreamComparatorTest.java import org.junit.Test; import rx.Notification; import java.util.ArrayList; import java.util.List; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static rx.Notification.createOnError; import static rx.Notification.createOnNext; import static rx.marble.RecordedStreamComparator.EventComparisonResult.*; package rx.marble; /** * Created by Alexandre Victoor on 26/10/2016. */ public class RecordedStreamComparatorTest { @Test public void should_detect_missing_event_in_actual_records() { // given Recorded<?> onCompletedEvent = new Recorded<>(10, Notification.createOnCompleted()); List<Recorded<?>> actualRecords = asList(); List<Recorded<?>> expectedRecords = new ArrayList<>(); expectedRecords.add(onCompletedEvent); // when RecordedStreamComparator.StreamComparison result = new RecordedStreamComparator().compare(actualRecords, expectedRecords); // then assertThat(result.streamEquals).isFalse(); assertThat(result.unitComparisons).hasSize(1); assertThat(result.unitComparisons.get(0)).isEqualToComparingFieldByField(
new RecordedStreamComparator.EventComparison(onCompletedEvent, RecordedStreamComparator.EventComparisonResult.ONLY_ON_EXPECTED)
alexvictoor/MarbleTest4J
src/test/java/rx/marble/junit/DemoTest.java
// Path: src/main/java/rx/marble/ColdObservable.java // public class ColdObservable<T> extends Observable<T> implements TestableObservable<T> { // // private final List<Recorded<T>> notifications; // private List<SubscriptionLog> subscriptions = new ArrayList<>(); // // private ColdObservable(OnSubscribe<T> f, List<Recorded<T>> notifications) { // super(f); // this.notifications = notifications; // } // // @Override // public List<SubscriptionLog> getSubscriptions() { // return Collections.unmodifiableList(subscriptions); // } // // @Override // public List<Recorded<T>> getMessages() { // return Collections.unmodifiableList(notifications); // } // // public static <T> ColdObservable<T> create(Scheduler scheduler, Recorded<T>... notifications) { // return create(scheduler, Arrays.asList(notifications)); // } // // public static <T> ColdObservable<T> create(Scheduler scheduler, List<Recorded<T>> notifications) { // OnSubscribeHandler<T> onSubscribeFunc = new OnSubscribeHandler<>(scheduler, notifications); // ColdObservable<T> observable = new ColdObservable<>(onSubscribeFunc, notifications); // onSubscribeFunc.observable = observable; // return observable; // } // // // private static class OnSubscribeHandler<T> implements Observable.OnSubscribe<T> { // // private final Scheduler scheduler; // private final List<Recorded<T>> notifications; // public ColdObservable observable; // // public OnSubscribeHandler(Scheduler scheduler, List<Recorded<T>> notifications) { // this.scheduler = scheduler; // this.notifications = notifications; // } // // public void call(final Subscriber<? super T> subscriber) { // final SubscriptionLog subscriptionLog = new SubscriptionLog(scheduler.now()); // observable.subscriptions.add(subscriptionLog); // final int subscriptionIndex = observable.getSubscriptions().size() - 1; // Scheduler.Worker worker = scheduler.createWorker(); // subscriber.add(worker); // not scheduling after unsubscribe // // for (final Recorded<T> notification: notifications) { // worker.schedule(new Action0() { // @Override // public void call() { // notification.value.accept(subscriber); // } // }, notification.time, TimeUnit.MILLISECONDS); // } // // subscriber.add((Subscriptions.create(new Action0() { // @Override // public void call() { // // on unsubscribe // observable.subscriptions.set( // subscriptionIndex, // new SubscriptionLog(subscriptionLog.subscribe, scheduler.now()) // ); // } // }))); // } // } // } // // Path: src/main/java/rx/marble/MapHelper.java // public static <V> Map<String, V> of(String k, V v) { // return Collections.singletonMap(k,v); // } // // Path: src/main/java/rx/marble/junit/MarbleRule.java // public class MarbleRule implements TestRule { // // private static ThreadLocal<MarbleScheduler> schedulerHolder = new ThreadLocal<>(); // // public final MarbleScheduler scheduler; // // public MarbleRule() { // scheduler = new MarbleScheduler(); // } // // public MarbleRule(long frameTimeFactor) { // scheduler = new MarbleScheduler(frameTimeFactor); // } // // public static <T> HotObservable<T> hot(String marbles, Map<String, T> values) { // return schedulerHolder.get().createHotObservable(marbles, values); // } // // public static HotObservable<String> hot(String marbles) { // return schedulerHolder.get().createHotObservable(marbles); // } // // public static <T> ColdObservable<T> cold(String marbles, Map<String, T> values) { // return schedulerHolder.get().createColdObservable(marbles, values); // } // // public static ColdObservable<String> cold(String marbles) { // return schedulerHolder.get().createColdObservable(marbles); // } // // public static ISetupTest expectObservable(Observable<?> actual) { // return schedulerHolder.get().expectObservable(actual); // } // // public static ISetupTest expectObservable(Observable<?> actual, String unsubscriptionMarbles) { // return schedulerHolder.get().expectObservable(actual, unsubscriptionMarbles); // } // // public static ISetupSubscriptionsTest expectSubscriptions(List<SubscriptionLog> subscriptions) { // return schedulerHolder.get().expectSubscriptions(subscriptions); // } // // @Override // public Statement apply(final Statement base, Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // schedulerHolder.set(scheduler); // try { // base.evaluate(); // scheduler.flush(); // } finally { // schedulerHolder.remove(); // } // // } // }; // } // }
import org.junit.Rule; import org.junit.Test; import rx.Observable; import rx.functions.Func1; import rx.functions.Func2; import rx.marble.ColdObservable; import java.util.Map; import static rx.marble.MapHelper.of; import static rx.marble.junit.MarbleRule.*;
package rx.marble.junit; public class DemoTest { @Rule
// Path: src/main/java/rx/marble/ColdObservable.java // public class ColdObservable<T> extends Observable<T> implements TestableObservable<T> { // // private final List<Recorded<T>> notifications; // private List<SubscriptionLog> subscriptions = new ArrayList<>(); // // private ColdObservable(OnSubscribe<T> f, List<Recorded<T>> notifications) { // super(f); // this.notifications = notifications; // } // // @Override // public List<SubscriptionLog> getSubscriptions() { // return Collections.unmodifiableList(subscriptions); // } // // @Override // public List<Recorded<T>> getMessages() { // return Collections.unmodifiableList(notifications); // } // // public static <T> ColdObservable<T> create(Scheduler scheduler, Recorded<T>... notifications) { // return create(scheduler, Arrays.asList(notifications)); // } // // public static <T> ColdObservable<T> create(Scheduler scheduler, List<Recorded<T>> notifications) { // OnSubscribeHandler<T> onSubscribeFunc = new OnSubscribeHandler<>(scheduler, notifications); // ColdObservable<T> observable = new ColdObservable<>(onSubscribeFunc, notifications); // onSubscribeFunc.observable = observable; // return observable; // } // // // private static class OnSubscribeHandler<T> implements Observable.OnSubscribe<T> { // // private final Scheduler scheduler; // private final List<Recorded<T>> notifications; // public ColdObservable observable; // // public OnSubscribeHandler(Scheduler scheduler, List<Recorded<T>> notifications) { // this.scheduler = scheduler; // this.notifications = notifications; // } // // public void call(final Subscriber<? super T> subscriber) { // final SubscriptionLog subscriptionLog = new SubscriptionLog(scheduler.now()); // observable.subscriptions.add(subscriptionLog); // final int subscriptionIndex = observable.getSubscriptions().size() - 1; // Scheduler.Worker worker = scheduler.createWorker(); // subscriber.add(worker); // not scheduling after unsubscribe // // for (final Recorded<T> notification: notifications) { // worker.schedule(new Action0() { // @Override // public void call() { // notification.value.accept(subscriber); // } // }, notification.time, TimeUnit.MILLISECONDS); // } // // subscriber.add((Subscriptions.create(new Action0() { // @Override // public void call() { // // on unsubscribe // observable.subscriptions.set( // subscriptionIndex, // new SubscriptionLog(subscriptionLog.subscribe, scheduler.now()) // ); // } // }))); // } // } // } // // Path: src/main/java/rx/marble/MapHelper.java // public static <V> Map<String, V> of(String k, V v) { // return Collections.singletonMap(k,v); // } // // Path: src/main/java/rx/marble/junit/MarbleRule.java // public class MarbleRule implements TestRule { // // private static ThreadLocal<MarbleScheduler> schedulerHolder = new ThreadLocal<>(); // // public final MarbleScheduler scheduler; // // public MarbleRule() { // scheduler = new MarbleScheduler(); // } // // public MarbleRule(long frameTimeFactor) { // scheduler = new MarbleScheduler(frameTimeFactor); // } // // public static <T> HotObservable<T> hot(String marbles, Map<String, T> values) { // return schedulerHolder.get().createHotObservable(marbles, values); // } // // public static HotObservable<String> hot(String marbles) { // return schedulerHolder.get().createHotObservable(marbles); // } // // public static <T> ColdObservable<T> cold(String marbles, Map<String, T> values) { // return schedulerHolder.get().createColdObservable(marbles, values); // } // // public static ColdObservable<String> cold(String marbles) { // return schedulerHolder.get().createColdObservable(marbles); // } // // public static ISetupTest expectObservable(Observable<?> actual) { // return schedulerHolder.get().expectObservable(actual); // } // // public static ISetupTest expectObservable(Observable<?> actual, String unsubscriptionMarbles) { // return schedulerHolder.get().expectObservable(actual, unsubscriptionMarbles); // } // // public static ISetupSubscriptionsTest expectSubscriptions(List<SubscriptionLog> subscriptions) { // return schedulerHolder.get().expectSubscriptions(subscriptions); // } // // @Override // public Statement apply(final Statement base, Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // schedulerHolder.set(scheduler); // try { // base.evaluate(); // scheduler.flush(); // } finally { // schedulerHolder.remove(); // } // // } // }; // } // } // Path: src/test/java/rx/marble/junit/DemoTest.java import org.junit.Rule; import org.junit.Test; import rx.Observable; import rx.functions.Func1; import rx.functions.Func2; import rx.marble.ColdObservable; import java.util.Map; import static rx.marble.MapHelper.of; import static rx.marble.junit.MarbleRule.*; package rx.marble.junit; public class DemoTest { @Rule
public MarbleRule marble = new MarbleRule();
alexvictoor/MarbleTest4J
src/test/java/rx/marble/junit/DemoTest.java
// Path: src/main/java/rx/marble/ColdObservable.java // public class ColdObservable<T> extends Observable<T> implements TestableObservable<T> { // // private final List<Recorded<T>> notifications; // private List<SubscriptionLog> subscriptions = new ArrayList<>(); // // private ColdObservable(OnSubscribe<T> f, List<Recorded<T>> notifications) { // super(f); // this.notifications = notifications; // } // // @Override // public List<SubscriptionLog> getSubscriptions() { // return Collections.unmodifiableList(subscriptions); // } // // @Override // public List<Recorded<T>> getMessages() { // return Collections.unmodifiableList(notifications); // } // // public static <T> ColdObservable<T> create(Scheduler scheduler, Recorded<T>... notifications) { // return create(scheduler, Arrays.asList(notifications)); // } // // public static <T> ColdObservable<T> create(Scheduler scheduler, List<Recorded<T>> notifications) { // OnSubscribeHandler<T> onSubscribeFunc = new OnSubscribeHandler<>(scheduler, notifications); // ColdObservable<T> observable = new ColdObservable<>(onSubscribeFunc, notifications); // onSubscribeFunc.observable = observable; // return observable; // } // // // private static class OnSubscribeHandler<T> implements Observable.OnSubscribe<T> { // // private final Scheduler scheduler; // private final List<Recorded<T>> notifications; // public ColdObservable observable; // // public OnSubscribeHandler(Scheduler scheduler, List<Recorded<T>> notifications) { // this.scheduler = scheduler; // this.notifications = notifications; // } // // public void call(final Subscriber<? super T> subscriber) { // final SubscriptionLog subscriptionLog = new SubscriptionLog(scheduler.now()); // observable.subscriptions.add(subscriptionLog); // final int subscriptionIndex = observable.getSubscriptions().size() - 1; // Scheduler.Worker worker = scheduler.createWorker(); // subscriber.add(worker); // not scheduling after unsubscribe // // for (final Recorded<T> notification: notifications) { // worker.schedule(new Action0() { // @Override // public void call() { // notification.value.accept(subscriber); // } // }, notification.time, TimeUnit.MILLISECONDS); // } // // subscriber.add((Subscriptions.create(new Action0() { // @Override // public void call() { // // on unsubscribe // observable.subscriptions.set( // subscriptionIndex, // new SubscriptionLog(subscriptionLog.subscribe, scheduler.now()) // ); // } // }))); // } // } // } // // Path: src/main/java/rx/marble/MapHelper.java // public static <V> Map<String, V> of(String k, V v) { // return Collections.singletonMap(k,v); // } // // Path: src/main/java/rx/marble/junit/MarbleRule.java // public class MarbleRule implements TestRule { // // private static ThreadLocal<MarbleScheduler> schedulerHolder = new ThreadLocal<>(); // // public final MarbleScheduler scheduler; // // public MarbleRule() { // scheduler = new MarbleScheduler(); // } // // public MarbleRule(long frameTimeFactor) { // scheduler = new MarbleScheduler(frameTimeFactor); // } // // public static <T> HotObservable<T> hot(String marbles, Map<String, T> values) { // return schedulerHolder.get().createHotObservable(marbles, values); // } // // public static HotObservable<String> hot(String marbles) { // return schedulerHolder.get().createHotObservable(marbles); // } // // public static <T> ColdObservable<T> cold(String marbles, Map<String, T> values) { // return schedulerHolder.get().createColdObservable(marbles, values); // } // // public static ColdObservable<String> cold(String marbles) { // return schedulerHolder.get().createColdObservable(marbles); // } // // public static ISetupTest expectObservable(Observable<?> actual) { // return schedulerHolder.get().expectObservable(actual); // } // // public static ISetupTest expectObservable(Observable<?> actual, String unsubscriptionMarbles) { // return schedulerHolder.get().expectObservable(actual, unsubscriptionMarbles); // } // // public static ISetupSubscriptionsTest expectSubscriptions(List<SubscriptionLog> subscriptions) { // return schedulerHolder.get().expectSubscriptions(subscriptions); // } // // @Override // public Statement apply(final Statement base, Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // schedulerHolder.set(scheduler); // try { // base.evaluate(); // scheduler.flush(); // } finally { // schedulerHolder.remove(); // } // // } // }; // } // }
import org.junit.Rule; import org.junit.Test; import rx.Observable; import rx.functions.Func1; import rx.functions.Func2; import rx.marble.ColdObservable; import java.util.Map; import static rx.marble.MapHelper.of; import static rx.marble.junit.MarbleRule.*;
package rx.marble.junit; public class DemoTest { @Rule public MarbleRule marble = new MarbleRule(); @Test public void should_map() { // given Observable<String> input = hot("a-b-c-d"); // when Observable<String> output = input.map(new Func1<String, String>() { @Override public String call(String s) { return s.toUpperCase(); } }); // then expectObservable(output).toBe("A-B-C-D"); } @Test public void should_sum() { // given
// Path: src/main/java/rx/marble/ColdObservable.java // public class ColdObservable<T> extends Observable<T> implements TestableObservable<T> { // // private final List<Recorded<T>> notifications; // private List<SubscriptionLog> subscriptions = new ArrayList<>(); // // private ColdObservable(OnSubscribe<T> f, List<Recorded<T>> notifications) { // super(f); // this.notifications = notifications; // } // // @Override // public List<SubscriptionLog> getSubscriptions() { // return Collections.unmodifiableList(subscriptions); // } // // @Override // public List<Recorded<T>> getMessages() { // return Collections.unmodifiableList(notifications); // } // // public static <T> ColdObservable<T> create(Scheduler scheduler, Recorded<T>... notifications) { // return create(scheduler, Arrays.asList(notifications)); // } // // public static <T> ColdObservable<T> create(Scheduler scheduler, List<Recorded<T>> notifications) { // OnSubscribeHandler<T> onSubscribeFunc = new OnSubscribeHandler<>(scheduler, notifications); // ColdObservable<T> observable = new ColdObservable<>(onSubscribeFunc, notifications); // onSubscribeFunc.observable = observable; // return observable; // } // // // private static class OnSubscribeHandler<T> implements Observable.OnSubscribe<T> { // // private final Scheduler scheduler; // private final List<Recorded<T>> notifications; // public ColdObservable observable; // // public OnSubscribeHandler(Scheduler scheduler, List<Recorded<T>> notifications) { // this.scheduler = scheduler; // this.notifications = notifications; // } // // public void call(final Subscriber<? super T> subscriber) { // final SubscriptionLog subscriptionLog = new SubscriptionLog(scheduler.now()); // observable.subscriptions.add(subscriptionLog); // final int subscriptionIndex = observable.getSubscriptions().size() - 1; // Scheduler.Worker worker = scheduler.createWorker(); // subscriber.add(worker); // not scheduling after unsubscribe // // for (final Recorded<T> notification: notifications) { // worker.schedule(new Action0() { // @Override // public void call() { // notification.value.accept(subscriber); // } // }, notification.time, TimeUnit.MILLISECONDS); // } // // subscriber.add((Subscriptions.create(new Action0() { // @Override // public void call() { // // on unsubscribe // observable.subscriptions.set( // subscriptionIndex, // new SubscriptionLog(subscriptionLog.subscribe, scheduler.now()) // ); // } // }))); // } // } // } // // Path: src/main/java/rx/marble/MapHelper.java // public static <V> Map<String, V> of(String k, V v) { // return Collections.singletonMap(k,v); // } // // Path: src/main/java/rx/marble/junit/MarbleRule.java // public class MarbleRule implements TestRule { // // private static ThreadLocal<MarbleScheduler> schedulerHolder = new ThreadLocal<>(); // // public final MarbleScheduler scheduler; // // public MarbleRule() { // scheduler = new MarbleScheduler(); // } // // public MarbleRule(long frameTimeFactor) { // scheduler = new MarbleScheduler(frameTimeFactor); // } // // public static <T> HotObservable<T> hot(String marbles, Map<String, T> values) { // return schedulerHolder.get().createHotObservable(marbles, values); // } // // public static HotObservable<String> hot(String marbles) { // return schedulerHolder.get().createHotObservable(marbles); // } // // public static <T> ColdObservable<T> cold(String marbles, Map<String, T> values) { // return schedulerHolder.get().createColdObservable(marbles, values); // } // // public static ColdObservable<String> cold(String marbles) { // return schedulerHolder.get().createColdObservable(marbles); // } // // public static ISetupTest expectObservable(Observable<?> actual) { // return schedulerHolder.get().expectObservable(actual); // } // // public static ISetupTest expectObservable(Observable<?> actual, String unsubscriptionMarbles) { // return schedulerHolder.get().expectObservable(actual, unsubscriptionMarbles); // } // // public static ISetupSubscriptionsTest expectSubscriptions(List<SubscriptionLog> subscriptions) { // return schedulerHolder.get().expectSubscriptions(subscriptions); // } // // @Override // public Statement apply(final Statement base, Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // schedulerHolder.set(scheduler); // try { // base.evaluate(); // scheduler.flush(); // } finally { // schedulerHolder.remove(); // } // // } // }; // } // } // Path: src/test/java/rx/marble/junit/DemoTest.java import org.junit.Rule; import org.junit.Test; import rx.Observable; import rx.functions.Func1; import rx.functions.Func2; import rx.marble.ColdObservable; import java.util.Map; import static rx.marble.MapHelper.of; import static rx.marble.junit.MarbleRule.*; package rx.marble.junit; public class DemoTest { @Rule public MarbleRule marble = new MarbleRule(); @Test public void should_map() { // given Observable<String> input = hot("a-b-c-d"); // when Observable<String> output = input.map(new Func1<String, String>() { @Override public String call(String s) { return s.toUpperCase(); } }); // then expectObservable(output).toBe("A-B-C-D"); } @Test public void should_sum() { // given
Observable<Integer> input = cold("a-b-c-d", of("a", 1, "b", 2, "c", 3, "d", 4));
alexvictoor/MarbleTest4J
src/test/java/reactor/junit/DemoTest.java
// Path: src/main/java/reactor/ColdFlux.java // public class ColdFlux<T> extends Flux<T> implements TestablePublisher<T> { // // private final TestablePublisher<T> publisher; // // protected ColdFlux(TestablePublisher<T> publisher) { // this.publisher = publisher; // } // // @Override // public void subscribe(Subscriber<? super T> s) { // publisher.subscribe(s); // } // // @Override // public List<SubscriptionLog> getSubscriptions() { // return publisher.getSubscriptions(); // } // // @Override // public List<Recorded<T>> getMessages() { // return publisher.getMessages(); // } // // public static <T> ColdFlux<T> create(Scheduler scheduler, Recorded<T>... notifications) { // return create(scheduler, Arrays.asList(notifications)); // } // // public static <T> ColdFlux<T> create(final Scheduler scheduler, List<Recorded<T>> notifications) { // // ColdPublisher<T> coldPublisher = new ColdPublisher<>(new SchedulerFactory() { // @Override // public org.reactivestreams.Scheduler create() { // return new SchedulerAdapter(scheduler); // } // }, notifications); // // return new ColdFlux<>(coldPublisher); // } // // } // // Path: src/main/java/reactor/MapHelper.java // public class MapHelper { // // public static <V> Map<String, V> of(String k, V v) { // return Collections.singletonMap(k,v); // } // // public static <V> Map<String, V> of(String k1, V v1, String k2, V v2) { // Map<String, V> map = new HashMap<>(); // map.put(k1, v1); // map.put(k2, v2); // return map; // } // // public static <V> Map<String, V> of(String k1, V v1, String k2, V v2, String k3, V v3) { // Map<String, V> result = of(k1, v1, k2, v2); // result.put(k3, v3); // return result; // } // // public static <V> Map<String, V> of(String k1, V v1, String k2, V v2, String k3, V v3, String k4, V v4) { // Map<String, V> result = of(k1, v1, k2, v2, k3, v3); // result.put(k4, v4); // return result; // } // // public static <V> Map<String, V> of(String k1, V v1, String k2, V v2, String k3, V v3, String k4, V v4, String k5, V v5) { // Map<String, V> result = of(k1, v1, k2, v2, k3, v3, k4, v4); // result.put(k5, v5); // return result; // } // } // // Path: src/main/java/reactor/junit/MarbleRule.java // public static ISetupTest expectFlux(Flux<?> actual) { // return schedulerHolder.get().expectFlux(actual); // } // // Path: src/main/java/reactor/junit/MarbleRule.java // public class MarbleRule implements TestRule { // // private static ThreadLocal<MarbleScheduler> schedulerHolder = new ThreadLocal<>(); // // public final MarbleScheduler scheduler; // // public MarbleRule() { // scheduler = new MarbleScheduler(); // } // // public MarbleRule(long frameTimeFactor) { // scheduler = new MarbleScheduler(frameTimeFactor); // } // // public static <T> HotFlux<T> hot(String marbles, Map<String, T> values) { // return schedulerHolder.get().createHotFlux(marbles, values); // } // // public static HotFlux<String> hot(String marbles) { // return schedulerHolder.get().createHotFlux(marbles); // } // // public static <T> ColdFlux<T> cold(String marbles, Map<String, T> values) { // return schedulerHolder.get().createColdFlux(marbles, values); // } // // public static ColdFlux<String> cold(String marbles) { // return schedulerHolder.get().createColdFlux(marbles); // } // // public static ISetupTest expectFlux(Flux<?> actual) { // return schedulerHolder.get().expectFlux(actual); // } // // public static ISetupTest expectFlux(Flux<?> actual, String unsubscriptionMarbles) { // return schedulerHolder.get().expectFlux(actual, unsubscriptionMarbles); // } // // public static ISetupTest expectMono(Mono<?> actual) { // return schedulerHolder.get().expectFlux(actual.flux()); // } // // public static ISetupTest expectMono(Mono<?> actual, String unsubscriptionMarbles) { // return schedulerHolder.get().expectFlux(actual.flux(), unsubscriptionMarbles); // } // // public static ISetupSubscriptionsTest expectSubscriptions(List<SubscriptionLog> subscriptions) { // return schedulerHolder.get().expectSubscriptions(subscriptions); // } // // @Override // public Statement apply(final Statement base, Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // schedulerHolder.set(scheduler); // try { // base.evaluate(); // scheduler.flush(); // } finally { // schedulerHolder.remove(); // } // // } // }; // } // }
import org.junit.Rule; import org.junit.Test; import reactor.ColdFlux; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.util.Map; import java.util.function.BiFunction; import java.util.function.Function; import static reactor.MapHelper.*; import static reactor.junit.MarbleRule.expectFlux; import static reactor.junit.MarbleRule.*;
package reactor.junit; /** * Created by Alexandre Victoor on 26/04/2017. */ public class DemoTest { @Rule
// Path: src/main/java/reactor/ColdFlux.java // public class ColdFlux<T> extends Flux<T> implements TestablePublisher<T> { // // private final TestablePublisher<T> publisher; // // protected ColdFlux(TestablePublisher<T> publisher) { // this.publisher = publisher; // } // // @Override // public void subscribe(Subscriber<? super T> s) { // publisher.subscribe(s); // } // // @Override // public List<SubscriptionLog> getSubscriptions() { // return publisher.getSubscriptions(); // } // // @Override // public List<Recorded<T>> getMessages() { // return publisher.getMessages(); // } // // public static <T> ColdFlux<T> create(Scheduler scheduler, Recorded<T>... notifications) { // return create(scheduler, Arrays.asList(notifications)); // } // // public static <T> ColdFlux<T> create(final Scheduler scheduler, List<Recorded<T>> notifications) { // // ColdPublisher<T> coldPublisher = new ColdPublisher<>(new SchedulerFactory() { // @Override // public org.reactivestreams.Scheduler create() { // return new SchedulerAdapter(scheduler); // } // }, notifications); // // return new ColdFlux<>(coldPublisher); // } // // } // // Path: src/main/java/reactor/MapHelper.java // public class MapHelper { // // public static <V> Map<String, V> of(String k, V v) { // return Collections.singletonMap(k,v); // } // // public static <V> Map<String, V> of(String k1, V v1, String k2, V v2) { // Map<String, V> map = new HashMap<>(); // map.put(k1, v1); // map.put(k2, v2); // return map; // } // // public static <V> Map<String, V> of(String k1, V v1, String k2, V v2, String k3, V v3) { // Map<String, V> result = of(k1, v1, k2, v2); // result.put(k3, v3); // return result; // } // // public static <V> Map<String, V> of(String k1, V v1, String k2, V v2, String k3, V v3, String k4, V v4) { // Map<String, V> result = of(k1, v1, k2, v2, k3, v3); // result.put(k4, v4); // return result; // } // // public static <V> Map<String, V> of(String k1, V v1, String k2, V v2, String k3, V v3, String k4, V v4, String k5, V v5) { // Map<String, V> result = of(k1, v1, k2, v2, k3, v3, k4, v4); // result.put(k5, v5); // return result; // } // } // // Path: src/main/java/reactor/junit/MarbleRule.java // public static ISetupTest expectFlux(Flux<?> actual) { // return schedulerHolder.get().expectFlux(actual); // } // // Path: src/main/java/reactor/junit/MarbleRule.java // public class MarbleRule implements TestRule { // // private static ThreadLocal<MarbleScheduler> schedulerHolder = new ThreadLocal<>(); // // public final MarbleScheduler scheduler; // // public MarbleRule() { // scheduler = new MarbleScheduler(); // } // // public MarbleRule(long frameTimeFactor) { // scheduler = new MarbleScheduler(frameTimeFactor); // } // // public static <T> HotFlux<T> hot(String marbles, Map<String, T> values) { // return schedulerHolder.get().createHotFlux(marbles, values); // } // // public static HotFlux<String> hot(String marbles) { // return schedulerHolder.get().createHotFlux(marbles); // } // // public static <T> ColdFlux<T> cold(String marbles, Map<String, T> values) { // return schedulerHolder.get().createColdFlux(marbles, values); // } // // public static ColdFlux<String> cold(String marbles) { // return schedulerHolder.get().createColdFlux(marbles); // } // // public static ISetupTest expectFlux(Flux<?> actual) { // return schedulerHolder.get().expectFlux(actual); // } // // public static ISetupTest expectFlux(Flux<?> actual, String unsubscriptionMarbles) { // return schedulerHolder.get().expectFlux(actual, unsubscriptionMarbles); // } // // public static ISetupTest expectMono(Mono<?> actual) { // return schedulerHolder.get().expectFlux(actual.flux()); // } // // public static ISetupTest expectMono(Mono<?> actual, String unsubscriptionMarbles) { // return schedulerHolder.get().expectFlux(actual.flux(), unsubscriptionMarbles); // } // // public static ISetupSubscriptionsTest expectSubscriptions(List<SubscriptionLog> subscriptions) { // return schedulerHolder.get().expectSubscriptions(subscriptions); // } // // @Override // public Statement apply(final Statement base, Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // schedulerHolder.set(scheduler); // try { // base.evaluate(); // scheduler.flush(); // } finally { // schedulerHolder.remove(); // } // // } // }; // } // } // Path: src/test/java/reactor/junit/DemoTest.java import org.junit.Rule; import org.junit.Test; import reactor.ColdFlux; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.util.Map; import java.util.function.BiFunction; import java.util.function.Function; import static reactor.MapHelper.*; import static reactor.junit.MarbleRule.expectFlux; import static reactor.junit.MarbleRule.*; package reactor.junit; /** * Created by Alexandre Victoor on 26/04/2017. */ public class DemoTest { @Rule
public MarbleRule marble = new MarbleRule();
opensciencemap/vtm-app
src/org/oscim/app/location/Compass.java
// Path: src/org/oscim/app/App.java // public class App extends Application { // // public final static Logger log = LoggerFactory.getLogger(App.class); // // public static Map map; // public static MapView view; // public static Resources res; // public static TileMap activity; // // public static POISearch poiSearch; // public static RouteSearch routeSearch; // // @Override // public void onCreate() { // super.onCreate(); // res = getResources(); // } // // public static void lockOrientation(Activity activity) { // Display display = ((WindowManager) activity.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); // int rotation = display.getRotation(); // int tempOrientation = activity.getResources().getConfiguration().orientation; // int orientation = 0; // switch (tempOrientation) // { // case Configuration.ORIENTATION_LANDSCAPE: // if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_90) // orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; // else // orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE; // break; // case Configuration.ORIENTATION_PORTRAIT: // if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_270) // orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; // else // orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT; // } // activity.setRequestedOrientation(orientation); // } // }
import android.widget.ImageView; import org.oscim.app.App; import org.oscim.app.R; import org.oscim.core.MapPosition; import org.oscim.event.Event; import org.oscim.layers.Layer; import org.oscim.map.Map; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.view.animation.Animation; import android.view.animation.RotateAnimation;
/* * Copyright 2013 Ahmad Saleem * Copyright 2013 Hannes Janetzek * * This program is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * This program 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.oscim.app.location; @SuppressWarnings("deprecation") public class Compass extends Layer implements SensorEventListener, Map.UpdateListener { // final static Logger log = LoggerFactory.getLogger(Compass.class); public enum Mode { OFF, C2D, C3D, } private final SensorManager mSensorManager; private final ImageView mArrowView; // private final float[] mRotationM = new float[9]; private final float[] mRotationV = new float[3]; // private float[] mAccelV = new float[3]; // private float[] mMagnetV = new float[3]; // private boolean mLastAccelerometerSet; // private boolean mLastMagnetometerSet; private float mCurRotation; private float mCurTilt; private boolean mControlOrientation; private Mode mMode = Mode.OFF; private int mListeners; @Override public void onMapEvent(Event e, MapPosition mapPosition) { if (!mControlOrientation) { float rotation = -mapPosition.bearing; adjustArrow(rotation, rotation); } } public Compass(Context context, Map map) { super(map); mSensorManager = (SensorManager) context .getSystemService(Context.SENSOR_SERVICE); // List<Sensor> s = mSensorManager.getSensorList(Sensor.TYPE_ALL); // for (Sensor sensor : s) // log.debug(sensor.toString());
// Path: src/org/oscim/app/App.java // public class App extends Application { // // public final static Logger log = LoggerFactory.getLogger(App.class); // // public static Map map; // public static MapView view; // public static Resources res; // public static TileMap activity; // // public static POISearch poiSearch; // public static RouteSearch routeSearch; // // @Override // public void onCreate() { // super.onCreate(); // res = getResources(); // } // // public static void lockOrientation(Activity activity) { // Display display = ((WindowManager) activity.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); // int rotation = display.getRotation(); // int tempOrientation = activity.getResources().getConfiguration().orientation; // int orientation = 0; // switch (tempOrientation) // { // case Configuration.ORIENTATION_LANDSCAPE: // if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_90) // orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; // else // orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE; // break; // case Configuration.ORIENTATION_PORTRAIT: // if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_270) // orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; // else // orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT; // } // activity.setRequestedOrientation(orientation); // } // } // Path: src/org/oscim/app/location/Compass.java import android.widget.ImageView; import org.oscim.app.App; import org.oscim.app.R; import org.oscim.core.MapPosition; import org.oscim.event.Event; import org.oscim.layers.Layer; import org.oscim.map.Map; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.view.animation.Animation; import android.view.animation.RotateAnimation; /* * Copyright 2013 Ahmad Saleem * Copyright 2013 Hannes Janetzek * * This program is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * This program 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.oscim.app.location; @SuppressWarnings("deprecation") public class Compass extends Layer implements SensorEventListener, Map.UpdateListener { // final static Logger log = LoggerFactory.getLogger(Compass.class); public enum Mode { OFF, C2D, C3D, } private final SensorManager mSensorManager; private final ImageView mArrowView; // private final float[] mRotationM = new float[9]; private final float[] mRotationV = new float[3]; // private float[] mAccelV = new float[3]; // private float[] mMagnetV = new float[3]; // private boolean mLastAccelerometerSet; // private boolean mLastMagnetometerSet; private float mCurRotation; private float mCurTilt; private boolean mControlOrientation; private Mode mMode = Mode.OFF; private int mListeners; @Override public void onMapEvent(Event e, MapPosition mapPosition) { if (!mControlOrientation) { float rotation = -mapPosition.bearing; adjustArrow(rotation, rotation); } } public Compass(Context context, Map map) { super(map); mSensorManager = (SensorManager) context .getSystemService(Context.SENSOR_SERVICE); // List<Sensor> s = mSensorManager.getSensorList(Sensor.TYPE_ALL); // for (Sensor sensor : s) // log.debug(sensor.toString());
mArrowView = (ImageView) App.activity.findViewById(R.id.compass);
opensciencemap/vtm-app
src/org/osmdroid/location/OverpassPOIProvider.java
// Path: src/org/osmdroid/utils/HttpConnection.java // public class HttpConnection { // final static Logger log = LoggerFactory.getLogger(HttpConnection.class); // // private DefaultHttpClient client; // private InputStream stream; // private HttpEntity entity; // private String mUserAgent; // // private final static int TIMEOUT_CONNECTION = 3000; //ms // private final static int TIMEOUT_SOCKET = 8000; //ms // // /** // * Constructor. Opens the url with an HttpURLConnection, then opens a stream // * on it. param sUrl : url to open // */ // public HttpConnection() { // stream = null; // entity = null; // HttpParams httpParameters = new BasicHttpParams(); // /* useful? HttpProtocolParams.setContentCharset(httpParameters, // * "UTF-8"); HttpProtocolParams.setHttpElementCharset(httpParameters, // * "UTF-8"); */ // // Set the timeout in milliseconds until a connection is established. // HttpConnectionParams.setConnectionTimeout(httpParameters, TIMEOUT_CONNECTION); // // Set the default socket timeout (SO_TIMEOUT) // // in milliseconds which is the timeout for waiting for data. // HttpConnectionParams.setSoTimeout(httpParameters, TIMEOUT_SOCKET); // client = new DefaultHttpClient(httpParameters); // //TODO: created here. Reuse to do for better perfs???... // } // // public void setUserAgent(String userAgent) { // mUserAgent = userAgent; // } // // public void doGet(String sUrl) { // HttpGet request = new HttpGet(sUrl); // if (mUserAgent != null) // request.setHeader("User-Agent", mUserAgent); // try { // HttpResponse response = client.execute(request); // StatusLine status = response.getStatusLine(); // if (status.getStatusCode() != 200) { // log.error("Invalid response from server: " + status.toString()); // } else { // entity = response.getEntity(); // } // } catch (IOException e) { // e.printStackTrace(); // } // } // // public void doPost(String sUrl, List<NameValuePair> nameValuePairs) { // HttpPost request = new HttpPost(sUrl); // if (mUserAgent != null) // request.setHeader("User-Agent", mUserAgent); // try { // request.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // HttpResponse response = client.execute(request); // StatusLine status = response.getStatusLine(); // if (status.getStatusCode() != 200) { // log.error("Invalid response from server: " + status.toString()); // } else { // entity = response.getEntity(); // } // } catch (ClientProtocolException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // } // // /** // * @return the opened InputStream, or null if creation failed for any // * reason. // */ // public InputStream getStream() { // try { // if (entity != null) // stream = entity.getContent(); // } catch (IOException e) { // e.printStackTrace(); // } // return stream; // } // // /** // * @return the whole content as a String, or null if creation failed for any // * reason. // */ // public String getContentAsString() { // try { // if (entity != null) { // return EntityUtils.toString(entity, "UTF-8"); // //setting the charset is important if none found in the entity. // } // return null; // } catch (IOException e) { // e.printStackTrace(); // return null; // } // } // // /** // * Calling close once is mandatory. // */ // public void close() { // if (stream != null) { // try { // stream.close(); // stream = null; // } catch (IOException e) { // e.printStackTrace(); // } // } // if (entity != null) { // try { // entity.consumeContent(); // //"finish". Important if we want to reuse the client object one day... // entity = null; // } catch (IOException e) { // e.printStackTrace(); // } // } // if (client != null) { // client.getConnectionManager().shutdown(); // client = null; // } // } // // }
import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import org.oscim.core.BoundingBox; import org.oscim.core.GeoPoint; import org.oscim.core.Tag; import org.oscim.core.osm.OsmData; import org.oscim.core.osm.OsmNode; import org.oscim.utils.osmpbf.OsmPbfReader; import org.osmdroid.utils.HttpConnection; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package org.osmdroid.location; public class OverpassPOIProvider implements POIProvider { final static Logger log = LoggerFactory .getLogger(OverpassPOIProvider.class); public static final String TAG_KEY_WEBSITE = "website".intern(); @Override public List<POI> getPOIInside(BoundingBox boundingBox, String query, int maxResults) {
// Path: src/org/osmdroid/utils/HttpConnection.java // public class HttpConnection { // final static Logger log = LoggerFactory.getLogger(HttpConnection.class); // // private DefaultHttpClient client; // private InputStream stream; // private HttpEntity entity; // private String mUserAgent; // // private final static int TIMEOUT_CONNECTION = 3000; //ms // private final static int TIMEOUT_SOCKET = 8000; //ms // // /** // * Constructor. Opens the url with an HttpURLConnection, then opens a stream // * on it. param sUrl : url to open // */ // public HttpConnection() { // stream = null; // entity = null; // HttpParams httpParameters = new BasicHttpParams(); // /* useful? HttpProtocolParams.setContentCharset(httpParameters, // * "UTF-8"); HttpProtocolParams.setHttpElementCharset(httpParameters, // * "UTF-8"); */ // // Set the timeout in milliseconds until a connection is established. // HttpConnectionParams.setConnectionTimeout(httpParameters, TIMEOUT_CONNECTION); // // Set the default socket timeout (SO_TIMEOUT) // // in milliseconds which is the timeout for waiting for data. // HttpConnectionParams.setSoTimeout(httpParameters, TIMEOUT_SOCKET); // client = new DefaultHttpClient(httpParameters); // //TODO: created here. Reuse to do for better perfs???... // } // // public void setUserAgent(String userAgent) { // mUserAgent = userAgent; // } // // public void doGet(String sUrl) { // HttpGet request = new HttpGet(sUrl); // if (mUserAgent != null) // request.setHeader("User-Agent", mUserAgent); // try { // HttpResponse response = client.execute(request); // StatusLine status = response.getStatusLine(); // if (status.getStatusCode() != 200) { // log.error("Invalid response from server: " + status.toString()); // } else { // entity = response.getEntity(); // } // } catch (IOException e) { // e.printStackTrace(); // } // } // // public void doPost(String sUrl, List<NameValuePair> nameValuePairs) { // HttpPost request = new HttpPost(sUrl); // if (mUserAgent != null) // request.setHeader("User-Agent", mUserAgent); // try { // request.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // HttpResponse response = client.execute(request); // StatusLine status = response.getStatusLine(); // if (status.getStatusCode() != 200) { // log.error("Invalid response from server: " + status.toString()); // } else { // entity = response.getEntity(); // } // } catch (ClientProtocolException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // } // // /** // * @return the opened InputStream, or null if creation failed for any // * reason. // */ // public InputStream getStream() { // try { // if (entity != null) // stream = entity.getContent(); // } catch (IOException e) { // e.printStackTrace(); // } // return stream; // } // // /** // * @return the whole content as a String, or null if creation failed for any // * reason. // */ // public String getContentAsString() { // try { // if (entity != null) { // return EntityUtils.toString(entity, "UTF-8"); // //setting the charset is important if none found in the entity. // } // return null; // } catch (IOException e) { // e.printStackTrace(); // return null; // } // } // // /** // * Calling close once is mandatory. // */ // public void close() { // if (stream != null) { // try { // stream.close(); // stream = null; // } catch (IOException e) { // e.printStackTrace(); // } // } // if (entity != null) { // try { // entity.consumeContent(); // //"finish". Important if we want to reuse the client object one day... // entity = null; // } catch (IOException e) { // e.printStackTrace(); // } // } // if (client != null) { // client.getConnectionManager().shutdown(); // client = null; // } // } // // } // Path: src/org/osmdroid/location/OverpassPOIProvider.java import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import org.oscim.core.BoundingBox; import org.oscim.core.GeoPoint; import org.oscim.core.Tag; import org.oscim.core.osm.OsmData; import org.oscim.core.osm.OsmNode; import org.oscim.utils.osmpbf.OsmPbfReader; import org.osmdroid.utils.HttpConnection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package org.osmdroid.location; public class OverpassPOIProvider implements POIProvider { final static Logger log = LoggerFactory .getLogger(OverpassPOIProvider.class); public static final String TAG_KEY_WEBSITE = "website".intern(); @Override public List<POI> getPOIInside(BoundingBox boundingBox, String query, int maxResults) {
HttpConnection connection = new HttpConnection();
opensciencemap/vtm-app
src/org/oscim/app/preferences/EditPreferences.java
// Path: src/org/oscim/app/App.java // public class App extends Application { // // public final static Logger log = LoggerFactory.getLogger(App.class); // // public static Map map; // public static MapView view; // public static Resources res; // public static TileMap activity; // // public static POISearch poiSearch; // public static RouteSearch routeSearch; // // @Override // public void onCreate() { // super.onCreate(); // res = getResources(); // } // // public static void lockOrientation(Activity activity) { // Display display = ((WindowManager) activity.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); // int rotation = display.getRotation(); // int tempOrientation = activity.getResources().getConfiguration().orientation; // int orientation = 0; // switch (tempOrientation) // { // case Configuration.ORIENTATION_LANDSCAPE: // if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_90) // orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; // else // orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE; // break; // case Configuration.ORIENTATION_PORTRAIT: // if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_270) // orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; // else // orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT; // } // activity.setRequestedOrientation(orientation); // } // }
import org.oscim.app.App; import org.oscim.app.R; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity;
/* * Copyright 2010, 2011, 2012 mapsforge.org * * This program is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * This program 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.oscim.app.preferences; /** * Activity to edit the application preferences. */ public class EditPreferences extends PreferenceActivity { @SuppressWarnings("deprecation") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); Preference button = (Preference) findPreference("clear_cache"); button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference arg0) {
// Path: src/org/oscim/app/App.java // public class App extends Application { // // public final static Logger log = LoggerFactory.getLogger(App.class); // // public static Map map; // public static MapView view; // public static Resources res; // public static TileMap activity; // // public static POISearch poiSearch; // public static RouteSearch routeSearch; // // @Override // public void onCreate() { // super.onCreate(); // res = getResources(); // } // // public static void lockOrientation(Activity activity) { // Display display = ((WindowManager) activity.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); // int rotation = display.getRotation(); // int tempOrientation = activity.getResources().getConfiguration().orientation; // int orientation = 0; // switch (tempOrientation) // { // case Configuration.ORIENTATION_LANDSCAPE: // if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_90) // orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; // else // orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE; // break; // case Configuration.ORIENTATION_PORTRAIT: // if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_270) // orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; // else // orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT; // } // activity.setRequestedOrientation(orientation); // } // } // Path: src/org/oscim/app/preferences/EditPreferences.java import org.oscim.app.App; import org.oscim.app.R; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; /* * Copyright 2010, 2011, 2012 mapsforge.org * * This program is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * This program 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.oscim.app.preferences; /** * Activity to edit the application preferences. */ public class EditPreferences extends PreferenceActivity { @SuppressWarnings("deprecation") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); Preference button = (Preference) findPreference("clear_cache"); button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference arg0) {
App.activity.getMapLayers().deleteCache();
opensciencemap/vtm-app
src/org/osmdroid/location/POI.java
// Path: src/org/osmdroid/utils/BonusPackHelper.java // public class BonusPackHelper { // // /** Log tag. */ // public static final String LOG_TAG = "BONUSPACK"; // // /** User agent sent to services by default */ // public static final String DEFAULT_USER_AGENT = "OsmBonusPack/1"; // // /** // * @return true if the device is the emulator, false if actual device. // */ // public static boolean isEmulator() { // //return Build.MANUFACTURER.equals("unknown"); // return ("google_sdk".equals(Build.PRODUCT) || "sdk".equals(Build.PRODUCT)); // } // // /** // * @param connection // * ... // * @return the whole content of the http request, as a string // */ // private static String readStream(HttpConnection connection) { // String result = connection.getContentAsString(); // return result; // } // // /** // * sends an http request, and returns the whole content result in a String. // * // * @param url // * ... // * @return the whole content, or null if any issue. // */ // public static String requestStringFromUrl(String url) { // HttpConnection connection = new HttpConnection(); // connection.doGet(url); // String result = readStream(connection); // connection.close(); // return result; // } // // /** // * requestStringFromPost: do a post request to a url with name-value pairs, // * and returns the whole content result in a String. // * // * @param url // * ... // * @param nameValuePairs // * ... // * @return the content, or null if any issue. // */ // public static String requestStringFromPost(String url, List<NameValuePair> nameValuePairs) { // HttpConnection connection = new HttpConnection(); // connection.doPost(url, nameValuePairs); // String result = readStream(connection); // connection.close(); // return result; // } // // /** // * Loads a bitmap from a url. // * // * @param url // * ... // * @return the bitmap, or null if any issue. // */ // public static Bitmap loadBitmap(String url) { // Bitmap bitmap = null; // try { // InputStream is = (InputStream) new URL(url).getContent(); // bitmap = BitmapFactory.decodeStream(new FlushedInputStream(is)); // //Alternative providing better handling on loading errors? // /* Drawable d = Drawable.createFromStream(new // * FlushedInputStream(is), null); if (is != null) is.close(); if (d // * != null) bitmap = ((BitmapDrawable)d).getBitmap(); */ // } catch (FileNotFoundException e) { // //log.debug("image not available: " + url); // } catch (Exception e) { // e.printStackTrace(); // return null; // } // return bitmap; // } // // /** // * Workaround on Android issue see // * http://stackoverflow.com/questions/4601352 // * /createfromstream-in-android-returning-null-for-certain-url // */ // static class FlushedInputStream extends FilterInputStream { // public FlushedInputStream(InputStream inputStream) { // super(inputStream); // } // // @Override // public long skip(long n) throws IOException { // long totalBytesSkipped = 0L; // while (totalBytesSkipped < n) { // long bytesSkipped = in.skip(n - totalBytesSkipped); // if (bytesSkipped == 0L) { // int byteValue = read(); // if (byteValue < 0) // break; // we reached EOF // // bytesSkipped = 1; // we read one byte // } // totalBytesSkipped += bytesSkipped; // } // return totalBytesSkipped; // } // } // }
import org.oscim.app.R; import org.oscim.core.BoundingBox; import org.oscim.core.GeoPoint; import org.osmdroid.utils.BonusPackHelper; import android.graphics.Bitmap; import android.os.AsyncTask; import android.view.View; import android.widget.ImageView;
package org.osmdroid.location; /** * Point of Interest. Exact content may depend of the POI provider used. * * @see NominatimPOIProvider * @see GeoNamesPOIProvider * @author M.Kergall */ public class POI { /** IDs of POI services */ public static int POI_SERVICE_NOMINATIM = 100; public static int POI_SERVICE_GEONAMES_WIKIPEDIA = 200; public static int POI_SERVICE_FLICKR = 300; public static int POI_SERVICE_PICASA = 400; public static int POI_SERVICE_4SQUARE = 500; /** Identifies the service provider of this POI. */ public int serviceId; /** Nominatim: OSM ID. GeoNames: 0 */ public String id; /** location of the POI */ public GeoPoint location; public BoundingBox bbox; /** Nominatim "class", GeoNames "feature" */ public String category; /** type or title */ public String type; /** can be the name, the address, a short description */ public String description; /** url of the thumbnail. Null if none */ public String thumbnailPath; /** the thumbnail itself. Null if none */ public Bitmap thumbnail; /** url to a more detailed information page about this POI. Null if none */ public String url; /** * popularity of this POI, from 1 (lowest) to 100 (highest). 0 if not * defined. */ public int rank; /** number of attempts to load the thumbnail that have failed */ protected int mThumbnailLoadingFailures; public POI(int serviceId) { this.serviceId = serviceId; // lets all other fields empty or null. That's fine. } protected static int MAX_LOADING_ATTEMPTS = 2; /** * @return the POI thumbnail as a Bitmap, if any. If not done yet, it will * load the POI thumbnail from its url (in thumbnailPath field). */ public Bitmap getThumbnail() { if (thumbnail == null && thumbnailPath != null) {
// Path: src/org/osmdroid/utils/BonusPackHelper.java // public class BonusPackHelper { // // /** Log tag. */ // public static final String LOG_TAG = "BONUSPACK"; // // /** User agent sent to services by default */ // public static final String DEFAULT_USER_AGENT = "OsmBonusPack/1"; // // /** // * @return true if the device is the emulator, false if actual device. // */ // public static boolean isEmulator() { // //return Build.MANUFACTURER.equals("unknown"); // return ("google_sdk".equals(Build.PRODUCT) || "sdk".equals(Build.PRODUCT)); // } // // /** // * @param connection // * ... // * @return the whole content of the http request, as a string // */ // private static String readStream(HttpConnection connection) { // String result = connection.getContentAsString(); // return result; // } // // /** // * sends an http request, and returns the whole content result in a String. // * // * @param url // * ... // * @return the whole content, or null if any issue. // */ // public static String requestStringFromUrl(String url) { // HttpConnection connection = new HttpConnection(); // connection.doGet(url); // String result = readStream(connection); // connection.close(); // return result; // } // // /** // * requestStringFromPost: do a post request to a url with name-value pairs, // * and returns the whole content result in a String. // * // * @param url // * ... // * @param nameValuePairs // * ... // * @return the content, or null if any issue. // */ // public static String requestStringFromPost(String url, List<NameValuePair> nameValuePairs) { // HttpConnection connection = new HttpConnection(); // connection.doPost(url, nameValuePairs); // String result = readStream(connection); // connection.close(); // return result; // } // // /** // * Loads a bitmap from a url. // * // * @param url // * ... // * @return the bitmap, or null if any issue. // */ // public static Bitmap loadBitmap(String url) { // Bitmap bitmap = null; // try { // InputStream is = (InputStream) new URL(url).getContent(); // bitmap = BitmapFactory.decodeStream(new FlushedInputStream(is)); // //Alternative providing better handling on loading errors? // /* Drawable d = Drawable.createFromStream(new // * FlushedInputStream(is), null); if (is != null) is.close(); if (d // * != null) bitmap = ((BitmapDrawable)d).getBitmap(); */ // } catch (FileNotFoundException e) { // //log.debug("image not available: " + url); // } catch (Exception e) { // e.printStackTrace(); // return null; // } // return bitmap; // } // // /** // * Workaround on Android issue see // * http://stackoverflow.com/questions/4601352 // * /createfromstream-in-android-returning-null-for-certain-url // */ // static class FlushedInputStream extends FilterInputStream { // public FlushedInputStream(InputStream inputStream) { // super(inputStream); // } // // @Override // public long skip(long n) throws IOException { // long totalBytesSkipped = 0L; // while (totalBytesSkipped < n) { // long bytesSkipped = in.skip(n - totalBytesSkipped); // if (bytesSkipped == 0L) { // int byteValue = read(); // if (byteValue < 0) // break; // we reached EOF // // bytesSkipped = 1; // we read one byte // } // totalBytesSkipped += bytesSkipped; // } // return totalBytesSkipped; // } // } // } // Path: src/org/osmdroid/location/POI.java import org.oscim.app.R; import org.oscim.core.BoundingBox; import org.oscim.core.GeoPoint; import org.osmdroid.utils.BonusPackHelper; import android.graphics.Bitmap; import android.os.AsyncTask; import android.view.View; import android.widget.ImageView; package org.osmdroid.location; /** * Point of Interest. Exact content may depend of the POI provider used. * * @see NominatimPOIProvider * @see GeoNamesPOIProvider * @author M.Kergall */ public class POI { /** IDs of POI services */ public static int POI_SERVICE_NOMINATIM = 100; public static int POI_SERVICE_GEONAMES_WIKIPEDIA = 200; public static int POI_SERVICE_FLICKR = 300; public static int POI_SERVICE_PICASA = 400; public static int POI_SERVICE_4SQUARE = 500; /** Identifies the service provider of this POI. */ public int serviceId; /** Nominatim: OSM ID. GeoNames: 0 */ public String id; /** location of the POI */ public GeoPoint location; public BoundingBox bbox; /** Nominatim "class", GeoNames "feature" */ public String category; /** type or title */ public String type; /** can be the name, the address, a short description */ public String description; /** url of the thumbnail. Null if none */ public String thumbnailPath; /** the thumbnail itself. Null if none */ public Bitmap thumbnail; /** url to a more detailed information page about this POI. Null if none */ public String url; /** * popularity of this POI, from 1 (lowest) to 100 (highest). 0 if not * defined. */ public int rank; /** number of attempts to load the thumbnail that have failed */ protected int mThumbnailLoadingFailures; public POI(int serviceId) { this.serviceId = serviceId; // lets all other fields empty or null. That's fine. } protected static int MAX_LOADING_ATTEMPTS = 2; /** * @return the POI thumbnail as a Bitmap, if any. If not done yet, it will * load the POI thumbnail from its url (in thumbnailPath field). */ public Bitmap getThumbnail() { if (thumbnail == null && thumbnailPath != null) {
thumbnail = BonusPackHelper.loadBitmap(thumbnailPath);
opensciencemap/vtm-app
src/org/oscim/app/filepicker/FilePicker.java
// Path: src/org/oscim/app/filefilter/ValidFileFilter.java // public interface ValidFileFilter extends FileFilter { // /** // * @return the result of the last {@link #accept} call (might be null). // */ // OpenResult getFileOpenResult(); // }
import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.GridView; import java.io.File; import java.io.FileFilter; import java.util.Arrays; import java.util.Comparator; import org.oscim.app.R; import org.oscim.app.filefilter.ValidFileFilter; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Build;
/* * Copyright 2010, 2011, 2012 mapsforge.org * * This program is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * This program 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.oscim.app.filepicker; /** * A FilePicker displays the contents of directories. The user can navigate * within the file system and select a single * file whose path is then returned to the calling activity. The ordering of * directory contents can be specified via * {@link #setFileComparator(Comparator)}. By default subfolders and files are * grouped and each group is ordered * alphabetically. * <p> * A {@link FileFilter} can be activated via * {@link #setFileDisplayFilter(FileFilter)} to restrict the displayed files and * folders. By default all files and folders are visible. * <p> * Another <code>FileFilter</code> can be applied via * {@link #setFileSelectFilter(ValidFileFilter)} to check if a selected file is * valid before its path is returned. By default all files are considered as * valid and can be selected. */ public class FilePicker extends Activity implements AdapterView.OnItemClickListener { /** * The name of the extra data in the result {@link Intent}. */ public static final String SELECTED_FILE = "selectedFile"; private static final String CURRENT_DIRECTORY = "currentDirectory"; private static final String DEFAULT_DIRECTORY = "/"; private static final int DIALOG_FILE_INVALID = 0; // private static final int DIALOG_FILE_SELECT = 1; private static Comparator<File> fileComparator = getDefaultFileComparator(); private static FileFilter fileDisplayFilter;
// Path: src/org/oscim/app/filefilter/ValidFileFilter.java // public interface ValidFileFilter extends FileFilter { // /** // * @return the result of the last {@link #accept} call (might be null). // */ // OpenResult getFileOpenResult(); // } // Path: src/org/oscim/app/filepicker/FilePicker.java import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.GridView; import java.io.File; import java.io.FileFilter; import java.util.Arrays; import java.util.Comparator; import org.oscim.app.R; import org.oscim.app.filefilter.ValidFileFilter; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Build; /* * Copyright 2010, 2011, 2012 mapsforge.org * * This program is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * This program 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.oscim.app.filepicker; /** * A FilePicker displays the contents of directories. The user can navigate * within the file system and select a single * file whose path is then returned to the calling activity. The ordering of * directory contents can be specified via * {@link #setFileComparator(Comparator)}. By default subfolders and files are * grouped and each group is ordered * alphabetically. * <p> * A {@link FileFilter} can be activated via * {@link #setFileDisplayFilter(FileFilter)} to restrict the displayed files and * folders. By default all files and folders are visible. * <p> * Another <code>FileFilter</code> can be applied via * {@link #setFileSelectFilter(ValidFileFilter)} to check if a selected file is * valid before its path is returned. By default all files are considered as * valid and can be selected. */ public class FilePicker extends Activity implements AdapterView.OnItemClickListener { /** * The name of the extra data in the result {@link Intent}. */ public static final String SELECTED_FILE = "selectedFile"; private static final String CURRENT_DIRECTORY = "currentDirectory"; private static final String DEFAULT_DIRECTORY = "/"; private static final int DIALOG_FILE_INVALID = 0; // private static final int DIALOG_FILE_SELECT = 1; private static Comparator<File> fileComparator = getDefaultFileComparator(); private static FileFilter fileDisplayFilter;
private static ValidFileFilter fileSelectFilter;
opensciencemap/vtm-app
src/org/osmdroid/location/GeocoderNominatim.java
// Path: src/org/osmdroid/utils/BonusPackHelper.java // public class BonusPackHelper { // // /** Log tag. */ // public static final String LOG_TAG = "BONUSPACK"; // // /** User agent sent to services by default */ // public static final String DEFAULT_USER_AGENT = "OsmBonusPack/1"; // // /** // * @return true if the device is the emulator, false if actual device. // */ // public static boolean isEmulator() { // //return Build.MANUFACTURER.equals("unknown"); // return ("google_sdk".equals(Build.PRODUCT) || "sdk".equals(Build.PRODUCT)); // } // // /** // * @param connection // * ... // * @return the whole content of the http request, as a string // */ // private static String readStream(HttpConnection connection) { // String result = connection.getContentAsString(); // return result; // } // // /** // * sends an http request, and returns the whole content result in a String. // * // * @param url // * ... // * @return the whole content, or null if any issue. // */ // public static String requestStringFromUrl(String url) { // HttpConnection connection = new HttpConnection(); // connection.doGet(url); // String result = readStream(connection); // connection.close(); // return result; // } // // /** // * requestStringFromPost: do a post request to a url with name-value pairs, // * and returns the whole content result in a String. // * // * @param url // * ... // * @param nameValuePairs // * ... // * @return the content, or null if any issue. // */ // public static String requestStringFromPost(String url, List<NameValuePair> nameValuePairs) { // HttpConnection connection = new HttpConnection(); // connection.doPost(url, nameValuePairs); // String result = readStream(connection); // connection.close(); // return result; // } // // /** // * Loads a bitmap from a url. // * // * @param url // * ... // * @return the bitmap, or null if any issue. // */ // public static Bitmap loadBitmap(String url) { // Bitmap bitmap = null; // try { // InputStream is = (InputStream) new URL(url).getContent(); // bitmap = BitmapFactory.decodeStream(new FlushedInputStream(is)); // //Alternative providing better handling on loading errors? // /* Drawable d = Drawable.createFromStream(new // * FlushedInputStream(is), null); if (is != null) is.close(); if (d // * != null) bitmap = ((BitmapDrawable)d).getBitmap(); */ // } catch (FileNotFoundException e) { // //log.debug("image not available: " + url); // } catch (Exception e) { // e.printStackTrace(); // return null; // } // return bitmap; // } // // /** // * Workaround on Android issue see // * http://stackoverflow.com/questions/4601352 // * /createfromstream-in-android-returning-null-for-certain-url // */ // static class FlushedInputStream extends FilterInputStream { // public FlushedInputStream(InputStream inputStream) { // super(inputStream); // } // // @Override // public long skip(long n) throws IOException { // long totalBytesSkipped = 0L; // while (totalBytesSkipped < n) { // long bytesSkipped = in.skip(n - totalBytesSkipped); // if (bytesSkipped == 0L) { // int byteValue = read(); // if (byteValue < 0) // break; // we reached EOF // // bytesSkipped = 1; // we read one byte // } // totalBytesSkipped += bytesSkipped; // } // return totalBytesSkipped; // } // } // }
import java.io.IOException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.osmdroid.utils.BonusPackHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import android.content.Context; import android.location.Address;
/* Other possible OSM tags in Nominatim results not handled yet: subway, * golf_course, bus_stop, parking,... house, house_number, building * city_district (13e Arrondissement) road => or highway, ... sub-city * (like suburb) => locality, isolated_dwelling, hamlet ... * state_district */ return gAddress; } /** * @param latitude * ... * @param longitude * ... * @param maxResults * ... * @return ... * @throws IOException * ... */ public List<Address> getFromLocation(double latitude, double longitude, int maxResults) throws IOException { String url = mServiceUrl + "reverse?" + "format=json" + "&accept-language=" + mLocale.getLanguage() //+ "&addressdetails=1" + "&lat=" + latitude + "&lon=" + longitude; log.debug("GeocoderNominatim::getFromLocation:" + url);
// Path: src/org/osmdroid/utils/BonusPackHelper.java // public class BonusPackHelper { // // /** Log tag. */ // public static final String LOG_TAG = "BONUSPACK"; // // /** User agent sent to services by default */ // public static final String DEFAULT_USER_AGENT = "OsmBonusPack/1"; // // /** // * @return true if the device is the emulator, false if actual device. // */ // public static boolean isEmulator() { // //return Build.MANUFACTURER.equals("unknown"); // return ("google_sdk".equals(Build.PRODUCT) || "sdk".equals(Build.PRODUCT)); // } // // /** // * @param connection // * ... // * @return the whole content of the http request, as a string // */ // private static String readStream(HttpConnection connection) { // String result = connection.getContentAsString(); // return result; // } // // /** // * sends an http request, and returns the whole content result in a String. // * // * @param url // * ... // * @return the whole content, or null if any issue. // */ // public static String requestStringFromUrl(String url) { // HttpConnection connection = new HttpConnection(); // connection.doGet(url); // String result = readStream(connection); // connection.close(); // return result; // } // // /** // * requestStringFromPost: do a post request to a url with name-value pairs, // * and returns the whole content result in a String. // * // * @param url // * ... // * @param nameValuePairs // * ... // * @return the content, or null if any issue. // */ // public static String requestStringFromPost(String url, List<NameValuePair> nameValuePairs) { // HttpConnection connection = new HttpConnection(); // connection.doPost(url, nameValuePairs); // String result = readStream(connection); // connection.close(); // return result; // } // // /** // * Loads a bitmap from a url. // * // * @param url // * ... // * @return the bitmap, or null if any issue. // */ // public static Bitmap loadBitmap(String url) { // Bitmap bitmap = null; // try { // InputStream is = (InputStream) new URL(url).getContent(); // bitmap = BitmapFactory.decodeStream(new FlushedInputStream(is)); // //Alternative providing better handling on loading errors? // /* Drawable d = Drawable.createFromStream(new // * FlushedInputStream(is), null); if (is != null) is.close(); if (d // * != null) bitmap = ((BitmapDrawable)d).getBitmap(); */ // } catch (FileNotFoundException e) { // //log.debug("image not available: " + url); // } catch (Exception e) { // e.printStackTrace(); // return null; // } // return bitmap; // } // // /** // * Workaround on Android issue see // * http://stackoverflow.com/questions/4601352 // * /createfromstream-in-android-returning-null-for-certain-url // */ // static class FlushedInputStream extends FilterInputStream { // public FlushedInputStream(InputStream inputStream) { // super(inputStream); // } // // @Override // public long skip(long n) throws IOException { // long totalBytesSkipped = 0L; // while (totalBytesSkipped < n) { // long bytesSkipped = in.skip(n - totalBytesSkipped); // if (bytesSkipped == 0L) { // int byteValue = read(); // if (byteValue < 0) // break; // we reached EOF // // bytesSkipped = 1; // we read one byte // } // totalBytesSkipped += bytesSkipped; // } // return totalBytesSkipped; // } // } // } // Path: src/org/osmdroid/location/GeocoderNominatim.java import java.io.IOException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.osmdroid.utils.BonusPackHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import android.content.Context; import android.location.Address; /* Other possible OSM tags in Nominatim results not handled yet: subway, * golf_course, bus_stop, parking,... house, house_number, building * city_district (13e Arrondissement) road => or highway, ... sub-city * (like suburb) => locality, isolated_dwelling, hamlet ... * state_district */ return gAddress; } /** * @param latitude * ... * @param longitude * ... * @param maxResults * ... * @return ... * @throws IOException * ... */ public List<Address> getFromLocation(double latitude, double longitude, int maxResults) throws IOException { String url = mServiceUrl + "reverse?" + "format=json" + "&accept-language=" + mLocale.getLanguage() //+ "&addressdetails=1" + "&lat=" + latitude + "&lon=" + longitude; log.debug("GeocoderNominatim::getFromLocation:" + url);
String result = BonusPackHelper.requestStringFromUrl(url);
opensciencemap/vtm-app
src/org/osmdroid/location/NominatimPOIProvider.java
// Path: src/org/osmdroid/utils/BonusPackHelper.java // public class BonusPackHelper { // // /** Log tag. */ // public static final String LOG_TAG = "BONUSPACK"; // // /** User agent sent to services by default */ // public static final String DEFAULT_USER_AGENT = "OsmBonusPack/1"; // // /** // * @return true if the device is the emulator, false if actual device. // */ // public static boolean isEmulator() { // //return Build.MANUFACTURER.equals("unknown"); // return ("google_sdk".equals(Build.PRODUCT) || "sdk".equals(Build.PRODUCT)); // } // // /** // * @param connection // * ... // * @return the whole content of the http request, as a string // */ // private static String readStream(HttpConnection connection) { // String result = connection.getContentAsString(); // return result; // } // // /** // * sends an http request, and returns the whole content result in a String. // * // * @param url // * ... // * @return the whole content, or null if any issue. // */ // public static String requestStringFromUrl(String url) { // HttpConnection connection = new HttpConnection(); // connection.doGet(url); // String result = readStream(connection); // connection.close(); // return result; // } // // /** // * requestStringFromPost: do a post request to a url with name-value pairs, // * and returns the whole content result in a String. // * // * @param url // * ... // * @param nameValuePairs // * ... // * @return the content, or null if any issue. // */ // public static String requestStringFromPost(String url, List<NameValuePair> nameValuePairs) { // HttpConnection connection = new HttpConnection(); // connection.doPost(url, nameValuePairs); // String result = readStream(connection); // connection.close(); // return result; // } // // /** // * Loads a bitmap from a url. // * // * @param url // * ... // * @return the bitmap, or null if any issue. // */ // public static Bitmap loadBitmap(String url) { // Bitmap bitmap = null; // try { // InputStream is = (InputStream) new URL(url).getContent(); // bitmap = BitmapFactory.decodeStream(new FlushedInputStream(is)); // //Alternative providing better handling on loading errors? // /* Drawable d = Drawable.createFromStream(new // * FlushedInputStream(is), null); if (is != null) is.close(); if (d // * != null) bitmap = ((BitmapDrawable)d).getBitmap(); */ // } catch (FileNotFoundException e) { // //log.debug("image not available: " + url); // } catch (Exception e) { // e.printStackTrace(); // return null; // } // return bitmap; // } // // /** // * Workaround on Android issue see // * http://stackoverflow.com/questions/4601352 // * /createfromstream-in-android-returning-null-for-certain-url // */ // static class FlushedInputStream extends FilterInputStream { // public FlushedInputStream(InputStream inputStream) { // super(inputStream); // } // // @Override // public long skip(long n) throws IOException { // long totalBytesSkipped = 0L; // while (totalBytesSkipped < n) { // long bytesSkipped = in.skip(n - totalBytesSkipped); // if (bytesSkipped == 0L) { // int byteValue = read(); // if (byteValue < 0) // break; // we reached EOF // // bytesSkipped = 1; // we read one byte // } // totalBytesSkipped += bytesSkipped; // } // return totalBytesSkipped; // } // } // }
import java.net.URLEncoder; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.oscim.core.BoundingBox; import org.oscim.core.GeoPoint; import org.osmdroid.utils.BonusPackHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import android.graphics.Bitmap;
// urlString.append("&addressdetails=0"); return urlString; } private String getUrlInside(BoundingBox bb, String type, int maxResults) { StringBuffer urlString = getCommonUrl(type, maxResults); urlString.append("&viewbox=" + bb.getMaxLongitude() + "," + bb.getMaxLatitude() + "," + bb.getMinLongitude() + "," + bb.getMinLatitude()); return urlString.toString(); } private String getUrlCloseTo(GeoPoint p, String type, int maxResults, double maxDistance) { int maxD = (int) (maxDistance * 1E6); BoundingBox bb = new BoundingBox(p.latitudeE6 + maxD, p.longitudeE6 + maxD, p.latitudeE6 - maxD, p.longitudeE6 - maxD); return getUrlInside(bb, type, maxResults); } /** * @param url * full URL request * @return the list of POI, of null if technical issue. */ public ArrayList<POI> getThem(String url) { log.debug("NominatimPOIProvider:get:" + url);
// Path: src/org/osmdroid/utils/BonusPackHelper.java // public class BonusPackHelper { // // /** Log tag. */ // public static final String LOG_TAG = "BONUSPACK"; // // /** User agent sent to services by default */ // public static final String DEFAULT_USER_AGENT = "OsmBonusPack/1"; // // /** // * @return true if the device is the emulator, false if actual device. // */ // public static boolean isEmulator() { // //return Build.MANUFACTURER.equals("unknown"); // return ("google_sdk".equals(Build.PRODUCT) || "sdk".equals(Build.PRODUCT)); // } // // /** // * @param connection // * ... // * @return the whole content of the http request, as a string // */ // private static String readStream(HttpConnection connection) { // String result = connection.getContentAsString(); // return result; // } // // /** // * sends an http request, and returns the whole content result in a String. // * // * @param url // * ... // * @return the whole content, or null if any issue. // */ // public static String requestStringFromUrl(String url) { // HttpConnection connection = new HttpConnection(); // connection.doGet(url); // String result = readStream(connection); // connection.close(); // return result; // } // // /** // * requestStringFromPost: do a post request to a url with name-value pairs, // * and returns the whole content result in a String. // * // * @param url // * ... // * @param nameValuePairs // * ... // * @return the content, or null if any issue. // */ // public static String requestStringFromPost(String url, List<NameValuePair> nameValuePairs) { // HttpConnection connection = new HttpConnection(); // connection.doPost(url, nameValuePairs); // String result = readStream(connection); // connection.close(); // return result; // } // // /** // * Loads a bitmap from a url. // * // * @param url // * ... // * @return the bitmap, or null if any issue. // */ // public static Bitmap loadBitmap(String url) { // Bitmap bitmap = null; // try { // InputStream is = (InputStream) new URL(url).getContent(); // bitmap = BitmapFactory.decodeStream(new FlushedInputStream(is)); // //Alternative providing better handling on loading errors? // /* Drawable d = Drawable.createFromStream(new // * FlushedInputStream(is), null); if (is != null) is.close(); if (d // * != null) bitmap = ((BitmapDrawable)d).getBitmap(); */ // } catch (FileNotFoundException e) { // //log.debug("image not available: " + url); // } catch (Exception e) { // e.printStackTrace(); // return null; // } // return bitmap; // } // // /** // * Workaround on Android issue see // * http://stackoverflow.com/questions/4601352 // * /createfromstream-in-android-returning-null-for-certain-url // */ // static class FlushedInputStream extends FilterInputStream { // public FlushedInputStream(InputStream inputStream) { // super(inputStream); // } // // @Override // public long skip(long n) throws IOException { // long totalBytesSkipped = 0L; // while (totalBytesSkipped < n) { // long bytesSkipped = in.skip(n - totalBytesSkipped); // if (bytesSkipped == 0L) { // int byteValue = read(); // if (byteValue < 0) // break; // we reached EOF // // bytesSkipped = 1; // we read one byte // } // totalBytesSkipped += bytesSkipped; // } // return totalBytesSkipped; // } // } // } // Path: src/org/osmdroid/location/NominatimPOIProvider.java import java.net.URLEncoder; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.oscim.core.BoundingBox; import org.oscim.core.GeoPoint; import org.osmdroid.utils.BonusPackHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import android.graphics.Bitmap; // urlString.append("&addressdetails=0"); return urlString; } private String getUrlInside(BoundingBox bb, String type, int maxResults) { StringBuffer urlString = getCommonUrl(type, maxResults); urlString.append("&viewbox=" + bb.getMaxLongitude() + "," + bb.getMaxLatitude() + "," + bb.getMinLongitude() + "," + bb.getMinLatitude()); return urlString.toString(); } private String getUrlCloseTo(GeoPoint p, String type, int maxResults, double maxDistance) { int maxD = (int) (maxDistance * 1E6); BoundingBox bb = new BoundingBox(p.latitudeE6 + maxD, p.longitudeE6 + maxD, p.latitudeE6 - maxD, p.longitudeE6 - maxD); return getUrlInside(bb, type, maxResults); } /** * @param url * full URL request * @return the list of POI, of null if technical issue. */ public ArrayList<POI> getThem(String url) { log.debug("NominatimPOIProvider:get:" + url);
String jString = BonusPackHelper.requestStringFromUrl(url);
opensciencemap/vtm-app
src/org/oscim/overlay/DistanceTouchOverlay.java
// Path: src/org/osmdroid/overlays/MapEventsReceiver.java // public interface MapEventsReceiver { // // /** // * @param p // * the position where the event occurred. // * @return true if the event has been "consumed" and should not be handled // * by other objects. // */ // boolean singleTapUpHelper(GeoPoint p); // // /** // * @param p // * the position where the event occurred. // * @return true if the event has been "consumed" and should not be handled // * by other objects. // */ // boolean longPressHelper(GeoPoint p); // // /** // * @param p1 p2 // * the position where the event occurred for 2 finger. // * @return true if the event has been "consumed" and should not be handled // * by other objects. // */ // boolean longPressHelper(GeoPoint p1, GeoPoint p2); // }
import java.util.Timer; import java.util.TimerTask; import org.oscim.core.GeoPoint; import org.oscim.event.Event; import org.oscim.event.Gesture; import org.oscim.event.GestureListener; import org.oscim.event.MotionEvent; import org.oscim.layers.Layer; import org.oscim.map.Map; import org.osmdroid.overlays.MapEventsReceiver;
/* * Copyright 2013 Ahmad Saleem * Copyright 2013 Hannes Janetzek * * This program is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * This program 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.oscim.overlay; public class DistanceTouchOverlay extends Layer implements Map.InputListener, GestureListener { private static final int LONGPRESS_THRESHOLD = 800; private Timer mLongpressTimer; private float mPrevX1, mPrevX2, mPrevY1, mPrevY2; private float mCurX1, mCurX2, mCurY1, mCurY2; // private final static int POINTER_UP = -1; // private int mPointer1 = POINTER_UP; // private int mPointer2 = POINTER_UP;
// Path: src/org/osmdroid/overlays/MapEventsReceiver.java // public interface MapEventsReceiver { // // /** // * @param p // * the position where the event occurred. // * @return true if the event has been "consumed" and should not be handled // * by other objects. // */ // boolean singleTapUpHelper(GeoPoint p); // // /** // * @param p // * the position where the event occurred. // * @return true if the event has been "consumed" and should not be handled // * by other objects. // */ // boolean longPressHelper(GeoPoint p); // // /** // * @param p1 p2 // * the position where the event occurred for 2 finger. // * @return true if the event has been "consumed" and should not be handled // * by other objects. // */ // boolean longPressHelper(GeoPoint p1, GeoPoint p2); // } // Path: src/org/oscim/overlay/DistanceTouchOverlay.java import java.util.Timer; import java.util.TimerTask; import org.oscim.core.GeoPoint; import org.oscim.event.Event; import org.oscim.event.Gesture; import org.oscim.event.GestureListener; import org.oscim.event.MotionEvent; import org.oscim.layers.Layer; import org.oscim.map.Map; import org.osmdroid.overlays.MapEventsReceiver; /* * Copyright 2013 Ahmad Saleem * Copyright 2013 Hannes Janetzek * * This program is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * This program 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.oscim.overlay; public class DistanceTouchOverlay extends Layer implements Map.InputListener, GestureListener { private static final int LONGPRESS_THRESHOLD = 800; private Timer mLongpressTimer; private float mPrevX1, mPrevX2, mPrevY1, mPrevY2; private float mCurX1, mCurX2, mCurY1, mCurY2; // private final static int POINTER_UP = -1; // private int mPointer1 = POINTER_UP; // private int mPointer2 = POINTER_UP;
private final MapEventsReceiver mReceiver;
opentracing-contrib/java-jaxrs
examples/spring-boot/src/main/java/io/opentracing/contrib/jaxrs2/example/spring/boot/Configuration.java
// Path: opentracing-jaxrs2/src/main/java/io/opentracing/contrib/jaxrs2/server/SpanFinishingFilter.java // public class SpanFinishingFilter implements Filter { // // public SpanFinishingFilter() { // } // // /** // * @param tracer // * @deprecated use no-args constructor // */ // @Deprecated // public SpanFinishingFilter(Tracer tracer){ // } // // @Override // public void init(FilterConfig filterConfig) { // } // // @Override // public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) // throws IOException, ServletException { // // HttpServletResponse httpResponse = (HttpServletResponse)response; // HttpServletRequest httpRequest = (HttpServletRequest)request; // // try { // chain.doFilter(request, response); // } catch (Exception ex) { // SpanWrapper spanWrapper = getSpanWrapper(httpRequest); // if (spanWrapper != null) { // Tags.HTTP_STATUS.set(spanWrapper.get(), httpResponse.getStatus()); // addExceptionLogs(spanWrapper.get(), ex); // } // throw ex; // } finally { // SpanWrapper spanWrapper = getSpanWrapper(httpRequest); // if (spanWrapper != null) { // spanWrapper.getScope().close(); // if (request.isAsyncStarted()) { // request.getAsyncContext().addListener(new SpanFinisher(spanWrapper), request, response); // } else { // spanWrapper.finish(); // } // } // } // } // // private SpanWrapper getSpanWrapper(HttpServletRequest request) { // return CastUtils.cast(request.getAttribute(SpanWrapper.PROPERTY_NAME), SpanWrapper.class); // } // // @Override // public void destroy() { // } // // static class SpanFinisher implements AsyncListener { // private SpanWrapper spanWrapper; // SpanFinisher(SpanWrapper spanWrapper) { // this.spanWrapper = spanWrapper; // } // // @Override // public void onComplete(AsyncEvent event) throws IOException { // HttpServletResponse httpResponse = (HttpServletResponse)event.getSuppliedResponse(); // if (httpResponse.getStatus() >= 500) { // addExceptionLogs(spanWrapper.get(), event.getThrowable()); // } // Tags.HTTP_STATUS.set(spanWrapper.get(), httpResponse.getStatus()); // spanWrapper.finish(); // } // @Override // public void onTimeout(AsyncEvent event) throws IOException { // } // @Override // public void onError(AsyncEvent event) throws IOException { // // this handler is called when exception is thrown in async handler // // note that exception logs are added in filter not here // } // @Override // public void onStartAsync(AsyncEvent event) throws IOException { // } // } // // private static void addExceptionLogs(Span span, Throwable throwable) { // Tags.ERROR.set(span, true); // if (throwable != null) { // Map<String, Object> errorLogs = new HashMap<>(2); // errorLogs.put("event", Tags.ERROR.getKey()); // errorLogs.put("error.object", throwable); // span.log(errorLogs); // } // } // }
import io.opentracing.Tracer; import io.opentracing.contrib.jaxrs2.server.SpanFinishingFilter; import javax.servlet.DispatcherType; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean;
package io.opentracing.contrib.jaxrs2.example.spring.boot; /** * @author Pavol Loffay */ @org.springframework.context.annotation.Configuration public class Configuration { @Bean public Tracer tracer() { return new LoggingTracer(); } @Bean public FilterRegistrationBean spanFinishingFilter() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
// Path: opentracing-jaxrs2/src/main/java/io/opentracing/contrib/jaxrs2/server/SpanFinishingFilter.java // public class SpanFinishingFilter implements Filter { // // public SpanFinishingFilter() { // } // // /** // * @param tracer // * @deprecated use no-args constructor // */ // @Deprecated // public SpanFinishingFilter(Tracer tracer){ // } // // @Override // public void init(FilterConfig filterConfig) { // } // // @Override // public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) // throws IOException, ServletException { // // HttpServletResponse httpResponse = (HttpServletResponse)response; // HttpServletRequest httpRequest = (HttpServletRequest)request; // // try { // chain.doFilter(request, response); // } catch (Exception ex) { // SpanWrapper spanWrapper = getSpanWrapper(httpRequest); // if (spanWrapper != null) { // Tags.HTTP_STATUS.set(spanWrapper.get(), httpResponse.getStatus()); // addExceptionLogs(spanWrapper.get(), ex); // } // throw ex; // } finally { // SpanWrapper spanWrapper = getSpanWrapper(httpRequest); // if (spanWrapper != null) { // spanWrapper.getScope().close(); // if (request.isAsyncStarted()) { // request.getAsyncContext().addListener(new SpanFinisher(spanWrapper), request, response); // } else { // spanWrapper.finish(); // } // } // } // } // // private SpanWrapper getSpanWrapper(HttpServletRequest request) { // return CastUtils.cast(request.getAttribute(SpanWrapper.PROPERTY_NAME), SpanWrapper.class); // } // // @Override // public void destroy() { // } // // static class SpanFinisher implements AsyncListener { // private SpanWrapper spanWrapper; // SpanFinisher(SpanWrapper spanWrapper) { // this.spanWrapper = spanWrapper; // } // // @Override // public void onComplete(AsyncEvent event) throws IOException { // HttpServletResponse httpResponse = (HttpServletResponse)event.getSuppliedResponse(); // if (httpResponse.getStatus() >= 500) { // addExceptionLogs(spanWrapper.get(), event.getThrowable()); // } // Tags.HTTP_STATUS.set(spanWrapper.get(), httpResponse.getStatus()); // spanWrapper.finish(); // } // @Override // public void onTimeout(AsyncEvent event) throws IOException { // } // @Override // public void onError(AsyncEvent event) throws IOException { // // this handler is called when exception is thrown in async handler // // note that exception logs are added in filter not here // } // @Override // public void onStartAsync(AsyncEvent event) throws IOException { // } // } // // private static void addExceptionLogs(Span span, Throwable throwable) { // Tags.ERROR.set(span, true); // if (throwable != null) { // Map<String, Object> errorLogs = new HashMap<>(2); // errorLogs.put("event", Tags.ERROR.getKey()); // errorLogs.put("error.object", throwable); // span.log(errorLogs); // } // } // } // Path: examples/spring-boot/src/main/java/io/opentracing/contrib/jaxrs2/example/spring/boot/Configuration.java import io.opentracing.Tracer; import io.opentracing.contrib.jaxrs2.server.SpanFinishingFilter; import javax.servlet.DispatcherType; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; package io.opentracing.contrib.jaxrs2.example.spring.boot; /** * @author Pavol Loffay */ @org.springframework.context.annotation.Configuration public class Configuration { @Bean public Tracer tracer() { return new LoggingTracer(); } @Bean public FilterRegistrationBean spanFinishingFilter() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new SpanFinishingFilter());
opentracing-contrib/java-jaxrs
opentracing-jaxrs2-itest/apache-cxf/src/test/java/io/opentracing/contrib/jaxrs2/itest/cxf/ApacheCXFHelper.java
// Path: opentracing-jaxrs2-itest/common/src/main/java/io/opentracing/contrib/jaxrs2/itest/common/rest/InstrumentedRestApplication.java // public class InstrumentedRestApplication extends Application { // // private Client client; // private Tracer tracer; // private ServerTracingDynamicFeature serverTracingFeature; // // public InstrumentedRestApplication(@Context ServletContext context) { // this.serverTracingFeature = (ServerTracingDynamicFeature) context.getAttribute( // AbstractJettyTest.SERVER_TRACING_FEATURE); // this.client = (Client) context.getAttribute(AbstractJettyTest.CLIENT_ATTRIBUTE); // this.tracer = (Tracer) context.getAttribute(AbstractJettyTest.TRACER_ATTRIBUTE); // // if (serverTracingFeature == null || client == null || tracer == null) { // throw new IllegalArgumentException("Instrumented application is not initialized correctly. serverTracing:" // + serverTracingFeature + ", clientTracing: " + client); // } // } // // @Override // public Set<Object> getSingletons() { // Set<Object> objects = new HashSet<>(); // // objects.add(serverTracingFeature); // objects.add(new TestHandler(tracer, client)); // objects.add(new DisabledTestHandler(tracer)); // objects.add(new ServicesImpl()); // objects.add(new ServicesImplOverrideClassPath()); // objects.add(new ServicesImplOverrideMethodPath()); // objects.add(new DenyFilteredFeature()); // objects.add(new MappedExceptionMapper()); // // return Collections.unmodifiableSet(objects); // } // // /** // * A dynamic feature that introduces a request filter denying all requests to "filtered" // * endpoints. // * // * @author Maxime Petazzoni // */ // private static final class DenyFilteredFeature implements DynamicFeature { // @Override // public void configure(ResourceInfo resourceInfo, FeatureContext context) { // context.register(new ContainerRequestFilter() { // @Override // public void filter(ContainerRequestContext requestContext) throws IOException { // if (requestContext.getUriInfo().getPath().endsWith("filtered")) { // throw new ForbiddenException(); // } // } // }, Priorities.AUTHORIZATION); // } // } // // public static class MappedException extends WebApplicationException { // } // // private static class MappedExceptionMapper implements ExceptionMapper<MappedException> { // @Override // public Response toResponse(MappedException exception) { // return Response.status(405).build(); // } // } // }
import io.opentracing.contrib.jaxrs2.itest.common.rest.InstrumentedRestApplication; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder;
package io.opentracing.contrib.jaxrs2.itest.cxf; /** * @author Pavol Loffay */ public class ApacheCXFHelper { private ApacheCXFHelper() {} public static void initServletContext(ServletContextHandler context) { ServletHolder apacheCXFServlet = context.addServlet( org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet.class, "/*"); apacheCXFServlet.setInitOrder(0); apacheCXFServlet.setInitParameter(
// Path: opentracing-jaxrs2-itest/common/src/main/java/io/opentracing/contrib/jaxrs2/itest/common/rest/InstrumentedRestApplication.java // public class InstrumentedRestApplication extends Application { // // private Client client; // private Tracer tracer; // private ServerTracingDynamicFeature serverTracingFeature; // // public InstrumentedRestApplication(@Context ServletContext context) { // this.serverTracingFeature = (ServerTracingDynamicFeature) context.getAttribute( // AbstractJettyTest.SERVER_TRACING_FEATURE); // this.client = (Client) context.getAttribute(AbstractJettyTest.CLIENT_ATTRIBUTE); // this.tracer = (Tracer) context.getAttribute(AbstractJettyTest.TRACER_ATTRIBUTE); // // if (serverTracingFeature == null || client == null || tracer == null) { // throw new IllegalArgumentException("Instrumented application is not initialized correctly. serverTracing:" // + serverTracingFeature + ", clientTracing: " + client); // } // } // // @Override // public Set<Object> getSingletons() { // Set<Object> objects = new HashSet<>(); // // objects.add(serverTracingFeature); // objects.add(new TestHandler(tracer, client)); // objects.add(new DisabledTestHandler(tracer)); // objects.add(new ServicesImpl()); // objects.add(new ServicesImplOverrideClassPath()); // objects.add(new ServicesImplOverrideMethodPath()); // objects.add(new DenyFilteredFeature()); // objects.add(new MappedExceptionMapper()); // // return Collections.unmodifiableSet(objects); // } // // /** // * A dynamic feature that introduces a request filter denying all requests to "filtered" // * endpoints. // * // * @author Maxime Petazzoni // */ // private static final class DenyFilteredFeature implements DynamicFeature { // @Override // public void configure(ResourceInfo resourceInfo, FeatureContext context) { // context.register(new ContainerRequestFilter() { // @Override // public void filter(ContainerRequestContext requestContext) throws IOException { // if (requestContext.getUriInfo().getPath().endsWith("filtered")) { // throw new ForbiddenException(); // } // } // }, Priorities.AUTHORIZATION); // } // } // // public static class MappedException extends WebApplicationException { // } // // private static class MappedExceptionMapper implements ExceptionMapper<MappedException> { // @Override // public Response toResponse(MappedException exception) { // return Response.status(405).build(); // } // } // } // Path: opentracing-jaxrs2-itest/apache-cxf/src/test/java/io/opentracing/contrib/jaxrs2/itest/cxf/ApacheCXFHelper.java import io.opentracing.contrib.jaxrs2.itest.common.rest.InstrumentedRestApplication; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; package io.opentracing.contrib.jaxrs2.itest.cxf; /** * @author Pavol Loffay */ public class ApacheCXFHelper { private ApacheCXFHelper() {} public static void initServletContext(ServletContextHandler context) { ServletHolder apacheCXFServlet = context.addServlet( org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet.class, "/*"); apacheCXFServlet.setInitOrder(0); apacheCXFServlet.setInitParameter(
"javax.ws.rs.Application", InstrumentedRestApplication.class.getCanonicalName());
opentracing-contrib/java-jaxrs
opentracing-jaxrs2/src/main/java/io/opentracing/contrib/jaxrs2/client/ClientTracingFeature.java
// Path: opentracing-jaxrs2/src/main/java/io/opentracing/contrib/jaxrs2/serialization/InterceptorSpanDecorator.java // public interface InterceptorSpanDecorator { // // /** // * Decorate spans by outgoing object. // * // * @param context // * @param span // */ // void decorateRead(InterceptorContext context, Span span); // // /** // * Decorate spans by outgoing object. // * // * @param context // * @param span // */ // void decorateWrite(InterceptorContext context, Span span); // // /** // * Adds tags: \"media.type\", \"entity.type\" // */ // InterceptorSpanDecorator STANDARD_TAGS = new InterceptorSpanDecorator() { // @Override // public void decorateRead(InterceptorContext context, Span span) { // span.setTag("media.type", context.getMediaType().toString()); // span.setTag("entity.type", context.getType().getName()); // } // // @Override // public void decorateWrite(InterceptorContext context, Span span) { // decorateRead(context, span); // } // }; // }
import io.opentracing.Tracer; import io.opentracing.contrib.jaxrs2.serialization.InterceptorSpanDecorator; import io.opentracing.util.GlobalTracer; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.Priorities; import javax.ws.rs.client.Client; import javax.ws.rs.core.Feature; import javax.ws.rs.core.FeatureContext;
package io.opentracing.contrib.jaxrs2.client; /** * @author Pavol Loffay */ public class ClientTracingFeature implements Feature { private static final Logger log = Logger.getLogger(ClientTracingFeature.class.getName()); private Builder builder; /** * When using this constructor application has to call {@link GlobalTracer#registerIfAbsent(Tracer)} to register * tracer instance. * * For a custom configuration use {@link Builder#build()}. */ public ClientTracingFeature() { this(new Builder(GlobalTracer.get())); } private ClientTracingFeature(Builder builder) { this.builder = builder; } @Override public boolean configure(FeatureContext context) { if (log.isLoggable(Level.FINE)) { log.fine("Registering client OpenTracing, with configuration:" + builder.toString()); } context.register(new ClientTracingFilter(builder.tracer, builder.spanDecorators), builder.priority); if (builder.traceSerialization) { context.register( new ClientTracingInterceptor(builder.tracer, builder.serializationSpanDecorators), builder.serializationPriority); } return true; } /** * Builder for configuring {@link Client} to trace outgoing requests. * * By default get's operation name is HTTP method and get is decorated with * {@link ClientSpanDecorator#STANDARD_TAGS} which adds set of standard tags. */ public static class Builder { private Tracer tracer; private List<ClientSpanDecorator> spanDecorators;
// Path: opentracing-jaxrs2/src/main/java/io/opentracing/contrib/jaxrs2/serialization/InterceptorSpanDecorator.java // public interface InterceptorSpanDecorator { // // /** // * Decorate spans by outgoing object. // * // * @param context // * @param span // */ // void decorateRead(InterceptorContext context, Span span); // // /** // * Decorate spans by outgoing object. // * // * @param context // * @param span // */ // void decorateWrite(InterceptorContext context, Span span); // // /** // * Adds tags: \"media.type\", \"entity.type\" // */ // InterceptorSpanDecorator STANDARD_TAGS = new InterceptorSpanDecorator() { // @Override // public void decorateRead(InterceptorContext context, Span span) { // span.setTag("media.type", context.getMediaType().toString()); // span.setTag("entity.type", context.getType().getName()); // } // // @Override // public void decorateWrite(InterceptorContext context, Span span) { // decorateRead(context, span); // } // }; // } // Path: opentracing-jaxrs2/src/main/java/io/opentracing/contrib/jaxrs2/client/ClientTracingFeature.java import io.opentracing.Tracer; import io.opentracing.contrib.jaxrs2.serialization.InterceptorSpanDecorator; import io.opentracing.util.GlobalTracer; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.Priorities; import javax.ws.rs.client.Client; import javax.ws.rs.core.Feature; import javax.ws.rs.core.FeatureContext; package io.opentracing.contrib.jaxrs2.client; /** * @author Pavol Loffay */ public class ClientTracingFeature implements Feature { private static final Logger log = Logger.getLogger(ClientTracingFeature.class.getName()); private Builder builder; /** * When using this constructor application has to call {@link GlobalTracer#registerIfAbsent(Tracer)} to register * tracer instance. * * For a custom configuration use {@link Builder#build()}. */ public ClientTracingFeature() { this(new Builder(GlobalTracer.get())); } private ClientTracingFeature(Builder builder) { this.builder = builder; } @Override public boolean configure(FeatureContext context) { if (log.isLoggable(Level.FINE)) { log.fine("Registering client OpenTracing, with configuration:" + builder.toString()); } context.register(new ClientTracingFilter(builder.tracer, builder.spanDecorators), builder.priority); if (builder.traceSerialization) { context.register( new ClientTracingInterceptor(builder.tracer, builder.serializationSpanDecorators), builder.serializationPriority); } return true; } /** * Builder for configuring {@link Client} to trace outgoing requests. * * By default get's operation name is HTTP method and get is decorated with * {@link ClientSpanDecorator#STANDARD_TAGS} which adds set of standard tags. */ public static class Builder { private Tracer tracer; private List<ClientSpanDecorator> spanDecorators;
private List<InterceptorSpanDecorator> serializationSpanDecorators;
opentracing-contrib/java-jaxrs
opentracing-jaxrs2-itest/resteasy/src/test/java/io/opentracing/contrib/jaxrs2/itest/resteasy/RestEasyHelper.java
// Path: opentracing-jaxrs2-itest/common/src/main/java/io/opentracing/contrib/jaxrs2/itest/common/rest/InstrumentedRestApplication.java // public class InstrumentedRestApplication extends Application { // // private Client client; // private Tracer tracer; // private ServerTracingDynamicFeature serverTracingFeature; // // public InstrumentedRestApplication(@Context ServletContext context) { // this.serverTracingFeature = (ServerTracingDynamicFeature) context.getAttribute( // AbstractJettyTest.SERVER_TRACING_FEATURE); // this.client = (Client) context.getAttribute(AbstractJettyTest.CLIENT_ATTRIBUTE); // this.tracer = (Tracer) context.getAttribute(AbstractJettyTest.TRACER_ATTRIBUTE); // // if (serverTracingFeature == null || client == null || tracer == null) { // throw new IllegalArgumentException("Instrumented application is not initialized correctly. serverTracing:" // + serverTracingFeature + ", clientTracing: " + client); // } // } // // @Override // public Set<Object> getSingletons() { // Set<Object> objects = new HashSet<>(); // // objects.add(serverTracingFeature); // objects.add(new TestHandler(tracer, client)); // objects.add(new DisabledTestHandler(tracer)); // objects.add(new ServicesImpl()); // objects.add(new ServicesImplOverrideClassPath()); // objects.add(new ServicesImplOverrideMethodPath()); // objects.add(new DenyFilteredFeature()); // objects.add(new MappedExceptionMapper()); // // return Collections.unmodifiableSet(objects); // } // // /** // * A dynamic feature that introduces a request filter denying all requests to "filtered" // * endpoints. // * // * @author Maxime Petazzoni // */ // private static final class DenyFilteredFeature implements DynamicFeature { // @Override // public void configure(ResourceInfo resourceInfo, FeatureContext context) { // context.register(new ContainerRequestFilter() { // @Override // public void filter(ContainerRequestContext requestContext) throws IOException { // if (requestContext.getUriInfo().getPath().endsWith("filtered")) { // throw new ForbiddenException(); // } // } // }, Priorities.AUTHORIZATION); // } // } // // public static class MappedException extends WebApplicationException { // } // // private static class MappedExceptionMapper implements ExceptionMapper<MappedException> { // @Override // public Response toResponse(MappedException exception) { // return Response.status(405).build(); // } // } // }
import io.opentracing.contrib.jaxrs2.itest.common.rest.InstrumentedRestApplication; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder;
package io.opentracing.contrib.jaxrs2.itest.resteasy; /** * @author Pavol Loffay */ public class RestEasyHelper { public static void initServletContext(ServletContextHandler context) { ServletHolder restEasyServlet = context.addServlet( org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.class, "/*"); restEasyServlet.setInitOrder(0); restEasyServlet.setInitParameter(
// Path: opentracing-jaxrs2-itest/common/src/main/java/io/opentracing/contrib/jaxrs2/itest/common/rest/InstrumentedRestApplication.java // public class InstrumentedRestApplication extends Application { // // private Client client; // private Tracer tracer; // private ServerTracingDynamicFeature serverTracingFeature; // // public InstrumentedRestApplication(@Context ServletContext context) { // this.serverTracingFeature = (ServerTracingDynamicFeature) context.getAttribute( // AbstractJettyTest.SERVER_TRACING_FEATURE); // this.client = (Client) context.getAttribute(AbstractJettyTest.CLIENT_ATTRIBUTE); // this.tracer = (Tracer) context.getAttribute(AbstractJettyTest.TRACER_ATTRIBUTE); // // if (serverTracingFeature == null || client == null || tracer == null) { // throw new IllegalArgumentException("Instrumented application is not initialized correctly. serverTracing:" // + serverTracingFeature + ", clientTracing: " + client); // } // } // // @Override // public Set<Object> getSingletons() { // Set<Object> objects = new HashSet<>(); // // objects.add(serverTracingFeature); // objects.add(new TestHandler(tracer, client)); // objects.add(new DisabledTestHandler(tracer)); // objects.add(new ServicesImpl()); // objects.add(new ServicesImplOverrideClassPath()); // objects.add(new ServicesImplOverrideMethodPath()); // objects.add(new DenyFilteredFeature()); // objects.add(new MappedExceptionMapper()); // // return Collections.unmodifiableSet(objects); // } // // /** // * A dynamic feature that introduces a request filter denying all requests to "filtered" // * endpoints. // * // * @author Maxime Petazzoni // */ // private static final class DenyFilteredFeature implements DynamicFeature { // @Override // public void configure(ResourceInfo resourceInfo, FeatureContext context) { // context.register(new ContainerRequestFilter() { // @Override // public void filter(ContainerRequestContext requestContext) throws IOException { // if (requestContext.getUriInfo().getPath().endsWith("filtered")) { // throw new ForbiddenException(); // } // } // }, Priorities.AUTHORIZATION); // } // } // // public static class MappedException extends WebApplicationException { // } // // private static class MappedExceptionMapper implements ExceptionMapper<MappedException> { // @Override // public Response toResponse(MappedException exception) { // return Response.status(405).build(); // } // } // } // Path: opentracing-jaxrs2-itest/resteasy/src/test/java/io/opentracing/contrib/jaxrs2/itest/resteasy/RestEasyHelper.java import io.opentracing.contrib.jaxrs2.itest.common.rest.InstrumentedRestApplication; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; package io.opentracing.contrib.jaxrs2.itest.resteasy; /** * @author Pavol Loffay */ public class RestEasyHelper { public static void initServletContext(ServletContextHandler context) { ServletHolder restEasyServlet = context.addServlet( org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.class, "/*"); restEasyServlet.setInitOrder(0); restEasyServlet.setInitParameter(
"javax.ws.rs.Application", InstrumentedRestApplication.class.getCanonicalName());
opentracing-contrib/java-jaxrs
opentracing-jaxrs2/src/main/java/io/opentracing/contrib/jaxrs2/server/ServerTracingFilter.java
// Path: opentracing-jaxrs2/src/main/java/io/opentracing/contrib/jaxrs2/internal/CastUtils.java // public class CastUtils { // private static final Logger log = Logger.getLogger(CastUtils.class.getName()); // // private CastUtils() {} // // /** // * Casts given object to the given class. // * // * @param object // * @param clazz // * @param <T> // * @return casted object, or null if there is any error // */ // public static <T> T cast(Object object, Class<T> clazz) { // if (object == null || clazz == null) { // return null; // } // // try { // return clazz.cast(object); // } catch (ClassCastException ex) { // log.severe("Cannot cast to " + clazz.getName()); // return null; // } // } // } // // Path: opentracing-jaxrs2/src/main/java/io/opentracing/contrib/jaxrs2/internal/SpanWrapper.java // public class SpanWrapper { // // public static final String PROPERTY_NAME = SpanWrapper.class.getName() + ".activeSpanWrapper"; // // private Scope scope; // private Span span; // private AtomicBoolean finished = new AtomicBoolean(); // // public SpanWrapper(Span span, Scope scope) { // this.span = span; // this.scope = scope; // // } // // public Span get() { // return span; // } // // public Scope getScope() { // return scope; // } // // public void finish() { // if (finished.compareAndSet(false, true)) { // span.finish(); // } // } // // public boolean isFinished() { // return finished.get(); // } // } // // Path: opentracing-jaxrs2/src/main/java/io/opentracing/contrib/jaxrs2/internal/SpanWrapper.java // public static final String PROPERTY_NAME = SpanWrapper.class.getName() + ".activeSpanWrapper";
import io.opentracing.Scope; import io.opentracing.Span; import io.opentracing.SpanContext; import io.opentracing.Tracer; import io.opentracing.contrib.jaxrs2.internal.CastUtils; import io.opentracing.contrib.jaxrs2.internal.SpanWrapper; import io.opentracing.propagation.Format; import io.opentracing.tag.Tags; import javax.annotation.Priority; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Priorities; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.core.Context; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import static io.opentracing.contrib.jaxrs2.internal.SpanWrapper.PROPERTY_NAME;
package io.opentracing.contrib.jaxrs2.server; /** * @author Pavol Loffay */ @Priority(Priorities.HEADER_DECORATOR) public class ServerTracingFilter implements ContainerRequestFilter, ContainerResponseFilter { private static final Logger log = Logger.getLogger(ServerTracingFilter.class.getName()); private Tracer tracer; private List<ServerSpanDecorator> spanDecorators; private String operationName; private OperationNameProvider operationNameProvider; private Pattern skipPattern; private final boolean joinExistingActiveSpan; protected ServerTracingFilter( Tracer tracer, String operationName, List<ServerSpanDecorator> spanDecorators, OperationNameProvider operationNameProvider, Pattern skipPattern, boolean joinExistingActiveSpan) { this.tracer = tracer; this.operationName = operationName; this.spanDecorators = new ArrayList<>(spanDecorators); this.operationNameProvider = operationNameProvider; this.skipPattern = skipPattern; this.joinExistingActiveSpan = joinExistingActiveSpan; } @Context private HttpServletRequest httpServletRequest; @Override public void filter(ContainerRequestContext requestContext) { // return in case filter if registered twice
// Path: opentracing-jaxrs2/src/main/java/io/opentracing/contrib/jaxrs2/internal/CastUtils.java // public class CastUtils { // private static final Logger log = Logger.getLogger(CastUtils.class.getName()); // // private CastUtils() {} // // /** // * Casts given object to the given class. // * // * @param object // * @param clazz // * @param <T> // * @return casted object, or null if there is any error // */ // public static <T> T cast(Object object, Class<T> clazz) { // if (object == null || clazz == null) { // return null; // } // // try { // return clazz.cast(object); // } catch (ClassCastException ex) { // log.severe("Cannot cast to " + clazz.getName()); // return null; // } // } // } // // Path: opentracing-jaxrs2/src/main/java/io/opentracing/contrib/jaxrs2/internal/SpanWrapper.java // public class SpanWrapper { // // public static final String PROPERTY_NAME = SpanWrapper.class.getName() + ".activeSpanWrapper"; // // private Scope scope; // private Span span; // private AtomicBoolean finished = new AtomicBoolean(); // // public SpanWrapper(Span span, Scope scope) { // this.span = span; // this.scope = scope; // // } // // public Span get() { // return span; // } // // public Scope getScope() { // return scope; // } // // public void finish() { // if (finished.compareAndSet(false, true)) { // span.finish(); // } // } // // public boolean isFinished() { // return finished.get(); // } // } // // Path: opentracing-jaxrs2/src/main/java/io/opentracing/contrib/jaxrs2/internal/SpanWrapper.java // public static final String PROPERTY_NAME = SpanWrapper.class.getName() + ".activeSpanWrapper"; // Path: opentracing-jaxrs2/src/main/java/io/opentracing/contrib/jaxrs2/server/ServerTracingFilter.java import io.opentracing.Scope; import io.opentracing.Span; import io.opentracing.SpanContext; import io.opentracing.Tracer; import io.opentracing.contrib.jaxrs2.internal.CastUtils; import io.opentracing.contrib.jaxrs2.internal.SpanWrapper; import io.opentracing.propagation.Format; import io.opentracing.tag.Tags; import javax.annotation.Priority; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Priorities; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.core.Context; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import static io.opentracing.contrib.jaxrs2.internal.SpanWrapper.PROPERTY_NAME; package io.opentracing.contrib.jaxrs2.server; /** * @author Pavol Loffay */ @Priority(Priorities.HEADER_DECORATOR) public class ServerTracingFilter implements ContainerRequestFilter, ContainerResponseFilter { private static final Logger log = Logger.getLogger(ServerTracingFilter.class.getName()); private Tracer tracer; private List<ServerSpanDecorator> spanDecorators; private String operationName; private OperationNameProvider operationNameProvider; private Pattern skipPattern; private final boolean joinExistingActiveSpan; protected ServerTracingFilter( Tracer tracer, String operationName, List<ServerSpanDecorator> spanDecorators, OperationNameProvider operationNameProvider, Pattern skipPattern, boolean joinExistingActiveSpan) { this.tracer = tracer; this.operationName = operationName; this.spanDecorators = new ArrayList<>(spanDecorators); this.operationNameProvider = operationNameProvider; this.skipPattern = skipPattern; this.joinExistingActiveSpan = joinExistingActiveSpan; } @Context private HttpServletRequest httpServletRequest; @Override public void filter(ContainerRequestContext requestContext) { // return in case filter if registered twice
if (requestContext.getProperty(PROPERTY_NAME) != null || matchesSkipPattern(requestContext)) {