answer
stringlengths
17
10.2M
package org.jenkinsci.plugins.p4; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.perforce.p4java.exception.P4JavaException; import hudson.AbortException; import hudson.EnvVars; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.Plugin; import hudson.matrix.MatrixBuild; import hudson.matrix.MatrixConfiguration; import hudson.matrix.MatrixExecutionStrategy; import hudson.matrix.MatrixProject; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.Item; import hudson.model.Job; import hudson.model.Node; import hudson.model.Run; import hudson.model.TaskListener; import hudson.scm.ChangeLogParser; import hudson.scm.PollingResult; import hudson.scm.SCM; import hudson.scm.SCMDescriptor; import hudson.scm.SCMRevisionState; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import hudson.util.LogTaskListener; import jenkins.model.Jenkins; import net.sf.json.JSONException; import net.sf.json.JSONObject; import org.jenkinsci.Symbol; import org.jenkinsci.plugins.multiplescms.MultiSCM; import org.jenkinsci.plugins.p4.browsers.P4Browser; import org.jenkinsci.plugins.p4.browsers.SwarmBrowser; import org.jenkinsci.plugins.p4.build.ExecutorHelper; import org.jenkinsci.plugins.p4.build.NodeHelper; import org.jenkinsci.plugins.p4.build.P4EnvironmentContributor; import org.jenkinsci.plugins.p4.changes.P4ChangeEntry; import org.jenkinsci.plugins.p4.changes.P4ChangeParser; import org.jenkinsci.plugins.p4.changes.P4ChangeRef; import org.jenkinsci.plugins.p4.changes.P4ChangeSet; import org.jenkinsci.plugins.p4.changes.P4GraphRef; import org.jenkinsci.plugins.p4.changes.P4LabelRef; import org.jenkinsci.plugins.p4.changes.P4Ref; import org.jenkinsci.plugins.p4.client.ConnectionHelper; import org.jenkinsci.plugins.p4.credentials.P4BaseCredentials; import org.jenkinsci.plugins.p4.credentials.P4CredentialsImpl; import org.jenkinsci.plugins.p4.filters.Filter; import org.jenkinsci.plugins.p4.filters.FilterPerChangeImpl; import org.jenkinsci.plugins.p4.matrix.MatrixOptions; import org.jenkinsci.plugins.p4.populate.Populate; import org.jenkinsci.plugins.p4.review.P4Review; import org.jenkinsci.plugins.p4.review.ReviewProp; import org.jenkinsci.plugins.p4.scm.AbstractP4ScmSource; import org.jenkinsci.plugins.p4.scm.P4Path; import org.jenkinsci.plugins.p4.tagging.TagAction; import org.jenkinsci.plugins.p4.tasks.CheckoutStatus; import org.jenkinsci.plugins.p4.tasks.CheckoutTask; import org.jenkinsci.plugins.p4.tasks.PollTask; import org.jenkinsci.plugins.p4.tasks.RemoveClientTask; import org.jenkinsci.plugins.p4.workspace.ManualWorkspaceImpl; import org.jenkinsci.plugins.p4.workspace.SpecWorkspaceImpl; import org.jenkinsci.plugins.p4.workspace.StaticWorkspaceImpl; import org.jenkinsci.plugins.p4.workspace.StreamWorkspaceImpl; import org.jenkinsci.plugins.p4.workspace.TemplateWorkspaceImpl; import org.jenkinsci.plugins.p4.workspace.Workspace; import org.jenkinsci.plugins.workflow.job.properties.DisableConcurrentBuildsJobProperty; import org.kohsuke.stapler.AncestorInPath; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.StaplerRequest; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; public class PerforceScm extends SCM { private static Logger logger = Logger.getLogger(PerforceScm.class.getName()); private final String credential; private final Workspace workspace; private final List<Filter> filter; private final Populate populate; private final P4Browser browser; private final P4Ref revision; private transient P4Ref parentChange; private transient P4Review review; public static final int DEFAULT_FILE_LIMIT = 50; public static final int DEFAULT_CHANGE_LIMIT = 20; public String getCredential() { return credential; } public Workspace getWorkspace() { return workspace; } public List<Filter> getFilter() { return filter; } public Populate getPopulate() { return populate; } @Override public P4Browser getBrowser() { return browser; } public P4Review getReview() { return review; } public void setReview(P4Review review) { this.review = review; } /** * Helper function for converting an SCM object into a * PerforceScm object when appropriate. * * @param scm the SCM object * @return a PerforceScm instance or null */ public static PerforceScm convertToPerforceScm(SCM scm) { PerforceScm perforceScm = null; if (scm instanceof PerforceScm) { perforceScm = (PerforceScm) scm; } else { Jenkins jenkins = Jenkins.getInstance(); if (jenkins != null) { Plugin multiSCMPlugin = jenkins.getPlugin("multiple-scms"); if (multiSCMPlugin != null) { if (scm instanceof MultiSCM) { MultiSCM multiSCM = (MultiSCM) scm; for (SCM configuredSCM : multiSCM.getConfiguredSCMs()) { if (configuredSCM instanceof PerforceScm) { perforceScm = (PerforceScm) configuredSCM; break; } } } } } } return perforceScm; } /** * Create a constructor that takes non-transient fields, and add the * annotation @DataBoundConstructor to it. Using the annotation helps the * Stapler class to find which constructor that should be used when * automatically copying values from a web form to a class. * * @param credential Credential ID * @param workspace Workspace connection details * @param filter Polling filters * @param populate Populate options * @param browser Browser options */ @DataBoundConstructor public PerforceScm(String credential, Workspace workspace, List<Filter> filter, Populate populate, P4Browser browser) { this.credential = credential; this.workspace = workspace; this.filter = filter; this.populate = populate; this.browser = browser; this.revision = null; } public PerforceScm(AbstractP4ScmSource source, P4Path path, P4Ref revision) { this.credential = source.getCredential(); this.workspace = source.getWorkspace(path); this.filter = null; this.populate = source.getPopulate(); this.browser = source.getBrowser(); this.revision = revision; } public PerforceScm(String credential, Workspace workspace, Populate populate) { this.credential = credential; this.workspace = workspace; this.filter = null; this.populate = populate; this.browser = null; this.revision = null; } @Override public String getKey() { String delim = "-"; StringBuffer key = new StringBuffer("p4"); // add Credential key.append(delim); key.append(credential); // add Mapping/Stream key.append(delim); if (workspace instanceof ManualWorkspaceImpl) { ManualWorkspaceImpl ws = (ManualWorkspaceImpl) workspace; key.append(ws.getSpec().getView()); key.append(ws.getSpec().getStreamName()); } if (workspace instanceof StreamWorkspaceImpl) { StreamWorkspaceImpl ws = (StreamWorkspaceImpl) workspace; key.append(ws.getStreamName()); } if (workspace instanceof SpecWorkspaceImpl) { SpecWorkspaceImpl ws = (SpecWorkspaceImpl) workspace; key.append(ws.getSpecPath()); } if (workspace instanceof StaticWorkspaceImpl) { StaticWorkspaceImpl ws = (StaticWorkspaceImpl) workspace; key.append(ws.getName()); } if (workspace instanceof TemplateWorkspaceImpl) { TemplateWorkspaceImpl ws = (TemplateWorkspaceImpl) workspace; key.append(ws.getTemplateName()); } return key.toString(); } public static P4Browser findBrowser(String scmCredential) { // Retrieve item from request StaplerRequest req = Stapler.getCurrentRequest(); Job job = req == null ? null : req.findAncestorObject(Job.class); // If cannot retrieve item, check from root P4BaseCredentials credentials = job == null ? ConnectionHelper.findCredential(scmCredential, Jenkins.getActiveInstance()) : ConnectionHelper.findCredential(scmCredential, job); if (credentials == null) { logger.fine("Could not retrieve credentials from id: '${scmCredential}"); return null; } try { ConnectionHelper connection = new ConnectionHelper(credentials, null); String url = connection.getSwarm(); if (url != null) { return new SwarmBrowser(url); } else { return null; } } catch (P4JavaException e) { logger.info("Unable to access Perforce Property."); return null; } } /** * Calculate the state of the workspace of the given build. The returned * object is then fed into compareRemoteRevisionWith as the baseline * SCMRevisionState to determine if the build is necessary, and is added to * the build as an Action for later retrieval. */ @Override public SCMRevisionState calcRevisionsFromBuild(Run<?, ?> run, FilePath buildWorkspace, Launcher launcher, TaskListener listener) throws IOException, InterruptedException { // A baseline is not required... but a baseline object is, so we'll // return the NONE object. return SCMRevisionState.NONE; } /** * This method does the actual polling and returns a PollingResult. The * change attribute of the PollingResult the significance of the changes * detected by this poll. */ @Override public PollingResult compareRemoteRevisionWith(Job<?, ?> job, Launcher launcher, FilePath buildWorkspace, TaskListener listener, SCMRevisionState baseline) throws IOException, InterruptedException { PollingResult state = PollingResult.NO_CHANGES; Node node = NodeHelper.workspaceToNode(buildWorkspace); // Get last run and build workspace Run<?, ?> lastRun = job.getLastBuild(); // Build workspace is often null as requiresWorkspaceForPolling() returns false as a checked out workspace is // not needed, but we still need a client and artificial root for the view. // JENKINS-46908 if (buildWorkspace == null) { String defaultRoot = job.getRootDir().getAbsoluteFile().getAbsolutePath(); if (lastRun != null) { EnvVars env = lastRun.getEnvironment(listener); buildWorkspace = new FilePath(new File(env.get("WORKSPACE", defaultRoot))); } else { listener.getLogger().println("Warning Jenkins Workspace root not defined."); return PollingResult.NO_CHANGES; } } if (job instanceof MatrixProject) { if (isBuildParent(job)) { // Poll PARENT only EnvVars envVars = job.getEnvironment(node, listener); state = pollWorkspace(envVars, listener, buildWorkspace, lastRun); } else { // Poll CHILDREN only MatrixProject matrixProj = (MatrixProject) job; Collection<MatrixConfiguration> configs = matrixProj.getActiveConfigurations(); for (MatrixConfiguration config : configs) { EnvVars envVars = config.getEnvironment(node, listener); state = pollWorkspace(envVars, listener, buildWorkspace, lastRun); // exit early if changes found if (state == PollingResult.BUILD_NOW) { return PollingResult.BUILD_NOW; } } } } else { EnvVars envVars = job.getEnvironment(node, listener); state = pollWorkspace(envVars, listener, buildWorkspace, lastRun); } return state; } private boolean isConcurrentBuild(Job<?, ?> job) { return job instanceof AbstractProject ? ((AbstractProject) job).isConcurrentBuild() : job.getProperty(DisableConcurrentBuildsJobProperty.class) == null; } /** * Construct workspace from environment and then look for changes. * * @param envVars * @param listener * @throws InterruptedException * @throws IOException */ private PollingResult pollWorkspace(EnvVars envVars, TaskListener listener, FilePath buildWorkspace, Run<?, ?> lastRun) throws InterruptedException, IOException { PrintStream log = listener.getLogger(); // set NODE_NAME to Node or default "master" if not set String nodeName = NodeHelper.getNodeName(buildWorkspace); envVars.put("NODE_NAME", envVars.get("NODE_NAME", nodeName)); String executor = ExecutorHelper.getExecutorID(buildWorkspace); envVars.put("EXECUTOR_NUMBER", envVars.get("EXECUTOR_NUMBER", executor)); Workspace ws = (Workspace) workspace.clone(); // JENKINS-48434 by setting rootPath to null will leave client's root unchanged ws.setRootPath(null); ws.setExpand(envVars); // Set EXPANDED client String client = ws.getFullName(); log.println("P4: Polling on: " + nodeName + " with:" + client); List<P4Ref> changes = lookForChanges(buildWorkspace, ws, lastRun, listener); // Cleanup Perforce Client cleanupPerforceClient(lastRun, buildWorkspace, listener, ws); // Build if null (un-built) or if changes are found if (changes == null || !changes.isEmpty()) { return PollingResult.BUILD_NOW; } return PollingResult.NO_CHANGES; } /** * Look for un-built for changes * * @param ws * @param lastRun * @param listener * @return A list of changes found during polling, empty list if no changes (up-to-date). * Will return 'null' if no previous build. */ private List<P4Ref> lookForChanges(FilePath buildWorkspace, Workspace ws, Run<?, ?> lastRun, TaskListener listener) throws IOException, InterruptedException { // Set EXPANDED client String syncID = ws.getSyncID(); // Set EXPANDED pinned label/change String pin = populate.getPin(); if (pin != null && !pin.isEmpty()) { pin = ws.getExpand().format(pin, false); ws.getExpand().set(ReviewProp.P4_LABEL.toString(), pin); } // Calculate last change, build if null (JENKINS-40356) List<P4Ref> lastRefs = TagAction.getLastChange(lastRun, listener, syncID); if (lastRefs == null || lastRefs.isEmpty()) { // no previous build, return null. return null; } // Create task PollTask task = new PollTask(credential, lastRun, listener, filter, lastRefs); task.setWorkspace(ws); task.setLimit(pin); // Execute remote task List<P4Ref> changes = buildWorkspace.act(task); return changes; } /** * The checkout method is expected to check out modified files into the * project workspace. In Perforce terms a 'p4 sync' on the project's * workspace. Authorisation */ @Override public void checkout(Run<?, ?> run, Launcher launcher, FilePath buildWorkspace, TaskListener listener, File changelogFile, SCMRevisionState baseline) throws IOException, InterruptedException { PrintStream log = listener.getLogger(); boolean success = true; // Create task CheckoutTask task = new CheckoutTask(credential, run, listener, populate); // Update credential tracking CredentialsProvider.track(run, task.getCredential()); // Get workspace used for the Task Workspace ws = task.setEnvironment(run, workspace, buildWorkspace); // Add review to environment, if defined if (review != null) { ws.addEnv(ReviewProp.SWARM_REVIEW.toString(), review.getId()); ws.addEnv(ReviewProp.SWARM_STATUS.toString(), CheckoutStatus.SHELVED.toString()); } // Set the Workspace and initialise task.setWorkspace(ws); task.initialise(); // Override build change if polling per change. if (isIncremental()) { Run<?, ?> lastRun = run.getPreviousBuiltBuild(); List<P4Ref> changes = lookForChanges(buildWorkspace, ws, lastRun, listener); task.setIncrementalChanges(changes); } // SCMRevision build per change if (revision != null) { List<P4Ref> changes = Arrays.asList(revision); task.setIncrementalChanges(changes); } // Add tagging action to build, enabling label support. TagAction tag = new TagAction(run, credential); tag.setWorkspace(ws); tag.setRefChanges(task.getSyncChange()); // JENKINS-37442: Make the log file name available tag.setChangelog(changelogFile); run.addAction(tag); // Invoke build. String node = ws.getExpand().get("NODE_NAME"); Job<?, ?> job = run.getParent(); if (run instanceof MatrixBuild) { parentChange = new P4LabelRef(getChangeNumber(tag, run)); if (isBuildParent(job)) { log.println("Building Parent on Node: " + node); success &= buildWorkspace.act(task); } else { listener.getLogger().println("Skipping Parent build..."); success = true; } } else { if (job instanceof MatrixProject) { if (parentChange != null) { log.println("Using parent change: " + parentChange); task.setBuildChange(parentChange); } log.println("Building Child on Node: " + node); } else { log.println("Building on Node: " + node); } success &= buildWorkspace.act(task); } // Abort if build failed if (!success) { String msg = "P4: Build failed"; logger.warning(msg); throw new AbortException(msg); } // Write change log if changeLogFile has been set. if (changelogFile != null) { // Calculate changes prior to build (based on last build) listener.getLogger().println("P4 Task: saving built changes."); List<P4ChangeEntry> changes = calculateChanges(run, task); P4ChangeSet.store(changelogFile, changes); listener.getLogger().println("... done\n"); } else { listener.getLogger().println("P4Task: unable to save changes, null changelogFile.\n"); } // Cleanup Perforce Client cleanupPerforceClient(run, buildWorkspace, listener, ws); } private void cleanupPerforceClient(Run<?, ?> run, FilePath buildWorkspace, TaskListener listener, Workspace workspace) throws IOException, InterruptedException { // exit early if cleanup not required if (!workspace.isCleanup()) { return; } listener.getLogger().println("P4Task: cleanup Client: " + workspace.getFullName()); RemoveClientTask removeClientTask = new RemoveClientTask(credential, run, listener, false); // Set workspace used for the Task Workspace ws = removeClientTask.setEnvironment(run, workspace, buildWorkspace); removeClientTask.setWorkspace(ws); buildWorkspace.act(removeClientTask); } // Get Matrix Execution options private MatrixExecutionStrategy getMatrixExecutionStrategy(Job<?, ?> job) { if (job instanceof MatrixProject) { MatrixProject matrixProj = (MatrixProject) job; return matrixProj.getExecutionStrategy(); } return null; } boolean isBuildParent(Job<?, ?> job) { MatrixExecutionStrategy matrix = getMatrixExecutionStrategy(job); if (matrix instanceof MatrixOptions) { return ((MatrixOptions) matrix).isBuildParent(); } else { // if user hasn't configured "Perforce: Matrix Options" execution // strategy, default to false return false; } } private List<P4ChangeEntry> calculateChanges(Run<?, ?> run, CheckoutTask task) { List<P4ChangeEntry> list = new ArrayList<P4ChangeEntry>(); // Look for all changes since the last (completed) build. // The lastBuild from getPreviousBuild() may be in progress or blocked. Run<?, ?> lastBuild = run.getPreviousCompletedBuild(); String syncID = task.getSyncID(); List<P4Ref> lastRefs = TagAction.getLastChange(lastBuild, task.getListener(), syncID); if (lastRefs != null && !lastRefs.isEmpty()) { list.addAll(task.getChangesFull(lastRefs)); } // if empty, look for shelves in current build. The latest change // will not get listed as 'p4 changes n,n' will return no change if (list.isEmpty()) { List<P4Ref> lastRevisions = new ArrayList<>(); lastRevisions.add(task.getBuildChange()); if (lastRevisions != null && !lastRevisions.isEmpty()) { list.addAll(task.getChangesFull(lastRevisions)); } } // still empty! No previous build, so add current if ((lastBuild == null) && list.isEmpty()) { list.add(task.getCurrentChange()); } return list; } // Pre Jenkins 2.60 @Override public void buildEnvVars(AbstractBuild<?, ?> build, Map<String, String> env) { super.buildEnvVars(build, env); TagAction tagAction = TagAction.getLastAction(build); P4EnvironmentContributor.buildEnvironment(tagAction, env); } // Post Jenkins 2.60 JENKINS-37584 JENKINS-40885 public void buildEnvironment(Run<?, ?> run, Map<String, String> env) { TagAction tagAction = TagAction.getLastAction(run); P4EnvironmentContributor.buildEnvironment(tagAction, env); } private String getChangeNumber(TagAction tagAction, Run<?, ?> run) { List<P4Ref> builds = tagAction.getRefChanges(); for (P4Ref build : builds) { if (build instanceof P4ChangeRef) { // its a change, so return... return build.toString(); } if (build instanceof P4GraphRef) { continue; } try { // it is really a change number, so add change... int change = Integer.parseInt(build.toString()); return String.valueOf(change); } catch (NumberFormatException n) { // not a change number } try (ConnectionHelper p4 = new ConnectionHelper(run, credential, null)) { String name = build.toString(); // look for a label and return a change String change = p4.labelToChange(name); if (change != null) { return change; } // look for a counter and return change change = p4.counterToChange(name); if (change != null) { return change; } } catch (Exception e) { // log error, but try next item logger.severe("P4: Unable to getChangeNumber: " + e.getMessage()); } } return ""; } /** * The checkout method should, besides checking out the modified files, * write a changelog.xml file that contains the changes for a certain build. * The changelog.xml file is specific for each SCM implementation, and the * createChangeLogParser returns a parser that can parse the file and return * a ChangeLogSet. */ @Override public ChangeLogParser createChangeLogParser() { return new P4ChangeParser(credential); } /** * Called before a workspace is deleted on the given node, to provide SCM an * opportunity to perform clean up. */ @Override public boolean processWorkspaceBeforeDeletion(Job<?, ?> job, FilePath buildWorkspace, Node node) throws IOException, InterruptedException { logger.info("processWorkspaceBeforeDeletion"); Run<?, ?> run = job.getLastBuild(); if (run == null) { logger.warning("P4: No previous builds found"); return false; } // exit early if client workspace is undefined LogTaskListener listener = new LogTaskListener(logger, Level.INFO); EnvVars envVars = run.getEnvironment(listener); String client = envVars.get("P4_CLIENT"); if (client == null || client.isEmpty()) { logger.warning("P4: Unable to read P4_CLIENT"); return false; } // exit early if client workspace does not exist ConnectionHelper connection = new ConnectionHelper(run, credential, null); try { if (!connection.isClient(client)) { logger.warning("P4: client not found:" + client); return false; } } catch (Exception e) { logger.warning("P4: Not able to get connection"); return false; } // Setup Cleanup Task RemoveClientTask task = new RemoveClientTask(credential, job, listener); // Set workspace used for the Task Workspace ws = task.setEnvironment(run, workspace, buildWorkspace); task.setWorkspace(ws); boolean clean = buildWorkspace.act(task); logger.info("clean: " + clean); return clean; } @Override public DescriptorImpl getDescriptor() { return (DescriptorImpl) super.getDescriptor(); } /** * The relationship of Descriptor and SCM (the describable) is akin to class * and object. What this means is that the descriptor is used to create * instances of the describable. Usually the Descriptor is an internal class * in the SCM class named DescriptorImpl. The Descriptor should also contain * the global configuration options as fields, just like the SCM class * contains the configurations options for a job. * * @author pallen */ @Extension @Symbol("perforce") public static class DescriptorImpl extends SCMDescriptor<PerforceScm> { private boolean autoSave; private String credential; private String clientName; private String depotPath; private boolean autoSubmitOnChange; private boolean deleteClient; private boolean deleteFiles; private boolean hideTicket; private int maxFiles = DEFAULT_FILE_LIMIT; private int maxChanges = DEFAULT_CHANGE_LIMIT; public boolean isAutoSave() { return autoSave; } public String getCredential() { return credential; } public String getClientName() { return clientName; } public String getDepotPath() { return depotPath; } public boolean isAutoSubmitOnChange() { return autoSubmitOnChange; } public boolean isDeleteClient() { return deleteClient; } public boolean isDeleteFiles() { return deleteFiles; } public boolean isHideTicket() { return hideTicket; } public int getMaxFiles() { return maxFiles; } public int getMaxChanges() { return maxChanges; } /** * public no-argument constructor */ public DescriptorImpl() { super(PerforceScm.class, P4Browser.class); load(); } /** * Returns the name of the SCM, this is the name that will show up next * to CVS and Subversion when configuring a job. */ @Override public String getDisplayName() { return "Perforce Software"; } @Override public boolean isApplicable(Job project) { return true; } @Override public SCM newInstance(StaplerRequest req, JSONObject formData) throws FormException { PerforceScm scm = (PerforceScm) super.newInstance(req, formData); return scm; } /** * The configure method is invoked when the global configuration page is * submitted. In the method the data in the web form should be copied to * the Descriptor's fields. To persist the fields to the global * configuration XML file, the save() method must be called. Data is * defined in the global.jelly page. */ @Override public boolean configure(StaplerRequest req, JSONObject json) throws FormException { try { autoSave = json.getBoolean("autoSave"); credential = json.getString("credential"); clientName = json.getString("clientName"); depotPath = json.getString("depotPath"); autoSubmitOnChange = json.getBoolean("autoSubmitOnChange"); } catch (JSONException e) { logger.info("Unable to read Auto Version configuration."); autoSave = false; } try { deleteClient = json.getBoolean("deleteClient"); deleteFiles = json.getBoolean("deleteFiles"); } catch (JSONException e) { logger.info("Unable to read client cleanup configuration."); deleteClient = false; deleteFiles = false; } try { hideTicket = json.getBoolean("hideTicket"); } catch (JSONException e) { logger.info("Unable to read TICKET security configuration."); hideTicket = false; } try { maxFiles = json.getInt("maxFiles"); maxChanges = json.getInt("maxChanges"); } catch (JSONException e) { logger.info("Unable to read Max limits in configuration."); maxFiles = DEFAULT_FILE_LIMIT; maxChanges = DEFAULT_CHANGE_LIMIT; } save(); return true; } /** * Credentials list, a Jelly config method for a build job. * * @param project Jenkins project item * @param credential Perforce credential ID * @return A list of Perforce credential items to populate the jelly * Select list. */ public ListBoxModel doFillCredentialItems(@AncestorInPath Item project, @QueryParameter String credential) { return P4CredentialsImpl.doFillCredentialItems(project, credential); } /** * Credentials list, a Jelly config method for a build job. * * @param project Jenkins project item * @param value credential user input value * @return A list of Perforce credential items to populate the jelly * Select list. */ public FormValidation doCheckCredential(@AncestorInPath Item project, @QueryParameter String value) { return P4CredentialsImpl.doCheckCredential(project, value); } } /** * This methods determines if the SCM plugin can be used for polling */ @Override public boolean supportsPolling() { return true; } /** * This method should return true if the SCM requires a workspace for * polling. Perforce however can report submitted, pending and shelved * changes without needing a workspace */ @Override public boolean requiresWorkspaceForPolling() { return false; } /** * Incremental polling filter is set * * @return true if set */ private boolean isIncremental() { if (filter != null) { for (Filter f : filter) { if (f instanceof FilterPerChangeImpl) { if (((FilterPerChangeImpl) f).isPerChange()) { return true; } } } } return false; } }
package org.jenkinsci.remoting.util; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.security.Key; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Objects; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; /** * Utility methods to help working with {@link Key} instances. */ public final class KeyUtils { /** * Utility class. */ private KeyUtils() { throw new IllegalAccessError("Utility class"); } /** * Check two keys for equality. * * @param key1 the first key. * @param key2 the second key. * @return {@code true} if we can confirm that the two keys are identical, {@code false} otherwise. */ public static boolean equals(Key key1, Key key2) { if (key1 == key2) { return true; } if (key1 == null || key2 == null) { return false; } if (!equals(key1.getAlgorithm(), key1.getAlgorithm())) { return false; } if (!equals(key1.getFormat(), key1.getFormat())) { // expecting these to pretty much always be "X.509" for PublicKeys or "PKCS#8" for PrivateKeys return false; } byte[] encoded1 = key1.getEncoded(); byte[] encoded2 = key2.getEncoded(); if (encoded1 == null || encoded2 == null) { // If only one does not support encoding, then they are different. // If both do not support encoding, while they may be the same, we have no way of knowing. return false; } return MessageDigest.isEqual(key1.getEncoded(), key2.getEncoded()); } /** * A helper method for comparing two strings (we'd use StringUtils.equals only that adds more dependencies and * remoting has a generic need to be more self contained. * * @param str1 the first string. * @param str2 the second string. * @return {@code true} if the two strings are equal. */ private static boolean equals(String str1, String str2) { return Objects.equals(str1, str2); } /** * Returns the MD5 fingerprint of a key formatted in the normal way for key fingerprints * * @param key the key. * @return the MD5 fingerprint of the key. */ @Nonnull @SuppressFBWarnings(value = "WEAK_MESSAGE_DIGEST_MD5", justification = "Used for fingerprinting, not security.") public static String fingerprint(@CheckForNull Key key) { if (key == null) { return "null"; } try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.reset(); byte[] bytes = digest.digest(key.getEncoded()); StringBuilder result = new StringBuilder(Math.max(0, bytes.length * 3 - 1)); for (int i = 0; i < bytes.length; i++) { if (i > 0) { result.append(':'); } result.append(Character.forDigit((bytes[i] >> 4) & 0x0f, 16)); result.append(Character.forDigit(bytes[i] & 0x0f, 16)); } return result.toString(); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("JLS mandates MD5 support"); } } }
package org.jtrfp.trcl.obj; import java.awt.Color; import java.awt.Dimension; import java.util.concurrent.Future; import javax.media.opengl.GL3; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.jtrfp.trcl.AnimatedTexture; import org.jtrfp.trcl.ColorProcessor; import org.jtrfp.trcl.DummyFuture; import org.jtrfp.trcl.GammaCorrectingColorProcessor; import org.jtrfp.trcl.Model; import org.jtrfp.trcl.RenderMode; import org.jtrfp.trcl.Sequencer; import org.jtrfp.trcl.Texture; import org.jtrfp.trcl.TextureDescription; import org.jtrfp.trcl.Triangle; import org.jtrfp.trcl.beh.DestroysEverythingBehavior; import org.jtrfp.trcl.core.ResourceManager; import org.jtrfp.trcl.core.TR; import org.jtrfp.trcl.file.ModelingType; import org.jtrfp.trcl.file.Weapon; import org.jtrfp.trcl.obj.Explosion.ExplosionType; public class ProjectileFactory { private int projectileIndex=0; private final TR tr; private final Projectile [] projectiles = new Projectile[20]; private final double projectileSpeed; private final Weapon weapon; public ProjectileFactory(TR tr, Weapon weapon, ExplosionType explosionType){ this.tr=tr; this.weapon=weapon; this.projectileSpeed=weapon.getSpeed()/TR.crossPlatformScalar; Model modelToUse; Future<TextureDescription> t; Triangle [] tris; final int damageOnImpact=weapon.getDamage(); try{ modelToUse = new Model(false,tr); final ModelingType modelingType = weapon.getModelingType(); if(modelingType instanceof ModelingType.FlatModelingType){ ModelingType.FlatModelingType mt = (ModelingType.FlatModelingType)modelingType; Dimension dims = mt.getSegmentSize(); final int laserplaneLength = (int)(dims.getWidth()/TR.crossPlatformScalar); final int laserplaneWidth = (int)(dims.getHeight()/TR.crossPlatformScalar); t = tr.getResourceManager().getRAWAsTexture( mt.getRawFileName(), tr.getDarkIsClearPalette(), GammaCorrectingColorProcessor.singleton, tr.getGPU().getGl()); tris =(Triangle.quad2Triangles(new double[]{-laserplaneLength/2.,laserplaneLength/2.,laserplaneLength/2.,0}, new double[]{0,0,0,0}, new double[]{-laserplaneWidth/2.,-laserplaneWidth/2.,laserplaneWidth/2.,laserplaneWidth/2.}, new double[]{1,0,0,1}, new double[]{0,0,1,1}, t, RenderMode.STATIC));//UVtr tris[0].setAlphaBlended(true); tris[1].setAlphaBlended(true); modelToUse.addTriangles(tris); modelToUse.finalizeModel(); for(int i=0; i<projectiles.length; i++){ projectiles[i]=new ProjectileObject3D(tr,modelToUse, damageOnImpact, explosionType);} }//end if(isLaser) else if(modelingType instanceof ModelingType.BillboardModelingType){ final ModelingType.BillboardModelingType mt = (ModelingType.BillboardModelingType)modelingType; final Future<Texture> [] frames = new Future[mt.getRawFileNames().length]; final String [] fileNames = mt.getRawFileNames(); final ResourceManager mgr = tr.getResourceManager(); final Color [] pal = tr.getGlobalPalette(); ColorProcessor proc = GammaCorrectingColorProcessor.singleton; GL3 gl = tr.getGPU().getGl(); for(int i=0; i<frames.length;i++){ frames[i]=(Future)mgr.getRAWAsTexture(fileNames[i], pal, proc, gl); }//end for(frames) Future<TextureDescription> tex = new DummyFuture<TextureDescription>(new AnimatedTexture(new Sequencer(mt.getTimeInMillisPerFrame(),frames.length,false), frames)); ProjectileBillboard bb = new ProjectileBillboard(tr,weapon,tex,ExplosionType.Billow); for(int i=0; i<projectiles.length; i++){ projectiles[i]=bb;} }//end (billboard) else if(modelingType instanceof ModelingType.BINModelingType){ final ModelingType.BINModelingType mt = (ModelingType.BINModelingType)modelingType; modelToUse = tr.getResourceManager().getBINModel(mt.getBinFileName(), tr.getGlobalPalette(), tr.getGPU().getGl()); for(int i=0; i<projectiles.length; i++){ projectiles[i]=new ProjectileObject3D(tr,modelToUse, damageOnImpact, explosionType); } }//end BIN Modeling Type else{throw new RuntimeException("Unhandled ModelingType: "+modelingType.getClass().getName());} }//end try catch(Exception e){e.printStackTrace();} //CLAUSE: FFF needs destroysEvertyhing behavior if(weapon==Weapon.DAM){ for(int i=0; i<projectiles.length; i++){ ((WorldObject)projectiles[i]).addBehavior(new DestroysEverythingBehavior()); } }//end if(DAM) }//end constructor(...) public Projectile fire(double[] ds, Vector3D heading, WorldObject objectOfOrigin) { final Projectile result = projectiles[projectileIndex]; result.destroy(); result.reset(ds, heading.scalarMultiply(projectileSpeed), objectOfOrigin); tr.getWorld().add((WorldObject)result); projectileIndex++; projectileIndex%=projectiles.length; return result; }//end fire(...) public Projectile[] getProjectiles() { return projectiles; } public Weapon getWeapon() { return weapon; } }//end ProjectileFactory
package org.lightmare.ejb.meta; import static org.lightmare.jpa.JPAManager.closeEntityManagerFactories; import java.io.IOException; import java.net.URL; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import javax.persistence.EntityManagerFactory; import org.apache.log4j.Logger; import org.lightmare.ejb.exceptions.BeanInUseException; import org.lightmare.jpa.JPAManager; /** * Container class to save {@link MetaData} for bean interface {@link Class} and * connections {@link EntityManagerFactory}es for unit names * * @author Levan * */ public class MetaContainer { // Cached bean meta data private static final ConcurrentMap<String, MetaData> EJBS = new ConcurrentHashMap<String, MetaData>(); // Cached bean class name by its URL for undeploy processing private static final ConcurrentMap<URL, String> EJB_URLS = new ConcurrentHashMap<URL, String>(); private static final Logger LOG = Logger.getLogger(MetaContainer.class); /** * Adds {@link MetaData} to cache on specified bean name if absent and * returns previous value on this name or null if such value does not exists * * @param beanName * @param metaData * @return */ public static MetaData addMetaData(String beanName, MetaData metaData) { return EJBS.putIfAbsent(beanName, metaData); } /** * Check if {@link MetaData} is ceched for specified bean name if true * throws {@link BeanInUseException} * * @param beanName * @param metaData * @throws BeanInUseException */ public static void checkAndAddMetaData(String beanName, MetaData metaData) throws BeanInUseException { MetaData tmpMeta = addMetaData(beanName, metaData); if (tmpMeta != null) { throw new BeanInUseException(String.format( "bean %s is alredy in use", beanName)); } } /** * Checks if bean with associated name deployed and if yes if is deployment * in progress * * @param beanName * @return boolean */ public static boolean checkMetaData(String beanName) { boolean check; MetaData metaData = EJBS.get(beanName); check = metaData == null; if (!check) { check = metaData.isInProgress(); } return check; } /** * Checks if bean with associated name deployed * * @param beanName * @return boolean */ public boolean checkBean(String beanName) { return EJBS.containsKey(beanName); } /** * Waits while {@link MetaData#isInProgress()} is true * * @param metaData * @throws IOException */ public static void awaitMetaData(MetaData metaData) throws IOException { boolean inProgress = metaData.isInProgress(); if (inProgress) { synchronized (metaData) { while (inProgress) { try { metaData.wait(); inProgress = metaData.isInProgress(); } catch (InterruptedException ex) { throw new IOException(ex); } } } } } /** * Gets deployed bean {@link MetaData} by name without checking deployment * progress * * @param beanName * @return {@link MetaData} */ public static MetaData getMetaData(String beanName) { return EJBS.get(beanName); } /** * Check if {@link MetaData} with associated name deployed and if it is * waits while {@link MetaData#isInProgress()} true before return it * * @param beanName * @return {@link MetaData} * @throws IOException */ public static MetaData getSyncMetaData(String beanName) throws IOException { MetaData metaData = getMetaData(beanName); if (metaData == null) { throw new IOException(String.format("Bean %s is not deployed", beanName)); } awaitMetaData(metaData); return metaData; } /** * Gets bean name by containing archive {@link URL} address * * @param url * @return */ public static String getBeanName(URL url) { return EJB_URLS.get(url); } /** * Undeploys bean (removes it's {@link MetaData} from cache) * * @param url * @throws IOException */ public static void undeploy(URL url) throws IOException { synchronized (MetaContainer.class) { String beanName = getBeanName(url); @SuppressWarnings("unused") MetaData metaData; try { metaData = getSyncMetaData(beanName); } catch (IOException ex) { LOG.error(String.format( "Could not get bean resources %s cause %s", beanName, ex.getMessage()), ex); } removeMeta(beanName); metaData = null; } } /** * Removed {@link MetaData} from cache * * @param beanName */ public static void removeMeta(String beanName) { EJBS.remove(beanName); } public static EntityManagerFactory getConnection(String unitName) throws IOException { return JPAManager.getEntityManagerFactory(unitName); } public static void closeConnections() { closeEntityManagerFactories(); } public static Iterator<MetaData> getBeanClasses() { return EJBS.values().iterator(); } }
package org.mitre.synthea.export; import static org.mitre.synthea.export.ExportHelper.dateFromTimestamp; import static org.mitre.synthea.export.ExportHelper.iso8601Timestamp; import com.google.common.collect.Table; import com.google.gson.JsonObject; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.math.BigDecimal; import java.math.RoundingMode; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Locale; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.lang3.StringUtils; import org.mitre.synthea.helpers.Config; import org.mitre.synthea.helpers.RandomCodeGenerator; import org.mitre.synthea.helpers.RandomNumberGenerator; import org.mitre.synthea.helpers.Utilities; import org.mitre.synthea.modules.QualityOfLifeModule; import org.mitre.synthea.world.agents.Clinician; import org.mitre.synthea.world.agents.Payer; import org.mitre.synthea.world.agents.Person; import org.mitre.synthea.world.agents.Provider; import org.mitre.synthea.world.concepts.HealthRecord; import org.mitre.synthea.world.concepts.HealthRecord.CarePlan; import org.mitre.synthea.world.concepts.HealthRecord.Code; import org.mitre.synthea.world.concepts.HealthRecord.Device; import org.mitre.synthea.world.concepts.HealthRecord.Encounter; import org.mitre.synthea.world.concepts.HealthRecord.Entry; import org.mitre.synthea.world.concepts.HealthRecord.ImagingStudy; import org.mitre.synthea.world.concepts.HealthRecord.Medication; import org.mitre.synthea.world.concepts.HealthRecord.Observation; import org.mitre.synthea.world.concepts.HealthRecord.Procedure; import org.mitre.synthea.world.concepts.HealthRecord.Supply; /** * Researchers have requested a simple table-based format that could easily be * imported into any database for analysis. Unlike other formats which export a * single record per patient, this format generates 9 total files, and adds * lines to each based on the clinical events for each patient. These files are * intended to be analogous to database tables, with the patient UUID being a * foreign key. Files include: patients.csv, encounters.csv, allergies.csv, * medications.csv, conditions.csv, careplans.csv, observations.csv, * procedures.csv, and immunizations.csv. */ public class CSVExporter { /** * Writer for patients.csv. */ private OutputStreamWriter patients; /** * Writer for allergies.csv. */ private OutputStreamWriter allergies; /** * Writer for medications.csv. */ private OutputStreamWriter medications; /** * Writer for conditions.csv. */ private OutputStreamWriter conditions; /** * Writer for careplans.csv. */ private OutputStreamWriter careplans; /** * Writer for observations.csv. */ private OutputStreamWriter observations; /** * Writer for procedures.csv. */ private OutputStreamWriter procedures; /** * Writer for immunizations.csv. */ private OutputStreamWriter immunizations; /** * Writer for encounters.csv. */ private OutputStreamWriter encounters; /** * Writer for imaging_studies.csv */ private OutputStreamWriter imagingStudies; /** * Writer for devices.csv */ private OutputStreamWriter devices; /** * Writer for supplies.csv */ private OutputStreamWriter supplies; /** * Writer for organizations.csv */ private OutputStreamWriter organizations; /** * Writer for providers.csv */ private OutputStreamWriter providers; /** * Writer for payers.csv */ private OutputStreamWriter payers; /** * Writer for payerTransitions.csv */ private OutputStreamWriter payerTransitions; /** * Charset for specifying the character set of the output files. */ private Charset charset = Charset.forName(Config.get("exporter.encoding")); /** * System-dependent string for a line break. (\n on Mac, *nix, \r\n on Windows) */ private static final String NEWLINE = System.lineSeparator(); /** * Constructor for the CSVExporter - initialize the 9 specified files and store * the writers in fields. */ private CSVExporter() { try { File output = Exporter.getOutputFolder("csv", null); output.mkdirs(); Path outputDirectory = output.toPath(); if (Config.getAsBoolean("exporter.csv.folder_per_run")) { // we want a folder per run, so name it based on the timestamp // TODO: do we want to consider names based on the current generation options? String timestamp = ExportHelper.iso8601Timestamp(System.currentTimeMillis()); String subfolderName = timestamp.replaceAll("\\W+", "_"); // make sure it's filename-safe outputDirectory = outputDirectory.resolve(subfolderName); outputDirectory.toFile().mkdirs(); } File patientsFile = outputDirectory.resolve("patients.csv").toFile(); boolean append = patientsFile.exists() && Config.getAsBoolean("exporter.csv.append_mode"); patients = new OutputStreamWriter(new FileOutputStream(patientsFile, append), charset); File allergiesFile = outputDirectory.resolve("allergies.csv").toFile(); allergies = new OutputStreamWriter(new FileOutputStream(allergiesFile, append), charset); File medicationsFile = outputDirectory.resolve("medications.csv").toFile(); medications = new OutputStreamWriter(new FileOutputStream(medicationsFile, append), charset); File conditionsFile = outputDirectory.resolve("conditions.csv").toFile(); conditions = new OutputStreamWriter(new FileOutputStream(conditionsFile, append), charset); File careplansFile = outputDirectory.resolve("careplans.csv").toFile(); careplans = new OutputStreamWriter(new FileOutputStream(careplansFile, append), charset); File observationsFile = outputDirectory.resolve("observations.csv").toFile(); observations = new OutputStreamWriter( new FileOutputStream(observationsFile, append), charset); File proceduresFile = outputDirectory.resolve("procedures.csv").toFile(); procedures = new OutputStreamWriter(new FileOutputStream(proceduresFile, append), charset); File immunizationsFile = outputDirectory.resolve("immunizations.csv").toFile(); immunizations = new OutputStreamWriter( new FileOutputStream(immunizationsFile, append), charset); File encountersFile = outputDirectory.resolve("encounters.csv").toFile(); encounters = new OutputStreamWriter(new FileOutputStream(encountersFile, append), charset); File imagingStudiesFile = outputDirectory.resolve("imaging_studies.csv").toFile(); imagingStudies = new OutputStreamWriter( new FileOutputStream(imagingStudiesFile, append), charset); File devicesFile = outputDirectory.resolve("devices.csv").toFile(); devices = new OutputStreamWriter(new FileOutputStream(devicesFile, append), charset); File suppliesFile = outputDirectory.resolve("supplies.csv").toFile(); supplies = new OutputStreamWriter(new FileOutputStream(suppliesFile, append), charset); File organizationsFile = outputDirectory.resolve("organizations.csv").toFile(); File providersFile = outputDirectory.resolve("providers.csv").toFile(); organizations = new OutputStreamWriter( new FileOutputStream(organizationsFile, append), charset); providers = new OutputStreamWriter(new FileOutputStream(providersFile, append), charset); File payersFile = outputDirectory.resolve("payers.csv").toFile(); File payerTransitionsFile = outputDirectory.resolve("payer_transitions.csv").toFile(); payers = new OutputStreamWriter(new FileOutputStream(payersFile, append), charset); payerTransitions = new OutputStreamWriter( new FileOutputStream(payerTransitionsFile, append), charset); if (!append) { writeCSVHeaders(); } } catch (IOException e) { // wrap the exception in a runtime exception. // the singleton pattern below doesn't work if the constructor can throw // and if these do throw ioexceptions there's nothing we can do anyway throw new RuntimeException(e); } } /** * Write the headers to each of the CSV files. * @throws IOException if any IO error occurs */ private void writeCSVHeaders() throws IOException { patients.write("Id,BIRTHDATE,DEATHDATE,SSN,DRIVERS,PASSPORT," + "PREFIX,FIRST,LAST,SUFFIX,MAIDEN,MARITAL,RACE,ETHNICITY,GENDER,BIRTHPLACE," + "ADDRESS,CITY,STATE,COUNTY,ZIP,LAT,LON,HEALTHCARE_EXPENSES,HEALTHCARE_COVERAGE"); patients.write(NEWLINE); allergies.write("START,STOP,PATIENT,ENCOUNTER,CODE,DESCRIPTION"); allergies.write(NEWLINE); medications.write( "START,STOP,PATIENT,PAYER,ENCOUNTER,CODE,DESCRIPTION,BASE_COST,PAYER_COVERAGE,DISPENSES," + "TOTALCOST,REASONCODE,REASONDESCRIPTION"); medications.write(NEWLINE); conditions.write("START,STOP,PATIENT,ENCOUNTER,CODE,DESCRIPTION"); conditions.write(NEWLINE); careplans.write( "Id,START,STOP,PATIENT,ENCOUNTER,CODE,DESCRIPTION,REASONCODE,REASONDESCRIPTION"); careplans.write(NEWLINE); observations.write("DATE,PATIENT,ENCOUNTER,CODE,DESCRIPTION,VALUE,UNITS,TYPE"); observations.write(NEWLINE); procedures.write("DATE,PATIENT,ENCOUNTER,CODE,DESCRIPTION,BASE_COST," + "REASONCODE,REASONDESCRIPTION"); procedures.write(NEWLINE); immunizations.write("DATE,PATIENT,ENCOUNTER,CODE,DESCRIPTION,BASE_COST"); immunizations.write(NEWLINE); encounters.write( "Id,START,STOP,PATIENT,ORGANIZATION,PROVIDER,PAYER,ENCOUNTERCLASS,CODE,DESCRIPTION," + "BASE_ENCOUNTER_COST,TOTAL_CLAIM_COST,PAYER_COVERAGE,REASONCODE,REASONDESCRIPTION"); encounters.write(NEWLINE); imagingStudies.write("Id,DATE,PATIENT,ENCOUNTER,SERIES_UID,BODYSITE_CODE,BODYSITE_DESCRIPTION," + "MODALITY_CODE,MODALITY_DESCRIPTION,INSTANCE_UID,SOP_CODE,SOP_DESCRIPTION"); imagingStudies.write(NEWLINE); devices.write("START,STOP,PATIENT,ENCOUNTER,CODE,DESCRIPTION,UDI"); devices.write(NEWLINE); supplies.write("DATE,PATIENT,ENCOUNTER,CODE,DESCRIPTION,QUANTITY"); supplies.write(NEWLINE); organizations.write("Id,NAME,ADDRESS,CITY,STATE,ZIP,LAT,LON,PHONE,REVENUE,UTILIZATION"); organizations.write(NEWLINE); providers.write("Id,ORGANIZATION,NAME,GENDER,SPECIALITY,ADDRESS,CITY,STATE,ZIP,LAT,LON," + "UTILIZATION"); providers.write(NEWLINE); payers.write("Id,NAME,ADDRESS,CITY,STATE_HEADQUARTERED,ZIP,PHONE,AMOUNT_COVERED," + "AMOUNT_UNCOVERED,REVENUE,COVERED_ENCOUNTERS,UNCOVERED_ENCOUNTERS,COVERED_MEDICATIONS," + "UNCOVERED_MEDICATIONS,COVERED_PROCEDURES,UNCOVERED_PROCEDURES," + "COVERED_IMMUNIZATIONS,UNCOVERED_IMMUNIZATIONS," + "UNIQUE_CUSTOMERS,QOLS_AVG,MEMBER_MONTHS"); payers.write(NEWLINE); payerTransitions.write("PATIENT,START_YEAR,END_YEAR,PAYER,OWNERSHIP"); payerTransitions.write(NEWLINE); } private static class SingletonHolder { /** * Singleton instance of the CSVExporter. */ private static final CSVExporter instance = new CSVExporter(); } /** * Get the current instance of the CSVExporter. * * @return the current instance of the CSVExporter. */ public static CSVExporter getInstance() { return SingletonHolder.instance; } /** * Export the organizations.csv and providers.csv files. This method should be * called once after all the Patient records have been exported using the * export(Person,long) method. * * @throws IOException if any IO errors occur. */ public void exportOrganizationsAndProviders() throws IOException { for (Provider org : Provider.getProviderList()) { // Check utilization for hospital before we export Table<Integer, String, AtomicInteger> utilization = org.getUtilization(); int totalEncounters = utilization.column(Provider.ENCOUNTERS).values().stream().mapToInt(ai -> ai.get()).sum(); if (totalEncounters > 0) { organization(org, totalEncounters); Map<String, ArrayList<Clinician>> providers = org.clinicianMap; for (String speciality : providers.keySet()) { ArrayList<Clinician> clinicians = providers.get(speciality); for (Clinician clinician : clinicians) { provider(clinician, org.getResourceID()); } } } organizations.flush(); providers.flush(); } } /** * Export the payers.csv file. This method should be called once after all the * Patient records have been exported using the export(Person,long) method. * * @throws IOException if any IO errors occur. */ public void exportPayers() throws IOException { // Export All Payers for (Payer payer : Payer.getAllPayers()) { payer(payer); payers.flush(); } // Export No Insurance statistics payer(Payer.noInsurance); payers.flush(); } /** * Export the payerTransitions.csv file. This method should be called once after all the * Patient records have been exported using the export(Person,long) method. * * @throws IOException if any IO errors occur. */ private void exportPayerTransitions(Person person, long stopTime) throws IOException { // The current year starts with the year of the person's birth. int currentYear = Utilities.getYear((long) person.attributes.get(Person.BIRTHDATE)); String previousPayerID = person.getPayerHistory()[0].getResourceID(); String previousOwnership = "Guardian"; int startYear = currentYear; for (int personAge = 0; personAge < 128; personAge++) { Payer currentPayer = person.getPayerAtAge(personAge); String currentOwnership = person.getPayerOwnershipAtAge(personAge); if (currentPayer == null) { return; } // Only write a new line if these conditions are met to export for year ranges of payers. if (!currentPayer.getResourceID().equals(previousPayerID) || !currentOwnership.equals(previousOwnership) || Utilities.convertCalendarYearsToTime(currentYear) >= stopTime || !person.alive(Utilities.convertCalendarYearsToTime(currentYear + 1))) { payerTransition(person, currentPayer, startYear, currentYear); previousPayerID = currentPayer.getResourceID(); previousOwnership = currentOwnership; startYear = currentYear + 1; payerTransitions.flush(); } currentYear++; } } /** * Add a single Person's health record info to the CSV records. * * @param person Person to write record data for * @param time Time the simulation ended * @throws IOException if any IO error occurs */ public void export(Person person, long time) throws IOException { String personID = patient(person, time); for (Encounter encounter : person.record.encounters) { String encounterID = encounter(person, personID, encounter); String payerID = encounter.claim.payer.uuid; for (HealthRecord.Entry condition : encounter.conditions) { /* condition to ignore codes other then retrieved from terminology url */ if (!StringUtils.isEmpty(Config.get("generate.terminology_service_url")) && !RandomCodeGenerator.selectedCodes.isEmpty()) { if (RandomCodeGenerator.selectedCodes.stream() .filter(code -> code.code.equals(condition.codes.get(0).code)) .findFirst().isPresent()) { condition(personID, encounterID, condition); } } else { condition(personID, encounterID, condition); } } for (HealthRecord.Entry allergy : encounter.allergies) { allergy(personID, encounterID, allergy); } for (Observation observation : encounter.observations) { observation(personID, encounterID, observation); } for (Procedure procedure : encounter.procedures) { procedure(personID, encounterID, procedure); } for (Medication medication : encounter.medications) { medication(personID, encounterID, payerID, medication, time); } for (HealthRecord.Entry immunization : encounter.immunizations) { immunization(personID, encounterID, immunization); } for (CarePlan careplan : encounter.careplans) { careplan(person, personID, encounterID, careplan); } for (ImagingStudy imagingStudy : encounter.imagingStudies) { imagingStudy(person, personID, encounterID, imagingStudy); } for (Device device : encounter.devices) { device(personID, encounterID, device); } for (Supply supply : encounter.supplies) { supply(personID, encounterID, encounter, supply); } } CSVExporter.getInstance().exportPayerTransitions(person, time); int yearsOfHistory = Integer.parseInt(Config.get("exporter.years_of_history")); Calendar cutOff = new GregorianCalendar(1900, 0, 1); if (yearsOfHistory > 0) { cutOff = Calendar.getInstance(); cutOff.set(cutOff.get(Calendar.YEAR) - yearsOfHistory, 0, 1); } Calendar now = Calendar.getInstance(); Calendar birthDay = Calendar.getInstance(); birthDay.setTimeInMillis((long) person.attributes.get(Person.BIRTHDATE)); String[] gbdMetrics = { QualityOfLifeModule.QALY, QualityOfLifeModule.DALY, QualityOfLifeModule.QOLS }; String unit = null; for (String score : gbdMetrics) { if (score.equals(QualityOfLifeModule.QOLS)) { unit = "{score}"; } else { // years in UCUM is "a" for Latin "Annus" unit = "a"; } @SuppressWarnings("unchecked") Map<Integer, Double> scores = (Map<Integer, Double>) person.attributes.get(score); for (Integer year : scores.keySet()) { birthDay.set(Calendar.YEAR, year); if (birthDay.after(cutOff) && birthDay.before(now)) { Observation obs = person.record.new Observation( birthDay.getTimeInMillis(), score, scores.get(year)); obs.unit = unit; Code code = new Code("GBD", score, score); obs.codes.add(code); observation(personID, "", obs); } } } patients.flush(); encounters.flush(); conditions.flush(); allergies.flush(); medications.flush(); careplans.flush(); observations.flush(); procedures.flush(); immunizations.flush(); imagingStudies.flush(); devices.flush(); supplies.flush(); } /** * Write a single Patient line, to patients.csv. * * @param person Person to write data for * @param time Time the simulation ended, to calculate age/deceased status * @return the patient's ID, to be referenced as a "foreign key" if necessary * @throws IOException if any IO error occurs */ private String patient(Person person, long time) throws IOException { // Id,BIRTHDATE,DEATHDATE,SSN,DRIVERS,PASSPORT,PREFIX, // FIRST,LAST,SUFFIX,MAIDEN,MARITAL,RACE,ETHNICITY,GENDER,BIRTHPLACE,ADDRESS // CITY,STATE,COUNTY,ZIP,LAT,LON,HEALTHCARE_EXPENSES,HEALTHCARE_COVERAGE String personID = (String) person.attributes.get(Person.ID); // check if we've already exported this patient demographic data yet, // otherwise the "split record" feature could add a duplicate entry. if (person.attributes.containsKey("exported_to_csv")) { return personID; } else { person.attributes.put("exported_to_csv", personID); } StringBuilder s = new StringBuilder(); s.append(personID).append(','); s.append(dateFromTimestamp((long) person.attributes.get(Person.BIRTHDATE))).append(','); if (!person.alive(time)) { s.append(dateFromTimestamp((Long) person.attributes.get(Person.DEATHDATE))); } for (String attribute : new String[] { Person.IDENTIFIER_SSN, Person.IDENTIFIER_DRIVERS, Person.IDENTIFIER_PASSPORT, Person.NAME_PREFIX, Person.FIRST_NAME, Person.LAST_NAME, Person.NAME_SUFFIX, Person.MAIDEN_NAME, Person.MARITAL_STATUS, Person.RACE, Person.ETHNICITY, Person.GENDER, Person.BIRTHPLACE, Person.ADDRESS, Person.CITY, Person.STATE, "county", Person.ZIP }) { String value = (String) person.attributes.getOrDefault(attribute, ""); s.append(',').append(clean(value)); } // LAT,LON s.append(',').append(person.getY()).append(',').append(person.getX()).append(','); // HEALTHCARE_EXPENSES s.append(person.getHealthcareExpenses()).append(','); // HEALTHCARE_COVERAGE s.append(person.getHealthcareCoverage()); // QALYS // s.append(person.attributes.get("most-recent-qaly")).append(','); // DALYS // s.append(person.attributes.get("most-recent-daly")); s.append(NEWLINE); write(s.toString(), patients); return personID; } /** * Write a single Encounter line to encounters.csv. * * @param rand Source of randomness to use when generating ids etc * @param personID The ID of the person that had this encounter * @param encounter The encounter itself * @return The encounter ID, to be referenced as a "foreign key" if necessary * @throws IOException if any IO error occurs */ private String encounter(RandomNumberGenerator rand, String personID, Encounter encounter) throws IOException { // Id,START,STOP,PATIENT,ORGANIZATION,PROVIDER,PAYER,ENCOUNTERCLASS,CODE,DESCRIPTION, // BASE_ENCOUNTER_COST,TOTAL_CLAIM_COST,PAYER_COVERAGE,REASONCODE,REASONDESCRIPTION StringBuilder s = new StringBuilder(); String encounterID = rand.randUUID().toString(); s.append(encounterID).append(','); // START s.append(iso8601Timestamp(encounter.start)).append(','); // STOP if (encounter.stop != 0L) { s.append(iso8601Timestamp(encounter.stop)).append(','); } else { s.append(','); } // PATIENT s.append(personID).append(','); // ORGANIZATION if (encounter.provider != null) { s.append(encounter.provider.getResourceID()).append(','); } else { s.append(','); } // PROVIDER if (encounter.clinician != null) { s.append(encounter.clinician.getResourceID()).append(','); } else { s.append(','); } // PAYER if (encounter.claim.payer != null) { s.append(encounter.claim.payer.getResourceID()).append(','); } else { s.append(','); } // ENCOUNTERCLASS if (encounter.type != null) { s.append(encounter.type.toLowerCase()).append(','); } else { s.append(','); } // CODE Code coding = encounter.codes.get(0); s.append(coding.code).append(','); // DESCRIPTION s.append(clean(coding.display)).append(','); // BASE_ENCOUNTER_COST s.append(String.format(Locale.US, "%.2f", encounter.getCost())).append(','); // TOTAL_COST s.append(String.format(Locale.US, "%.2f", encounter.claim.getTotalClaimCost())).append(','); // PAYER_COVERAGE s.append(String.format(Locale.US, "%.2f", encounter.claim.getCoveredCost())).append(','); // REASONCODE & REASONDESCRIPTION if (encounter.reason == null) { s.append(","); } else { s.append(encounter.reason.code).append(','); s.append(clean(encounter.reason.display)); } s.append(NEWLINE); write(s.toString(), encounters); return encounterID; } /** * Write a single Condition to conditions.csv. * * @param personID ID of the person that has the condition. * @param encounterID ID of the encounter where the condition was diagnosed * @param condition The condition itself * @throws IOException if any IO error occurs */ private void condition(String personID, String encounterID, Entry condition) throws IOException { // START,STOP,PATIENT,ENCOUNTER,CODE,DESCRIPTION StringBuilder s = new StringBuilder(); s.append(dateFromTimestamp(condition.start)).append(','); if (condition.stop != 0L) { s.append(dateFromTimestamp(condition.stop)); } s.append(','); s.append(personID).append(','); s.append(encounterID).append(','); Code coding = condition.codes.get(0); s.append(coding.code).append(','); s.append(clean(coding.display)); s.append(NEWLINE); write(s.toString(), conditions); } /** * Write a single Allergy to allergies.csv. * * @param personID ID of the person that has the allergy. * @param encounterID ID of the encounter where the allergy was diagnosed * @param allergy The allergy itself * @throws IOException if any IO error occurs */ private void allergy(String personID, String encounterID, Entry allergy) throws IOException { // START,STOP,PATIENT,ENCOUNTER,CODE,DESCRIPTION StringBuilder s = new StringBuilder(); s.append(dateFromTimestamp(allergy.start)).append(','); if (allergy.stop != 0L) { s.append(dateFromTimestamp(allergy.stop)); } s.append(','); s.append(personID).append(','); s.append(encounterID).append(','); Code coding = allergy.codes.get(0); s.append(coding.code).append(','); s.append(clean(coding.display)); s.append(NEWLINE); write(s.toString(), allergies); } /** * Write a single Observation to observations.csv. * * @param personID ID of the person to whom the observation applies. * @param encounterID ID of the encounter where the observation was taken * @param observation The observation itself * @throws IOException if any IO error occurs */ private void observation(String personID, String encounterID, Observation observation) throws IOException { if (observation.value == null) { if (observation.observations != null && !observation.observations.isEmpty()) { // just loop through the child observations for (Observation subObs : observation.observations) { observation(personID, encounterID, subObs); } } // no value so nothing more to report here return; } // DATE,PATIENT,ENCOUNTER,CODE,DESCRIPTION,VALUE,UNITS StringBuilder s = new StringBuilder(); s.append(iso8601Timestamp(observation.start)).append(','); s.append(personID).append(','); s.append(encounterID).append(','); Code coding = observation.codes.get(0); s.append(coding.code).append(','); s.append(clean(coding.display)).append(','); String value = ExportHelper.getObservationValue(observation); String type = ExportHelper.getObservationType(observation); s.append(value).append(','); s.append(observation.unit).append(','); s.append(type); s.append(NEWLINE); write(s.toString(), observations); } /** * Write a single Procedure to procedures.csv. * * @param personID ID of the person on whom the procedure was performed. * @param encounterID ID of the encounter where the procedure was performed * @param payerID ID of the payer who covered the immunization. * @param procedure The procedure itself * @throws IOException if any IO error occurs */ private void procedure(String personID, String encounterID, Procedure procedure) throws IOException { // DATE,PATIENT,ENCOUNTER,CODE,DESCRIPTION,COST,REASONCODE,REASONDESCRIPTION StringBuilder s = new StringBuilder(); s.append(iso8601Timestamp(procedure.start)).append(','); s.append(personID).append(','); s.append(encounterID).append(','); // CODE Code coding = procedure.codes.get(0); s.append(coding.code).append(','); // DESCRIPTION s.append(clean(coding.display)).append(','); // BASE_COST s.append(String.format(Locale.US, "%.2f", procedure.getCost())).append(','); // REASONCODE & REASONDESCRIPTION if (procedure.reasons.isEmpty()) { s.append(','); // reason code & desc } else { Code reason = procedure.reasons.get(0); s.append(reason.code).append(','); s.append(clean(reason.display)); } s.append(NEWLINE); write(s.toString(), procedures); } /** * Write a single Medication to medications.csv. * * @param personID ID of the person prescribed the medication. * @param encounterID ID of the encounter where the medication was prescribed * @param payerID ID of the payer who covered the immunization. * @param medication The medication itself * @param stopTime End time * @throws IOException if any IO error occurs */ private void medication(String personID, String encounterID, String payerID, Medication medication, long stopTime) throws IOException { // START,STOP,PATIENT,PAYER,ENCOUNTER,CODE,DESCRIPTION, // BASE_COST,PAYER_COVERAGE,DISPENSES,TOTALCOST,REASONCODE,REASONDESCRIPTION StringBuilder s = new StringBuilder(); s.append(iso8601Timestamp(medication.start)).append(','); if (medication.stop != 0L) { s.append(iso8601Timestamp(medication.stop)); } s.append(','); s.append(personID).append(','); s.append(payerID).append(','); s.append(encounterID).append(','); // CODE Code coding = medication.codes.get(0); s.append(coding.code).append(','); // DESCRIPTION s.append(clean(coding.display)).append(','); // BASE_COST BigDecimal cost = medication.getCost(); s.append(String.format(Locale.US, "%.2f", cost)).append(','); // PAYER_COVERAGE s.append(String.format(Locale.US, "%.2f", medication.claim.getCoveredCost())).append(','); long dispenses = 1; // dispenses = refills + original // makes the math cleaner and more explicit. dispenses * unit cost = total cost long stop = medication.stop; if (stop == 0L) { stop = stopTime; } long medDuration = stop - medication.start; if (medication.prescriptionDetails != null && medication.prescriptionDetails.has("refills")) { dispenses = medication.prescriptionDetails.get("refills").getAsInt(); } else if (medication.prescriptionDetails != null && medication.prescriptionDetails.has("duration")) { JsonObject duration = medication.prescriptionDetails.getAsJsonObject("duration"); long quantity = duration.get("quantity").getAsLong(); String unit = duration.get("unit").getAsString(); long durationMs = Utilities.convertTime(unit, quantity); dispenses = medDuration / durationMs; } else { // assume 1 refill / month long durationMs = Utilities.convertTime("months", 1); dispenses = medDuration / durationMs; } if (dispenses < 1) { // integer division could leave us with 0, // ex. if the active time (start->stop) is less than the provided duration // or less than a month if no duration provided dispenses = 1; } s.append(dispenses).append(','); BigDecimal totalCost = cost.multiply( BigDecimal.valueOf(dispenses)).setScale(2, RoundingMode.DOWN); //Truncate 2 decimal places s.append(String.format(Locale.US, "%.2f", totalCost)).append(','); if (medication.reasons.isEmpty()) { s.append(','); // reason code & desc } else { Code reason = medication.reasons.get(0); s.append(reason.code).append(','); s.append(clean(reason.display)); } s.append(NEWLINE); write(s.toString(), medications); } /** * Write a single Immunization to immunizations.csv. * * @param personID ID of the person on whom the immunization was performed. * @param encounterID ID of the encounter where the immunization was performed. * @param payerID ID of the payer who covered the immunization. * @param immunization The immunization itself * @throws IOException if any IO error occurs */ private void immunization(String personID, String encounterID, Entry immunization) throws IOException { // DATE,PATIENT,ENCOUNTER,CODE,DESCRIPTION,BASE_COST StringBuilder s = new StringBuilder(); s.append(iso8601Timestamp(immunization.start)).append(','); s.append(personID).append(','); s.append(encounterID).append(','); // CODE Code coding = immunization.codes.get(0); s.append(coding.code).append(','); // DESCRIPTION s.append(clean(coding.display)).append(','); // BASE_COST s.append(String.format(Locale.US, "%.2f", immunization.getCost())); s.append(NEWLINE); write(s.toString(), immunizations); } /** * Write a single CarePlan to careplans.csv. * * @param rand Source of randomness to use when generating ids etc * @param personID ID of the person prescribed the careplan. * @param encounterID ID of the encounter where the careplan was prescribed * @param careplan The careplan itself * @throws IOException if any IO error occurs */ private String careplan(RandomNumberGenerator rand, String personID, String encounterID, CarePlan careplan) throws IOException { // Id,START,STOP,PATIENT,ENCOUNTER,CODE,DESCRIPTION,REASONCODE,REASONDESCRIPTION StringBuilder s = new StringBuilder(); String careplanID = rand.randUUID().toString(); s.append(careplanID).append(','); s.append(dateFromTimestamp(careplan.start)).append(','); if (careplan.stop != 0L) { s.append(dateFromTimestamp(careplan.stop)); } s.append(','); s.append(personID).append(','); s.append(encounterID).append(','); Code coding = careplan.codes.get(0); s.append(coding.code).append(','); s.append(coding.display).append(','); if (careplan.reasons.isEmpty()) { s.append(','); // reason code & desc } else { Code reason = careplan.reasons.get(0); s.append(reason.code).append(','); s.append(clean(reason.display)); } s.append(NEWLINE); write(s.toString(), careplans); return careplanID; } /** * Write a single ImagingStudy to imaging_studies.csv. * * @param rand Source of randomness to use when generating ids etc * @param personID ID of the person the ImagingStudy was taken of. * @param encounterID ID of the encounter where the ImagingStudy was performed * @param imagingStudy The ImagingStudy itself * @throws IOException if any IO error occurs */ private String imagingStudy(RandomNumberGenerator rand, String personID, String encounterID, ImagingStudy imagingStudy) throws IOException { // Id,DATE,PATIENT,ENCOUNTER,SERIES_UID,BODYSITE_CODE,BODYSITE_DESCRIPTION, // MODALITY_CODE,MODALITY_DESCRIPTION,INSTANCE_UID,SOP_CODE,SOP_DESCRIPTION StringBuilder s = new StringBuilder(); String studyID = rand.randUUID().toString(); for(ImagingStudy.Series series: imagingStudy.series) { String seriesDicomUid = series.dicomUid; Code bodySite = series.bodySite; Code modality = series.modality; for(ImagingStudy.Instance instance: series.instances) { String instanceDicomUid = instance.dicomUid; Code sopClass = instance.sopClass; s.append(studyID).append(','); s.append(iso8601Timestamp(imagingStudy.start)).append(','); s.append(personID).append(','); s.append(encounterID).append(','); s.append(seriesDicomUid).append(','); s.append(bodySite.code).append(','); s.append(bodySite.display).append(','); s.append(modality.code).append(','); s.append(modality.display).append(','); s.append(instanceDicomUid).append(','); s.append(sopClass.code).append(','); s.append(sopClass.display); s.append(NEWLINE); } } write(s.toString(), imagingStudies); return studyID; } /** * Write a single Device to devices.csv. * * @param personID ID of the person the Device is affixed to. * @param encounterID ID of the encounter where the Device was associated * @param device The Device itself * @throws IOException if any IO error occurs */ private void device(String personID, String encounterID, Device device) throws IOException { // START,STOP,PATIENT,ENCOUNTER,CODE,DESCRIPTION,UDI StringBuilder s = new StringBuilder(); s.append(iso8601Timestamp(device.start)).append(','); if (device.stop != 0L) { s.append(iso8601Timestamp(device.stop)); } s.append(','); s.append(personID).append(','); s.append(encounterID).append(','); Code code = device.codes.get(0); s.append(code.code).append(','); s.append(clean(code.display)).append(','); s.append(device.udi); s.append(NEWLINE); write(s.toString(), devices); } /** * Write a single Supply to supplies.csv. * * @param personID ID of the person the supply was used for. * @param encounterID ID of the encounter where the supply was used * @param supply The supply itself * @throws IOException if any IO error occurs */ private void supply(String personID, String encounterID, Encounter encounter, Supply supply) throws IOException { // DATE,PATIENT,ENCOUNTER,CODE,DESCRIPTION,QUANTITY StringBuilder s = new StringBuilder(); s.append(dateFromTimestamp(supply.start)).append(','); s.append(personID).append(','); s.append(encounterID).append(','); Code code = supply.codes.get(0); s.append(code.code).append(','); s.append(clean(code.display)).append(','); s.append(supply.quantity); s.append(NEWLINE); write(s.toString(), supplies); } /** * Write a single organization to organizations.csv * * @param org The organization to be written * @param utilization The total number of encounters for the org * @throws IOException if any IO error occurs */ private void organization(Provider org, int utilization) throws IOException { // Id,NAME,ADDRESS,CITY,STATE,ZIP,PHONE,REVENUE,UTILIZATION StringBuilder s = new StringBuilder(); s.append(org.getResourceID()).append(','); s.append(clean(org.name)).append(','); s.append(clean(org.address)).append(','); s.append(org.city).append(','); s.append(org.state).append(','); s.append(org.zip).append(','); s.append(org.getY()).append(','); s.append(org.getX()).append(','); s.append(org.phone).append(','); s.append(org.getRevenue()).append(','); s.append(utilization); s.append(NEWLINE); write(s.toString(), organizations); } /** * Write a single clinician to providers.csv * * @param provider The provider information to be written * @param orgId ID of the organization the provider belongs to * @throws IOException if any IO error occurs */ private void provider(Clinician provider, String orgId) throws IOException { // Id,ORGANIZATION,NAME,GENDER,SPECIALITY,ADDRESS,CITY,STATE,ZIP,UTILIZATION StringBuilder s = new StringBuilder(); s.append(provider.getResourceID()).append(','); s.append(orgId).append(','); for (String attribute : new String[] { Clinician.NAME, Clinician.GENDER, Clinician.SPECIALTY, Clinician.ADDRESS, Clinician.CITY, Clinician.STATE, Clinician.ZIP }) { String value = (String) provider.attributes.getOrDefault(attribute, ""); s.append(clean(value)).append(','); } s.append(provider.getY()).append(','); s.append(provider.getX()).append(','); s.append(provider.getEncounterCount()); s.append(NEWLINE); write(s.toString(), providers); } /** * Write a single payer to payers.csv. * * @param payer The payer to be exported. * @throws IOException if any IO error occurs. */ private void payer(Payer payer) throws IOException { // Id,NAME,ADDRESS,CITY,STATE_HEADQUARTERED,ZIP,PHONE,AMOUNT_COVERED,AMOUNT_UNCOVERED,REVENUE, // COVERED_ENCOUNTERS,UNCOVERED_ENCOUNTERS,COVERED_MEDICATIONS,UNCOVERED_MEDICATIONS, // COVERED_PROCEDURES,UNCOVERED_PROCEDURES,COVERED_IMMUNIZATIONS,UNCOVERED_IMMUNIZATIONS, // UNIQUE_CUSTOMERS,QOLS_AVG,MEMBER_MONTHS StringBuilder s = new StringBuilder(); // UUID s.append(payer.getResourceID()).append(','); // NAME s.append(payer.getName()).append(','); // Second Class Attributes for (String attribute : new String[] { "address", "city", "state_headquartered", "zip", "phone" }) { String value = (String) payer.getAttributes().getOrDefault(attribute, ""); s.append(clean(value)).append(','); } // AMOUNT_COVERED s.append(String.format(Locale.US, "%.2f", payer.getAmountCovered())).append(','); // AMOUNT_UNCOVERED s.append(String.format(Locale.US, "%.2f", payer.getAmountUncovered())).append(','); // REVENUE s.append(String.format(Locale.US, "%.2f", payer.getRevenue())).append(','); // Covered/Uncovered Encounters/Medications/Procedures/Immunizations s.append(payer.getEncountersCoveredCount()).append(","); s.append(payer.getEncountersUncoveredCount()).append(","); s.append(payer.getMedicationsCoveredCount()).append(","); s.append(payer.getMedicationsUncoveredCount()).append(","); s.append(payer.getProceduresCoveredCount()).append(","); s.append(payer.getProceduresUncoveredCount()).append(","); s.append(payer.getImmunizationsCoveredCount()).append(","); s.append(payer.getImmunizationsUncoveredCount()).append(","); // UNIQUE CUSTOMERS s.append(payer.getUniqueCustomers()).append(","); // QOLS_AVG s.append(payer.getQolsAverage()).append(","); // MEMBER_MONTHS (Note that this converts the number of years covered to months) s.append(payer.getNumYearsCovered() * 12); s.append(NEWLINE); write(s.toString(), payers); } /** * Write a single range of unchanged payer history to payer_transitions.csv * * @param person The person whose payer history to write. * @param payer The payer of the person's current range of payer history. * @param startYear The first year of this payer history. * @param endYear The final year of this payer history. * @throws IOException if any IO error occurs */ private void payerTransition(Person person, Payer payer, int startYear, int endYear) throws IOException { // PATIENT_ID,START_YEAR,END_YEAR,PAYER_ID,OWNERSHIP StringBuilder s = new StringBuilder(); // PATIENT_ID s.append(person.attributes.get(Person.ID)).append(","); // START_YEAR s.append(startYear).append(','); // END_YEAR s.append(endYear).append(','); // PAYER_ID s.append(payer.getResourceID()).append(','); // OWNERSHIP s.append(person.getPayerOwnershipAtTime(Utilities.convertCalendarYearsToTime(startYear))); s.append(NEWLINE); write(s.toString(), payerTransitions); } /** * Replaces commas and line breaks in the source string with a single space. * Null is replaced with the empty string. */ private static String clean(String src) { if (src == null) { return ""; } else { return src.replaceAll("\\r\\n|\\r|\\n|,", " ").trim(); } } /** * Helper method to write a line to a File. Extracted to a separate method here * to make it a little easier to replace implementations. * * @param line The line to write * @param writer The place to write it * @throws IOException if an I/O error occurs */ private static void write(String line, OutputStreamWriter writer) throws IOException { synchronized (writer) { writer.write(line); } } }
import java.util.*; /** * A map of the tunnel system. */ public class Map { public Map (Vector<String> input, boolean debug) { _theMap = new Vector<Cell>(); _nodeMap = null; _keys = new Vector<Character>(); _doors = new Vector<Character>(); _debug = debug; createMap(input); } public Coordinate getEntrance () { return _entrance; } public Node getStartingNode () { if (_nodeMap != null) return _nodeMap[_entrance.getX()][_entrance.getY()]; return createGraph(); } public int numberOfDoors () { return _doors.size(); } public int numberOfKeys () { return _keys.size(); } @Override public String toString () { Enumeration<Cell> iter = _theMap.elements(); int index = 1; String str = "Map <"+_maxX+", "+_maxY+">:\n\n"; while (iter.hasMoreElements()) { str += iter.nextElement().getContents(); if (index++ == _maxX) { str += "\n"; index = 1; } } return str; } // create the map from input private void createMap (Vector<String> input) { Enumeration<String> iter = input.elements(); int y = -1; _maxX = input.get(0).length(); // all lines are the same length (check?) while (iter.hasMoreElements()) { y++; String line = iter.nextElement(); for (int x = 0; x < _maxX; x++) { Cell theCell = new Cell(new Coordinate(x, y), line.charAt(x), _debug); if (theCell.isEntrance()) _entrance = theCell.position(); // should be only one! else { if (theCell.isKey()) _keys.add(theCell.getContents()); else { if (theCell.isDoor()) _doors.add(theCell.getContents()); } } if (_debug) System.out.println(theCell); _theMap.add(theCell); } } _maxY = y+1; } /* * From the map create a graph. */ private Node createGraph () // temporary public for testing! { Enumeration<Cell> iter = _theMap.elements(); int x = 0; int y = 0; _nodeMap = new Node[_maxX][_maxY]; while (iter.hasMoreElements()) { _nodeMap[x][y] = new Node(iter.nextElement()); x++; if (x == _maxX) { x = 0; y++; } } for (int i = 0; i < _maxX; i++) { for (int j = 0; j < _maxY; j++) { Node up = null; Node down = null; Node left = null; Node right = null; if (i -1 >= 0) left = _nodeMap[i-1][j]; if (i +1 < _maxX) right = _nodeMap[i +1][j]; if (j -1 >= 0) up = _nodeMap[i][j -1]; if (j +1 < _maxY) down = _nodeMap[i][j +1]; _nodeMap[i][j].setLinks(up, down, left, right); } } if (_debug) { for (x = 0; x < _maxX; x++) { for (y = 0; y < _maxY; y++) { System.out.println("\n"+_nodeMap[x][y]); } } } return _nodeMap[_entrance.getX()][_entrance.getY()]; } private Vector<Cell> _theMap; private Node[][] _nodeMap; private int _maxX; private int _maxY; private Coordinate _entrance; private Vector<Character> _keys; private Vector<Character> _doors; private boolean _debug; }
package org.nio4r; import java.util.Iterator; import java.io.IOException; import java.nio.channels.Channel; import java.nio.channels.SocketChannel; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import org.jruby.Ruby; import org.jruby.RubyModule; import org.jruby.RubyClass; import org.jruby.RubyObject; import org.jruby.RubyIO; import org.jruby.RubyNumeric; import org.jruby.RubyArray; import org.jruby.anno.JRubyMethod; import org.jruby.runtime.ObjectAllocator; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.load.Library; import org.jruby.runtime.builtin.IRubyObject; import org.jruby.runtime.Block; public class Nio4r implements Library { private Ruby ruby; public void load(final Ruby ruby, boolean bln) { this.ruby = ruby; RubyModule nio = ruby.defineModule("NIO"); RubyClass selector = ruby.defineClassUnder("Selector", ruby.getObject(), new ObjectAllocator() { public IRubyObject allocate(Ruby ruby, RubyClass rc) { return new Selector(ruby, rc); } }, nio); selector.defineAnnotatedMethods(Selector.class); RubyClass monitor = ruby.defineClassUnder("Monitor", ruby.getObject(), new ObjectAllocator() { public IRubyObject allocate(Ruby ruby, RubyClass rc) { return new Monitor(ruby, rc); } }, nio); monitor.defineAnnotatedMethods(Monitor.class); } public static int symbolToInterestOps(Ruby ruby, SelectableChannel channel, IRubyObject interest) { if(interest == ruby.newSymbol("r")) { if((channel.validOps() & SelectionKey.OP_ACCEPT) != 0) { return SelectionKey.OP_ACCEPT; } else { return SelectionKey.OP_READ; } } else if(interest == ruby.newSymbol("w")) { if(channel instanceof SocketChannel && !((SocketChannel)channel).isConnected()) { return SelectionKey.OP_CONNECT; } else { return SelectionKey.OP_WRITE; } } else if(interest == ruby.newSymbol("rw")) { int interestOps = 0; /* nio4r emulates the POSIX behavior, which is sloppy about allowed modes */ if((channel.validOps() & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0) { interestOps |= symbolToInterestOps(ruby, channel, ruby.newSymbol("r")); } if((channel.validOps() & (SelectionKey.OP_WRITE | SelectionKey.OP_CONNECT)) != 0) { interestOps |= symbolToInterestOps(ruby, channel, ruby.newSymbol("w")); } return interestOps; } else { throw ruby.newArgumentError("invalid interest type: " + interest); } } public static IRubyObject interestOpsToSymbol(Ruby ruby, int interestOps) { switch(interestOps) { case SelectionKey.OP_READ: case SelectionKey.OP_ACCEPT: return ruby.newSymbol("r"); case SelectionKey.OP_WRITE: case SelectionKey.OP_CONNECT: return ruby.newSymbol("w"); case SelectionKey.OP_READ | SelectionKey.OP_CONNECT: case SelectionKey.OP_READ | SelectionKey.OP_WRITE: return ruby.newSymbol("rw"); default: throw ruby.newArgumentError("unknown interest op combination"); } } public class Selector extends RubyObject { private java.nio.channels.Selector selector; public Selector(final Ruby ruby, RubyClass rubyClass) { super(ruby, rubyClass); } @JRubyMethod public IRubyObject initialize(ThreadContext context) { try { selector = java.nio.channels.Selector.open(); } catch(IOException ie) { throw context.runtime.newIOError(ie.getLocalizedMessage()); } return context.nil; } @JRubyMethod public IRubyObject close(ThreadContext context) { try { selector.close(); } catch(IOException ie) { throw context.runtime.newIOError(ie.getLocalizedMessage()); } return context.nil; } @JRubyMethod(name = "closed?") public IRubyObject isClosed(ThreadContext context) { Ruby runtime = context.getRuntime(); return selector.isOpen() ? runtime.getFalse() : runtime.getTrue(); } @JRubyMethod public IRubyObject register(ThreadContext context, IRubyObject io, IRubyObject interests) { Ruby runtime = context.getRuntime(); Channel raw_channel = ((RubyIO)io).getChannel(); if(!(raw_channel instanceof SelectableChannel)) { throw runtime.newArgumentError("not a selectable IO object"); } SelectableChannel channel = (SelectableChannel)raw_channel; try { channel.configureBlocking(false); } catch(IOException ie) { throw runtime.newIOError(ie.getLocalizedMessage()); } int interestOps = Nio4r.symbolToInterestOps(runtime, channel, interests); SelectionKey key; try { key = channel.register(selector, interestOps); } catch(java.lang.IllegalArgumentException ia) { throw runtime.newArgumentError("mode not supported for this object: " + interests); } catch(java.nio.channels.ClosedChannelException cce) { throw context.runtime.newIOError(cce.getLocalizedMessage()); } RubyClass monitorClass = runtime.getModule("NIO").getClass("Monitor"); Monitor monitor = (Monitor)monitorClass.newInstance(context, io, interests, null); monitor.setSelectionKey(key); return monitor; } @JRubyMethod public IRubyObject deregister(ThreadContext context, IRubyObject io) { Ruby runtime = context.getRuntime(); Channel raw_channel = ((RubyIO)io).getChannel(); if(!(raw_channel instanceof SelectableChannel)) { throw runtime.newArgumentError("not a selectable IO object"); } SelectableChannel channel = (SelectableChannel)raw_channel; SelectionKey key = channel.keyFor(selector); if(key == null) return context.nil; Monitor monitor = (Monitor)key.attachment(); monitor.close(context); return monitor; } @JRubyMethod(name = "registered?") public IRubyObject isRegistered(ThreadContext context, IRubyObject io) { Ruby runtime = context.getRuntime(); Channel raw_channel = ((RubyIO)io).getChannel(); if(!(raw_channel instanceof SelectableChannel)) { throw runtime.newArgumentError("not a selectable IO object"); } SelectableChannel channel = (SelectableChannel)raw_channel; SelectionKey key = channel.keyFor(selector); if(key == null) return context.nil; if(((Monitor)key.attachment()).isClosed(context) == runtime.getTrue()) { return runtime.getFalse(); } else { return runtime.getTrue(); } } @JRubyMethod public synchronized IRubyObject select(ThreadContext context, Block block) { return select(context, context.nil, block); } @JRubyMethod public synchronized IRubyObject select(ThreadContext context, IRubyObject timeout, Block block) { Ruby runtime = context.getRuntime(); int ready = doSelect(runtime, timeout); /* Timeout or wakeup */ if(ready <= 0) return context.nil; RubyArray array = null; if(!block.isGiven()) { array = runtime.newArray(selector.selectedKeys().size()); } Iterator selectedKeys = selector.selectedKeys().iterator(); while (selectedKeys.hasNext()) { SelectionKey key = (SelectionKey)selectedKeys.next(); processKey(key); selectedKeys.remove(); if(block.isGiven()) { block.call(context, (IRubyObject)key.attachment()); } else { array.add(key.attachment()); } } if(block.isGiven()) { return RubyNumeric.int2fix(runtime, ready); } else { return array; } } @JRubyMethod public synchronized IRubyObject select_each(ThreadContext context, Block block) { return select_each(context, context.nil, block); } @JRubyMethod public synchronized IRubyObject select_each(ThreadContext context, IRubyObject timeout, Block block) { Ruby runtime = context.getRuntime(); int ready = doSelect(runtime, timeout); /* Timeout or wakeup */ if(ready <= 0) return context.nil; Iterator selectedKeys = selector.selectedKeys().iterator(); while (selectedKeys.hasNext()) { SelectionKey key = (SelectionKey)selectedKeys.next(); processKey(key); selectedKeys.remove(); block.call(context, (IRubyObject)key.attachment()); } return context.nil; } private int doSelect(Ruby runtime, IRubyObject timeout) { try { if(timeout.isNil()) { return selector.select(); } else { double t = RubyNumeric.num2dbl(timeout); if(t == 0) { return selector.selectNow(); } else if(t < 0) { throw runtime.newArgumentError("time interval must be positive"); } else { return selector.select((long)(t * 1000)); } } } catch(IOException ie) { throw runtime.newIOError(ie.getLocalizedMessage()); } } // Remove connect interest from connected sockets private void processKey(SelectionKey key) { if((key.readyOps() & SelectionKey.OP_CONNECT) != 0) { int interestOps = key.interestOps(); interestOps &= ~SelectionKey.OP_CONNECT; interestOps |= SelectionKey.OP_WRITE; key.interestOps(interestOps); } } @JRubyMethod public IRubyObject wakeup(ThreadContext context) { if(!selector.isOpen()) { throw context.getRuntime().newIOError("selector is closed"); } selector.wakeup(); return context.nil; } } public class Monitor extends RubyObject { private SelectionKey key; private RubyIO io; private IRubyObject interestSym, value, closed; public Monitor(final Ruby ruby, RubyClass rubyClass) { super(ruby, rubyClass); } @JRubyMethod public IRubyObject initialize(ThreadContext context, IRubyObject selectable, IRubyObject interests) { io = (RubyIO)selectable; interestSym = interests; value = context.nil; closed = context.getRuntime().getFalse(); return context.nil; } public void setSelectionKey(SelectionKey k) { key = k; key.attach(this); } @JRubyMethod public IRubyObject io(ThreadContext context) { return io; } @JRubyMethod public IRubyObject interests(ThreadContext context) { return interestSym; } @JRubyMethod public IRubyObject readiness(ThreadContext context) { return Nio4r.interestOpsToSymbol(context.getRuntime(), key.readyOps()); } @JRubyMethod(name = "readable?") public IRubyObject isReadable(ThreadContext context) { Ruby runtime = context.getRuntime(); int readyOps = key.readyOps(); if((readyOps & SelectionKey.OP_READ) != 0 || (readyOps & SelectionKey.OP_ACCEPT) != 0) { return runtime.getTrue(); } else { return runtime.getFalse(); } } @JRubyMethod(name = {"writable?", "writeable?"}) public IRubyObject writable(ThreadContext context) { Ruby runtime = context.getRuntime(); int readyOps = key.readyOps(); if((readyOps & SelectionKey.OP_WRITE) != 0 || (readyOps & SelectionKey.OP_CONNECT) != 0) { return runtime.getTrue(); } else { return runtime.getFalse(); } } @JRubyMethod(name = "value") public IRubyObject getValue(ThreadContext context) { return value; } @JRubyMethod(name = "value=") public IRubyObject setValue(ThreadContext context, IRubyObject obj) { value = obj; return context.nil; } @JRubyMethod public IRubyObject close(ThreadContext context) { key.cancel(); closed = context.getRuntime().getTrue(); return context.nil; } @JRubyMethod(name = "closed?") public IRubyObject isClosed(ThreadContext context) { return closed; } } }
package com.fasterxml.jackson.core.util; import java.io.*; import java.util.Iterator; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.JsonParser.NumberType; import com.fasterxml.jackson.core.type.ResolvedType; import com.fasterxml.jackson.core.type.TypeReference; import static org.junit.Assert.assertArrayEquals; public class TestDelegates extends com.fasterxml.jackson.core.BaseTest { static class POJO { public int x = 3; } static class BogusCodec extends ObjectCodec { public Object pojoWritten; public TreeNode treeWritten; @Override public Version version() { return Version.unknownVersion(); } @Override public <T> T readValue(JsonParser p, Class<T> valueType) { return null; } @Override public <T> T readValue(JsonParser p, TypeReference<T> valueTypeRef) { return null; } @Override public <T> T readValue(JsonParser p, ResolvedType valueType) { return null; } @Override public <T> Iterator<T> readValues(JsonParser p, Class<T> valueType) { return null; } @Override public <T> Iterator<T> readValues(JsonParser p, TypeReference<T> valueTypeRef) throws IOException { return null; } @Override public <T> Iterator<T> readValues(JsonParser p, ResolvedType valueType) { return null; } @Override public void writeValue(JsonGenerator gen, Object value) throws IOException { gen.writeString("pojo"); pojoWritten = value; } @Override public <T extends TreeNode> T readTree(JsonParser p) { return null; } @Override public void writeTree(JsonGenerator gen, TreeNode tree) throws IOException { gen.writeString("tree"); treeWritten = tree; } @Override public TreeNode createObjectNode() { return null; } @Override public TreeNode createArrayNode() { return null; } @Override public TreeNode missingNode() { return null; } @Override public TreeNode nullNode() { return null; } @Override public JsonParser treeAsTokens(TreeNode n) { return null; } @Override public <T> T treeToValue(TreeNode n, Class<T> valueType) { return null; } } static class BogusTree implements TreeNode { @Override public JsonToken asToken() { return null; } @Override public NumberType numberType() { return null; } @Override public int size() { return 0; } @Override public boolean isValueNode() { return false; } @Override public boolean isContainerNode() { return false; } @Override public boolean isMissingNode() { return false; } @Override public boolean isArray() { return false; } @Override public boolean isObject() { return false; } @Override public TreeNode get(String fieldName) { return null; } @Override public TreeNode get(int index) { return null; } @Override public TreeNode path(String fieldName) { return null; } @Override public TreeNode path(int index) { return null; } @Override public Iterator<String> fieldNames() { return null; } @Override public TreeNode at(JsonPointer ptr) { return null; } @Override public TreeNode at(String jsonPointerExpression) { return null; } @Override public JsonParser traverse() { return null; } @Override public JsonParser traverse(ObjectCodec codec) { return null; } } private final JsonFactory JSON_F = new JsonFactory(); /** * Test default, non-overridden parser delegate. */ public void testParserDelegate() throws IOException { final String TOKEN ="foo"; JsonParser parser = JSON_F.createParser("[ 1, true, null, { \"a\": \"foo\" }, \"AQI=\" ]"); JsonParserDelegate del = new JsonParserDelegate(parser); // Basic capabilities for parser: assertFalse(del.canParseAsync()); assertFalse(del.canReadObjectId()); assertFalse(del.canReadTypeId()); assertFalse(del.requiresCustomCodec()); assertEquals(parser.version(), del.version()); // configuration assertFalse(del.isEnabled(JsonParser.Feature.ALLOW_COMMENTS)); assertFalse(del.isEnabled(StreamReadFeature.IGNORE_UNDEFINED)); assertSame(parser, del.delegate()); assertNull(del.getSchema()); // initial state assertNull(del.currentToken()); assertFalse(del.hasCurrentToken()); assertFalse(del.hasTextCharacters()); assertNull(del.getCurrentValue()); assertNull(del.getCurrentName()); assertToken(JsonToken.START_ARRAY, del.nextToken()); assertEquals(JsonTokenId.ID_START_ARRAY, del.currentTokenId()); assertTrue(del.hasToken(JsonToken.START_ARRAY)); assertFalse(del.hasToken(JsonToken.START_OBJECT)); assertTrue(del.hasTokenId(JsonTokenId.ID_START_ARRAY)); assertFalse(del.hasTokenId(JsonTokenId.ID_START_OBJECT)); assertTrue(del.isExpectedStartArrayToken()); assertFalse(del.isExpectedStartObjectToken()); assertEquals("[", del.getText()); assertNotNull(del.getParsingContext()); assertSame(parser.getParsingContext(), del.getParsingContext()); assertToken(JsonToken.VALUE_NUMBER_INT, del.nextToken()); assertEquals(1, del.getIntValue()); assertEquals(1, del.getValueAsInt()); assertEquals(1, del.getValueAsInt(3)); assertEquals(1L, del.getValueAsLong()); assertEquals(1L, del.getValueAsLong(3L)); assertEquals(1L, del.getLongValue()); assertEquals(1d, del.getValueAsDouble()); assertEquals(1d, del.getValueAsDouble(0.25)); assertEquals(1d, del.getDoubleValue()); assertTrue(del.getValueAsBoolean()); assertTrue(del.getValueAsBoolean(false)); assertEquals((byte)1, del.getByteValue()); assertEquals((short)1, del.getShortValue()); assertEquals(1f, del.getFloatValue()); assertFalse(del.isNaN()); assertEquals(NumberType.INT, del.getNumberType()); assertEquals(Integer.valueOf(1), del.getNumberValue()); assertNull(del.getEmbeddedObject()); assertToken(JsonToken.VALUE_TRUE, del.nextToken()); assertTrue(del.getBooleanValue()); assertEquals(parser.getCurrentLocation(), del.getCurrentLocation()); assertNull(del.getTypeId()); assertNull(del.getObjectId()); assertToken(JsonToken.VALUE_NULL, del.nextToken()); assertNull(del.getCurrentValue()); del.setCurrentValue(TOKEN); assertToken(JsonToken.START_OBJECT, del.nextToken()); assertNull(del.getCurrentValue()); assertToken(JsonToken.FIELD_NAME, del.nextToken()); assertEquals("a", del.getCurrentName()); assertToken(JsonToken.VALUE_STRING, del.nextToken()); assertTrue(del.hasTextCharacters()); assertEquals("foo", del.getText()); assertToken(JsonToken.END_OBJECT, del.nextToken()); assertEquals(TOKEN, del.getCurrentValue()); assertToken(JsonToken.VALUE_STRING, del.nextToken()); assertArrayEquals(new byte[] { 1, 2 }, del.getBinaryValue()); assertToken(JsonToken.END_ARRAY, del.nextToken()); del.close(); assertTrue(del.isClosed()); assertTrue(parser.isClosed()); parser.close(); } /** * Test default, non-overridden generator delegate. */ public void testGeneratorDelegate() throws IOException { final String TOKEN ="foo"; StringWriter sw = new StringWriter(); JsonGenerator g0 = JSON_F.createGenerator(sw); JsonGeneratorDelegate del = new JsonGeneratorDelegate(g0); // Basic capabilities for parser: assertTrue(del.canOmitFields()); assertFalse(del.canWriteBinaryNatively()); assertTrue(del.canWriteFormattedNumbers()); assertFalse(del.canWriteObjectId()); assertFalse(del.canWriteTypeId()); assertEquals(g0.version(), del.version()); // configuration assertTrue(del.isEnabled(JsonGenerator.Feature.QUOTE_FIELD_NAMES)); assertFalse(del.isEnabled(StreamWriteFeature.IGNORE_UNKNOWN)); assertSame(g0, del.delegate()); assertSame(g0, del.getDelegate()); // deprecated as of 2.11 // initial state assertNull(del.getSchema()); assertNull(del.getPrettyPrinter()); del.writeStartArray(); assertEquals(1, del.getOutputBuffered()); del.writeNumber(13); del.writeNull(); del.writeBoolean(false); del.writeString("foo"); // verify that we can actually set/get "current value" as expected, even with delegates assertNull(del.getCurrentValue()); del.setCurrentValue(TOKEN); del.writeStartObject(); assertNull(del.getCurrentValue()); del.writeEndObject(); assertEquals(TOKEN, del.getCurrentValue()); del.writeStartArray(0); del.writeEndArray(); del.writeEndArray(); del.flush(); del.close(); assertTrue(del.isClosed()); assertTrue(g0.isClosed()); assertEquals("[13,null,false,\"foo\",{},[]]", sw.toString()); g0.close(); } public void testNotDelegateCopyMethods() throws IOException { JsonParser jp = JSON_F.createParser("[{\"a\":[1,2,{\"b\":3}],\"c\":\"d\"},{\"e\":false},null]"); StringWriter sw = new StringWriter(); JsonGenerator jg = new JsonGeneratorDelegate(JSON_F.createGenerator(sw), false) { @Override public void writeFieldName(String name) throws IOException { super.writeFieldName(name+"-test"); super.writeBoolean(true); super.writeFieldName(name); } }; jp.nextToken(); jg.copyCurrentStructure(jp); jg.flush(); assertEquals("[{\"a-test\":true,\"a\":[1,2,{\"b-test\":true,\"b\":3}],\"c-test\":true,\"c\":\"d\"},{\"e-test\":true,\"e\":false},null]", sw.toString()); jp.close(); jg.close(); } @SuppressWarnings("resource") public void testGeneratorWithCodec() throws IOException { BogusCodec codec = new BogusCodec(); StringWriter sw = new StringWriter(); JsonGenerator g0 = JSON_F.createGenerator(sw); g0.setCodec(codec); JsonGeneratorDelegate del = new JsonGeneratorDelegate(g0, false); del.writeStartArray(); POJO pojo = new POJO(); del.writeObject(pojo); TreeNode tree = new BogusTree(); del.writeTree(tree); del.writeEndArray(); del.close(); assertEquals("[\"pojo\",\"tree\"]", sw.toString()); assertSame(tree, codec.treeWritten); assertSame(pojo, codec.pojoWritten); } }
package team046; import battlecode.common.*; public class RobotPlayer { private static RobotController rc; private static int round; private static double power; private static int zergRushChannel = randomWithRange(0, GameConstants.BROADCAST_MAX_CHANNELS); private static int zergRushCode = randomWithRange(2, GameConstants.BROADCAST_MAX_CHANNELS); private static int EncampmentBuilderChannel = randomWithRange(0, GameConstants.BROADCAST_MAX_CHANNELS); private static int EncampmentSearchStartedChannel = randomWithRange(0, GameConstants.BROADCAST_MAX_CHANNELS); private static int SupplierBuilt = randomWithRange(0, GameConstants.BROADCAST_MAX_CHANNELS); private static int researchNuke = randomWithRange(0, GameConstants.BROADCAST_MAX_CHANNELS); public static void run(RobotController MyJohn12LongRC) { rc = MyJohn12LongRC; while (true) { try { round = Clock.getRoundNum(); power = rc.getTeamPower(); if (rc.getType() == RobotType.HQ) { HQ(); } else if (rc.getType() == RobotType.SOLDIER) { Soldier(); } else if (rc.getType() == RobotType.ARTILLERY) { Artillery(); } rc.yield(); } catch (Exception e) { e.printStackTrace(); break; } } } private static void HQ() throws GameActionException { if (rc.isActive()) { if (rc.senseEnemyNukeHalfDone() && rc.readBroadcast(zergRushChannel) != zergRushCode) { rc.broadcast(zergRushChannel, zergRushCode); } else if (round > 50 && !rc.hasUpgrade(Upgrade.PICKAXE)) { rc.researchUpgrade(Upgrade.PICKAXE); return; } else if (round > 100 && !rc.hasUpgrade(Upgrade.FUSION)) { rc.researchUpgrade(Upgrade.FUSION); return; } else if (round > 150 && !rc.hasUpgrade(Upgrade.VISION)) { rc.researchUpgrade(Upgrade.VISION); return; } else if (round > 2000 || power > 250) { // Check for a cue from a robot if (power > GameConstants.BROADCAST_READ_COST && rc.readBroadcast(researchNuke) == 1) { rc.researchUpgrade(Upgrade.NUKE); return; } // Check the HQ's own surroundings else if (rc.senseNearbyGameObjects(Robot.class, 33, rc.getTeam()).length > 30) { rc.researchUpgrade(Upgrade.NUKE); return; } } // Find an available spawn direction MapLocation hqLocation = rc.senseHQLocation(); MapLocation nextLoc; for (Direction dir : Direction.values()) { if (dir != Direction.NONE && dir != Direction.OMNI && rc.canMove(dir)) { nextLoc = hqLocation.add(dir); Team mine = rc.senseMine(nextLoc); if (mine == null || mine == rc.getTeam()) { rc.spawn(dir); break; } } } } } private static void Soldier() throws GameActionException { if (rc.isActive()) { int EncampmentBuilderRobotID; int EncampmentSearchStartedRound; MapLocation rLoc = rc.getLocation(); MapLocation targetLoc = null; // Get the Encampment builder robot ID (or zero) if (power > GameConstants.BROADCAST_READ_COST * 2) { EncampmentBuilderRobotID = rc.readBroadcast(EncampmentBuilderChannel); EncampmentSearchStartedRound = rc.readBroadcast(EncampmentSearchStartedChannel); power -= GameConstants.BROADCAST_READ_COST * 2; } else { EncampmentBuilderRobotID = -1; EncampmentSearchStartedRound = 0; } if (power > GameConstants.BROADCAST_SEND_COST * 2 && (EncampmentBuilderRobotID == 0 || EncampmentSearchStartedRound + GameConstants.CAPTURE_ROUND_DELAY < round)) { rc.broadcast(EncampmentBuilderChannel, rc.getRobot().getID()); rc.broadcast(EncampmentSearchStartedChannel, round); power -= GameConstants.BROADCAST_SEND_COST * 2; EncampmentBuilderRobotID = rc.getRobot().getID(); } // Check for zerg command if (power > GameConstants.BROADCAST_READ_COST && rc.readBroadcast(zergRushChannel) == zergRushCode) { targetLoc = rc.senseEnemyHQLocation(); power -= GameConstants.BROADCAST_READ_COST; } // Handle Encampment builder robot (including movement) else if (EncampmentBuilderRobotID == rc.getRobot().getID()) { BuildEncampment(rLoc); return; } // Check for and plant mines else if (rc.senseMine(rLoc) == null) { rc.layMine(); return; } else { // Get scared Robot[] nearbyEnemies = rc.senseNearbyGameObjects(Robot.class, 3, rc.getTeam().opponent()); if (nearbyEnemies.length > 0) { return; } } // Set rally point if (targetLoc == null) { MapLocation goodHQ = rc.senseHQLocation(); if (goodHQ.x <= 2 || goodHQ.x >= rc.getMapWidth() - 2) { MapLocation rudeHQ = rc.senseEnemyHQLocation(); Direction dir = goodHQ.directionTo(rudeHQ); int xm = 1, ym = 1; switch (dir) { case NORTH: xm = 0; ym = -3; break; case NORTH_EAST: xm = 3; ym = -3; break; case EAST: xm = 3; ym = 0; break; case SOUTH_EAST: xm = 3; ym = 3; break; case SOUTH: xm = 0; ym = 3; break; case SOUTH_WEST: xm = -3; ym = 3; break; case WEST: xm = -3; ym = 0; break; case NORTH_WEST: xm = -3; ym = -3; break; } targetLoc = new MapLocation(goodHQ.x + xm, goodHQ.y + ym); } else { MapLocation rallyPoints[] = { new MapLocation(goodHQ.x + randomWithRange(1,3), goodHQ.y + randomWithRange(1,3)), new MapLocation(goodHQ.x - randomWithRange(1,3), goodHQ.y - randomWithRange(1,3)) }; targetLoc = rallyPoints[randomWithRange(0, rallyPoints.length - 1)]; } } // If already on targetLoc, sense buddies and send nuke research signal if (power > GameConstants.BROADCAST_READ_COST + GameConstants.BROADCAST_SEND_COST) { int currentStatus = rc.readBroadcast(researchNuke); if (rLoc.equals(targetLoc)) { Robot[] myFriends = rc.senseNearbyGameObjects(Robot.class, 33, rc.getTeam()); if (myFriends.length > 30 && currentStatus == 0) { rc.broadcast(researchNuke, 1); } else if (myFriends.length < 30 && currentStatus != 0) { rc.broadcast(researchNuke, 0); } return; } } MoveRobot(rLoc, targetLoc); } } private static void Artillery() throws GameActionException { if (rc.isActive()) { Robot[] baddies = rc.senseNearbyGameObjects(Robot.class, 33, rc.getTeam().opponent()); if (baddies.length > 0) { RobotInfo baddieInfo = rc.senseRobotInfo(baddies[0]); if (rc.canAttackSquare(baddieInfo.location)) { rc.attackSquare(baddieInfo.location); } } } } private static void MoveRobot(MapLocation rLoc, MapLocation targetLoc) throws GameActionException { Direction dir = rLoc.directionTo(targetLoc); if (dir == Direction.NONE) { return; } else if (dir == Direction.OMNI) { dir = Direction.EAST; } // If the bot can't move in the default direction, test all other directions if (!rc.canMove(dir)) { int shortest = 1000, testDist; Direction bestDir = dir; MapLocation testLoc; for (Direction testDir : Direction.values()) { if (testDir != dir && testDir != Direction.NONE && testDir != Direction.OMNI && rc.canMove(testDir)) { testLoc = rLoc.add(testDir); testDist = testLoc.distanceSquaredTo(targetLoc); if (testDist < shortest) { shortest = testDist; bestDir = testDir; } } } // If the direction hasn't changed, there is just no where to go. if (bestDir == dir) { return; } dir = bestDir; } MapLocation nextLoc = rLoc.add(dir); Team mine = rc.senseMine(nextLoc); if (mine == Team.NEUTRAL || mine == rc.getTeam().opponent()) { rc.defuseMine(nextLoc); } else { rc.move(dir); } } private static void BuildEncampment(MapLocation rLoc) throws GameActionException { if (power > rc.senseCaptureCost()) { if (rc.senseEncampmentSquare(rLoc)) { // Check how close the encampment is to HQ, if close build an artillery MapLocation goodHQ = rc.senseHQLocation(); if (goodHQ.distanceSquaredTo(rLoc) < 40) { rc.captureEncampment(RobotType.ARTILLERY); } // Otherwise, check status of supplier build and do another one or generator else if (power > GameConstants.BROADCAST_READ_COST + GameConstants.BROADCAST_SEND_COST) { if (rc.readBroadcast(SupplierBuilt) == 0) { rc.captureEncampment(RobotType.SUPPLIER); rc.broadcast(SupplierBuilt, 1); power -= GameConstants.BROADCAST_READ_COST + GameConstants.BROADCAST_SEND_COST; } else { rc.captureEncampment(RobotType.GENERATOR); rc.broadcast(SupplierBuilt, 0); power -= GameConstants.BROADCAST_SEND_COST; } } } else { MapLocation encampmentSquares[] = rc.senseAllEncampmentSquares(); MapLocation goodEncampments[] = rc.senseAlliedEncampmentSquares(); MapLocation targetLoc = encampmentSquares[0]; int closest = 1000; checkLocations: for (MapLocation loc : encampmentSquares) { int dist = rLoc.distanceSquaredTo(loc); if (dist < closest) { for (MapLocation goodLoc : goodEncampments) { if (goodLoc.equals(loc)) { continue checkLocations; } } targetLoc = loc; closest = dist; } } MoveRobot(rLoc, targetLoc); } } } private static int randomWithRange(int min, int max) { int range = Math.abs(max - min) + 1; return (int)(Math.random() * range) + (min <= max ? min : max); } }
package com.github.piotrkot.mustache.tags; import com.github.piotrkot.mustache.Contents; import com.github.piotrkot.mustache.TagIndicate; import com.google.common.collect.ImmutableMap; import java.util.Collections; import java.util.regex.Pattern; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Test; /** * Test to Partial. * @author Piotr Kotlicki (piotr.kotlicki@gmail.com) * @version $Id$ * @since 1.0 */ public final class PartialTest { /** * Should render partial. * @throws Exception If fails. */ @Test public void shouldRenderWithPartial() throws Exception { MatcherAssert.assertThat( new Partial( new SquareIndicate() ).render( new Contents( "A [[>var]] B [[>miss]]" ).asString(), Collections.singletonMap("var", "inj") ), Matchers.is("A inj B ") ); } /** * Should render partial with sequence. * @throws Exception If fails. */ @Test public void shouldRenderWithPartialSequence() throws Exception { MatcherAssert.assertThat( new Partial( new SquareIndicate() ).render( new Contents( "A [[>seq]] B" ).asString(), ImmutableMap.of( "seq", "[[#a]][[x]][[/a]] [[^b]]D[[/b]] [[>more]] [[y]]", "a", Collections.singletonList(ImmutableMap.of("x", "X")), "b", Boolean.FALSE, "y", "Y" ) ), Matchers.is("A X D [[>more]] Y B") ); } /** * Tag indicate with double square parentheses. */ private class SquareIndicate implements TagIndicate { @Override public String safeStart() { return Pattern.quote("[["); } @Override public String safeEnd() { return Pattern.quote("]]"); } } }
package team353; import battlecode.common.*; import java.util.*; public class RobotPlayer { public static class smuConstants { public static int roundToBuildAEROSPACELAB = 2000; public static int roundToBuildBARRACKS = 500; public static int roundToBuildBASHER = 1200; public static int roundToBuildBEAVER = 0; public static int roundToBuildCOMMANDER = 2000; public static int roundToBuildCOMPUTER = 2000; public static int roundToBuildDRONE = 2000; public static int roundToBuildHANDWASHSTATION = 1800; public static int roundToBuildHQ = 2001; public static int roundToBuildHELIPAD = 2000; public static int roundToBuildLAUNCHER = 2000; public static int roundToBuildMINER = 1; public static int roundToBuildMINERFACTORY = 10; public static int roundToBuildMISSILE = 2000; public static int roundToBuildSOLDIER = 200; public static int roundToBuildSUPPLYDEPOT = 800; public static int roundToBuildTANK = 1100; public static int roundToBuildTANKFACTORY = 1000; public static int roundToBuildTECHNOLOGYINSTITUTE = 2000; public static int roundToBuildTOWER = 2001; public static int roundToBuildTRAININGFIELD = 2000; public static final int[] roundToBuild = new int[] {0, roundToBuildAEROSPACELAB, roundToBuildBARRACKS, roundToBuildBASHER, roundToBuildBEAVER, roundToBuildCOMMANDER, roundToBuildCOMPUTER, roundToBuildDRONE, roundToBuildHANDWASHSTATION, roundToBuildHELIPAD, roundToBuildHQ, roundToBuildLAUNCHER, roundToBuildMINER, roundToBuildMINERFACTORY, roundToBuildMISSILE, roundToBuildSOLDIER, roundToBuildSUPPLYDEPOT, roundToBuildTANK, roundToBuildTANKFACTORY, roundToBuildTECHNOLOGYINSTITUTE, roundToBuildTOWER, roundToBuildTRAININGFIELD}; public static int roundToFinishAEROSPACELAB = 2000; public static int roundToFinishBARRACKS = 1500; public static int roundToFinishBASHER = 1700; public static int roundToFinishBEAVER = 0; public static int roundToFinishCOMMANDER = 2000; public static int roundToFinishCOMPUTER = 2000; public static int roundToFinishDRONE = 2000; public static int roundToFinishHANDWASHSTATION = 1700; public static int roundToFinishHQ = 2001; public static int roundToFinishHELIPAD = 2000; public static int roundToFinishLAUNCHER = 2000; public static int roundToFinishMINER = 1; public static int roundToFinishMINERFACTORY = 490; public static int roundToFinishMISSILE = 2000; public static int roundToFinishSOLDIER = 50; public static int roundToFinishSUPPLYDEPOT = 1200; public static int roundToFinishTANK = 1800; public static int roundToFinishTANKFACTORY = 1400; public static int roundToFinishTECHNOLOGYINSTITUTE = 2000; public static int roundToFinishTOWER = 2001; public static int roundToFinishTRAININGFIELD = 2000; public static final int[] roundToFinish = new int[] {0, roundToFinishAEROSPACELAB, roundToFinishBARRACKS, roundToFinishBASHER, roundToFinishBEAVER, roundToFinishCOMMANDER, roundToFinishCOMPUTER, roundToFinishDRONE, roundToFinishHANDWASHSTATION, roundToFinishHELIPAD, roundToFinishHQ, roundToFinishLAUNCHER, roundToFinishMINER, roundToFinishMINERFACTORY, roundToFinishMISSILE, roundToFinishSOLDIER, roundToFinishSUPPLYDEPOT, roundToFinishTANK, roundToFinishTANKFACTORY, roundToFinishTECHNOLOGYINSTITUTE, roundToFinishTOWER, roundToFinishTRAININGFIELD}; public static int desiredNumOfAEROSPACELAB = 0; public static int desiredNumOfBARRACKS = 4; public static int desiredNumOfBASHER = 50; public static int desiredNumOfBEAVER = 10; public static int desiredNumOfCOMMANDER = 0; public static int desiredNumOfCOMPUTER = 0; public static int desiredNumOfDRONE = 0; public static int desiredNumOfHANDWASHSTATION = 3; public static int desiredNumOfHQ = 0; public static int desiredNumOfHELIPAD = 0; public static int desiredNumOfLAUNCHER = 0; public static int desiredNumOfMINER = 50; public static int desiredNumOfMINERFACTORY = 2; public static int desiredNumOfMISSILE = 0; public static int desiredNumOfSOLDIER = 120; public static int desiredNumOfSUPPLYDEPOT = 5; public static int desiredNumOfTANK = 20; public static int desiredNumOfTANKFACTORY = 2; public static int desiredNumOfTECHNOLOGYINSTITUTE = 0; public static int desiredNumOfTOWER = 0; public static int desiredNumOfTRAININGFIELD = 0; public static final int[] desiredNumOf = new int[] {0, desiredNumOfAEROSPACELAB, desiredNumOfBARRACKS, desiredNumOfBASHER, desiredNumOfBEAVER, desiredNumOfCOMMANDER, desiredNumOfCOMPUTER, desiredNumOfDRONE, desiredNumOfHANDWASHSTATION, desiredNumOfHELIPAD, desiredNumOfHQ, desiredNumOfLAUNCHER, desiredNumOfMINER, desiredNumOfMINERFACTORY, desiredNumOfMISSILE, desiredNumOfSOLDIER, desiredNumOfSUPPLYDEPOT, desiredNumOfTANK, desiredNumOfTANKFACTORY, desiredNumOfTECHNOLOGYINSTITUTE, desiredNumOfTOWER, desiredNumOfTRAININGFIELD}; public static int roundToLaunchAttack = 1600; public static int roundToDefendTowers = 500; public static int roundToFormSupplyConvoy = 400; // roundToBuildSOLDIERS; public static int RADIUS_FOR_SUPPLY_CONVOY = 2; public static int numTowersRemainingToAttackHQ = 1; public static double weightExponentMagic = 0.3; public static double weightScaleMagic = 0.8; public static int currentOreGoal = 100; public static double percentBeaversToGoToSecondBase = 0.4; // Defence public static int NUM_TOWER_PROTECTORS = 4; public static int NUM_HOLE_PROTECTORS = 3; public static int PROTECT_OTHERS_RANGE = 10; public static int DISTANCE_TO_START_PROTECTING_SQUARED = 200; // Idle States public static MapLocation defenseRallyPoint; public static int PROTECT_HOLE = 1; public static int PROTECT_TOWER = 2; // Supply public static int NUM_ROUNDS_TO_KEEP_SUPPLIED = 20; // Contain public static int CLOCKWISE = 0; public static int COUNTERCLOCKWISE = 1; public static int CURRENTLY_BEING_CONTAINED = 1; public static int NOT_CURRENTLY_BEING_CONTAINED = 2; } public static class smuIndices { public static int RALLY_POINT_X = 0; public static int RALLY_POINT_Y = 1; //Economy public static int freqQueue = 11; public static int HQ_BEING_CONTAINED = 20; public static final int freqNumAEROSPACELAB = 301; public static final int freqNumBARRACKS = 302; public static final int freqNumBASHER = 303; public static final int freqNumBEAVER = 304; public static final int freqNumCOMMANDER = 305; public static final int freqNumCOMPUTER = 306; public static final int freqNumDRONE = 307; public static final int freqNumHANDWASHSTATION = 308; public static final int freqNumHELIPAD = 309; public static final int freqNumHQ = 310; public static final int freqNumLAUNCHER = 311; public static final int freqNumMINER = 312; public static final int freqNumMINERFACTORY = 313; public static final int freqNumMISSILE = 314; public static final int freqNumSOLDIER = 315; public static final int freqNumSUPPLYDEPOT = 316; public static final int freqNumTANK = 317; public static final int freqNumTANKFACTORY = 318; public static final int freqNumTECHNOLOGYINSTITUTE = 319; public static final int freqNumTOWER = 320; public static final int freqNumTRAININGFIELD = 321; public static final int[] freqNum = new int[] {0, freqNumAEROSPACELAB, freqNumBARRACKS, freqNumBASHER, freqNumBEAVER, freqNumCOMMANDER, freqNumCOMPUTER, freqNumDRONE, freqNumHANDWASHSTATION, freqNumHELIPAD, freqNumHQ, freqNumLAUNCHER, freqNumMINER, freqNumMINERFACTORY, freqNumMISSILE, freqNumSOLDIER, freqNumSUPPLYDEPOT, freqNumTANK, freqNumTANKFACTORY, freqNumTECHNOLOGYINSTITUTE, freqNumTOWER, freqNumTRAININGFIELD}; public static int TOWER_HOLES_BEGIN = 2000; } public static void run(RobotController rc) { BaseBot myself; if (rc.getType() == RobotType.HQ) { myself = new HQ(rc); } else if (rc.getType() == RobotType.MINER) { myself = new Miner(rc); } else if (rc.getType() == RobotType.MINERFACTORY) { myself = new Minerfactory(rc); } else if (rc.getType() == RobotType.BEAVER) { myself = new Beaver(rc); } else if (rc.getType() == RobotType.BARRACKS) { myself = new Barracks(rc); } else if (rc.getType() == RobotType.SOLDIER) { myself = new Soldier(rc); } else if (rc.getType() == RobotType.BASHER) { myself = new Basher(rc); } else if (rc.getType() == RobotType.HELIPAD) { myself = new Helipad(rc); } else if (rc.getType() == RobotType.DRONE) { myself = new Drone(rc); } else if (rc.getType() == RobotType.TOWER) { myself = new Tower(rc); } else if (rc.getType() == RobotType.SUPPLYDEPOT) { myself = new Supplydepot(rc); } else if (rc.getType() == RobotType.HANDWASHSTATION) { myself = new Handwashstation(rc); } else if (rc.getType() == RobotType.TANKFACTORY) { myself = new Tankfactory(rc); } else if (rc.getType() == RobotType.TANK) { myself = new Tank(rc); } else { myself = new BaseBot(rc); } while (true) { try { myself.go(); } catch (Exception e) { e.printStackTrace(); } } } public static class BaseBot { protected RobotController rc; protected MapLocation myHQ, theirHQ; protected Team myTeam, theirTeam; protected int myRange; protected RobotType myType; static Random rand; public BaseBot(RobotController rc) { this.rc = rc; this.myHQ = rc.senseHQLocation(); this.theirHQ = rc.senseEnemyHQLocation(); this.myTeam = rc.getTeam(); this.theirTeam = this.myTeam.opponent(); this.myType = rc.getType(); this.myRange = myType.attackRadiusSquared; rand = new Random(rc.getID()); } public int getDistanceSquared(MapLocation A, MapLocation B){ return (A.x - B.x)*(A.x - B.x) + (A.y - B.y)*(A.y - B.y); } public int getDistanceSquared(MapLocation A){ MapLocation B = rc.getLocation(); return (A.x - B.x)*(A.x - B.x) + (A.y - B.y)*(A.y - B.y); } public Direction[] getDirectionsToward(MapLocation dest) { Direction toDest = rc.getLocation().directionTo(dest); Direction[] dirs = {toDest, toDest.rotateLeft(), toDest.rotateRight(), toDest.rotateLeft().rotateLeft(), toDest.rotateRight().rotateRight()}; return dirs; } public Direction[] getDirectionsAway(MapLocation dest) { Direction toDest = rc.getLocation().directionTo(dest).opposite(); Direction[] dirs = {toDest, toDest.rotateLeft(), toDest.rotateRight(), toDest.rotateLeft().rotateLeft(), toDest.rotateRight().rotateRight()}; return dirs; } public Direction getMoveDir(MapLocation dest) { Direction[] dirs = getDirectionsToward(dest); for (Direction d : dirs) { if (rc.canMove(d)) { return d; } } return null; } public Direction getMoveDirAway(MapLocation dest) { Direction[] dirs = getDirectionsAway(dest); for (Direction d : dirs) { if (rc.canMove(d)) { return d; } } return null; } public Direction getMoveDirRand(MapLocation dest) { //TODO return a random direction Direction[] dirs = getDirectionsToward(dest); for (Direction d : dirs) { if (rc.canMove(d)) { return d; } } return null; } public Direction getMoveDirAwayRand(MapLocation dest) { //TODO return a random direction Direction[] dirs = getDirectionsAway(dest); for (Direction d : dirs) { if (rc.canMove(d)) { return d; } } return null; } //Will return a single direction for spawning. (Uses getDirectionsToward()) public Direction getSpawnDir(RobotType type) { Direction[] dirs = getDirectionsToward(this.theirHQ); for (Direction d : dirs) { if (rc.canSpawn(d, type)) { return d; } } dirs = getDirectionsToward(this.myHQ); for (Direction d : dirs) { if (rc.canSpawn(d, type)) { return d; } else { //System.out.println("Could not find valid spawn location!"); } } return null; } //Will return a single direction for building. (Uses getDirectionsToward()) public Direction getBuildDir(RobotType type) { Direction[] dirs = getDirectionsToward(this.theirHQ); for (Direction d : dirs) { if (rc.canBuild(d, type)) { return d; } } dirs = getDirectionsToward(this.myHQ); for (Direction d : dirs) { if (rc.canBuild(d, type)) { return d; } else { //System.out.println("Could not find valid build location!"); } } return null; } public RobotInfo[] getAllies() { RobotInfo[] allies = rc.senseNearbyRobots(Integer.MAX_VALUE, myTeam); return allies; } public RobotInfo[] getEnemiesInAttackingRange() { RobotInfo[] enemies = rc.senseNearbyRobots(myRange, theirTeam); return enemies; } public void attackLeastHealthEnemy(RobotInfo[] enemies) throws GameActionException { if (enemies.length == 0) { return; } double minEnergon = Double.MAX_VALUE; MapLocation toAttack = null; for (RobotInfo info : enemies) { if (info.health < minEnergon) { toAttack = info.location; minEnergon = info.health; } } if (toAttack != null) { rc.attackLocation(toAttack); } } public void attackLeastHealthEnemyInRange() throws GameActionException { RobotInfo[] enemies = getEnemiesInAttackingRange(); if (enemies.length > 0) { if (rc.isWeaponReady()) { attackLeastHealthEnemy(enemies); } } } public void moveToRallyPoint() throws GameActionException { if (rc.isCoreReady()) { int rallyX = rc.readBroadcast(smuIndices.RALLY_POINT_X); int rallyY = rc.readBroadcast(smuIndices.RALLY_POINT_Y); MapLocation rallyPoint = new MapLocation(rallyX, rallyY); RobotInfo[] robots = rc.senseNearbyRobots(rallyPoint, 10, myTeam); if (Clock.getRoundNum() > smuConstants.roundToLaunchAttack || rc.getLocation().distanceSquaredTo(rallyPoint) > 8 + Clock.getRoundNum() / 100) { Direction newDir = getMoveDir(rallyPoint); if (newDir != null) { rc.move(newDir); } } } } //Returns the current rally point MapLocation public MapLocation getRallyPoint() throws GameActionException { int rallyX = rc.readBroadcast(smuIndices.RALLY_POINT_X); int rallyY = rc.readBroadcast(smuIndices.RALLY_POINT_Y); MapLocation rallyPoint = new MapLocation(rallyX, rallyY); return rallyPoint; } //Moves a random safe direction from input array public void moveOptimally(Direction[] optimalDirections) throws GameActionException { //TODO check safety if (optimalDirections != null) { boolean lookingForDirection = true; while(lookingForDirection){ MapLocation[] enemyTowers = rc.senseEnemyTowerLocations(); Direction randomDirection = optimalDirections[(int) (rand.nextDouble()*optimalDirections.length)]; MapLocation tileInFront = rc.getLocation().add(randomDirection); //check that the direction in front is not a tile that can be attacked by the enemy towers boolean tileInFrontSafe = true; for(MapLocation m: enemyTowers){ if(m.distanceSquaredTo(tileInFront)<=RobotType.TOWER.attackRadiusSquared){ tileInFrontSafe = false; break; } } //check that we are not facing off the edge of the map TerrainTile terrainTileInFront = rc.senseTerrainTile(tileInFront); if(!tileInFrontSafe || terrainTileInFront == TerrainTile.OFF_MAP || (myType != RobotType.DRONE && terrainTileInFront!=TerrainTile.NORMAL)){ randomDirection = randomDirection.rotateLeft(); }else{ //try to move in the randomDirection direction if(rc.isCoreReady()&&rc.canMove(randomDirection)){ rc.move(randomDirection); lookingForDirection = false; return; } } } //System.out.println("No suitable direction found!"); } } //Gets optimal directions and then calls moveOptimally() with those directions. public void moveOptimally() throws GameActionException { Direction[] optimalDirections = getOptimalDirections(); if (optimalDirections != null) { moveOptimally(optimalDirections); } } //TODO Finish public Direction[] getOptimalDirections() throws GameActionException { // The switch statement should result in an array of directions that make sense //for the RobotType. Safety is considered in moveOptimally() RobotType currentRobotType = rc.getType(); Direction[] optimalDirections = null; switch(currentRobotType){ case BASHER: break; case BEAVER: if (getDistanceSquared(this.myHQ) < 50){ optimalDirections = getDirectionsAway(this.myHQ); } optimalDirections = Direction.values(); break; case COMMANDER: break; case COMPUTER: break; case DRONE: optimalDirections = getDirectionsToward(this.theirHQ); break; case LAUNCHER: break; case MINER: if (getDistanceSquared(this.myHQ) < 50){ optimalDirections = getDirectionsToward(this.myHQ); } optimalDirections = Direction.values(); break; case MISSILE: break; case SOLDIER: break; case TANK: break; default: //error } //Done RobotType specific actions. return optimalDirections; } //Spawns or Queues the unit if it is needed public boolean tryToSpawn(RobotType spawnType) throws GameActionException{ int round = Clock.getRoundNum(); double ore = rc.getTeamOre(); int spawnTypeInt = RobotTypeToInt(spawnType); int spawnQueue = rc.readBroadcast(smuIndices.freqQueue); //Check if we actually need anymore spawnType units if (round > smuConstants.roundToBuild[spawnTypeInt] && rc.readBroadcast(smuIndices.freqNum[spawnTypeInt]) < smuConstants.desiredNumOf[spawnTypeInt]){ if(ore > myType.oreCost){ if (spawnUnit(spawnType)) return true; } else { //Add spawnType to queue if (spawnQueue == 0){ rc.broadcast(smuIndices.freqQueue, spawnTypeInt); } return false; } } return false; } //Spawns unit based on calling type. Performs all checks. public boolean spawnOptimally() throws GameActionException { if (rc.isCoreReady()){ int spawnQueue = rc.readBroadcast(smuIndices.freqQueue); switch(myType){ case BARRACKS: if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.SOLDIER)){ if (tryToSpawn(RobotType.SOLDIER)) return true; } if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.BASHER)){ if (tryToSpawn(RobotType.BASHER)) return true; } break; case HQ: if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.BEAVER)){ if (tryToSpawn(RobotType.BEAVER)) return true; } break; case HELIPAD: if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.DRONE)){ if (tryToSpawn(RobotType.DRONE)) return true; } break; case AEROSPACELAB: if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.LAUNCHER)){ if (tryToSpawn(RobotType.LAUNCHER)) return true; } break; case MINERFACTORY: if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.MINER)){ if (tryToSpawn(RobotType.MINER)) return true; } break; case TANKFACTORY: if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.TANK)){ if (tryToSpawn(RobotType.TANK)) return true; } break; case TECHNOLOGYINSTITUTE: if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.COMPUTER)){ if (tryToSpawn(RobotType.COMPUTER)) return true; } break; case TRAININGFIELD: if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.COMMANDER)){ if (tryToSpawn(RobotType.COMMANDER)) return true; } break; default: System.out.println("ERROR: No building type match found in spawnOptimally()!"); return false; } }//isCoreReady return false; } //Gets direction, checks delays, and spawns unit public boolean spawnUnit(RobotType spawnType) { //Get a direction and then actually spawn the unit. Direction randomDir = getSpawnDir(spawnType); if(rc.isCoreReady() && randomDir != null){ try { if (rc.canSpawn(randomDir, spawnType)) { rc.spawn(randomDir, spawnType); if (IntToRobotType(rc.readBroadcast(smuIndices.freqQueue)) == spawnType) { rc.broadcast(smuIndices.freqQueue, 0); } incrementCount(spawnType); return true; } } catch (GameActionException e) { e.printStackTrace(); } } return false; } //Spawns unit based on calling type. Performs all checks. public void buildOptimally() throws GameActionException { if (rc.isCoreReady()){ int round = Clock.getRoundNum(); double ore = rc.getTeamOre(); boolean buildingsOutrankUnits = true; int queue = rc.readBroadcast(smuIndices.freqQueue); //If there is something in the queue and we can not replace it, then return if (queue != 0 && !buildingsOutrankUnits){ //System.out.println("Queue full, can't outrank"); return; } Integer[] buildingInts = new Integer[] {RobotTypeToInt(RobotType.AEROSPACELAB), RobotTypeToInt(RobotType.BARRACKS), RobotTypeToInt(RobotType.HANDWASHSTATION), RobotTypeToInt(RobotType.HELIPAD), RobotTypeToInt(RobotType.MINERFACTORY), RobotTypeToInt(RobotType.SUPPLYDEPOT), RobotTypeToInt(RobotType.TANKFACTORY), RobotTypeToInt(RobotType.TECHNOLOGYINSTITUTE), RobotTypeToInt(RobotType.TRAININGFIELD)}; //Check if there is a building in queue if (Arrays.asList(buildingInts).contains(queue)) { //Build it if we can afford it if (ore > IntToRobotType(queue).oreCost) { //System.out.println("Satisfying queue."); buildUnit(IntToRobotType(queue)); } //Return either way, we can't replace buildings in the queue return; } //we should sort the array based on need Arrays.sort(buildingInts, new Comparator<Integer>() { public int compare(Integer type1, Integer type2) { double wType1 = 0; double wType2 = 0; try { wType1 = getWeightOfRobotType(IntToRobotType(type1)); wType2 = getWeightOfRobotType(IntToRobotType(type2)); } catch (GameActionException e) { e.printStackTrace(); } return Double.compare(wType1, wType2); } }); //for i in array of structures for (int buildTypeInt : buildingInts) { int currentBuildNum = rc.readBroadcast(smuIndices.freqNum[buildTypeInt]); if (round > smuConstants.roundToBuild[buildTypeInt] && smuConstants.desiredNumOf[buildTypeInt] > 0 && smuConstants.roundToBuild[buildTypeInt] < smuConstants.roundToFinish[buildTypeInt] && currentBuildNum < smuConstants.desiredNumOf[buildTypeInt]){ //We don't have as many buildings as we want... if (ore > IntToRobotType(buildTypeInt).oreCost){ buildUnit(IntToRobotType(buildTypeInt)); } else { double weightToBeat = getWeightOfRobotType(IntToRobotType(buildTypeInt)); double rolled = rand.nextDouble(); //System.out.println("Rolled "+ rolled + "for a " + buildTypeInt + " against " + weightToBeat); if (rolled < weightToBeat){ rc.broadcast(smuIndices.freqQueue, buildTypeInt); System.out.println("Scheduled a " + IntToRobotType(buildTypeInt).name() + ". Need " + IntToRobotType(buildTypeInt).oreCost + " ore."); } return; } } } } } //Gets direction, checks delays, and builds unit public boolean buildUnit(RobotType buildType) { //Get a direction and then actually build the unit. Direction randomDir = getBuildDir(buildType); if(rc.isCoreReady() && randomDir != null){ try { if (rc.canBuild(randomDir, buildType)) { rc.build(randomDir, buildType); if (IntToRobotType(rc.readBroadcast(smuIndices.freqQueue)) == buildType) { rc.broadcast(smuIndices.freqQueue, 0); } incrementCount(buildType); return true; } } catch (GameActionException e) { e.printStackTrace(); } } return false; } //TODO find a way to deal with deaths. public void incrementCount(RobotType type) throws GameActionException { switch(type){ case AEROSPACELAB: rc.broadcast(smuIndices.freqNumAEROSPACELAB, rc.readBroadcast(smuIndices.freqNumAEROSPACELAB)+1); break; case BARRACKS: rc.broadcast(smuIndices.freqNumBARRACKS, rc.readBroadcast(smuIndices.freqNumBARRACKS)+1); break; case BASHER: rc.broadcast(smuIndices.freqNumBASHER, rc.readBroadcast(smuIndices.freqNumBASHER)+1); break; case BEAVER: rc.broadcast(smuIndices.freqNumBEAVER, rc.readBroadcast(smuIndices.freqNumBEAVER)+1); break; case COMMANDER: rc.broadcast(smuIndices.freqNumCOMMANDER, rc.readBroadcast(smuIndices.freqNumCOMMANDER)+1); break; case COMPUTER: rc.broadcast(smuIndices.freqNumCOMPUTER, rc.readBroadcast(smuIndices.freqNumCOMPUTER)+1); break; case DRONE: rc.broadcast(smuIndices.freqNumDRONE, rc.readBroadcast(smuIndices.freqNumDRONE)+1); break; case HANDWASHSTATION: rc.broadcast(smuIndices.freqNumHANDWASHSTATION, rc.readBroadcast(smuIndices.freqNumHANDWASHSTATION)+1); break; case HELIPAD: rc.broadcast(smuIndices.freqNumHELIPAD, rc.readBroadcast(smuIndices.freqNumHELIPAD)+1); break; case LAUNCHER: rc.broadcast(smuIndices.freqNumLAUNCHER, rc.readBroadcast(smuIndices.freqNumLAUNCHER)+1); break; case MINER: rc.broadcast(smuIndices.freqNumMINER, rc.readBroadcast(smuIndices.freqNumMINER)+1); break; case MINERFACTORY: rc.broadcast(smuIndices.freqNumMINERFACTORY, rc.readBroadcast(smuIndices.freqNumMINERFACTORY)+1); break; case MISSILE: rc.broadcast(smuIndices.freqNumMISSILE, rc.readBroadcast(smuIndices.freqNumMISSILE)+1); break; case SOLDIER: rc.broadcast(smuIndices.freqNumSOLDIER, rc.readBroadcast(smuIndices.freqNumSOLDIER)+1); break; case SUPPLYDEPOT: rc.broadcast(smuIndices.freqNumSUPPLYDEPOT, rc.readBroadcast(smuIndices.freqNumSUPPLYDEPOT)+1); break; case TANK: rc.broadcast(smuIndices.freqNumTANK, rc.readBroadcast(smuIndices.freqNumTANK)+1); break; case TANKFACTORY: rc.broadcast(smuIndices.freqNumTANKFACTORY, rc.readBroadcast(smuIndices.freqNumTANKFACTORY)+1); break; case TECHNOLOGYINSTITUTE: rc.broadcast(smuIndices.freqNumTECHNOLOGYINSTITUTE, rc.readBroadcast(smuIndices.freqNumTECHNOLOGYINSTITUTE)+1); break; case TRAININGFIELD: rc.broadcast(smuIndices.freqNumTRAININGFIELD, rc.readBroadcast(smuIndices.freqNumTRAININGFIELD)+1); break; default: //System.out.println("ERRROR!"); return; } } public void transferSupplies() throws GameActionException { double lowestSupply = rc.getSupplyLevel(); if (lowestSupply == 0) { return; } int roundStart = Clock.getRoundNum(); final MapLocation myLocation = rc.getLocation(); RobotInfo[] nearbyAllies = rc.senseNearbyRobots(myLocation,GameConstants.SUPPLY_TRANSFER_RADIUS_SQUARED,rc.getTeam()); double transferAmount = 0; MapLocation suppliesToThisLocation = null; for(RobotInfo ri:nearbyAllies){ if (!ri.type.isBuilding && ri.supplyLevel < lowestSupply) { lowestSupply = ri.supplyLevel; transferAmount = (rc.getSupplyLevel()-ri.supplyLevel)/2; suppliesToThisLocation = ri.location; } } if(suppliesToThisLocation!=null){ if (roundStart == Clock.getRoundNum() && transferAmount > 0) { try { rc.transferSupplies((int)transferAmount, suppliesToThisLocation); } catch(GameActionException gax) { gax.printStackTrace(); } } } } // true, I'm in the convoy or going to be // false, no place in the convoy for me public boolean formSupplyConvoy() { Direction directionForChain = getSupplyConvoyDirection(myHQ); RobotInfo minerAtEdge = getUnitAtEdgeOfSupplyRangeOf(RobotType.MINER, myHQ, directionForChain); if (minerAtEdge == null){ goToLocation(myHQ.add(directionForChain, smuConstants.RADIUS_FOR_SUPPLY_CONVOY)); return true; } else if (minerAtEdge.ID == rc.getID()) { return true; } RobotInfo previousMiner = null; try { while ((minerAtEdge != null || !minerAtEdge.type.isBuilding) && minerAtEdge.location.distanceSquaredTo(getRallyPoint()) > 4) { directionForChain = getSupplyConvoyDirection(minerAtEdge.location); previousMiner = minerAtEdge; minerAtEdge = getUnitAtEdgeOfSupplyRangeOf(RobotType.MINER, minerAtEdge.location, directionForChain); if (minerAtEdge == null) { goToLocation(previousMiner.location.add(directionForChain, smuConstants.RADIUS_FOR_SUPPLY_CONVOY)); return true; } else if (minerAtEdge.ID == rc.getID()) { return true; } } } catch (GameActionException e) { e.printStackTrace(); } return false; } public Direction getSupplyConvoyDirection(MapLocation startLocation) { Direction directionForChain = myHQ.directionTo(theirHQ); MapLocation locationToGo = startLocation.add(directionForChain, smuConstants.RADIUS_FOR_SUPPLY_CONVOY); if (rc.senseTerrainTile(locationToGo) == TerrainTile.NORMAL) { RobotInfo robotInDirection; try { robotInDirection = rc.senseRobotAtLocation(locationToGo); if (robotInDirection == null || !robotInDirection.type.isBuilding) { return directionForChain; } } catch (GameActionException e) { e.printStackTrace(); } } Direction[] directions = {Direction.NORTH, Direction.NORTH_EAST, Direction.EAST, Direction.SOUTH_EAST, Direction.SOUTH, Direction.SOUTH_WEST, Direction.WEST, Direction.NORTH_WEST}; for (int i = 0; i < directions.length; i++) { locationToGo = startLocation.add(directions[i], smuConstants.RADIUS_FOR_SUPPLY_CONVOY); if (directions[i] != directionForChain && directions[i] != Direction.OMNI && directions[i] != Direction.NONE && rc.senseTerrainTile(locationToGo) == TerrainTile.NORMAL) { RobotInfo robotInDirection; try { robotInDirection = rc.senseRobotAtLocation(locationToGo); if (robotInDirection == null || !robotInDirection.type.isBuilding) { return directions[i]; } } catch (GameActionException e) { e.printStackTrace(); } } } return Direction.NONE; } public RobotInfo getUnitAtEdgeOfSupplyRangeOf(RobotType unitType, MapLocation startLocation, Direction directionForChain) { MapLocation locationInChain = startLocation.add(directionForChain, smuConstants.RADIUS_FOR_SUPPLY_CONVOY); if (rc.canSenseLocation(locationInChain)) { try { return rc.senseRobotAtLocation(locationInChain); } catch (GameActionException e) { e.printStackTrace(); } } return null; } public MapLocation getSecondBaseLocation() { Direction directionToTheirHQ = myHQ.directionTo(theirHQ); MapLocation secondBase = null; if (directionToTheirHQ == Direction.EAST || directionToTheirHQ == Direction.WEST) { secondBase = getSecondBaseLocationInDirections(Direction.NORTH, Direction.SOUTH); } else if (directionToTheirHQ == Direction.NORTH || directionToTheirHQ == Direction.SOUTH) { secondBase = getSecondBaseLocationInDirections(Direction.EAST, Direction.WEST); } else { Direction[] directions = breakdownDirection(directionToTheirHQ); secondBase = getSecondBaseLocationInDirections(directions[0], directions[1]); } if (secondBase != null) { secondBase = secondBase.add(myHQ.directionTo(secondBase), 4); } return secondBase; } public MapLocation getSecondBaseLocationInDirections(Direction dir1, Direction dir2) { MapLocation towers[] = rc.senseTowerLocations(); int maxDistance = Integer.MIN_VALUE; int maxDistanceIndex = -1; Direction dirToEnemy = myHQ.directionTo(theirHQ); Direction dir1left = dir1.rotateLeft(); Direction dir1right = dir1.rotateRight(); Direction dir2left = dir2.rotateLeft(); Direction dir2right = dir2.rotateRight(); for (int i = 0; i<towers.length; i++) { Direction dirToTower = myHQ.directionTo(towers[i]); if (dirToTower == dir1 || dirToTower == dir2 || (dir1left != dirToEnemy && dirToTower == dir1left) || (dir1right != dirToEnemy && dirToTower == dir1right) || (dir2left != dirToEnemy && dirToTower == dir2left) || (dir2right != dirToEnemy && dirToTower == dir2right)) { int distanceToTower = myHQ.distanceSquaredTo(towers[i]); if (distanceToTower > maxDistance) { maxDistance = distanceToTower; maxDistanceIndex = i; } } } if (maxDistanceIndex != -1) { return towers[maxDistanceIndex]; } return null; } public void beginningOfTurn() { if (rc.senseEnemyHQLocation() != null) { this.theirHQ = rc.senseEnemyHQLocation(); } } public void endOfTurn() { } public void go() throws GameActionException { beginningOfTurn(); execute(); endOfTurn(); } public void execute() throws GameActionException { rc.yield(); } public void supplyAndYield() throws GameActionException { transferSupplies(); rc.yield(); } public int myContainDirection = smuConstants.CLOCKWISE; public MapLocation myContainPreviousLocation; public void contain() { MapLocation enemyHQ = rc.senseEnemyHQLocation(); MapLocation[] enemyTowers = rc.senseEnemyTowerLocations(); MapLocation myLocation = rc.getLocation(); int radiusFromHQ = 24; if (enemyTowers.length >= 2) { radiusFromHQ = 35; } if (myLocation.distanceSquaredTo(enemyHQ) > radiusFromHQ + 3) { // move towards the HQ try { moveOptimally(); } catch (GameActionException e) { e.printStackTrace(); } } else { MapLocation locationToGo = null; Direction directionToGo = null; if (myContainDirection == smuConstants.CLOCKWISE) { directionToGo = getClockwiseDirection(myLocation, enemyHQ); } else { directionToGo = getCounterClockwiseDirection(myLocation, enemyHQ); } locationToGo = myLocation.add(directionToGo); if (rc.isPathable(RobotType.DRONE, locationToGo)) { if (isLocationSafe(locationToGo)) { goToLocation(locationToGo); } else { Direction[] directions = breakdownDirection(directionToGo); for (int i = 0; i < directions.length; i++) { locationToGo = myLocation.add(directions[i]); if (isLocationSafe(locationToGo)) { goToLocation(locationToGo); myContainPreviousLocation = myLocation; return; } } } } else if (myContainPreviousLocation.equals(myLocation)){ if (myContainDirection == smuConstants.CLOCKWISE) { myContainDirection = smuConstants.COUNTERCLOCKWISE; } else { myContainDirection = smuConstants.CLOCKWISE; } } } myContainPreviousLocation = myLocation; } public boolean isLocationSafe(MapLocation location) { if (location.distanceSquaredTo(theirHQ) > RobotType.HQ.attackRadiusSquared) { for (MapLocation tower : rc.senseEnemyTowerLocations()) { if (location.distanceSquaredTo(tower) <= RobotType.TOWER.attackRadiusSquared) { return false; } } return true; } return false; } public Direction[] breakdownDirection(Direction direction) { Direction[] breakdown = new Direction[2]; switch(direction) { case NORTH_EAST: breakdown[0] = Direction.NORTH; breakdown[1] = Direction.EAST; break; case SOUTH_EAST: breakdown[0] = Direction.SOUTH; breakdown[1] = Direction.EAST; break; case NORTH_WEST: breakdown[0] = Direction.NORTH; breakdown[1] = Direction.WEST; break; case SOUTH_WEST: breakdown[0] = Direction.SOUTH; breakdown[1] = Direction.WEST; break; default: break; } return breakdown; } public Direction getClockwiseDirection(MapLocation myLocation, MapLocation anchor) { Direction directionToAnchor = myLocation.directionTo(anchor); if (directionToAnchor.equals(Direction.EAST) || directionToAnchor.equals(Direction.SOUTH_EAST)) { return Direction.NORTH_EAST; } else if (directionToAnchor.equals(Direction.SOUTH) || directionToAnchor.equals(Direction.SOUTH_WEST)) { return Direction.SOUTH_EAST; } else if (directionToAnchor.equals(Direction.WEST) || directionToAnchor.equals(Direction.NORTH_WEST)) { return Direction.SOUTH_WEST; } else if (directionToAnchor.equals(Direction.NORTH) || directionToAnchor.equals(Direction.NORTH_EAST)) { return Direction.NORTH_WEST; } return Direction.NONE; } public Direction getCounterClockwiseDirection(MapLocation myLocation, MapLocation anchor) { Direction oppositeDirection = getClockwiseDirection(myLocation, anchor); if (oppositeDirection.equals(Direction.NORTH_EAST)) { return Direction.SOUTH_WEST; } else if (oppositeDirection.equals(Direction.SOUTH_EAST)) { return Direction.NORTH_WEST; } else if (oppositeDirection.equals(Direction.SOUTH_WEST)) { return Direction.NORTH_EAST; } else if (oppositeDirection.equals(Direction.NORTH_WEST)) { return Direction.SOUTH_WEST; } return Direction.NONE; } // Defend public boolean defendSelf() { RobotInfo[] nearbyEnemies = getEnemiesInAttackRange(); if(nearbyEnemies != null && nearbyEnemies.length > 0) { try { if (rc.isWeaponReady()) { attackLeastHealthEnemyInRange(); } } catch (GameActionException e) { e.printStackTrace(); } return true; } return false; } public boolean defendTeammates() { RobotInfo[] engagedRobots = getRobotsEngagedInAttack(); if(engagedRobots != null && engagedRobots.length>0) { // Check broadcasts for enemies that are being attacked // TODO: Calculate which enemy is attacking/within range/closest to teammate // For now, just picking the first enemy // Once our unit is in range of the other unit, A1 will takeover for (RobotInfo robot : engagedRobots) { if (robot.team == theirTeam) { goToLocation(robot.location); } } return true; } return false; } public boolean defendTowerHoles() { int towerHoleX = -1; try { towerHoleX = rc.readBroadcast(smuIndices.TOWER_HOLES_BEGIN); } catch (GameActionException e1) { e1.printStackTrace(); } boolean defendingHole = false; if(towerHoleX != -1) { int towerHolesIndex = smuIndices.TOWER_HOLES_BEGIN; int towerHoleY; do { try { towerHoleX = rc.readBroadcast(towerHolesIndex); towerHolesIndex++; towerHoleY = rc.readBroadcast(towerHolesIndex); towerHolesIndex++; if (towerHoleX != -1) { MapLocation holeLocation = new MapLocation(towerHoleX, towerHoleY); RobotInfo[] nearbyTeammates = rc.senseNearbyRobots(holeLocation, 5, myTeam); if (nearbyTeammates.length < smuConstants.NUM_HOLE_PROTECTORS && rc.getLocation().distanceSquaredTo(holeLocation) <= smuConstants.DISTANCE_TO_START_PROTECTING_SQUARED) { defendingHole = true; towerHoleX = -1; goToLocation(holeLocation); } } } catch (GameActionException e) { e.printStackTrace(); } } while(towerHoleX != -1); } return defendingHole; } public boolean defendTowers() { MapLocation[] myTowers = rc.senseTowerLocations(); MapLocation closestTower = null; try { closestTower = getRallyPoint(); } catch (GameActionException e) { e.printStackTrace(); } int closestDist = Integer.MAX_VALUE; for (MapLocation tower : myTowers) { RobotInfo[] nearbyRobots = getTeammatesNearTower(tower); if (nearbyRobots.length < smuConstants.NUM_TOWER_PROTECTORS && rc.getLocation().distanceSquaredTo(tower) <= smuConstants.DISTANCE_TO_START_PROTECTING_SQUARED) { //tower underprotected int dist = tower.distanceSquaredTo(theirHQ); if (dist < closestDist) { closestDist = dist; closestTower = tower; } } } goToLocation(closestTower); return true; } public boolean defend() { // A1, Protect Self boolean isProtectingSelf = defendSelf(); if (isProtectingSelf) { return true; } // A2, Protect Nearby boolean isProtectingTeammates = defendTeammates(); if (isProtectingTeammates) { return true; } if (Clock.getRoundNum() < smuConstants.roundToLaunchAttack && Clock.getRoundNum() > smuConstants.roundToDefendTowers && myType != RobotType.BEAVER && myType != RobotType.MINER) { // B1, Protect Holes Between Towers boolean isProtectingHoles = defendTowerHoles(); if (isProtectingHoles) { return true; } if(myType != RobotType.BEAVER && myType != RobotType.MINER) { // B2, Protect Towers boolean isProtectingTowers = defendTowers(); if (isProtectingTowers) { return true; } } } return false; } public int RobotTypeToInt(RobotType type){ switch(type) { case AEROSPACELAB: return 1; case BARRACKS: return 2; case BASHER: return 3; case BEAVER: return 4; case COMMANDER: return 5; case COMPUTER: return 6; case DRONE: return 7; case HANDWASHSTATION: return 8; case HELIPAD: return 9; case HQ: return 10; case LAUNCHER: return 11; case MINER: return 12; case MINERFACTORY: return 13; case MISSILE: return 14; case SOLDIER: return 15; case SUPPLYDEPOT: return 16; case TANK: return 17; case TANKFACTORY: return 18; case TECHNOLOGYINSTITUTE: return 19; case TOWER: return 20; case TRAININGFIELD: return 21; default: return -1; } } public RobotType IntToRobotType(int type){ switch(type) { case 1: return RobotType.AEROSPACELAB; case 2: return RobotType.BARRACKS; case 3: return RobotType.BASHER; case 4: return RobotType.BEAVER; case 5: return RobotType.COMMANDER; case 6: return RobotType.COMPUTER; case 7: return RobotType.DRONE; case 8: return RobotType.HANDWASHSTATION; case 9: return RobotType.HELIPAD; case 10: return RobotType.HQ; case 11: return RobotType.LAUNCHER; case 12: return RobotType.MINER; case 13: return RobotType.MINERFACTORY; case 14: return RobotType.MISSILE; case 15: return RobotType.SOLDIER; case 16: return RobotType.SUPPLYDEPOT; case 17: return RobotType.TANK; case 18: return RobotType.TANKFACTORY; case 19: return RobotType.TECHNOLOGYINSTITUTE; case 20: return RobotType.TOWER; case 21: return RobotType.TRAININGFIELD; default: return null; } } // //Returns a weight representing the 'need' for the RobotType // public double getWeightOfRobotType(RobotType type) throws GameActionException { // int typeInt = RobotTypeToInt(type); // if (smuConstants.desiredNumOf[typeInt] == 0) return 0; // double weight = smuConstants.roundToBuild[typeInt] + // (smuConstants.roundToFinish[typeInt] - smuConstants.roundToBuild[typeInt]) / // smuConstants.desiredNumOf[typeInt] * rc.readBroadcast(smuIndices.freqNum[typeInt]); // return weight; //Returns a weight representing the 'need' for the RobotType public double getWeightOfRobotType(RobotType type) throws GameActionException { int typeInt = RobotTypeToInt(type); int round = Clock.getRoundNum(); double weight; //Return zero if unit is not desired. (Divide by zero protection) if (smuConstants.desiredNumOf[typeInt] == 0) return 0; if (smuConstants.roundToBuild[typeInt] >= smuConstants.roundToFinish[typeInt]) return 0; if (round < smuConstants.roundToBuild[typeInt]) return 0; //The weight is equal to the surface drawn by z = x^(m*y) double x = (double)(round - smuConstants.roundToBuild[typeInt]) / (double) (smuConstants.roundToFinish[typeInt] - smuConstants.roundToBuild[typeInt]); double y = (double)rc.readBroadcast(smuIndices.freqNum[typeInt]) / (double) smuConstants.desiredNumOf[typeInt]; weight = smuConstants.weightScaleMagic * Math.pow(x, (smuConstants.weightExponentMagic + y)); //System.out.println("x: " + x + " y: " + y + " weight: " + weight); return weight; } /** * Simple helpers, more logic for these later */ public RobotInfo[] getEnemiesInAttackRange() { return rc.senseNearbyRobots(myRange, theirTeam); } public void goToLocation(MapLocation location) { try { if (rc.canSenseLocation(location) && rc.senseRobotAtLocation(location) != null && rc.getLocation().distanceSquaredTo(location)<3) { // 3 squares return; } } catch (GameActionException e1) { e1.printStackTrace(); } Direction direction = getMoveDir(location); if (direction != null && rc.isCoreReady()) { try { rc.move(direction); } catch (GameActionException e) { e.printStackTrace(); } } } public RobotInfo[] getRobotsEngagedInAttack() { RobotInfo[] nearbyRobots = rc.senseNearbyRobots(smuConstants.PROTECT_OTHERS_RANGE); boolean hasEnemy = false; boolean hasFriendly = false; for (RobotInfo robot : nearbyRobots) { if(robot.team == theirTeam) { hasEnemy = true; if (hasFriendly) { return nearbyRobots; } } else { hasFriendly = true; if (hasEnemy) { return nearbyRobots; } } } return null; } public RobotInfo[] getTeammatesNearTower(MapLocation towerLocation) { return rc.senseNearbyRobots(towerLocation, RobotType.TOWER.attackRadiusSquared, myTeam); } // Find out if there are any holes between a teams tower and their HQ public MapLocation[] computeHoles() { MapLocation[] towerLocations = rc.senseTowerLocations(); MapLocation[][] towerRadii = new MapLocation[towerLocations.length][]; for(int i = 0; i < towerLocations.length; i++) { // Get all map locations that a tower can attack MapLocation[] locations = MapLocation.getAllMapLocationsWithinRadiusSq(towerLocations[i], RobotType.TOWER.attackRadiusSquared); Arrays.sort(locations); towerRadii[i] = locations; } if(towerRadii.length == 0 || towerRadii[0] == null) { return null; } // Naively say, if overlapping by two towers, there is no path int[] overlapped = new int[towerRadii.length]; int holesBroadcastIndex = smuIndices.TOWER_HOLES_BEGIN; for(int i = 0; i<towerRadii.length; i++) { MapLocation[] locations = towerRadii[i]; boolean coveredLeft = false; boolean coveredRight = false; boolean coveredTop = false; boolean coveredBottom = false; for (int j = 0; j < towerRadii.length; j++) { if (j != i) { MapLocation[] otherLocations = towerRadii[j]; if (locations[0].x <= otherLocations[otherLocations.length-1].x && otherLocations[0].x <= locations[locations.length-1].x && locations[0].y <= otherLocations[otherLocations.length-1].y && otherLocations[0].y <= locations[locations.length-1].y) { overlapped[i]++; Direction otherTowerDir = towerLocations[i].directionTo(towerLocations[j]); if (otherTowerDir.equals(Direction.EAST) || otherTowerDir.equals(Direction.NORTH_EAST) || otherTowerDir.equals(Direction.SOUTH_EAST)) { coveredLeft = true; } if (otherTowerDir.equals(Direction.WEST) || otherTowerDir.equals(Direction.NORTH_WEST) || otherTowerDir.equals(Direction.SOUTH_WEST)) { coveredRight = true; } if (otherTowerDir.equals(Direction.NORTH) || otherTowerDir.equals(Direction.NORTH_EAST) || otherTowerDir.equals(Direction.NORTH_WEST)) { coveredTop = true; } if (otherTowerDir.equals(Direction.SOUTH) || otherTowerDir.equals(Direction.SOUTH_EAST) || otherTowerDir.equals(Direction.SOUTH_WEST)) { coveredBottom = true; } } } } if(overlapped[i]<2 && !rc.isPathable(RobotType.BEAVER, new MapLocation(locations[0].x - 1, locations[0].y))) { overlapped[i]++; coveredLeft = true; } if(overlapped[i]<2 && !rc.isPathable(RobotType.BEAVER, new MapLocation(locations[locations.length-1].x + 1, locations[0].y))) { overlapped[i]++; coveredRight = true; } if(overlapped[i]<2 && !rc.isPathable(RobotType.BEAVER, new MapLocation(locations[0].x, locations[0].y - 1))) { overlapped[i]++; coveredTop = true; } if(overlapped[i]<2 && !rc.isPathable(RobotType.BEAVER, new MapLocation(locations[0].x, locations[locations.length-1].y + 1))) { overlapped[i]++; coveredBottom = true; } //System.out.println("Tower " + i + " overlapped " + overlapped[i] + " " + towerLocations[i]); if (overlapped[i] < 2) { try { int towerAttackRadius = (int) Math.sqrt(RobotType.TOWER.attackRadiusSquared) + 1; if (!coveredLeft) { //System.out.println("Tower " + towerLocations[i] + " Not covered left"); rc.broadcast(holesBroadcastIndex, towerLocations[i].x - towerAttackRadius); rc.broadcast(holesBroadcastIndex + 1, towerLocations[i].y); holesBroadcastIndex+=2; } if (!coveredRight) { //System.out.println("Tower " + towerLocations[i] + " Not covered right"); rc.broadcast(holesBroadcastIndex, towerLocations[i].x + towerAttackRadius); rc.broadcast(holesBroadcastIndex + 1, towerLocations[i].y); holesBroadcastIndex+=2; } if (!coveredTop) { //System.out.println("Tower " + towerLocations[i] + " Not covered top"); rc.broadcast(holesBroadcastIndex, towerLocations[i].x); rc.broadcast(holesBroadcastIndex + 1, towerLocations[i].y - towerAttackRadius); holesBroadcastIndex+=2; } if (!coveredBottom) { //System.out.println("Tower " + towerLocations[i] + " Not covered bottom"); rc.broadcast(holesBroadcastIndex, towerLocations[i].x); rc.broadcast(holesBroadcastIndex + 1, towerLocations[i].y + towerAttackRadius); holesBroadcastIndex+=2; } } catch (GameActionException e) { e.printStackTrace(); } } } // Signify end of holes try { rc.broadcast(holesBroadcastIndex, -1); } catch (GameActionException e) { e.printStackTrace(); } //System.out.println("BYTEEND on " + Clock.getRoundNum() + ": " + Clock.getBytecodeNum()); return null; } } public static class HQ extends BaseBot { public HQ(RobotController rc) { super(rc); computeHoles(); } public boolean checkContainment() throws GameActionException { RobotInfo[] enemyRobotsContaining = rc.senseNearbyRobots(50, theirTeam); if (enemyRobotsContaining.length > 4) { rc.broadcast(smuIndices.HQ_BEING_CONTAINED, smuConstants.CURRENTLY_BEING_CONTAINED); return true; } else { rc.broadcast(smuIndices.HQ_BEING_CONTAINED, smuConstants.NOT_CURRENTLY_BEING_CONTAINED); return false; } } public void setRallyPoint() throws GameActionException { MapLocation rallyPoint = null; boolean beingContained = checkContainment(); if (!beingContained) { if (Clock.getRoundNum() < smuConstants.roundToLaunchAttack) { MapLocation[] ourTowers = rc.senseTowerLocations(); if (ourTowers != null && ourTowers.length > 0) { int closestTower = -1; int closestDistanceToEnemyHQ = Integer.MAX_VALUE; for (int i = 0; i < ourTowers.length; i++) { int currDistanceToEnemyHQ = ourTowers[i].distanceSquaredTo(theirHQ); if (currDistanceToEnemyHQ < closestDistanceToEnemyHQ) { closestDistanceToEnemyHQ = currDistanceToEnemyHQ; closestTower = i; } } rallyPoint = ourTowers[closestTower].add(ourTowers[closestTower].directionTo(theirHQ), 2); } } else { MapLocation[] enemyTowers = rc.senseEnemyTowerLocations(); if (enemyTowers == null || enemyTowers.length <= smuConstants.numTowersRemainingToAttackHQ) { rallyPoint = rc.senseEnemyHQLocation(); } else { rallyPoint = enemyTowers[0]; } } } else { rallyPoint = getSecondBaseLocation(); if (rallyPoint != null) { rallyPoint = rallyPoint.add(rallyPoint.directionTo(theirHQ), 8); } } if (rallyPoint != null) { rc.broadcast(smuIndices.RALLY_POINT_X, rallyPoint.x); rc.broadcast(smuIndices.RALLY_POINT_Y, rallyPoint.y); } } public void execute() throws GameActionException { spawnOptimally(); setRallyPoint(); attackLeastHealthEnemyInRange(); transferSupplies(); rc.yield(); } } //BEAVER public static class Beaver extends BaseBot { public MapLocation secondBase; public Beaver(RobotController rc) { super(rc); Random rand = new Random(rc.getID()); if (rand.nextDouble() < smuConstants.percentBeaversToGoToSecondBase) { secondBase = getSecondBaseLocation(); } } public void execute() throws GameActionException { if (secondBase != null && rc.getLocation().distanceSquaredTo(secondBase) > 6) { goToLocation(secondBase); } buildOptimally(); transferSupplies(); if (Clock.getRoundNum() > 400) defend(); if (rc.isCoreReady()) { //mine if (rc.senseOre(rc.getLocation()) > 0) { rc.mine(); } else { moveOptimally(); } } rc.yield(); } } //MINERFACTORY public static class Minerfactory extends BaseBot { public Minerfactory(RobotController rc) { super(rc); } public void execute() throws GameActionException { transferSupplies(); spawnOptimally(); rc.yield(); } } //MINER public static class Miner extends BaseBot { public Miner(RobotController rc) { super(rc); } public void execute() throws GameActionException { boolean inConvoy = false; if (Clock.getRoundNum()>smuConstants.roundToFormSupplyConvoy && rc.readBroadcast(smuIndices.HQ_BEING_CONTAINED) != smuConstants.CURRENTLY_BEING_CONTAINED) { inConvoy = formSupplyConvoy(); } if (!inConvoy) { if (!defend()) { if (rc.isCoreReady()) { //mine if (rc.senseOre(rc.getLocation()) > 0) { rc.mine(); } else { moveOptimally(); } } } } else if(!defendSelf()) { if (rc.isCoreReady()) { if (rc.senseOre(rc.getLocation()) > 0) { rc.mine(); } } } transferSupplies(); rc.yield(); } } //BARRACKS public static class Barracks extends BaseBot { public Barracks(RobotController rc) { super(rc); } public void execute() throws GameActionException { transferSupplies(); spawnOptimally(); rc.yield(); } } //SOLDIER public static class Soldier extends BaseBot { public Soldier(RobotController rc) { super(rc); } public void execute() throws GameActionException { if (!defend()) { moveToRallyPoint(); } transferSupplies(); rc.yield(); } } //BASHER public static class Basher extends BaseBot { public Basher(RobotController rc) { super(rc); } public void execute() throws GameActionException { boolean hasTakenAction = false; if (Clock.getRoundNum() < smuConstants.roundToLaunchAttack) { hasTakenAction = defendTowerHoles(); if (!hasTakenAction) { hasTakenAction = defendTowers(); } } if (!hasTakenAction) { moveToRallyPoint(); } transferSupplies(); rc.yield(); } } //TANK public static class Tank extends BaseBot { public Tank(RobotController rc) { super(rc); } public void execute() throws GameActionException { if (!defend()) { moveToRallyPoint(); } transferSupplies(); rc.yield(); } } //DRONE public static class Drone extends BaseBot { public Drone(RobotController rc) { super(rc); } public void execute() throws GameActionException { if (!defendSelf()) { if (Clock.getRoundNum() > 1800) { moveToRallyPoint(); } else { contain(); } } transferSupplies(); rc.yield(); } } //TOWER public static class Tower extends BaseBot { public Tower(RobotController rc) { super(rc); } public void execute() throws GameActionException { transferSupplies(); attackLeastHealthEnemyInRange(); rc.yield(); } } //SUPPLYDEPOT public static class Supplydepot extends BaseBot { public Supplydepot(RobotController rc) { super(rc); } public void execute() throws GameActionException { rc.yield(); } } //HANDWASHSTATION public static class Handwashstation extends BaseBot { public Handwashstation(RobotController rc) { super(rc); } public void execute() throws GameActionException { rc.yield(); } } //TANKFACTORY public static class Tankfactory extends BaseBot { public Tankfactory(RobotController rc) { super(rc); } public void execute() throws GameActionException { transferSupplies(); spawnOptimally(); rc.yield(); } } //HELIPAD public static class Helipad extends BaseBot { public Helipad(RobotController rc) { super(rc); } public void execute() throws GameActionException { transferSupplies(); spawnOptimally(); rc.yield(); } } }
package com.microsoft.sqlserver.jdbc.fips; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.security.Provider; import java.security.Security; import java.util.Enumeration; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import com.microsoft.sqlserver.testframework.Utils; /** * Class which will useful for checking if FIPS env. set or not. * @since 6.1.2 */ @RunWith(JUnitPlatform.class) public class FipsEnvTest { protected static Logger logger = Logger.getLogger("FipsEnvTest"); protected static Properties p = null; protected static final String ORACLE_JVM = "ORACLE_JVM"; protected static final String IBM_JVM = "IBM_JVM"; protected static final String SAP_JVM = "SAP_JVM"; protected static String currentJVM = ORACLE_JVM; /** * Before class init method. */ @BeforeAll public static void populateProperties() { p = System.getProperties(); if(p.getProperty("java.vendor").startsWith("IBM")) { currentJVM = IBM_JVM; } //TODO: Need to check this. if(p.getProperty("java.vendor").startsWith("SAP")) { currentJVM = SAP_JVM; } } /** * After stabilizing parameterized test case * TODO: Enable FIPS can be done in two ways. * <LI> JVM Level - Done. * <LI> Program Level - Not Done. * We need to test both on different environments. * @since 6.1.2 */ @Test public void testFIPSOnOracle() throws Exception { assumeTrue(ORACLE_JVM.equals(currentJVM), "Aborting test: As this is not Oracle Env. "); assumeTrue("FIPS".equals(Utils.getConfiguredProperty("FIPS_ENV")), "Aborting test case as FIPS_ENV property is not set. "); assertTrue(isFIPS("SunJSSE"),"FIPS Should be enabled"); //As JDK 1.7 is not supporting lambda for time being commenting. /* assumingThat("NSSFIPS".equals(Utils.getConfiguredProperty("FIPS_ENV")), () -> assertAll("All FIPS", () -> assertTrue(isFIPS("SunJSSE"), "FIPS should be Enabled."), () -> assertTrue(isFIPS("SunPKCS11-NSS"), "Testing"))); assumingThat("BCFIPS".equals(Utils.getConfiguredProperty("FIPS_ENV")), () -> assertAll("All FIPS", () -> assertTrue(isFIPS("SunJSSE"), "FIPS should be Enabled."), () -> assertTrue(isFIPS("BCFIPS"), "Testing"))); assumingThat("FIPS".equals(Utils.getConfiguredProperty("FIPS_ENV")), ()-> assertTrue(isFIPS("SunJSSE"), "FIPS Should be enabled")); */ } /** * It will test FIPS on IBM Env. * If JVM is not IBM test will not fail. It will simply skipped. * @since 6.1.2 */ @Test public void testFIPSOnIBM() throws Exception{ assumeTrue(IBM_JVM.equals(currentJVM), "Aborting test: As this is not IBM Env. "); assumeTrue("FIPS".equals(Utils.getConfiguredProperty("FIPS_ENV")), "Aborting test case as FIPS is not enabled. "); assertTrue(isFIPS("IBMJCEFIP"),"FIPS Should be enabled"); //As JDK 1.7 is not supporting lambda for time being commenting. /* assumingThat("NSSFIPS".equals(Utils.getConfiguredProperty("FIPS_ENV")), () -> assertAll("All FIPS", () -> assertTrue(isFIPS("IBMJCEFIP"), "FIPS should be Enabled."), () -> assertTrue(isFIPS("SunPKCS11-NSS"), "Testing"))); assumingThat("BCFIPS".equals(Utils.getConfiguredProperty("FIPS_ENV")), () -> assertAll("All FIPS", () -> assertTrue(isFIPS("IBMJCEFIPS"), "FIPS should be Enabled."), () -> assertTrue(isFIPS("BCFIPS"), "Testing"))); assumingThat("FIPS".equals(Utils.getConfiguredProperty("FIPS_ENV")), ()-> assertTrue(isFIPS("IBMJCEFIPS"), "FIPS Should be enabled")); */ } /** * In case of FIPs enabled this test method will call {@link #isFIPS(String)} with appropriate FIPS provider. * May be useful only for JDK 1.8 */ @Test @Disabled public void testFIPSEnv() { assumeTrue("FIPS".equals(Utils.getConfiguredProperty("FIPS_ENV")), "Aborting test: This is FIPS Enabled JVM"); //As JDK 1.7 is not supporting lambda for time being commenting. /* assumingThat(System.getProperty("java.vendor").startsWith("IBM"), () -> assertTrue(isFIPS("IBMJCEFIP"), "FIPS should be Enabled.")); assumingThat(System.getProperty("java.vendor").startsWith("Oracle"), () -> assertTrue(isFIPS("SunJSSE"), "FIPS should be Enabled.")); */ } /** * Just simple method to check if JVM is configured for FIPS or not. * CAUTION: We observed that <code>SSLContext.getDefault().getProvider</code> fails because it could not find any algorithm. * @param provider FIPS Provider * @return boolean * @throws Exception */ public static boolean isFIPS(String provider) throws Exception { Provider jsse = Security.getProvider(provider); if (logger.isLoggable(Level.FINE)) { logger.fine(jsse.toString()); logger.fine(jsse.getInfo()); } return jsse != null && jsse.getInfo().contains("FIPS"); } @Test @Disabled public void printJVMInfo() { Enumeration<Object> keys = p.keys(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); String value = (String) p.get(key); if (logger.isLoggable(Level.FINE)) { logger.fine(key + ": " + value); } } } }
package org.neo4j.index.lucene; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import org.neo4j.kernel.impl.transaction.xaframework.LogBuffer; import org.neo4j.kernel.impl.transaction.xaframework.XaCommand; abstract class LuceneCommand extends XaCommand { private final Long nodeId; private final String key; private final String value; private static final byte ADD_COMMAND = (byte) 1; private static final byte REMOVE_COMMAND = (byte) 2; LuceneCommand( Long nodeId, String key, String value ) { this.nodeId = nodeId; this.key = key; this.value = value; } LuceneCommand( CommandData data ) { this.nodeId = data.nodeId; this.key = data.key; this.value = data.value; } public Long getNodeId() { return nodeId; } public String getKey() { return key; } public String getValue() { return value; } @Override public void execute() { // TODO Auto-generated method stub } @Override public void writeToFile( LogBuffer buffer ) throws IOException { buffer.put( getCommandValue() ); buffer.putLong( getNodeId() != null ? getNodeId() : -1L ); char[] keyChars = getKey().toCharArray(); buffer.putInt( keyChars.length ); char[] valueChars = getValue() != null ? getValue().toCharArray() : null; buffer.putInt( valueChars != null ? valueChars.length : -1 ); buffer.put( keyChars ); if ( valueChars != null ) { buffer.put( valueChars ); } } protected abstract byte getCommandValue(); static class AddCommand extends LuceneCommand { AddCommand( Long nodeId, String key, String value ) { super( nodeId, key, value ); } AddCommand( CommandData data ) { super( data ); } @Override protected byte getCommandValue() { return ADD_COMMAND; } } static class RemoveCommand extends LuceneCommand { RemoveCommand( Long nodeId, String key, String value ) { super( nodeId, key, value ); } RemoveCommand( CommandData data ) { super( data ); } @Override protected byte getCommandValue() { return REMOVE_COMMAND; } } private static class CommandData { private final Long nodeId; private final String key; private final String value; CommandData( Long nodeId, String key, String value ) { this.nodeId = nodeId; this.key = key; this.value = value; } } static CommandData readCommandData( ReadableByteChannel channel, ByteBuffer buffer ) throws IOException { buffer.clear(); buffer.limit( 16 ); if ( channel.read( buffer ) != buffer.limit() ) { return null; } buffer.flip(); long nodeId = buffer.getLong(); int keyCharLength = buffer.getInt(); int valueCharLength = buffer.getInt(); char[] keyChars = new char[keyCharLength]; keyChars = readCharArray( channel, buffer, keyChars ); if ( keyChars == null ) { return null; } String key = new String( keyChars ); String value = null; if ( valueCharLength != -1 ) { char[] valueChars = new char[valueCharLength]; valueChars = readCharArray( channel, buffer, valueChars ); value = new String( valueChars ); } return new CommandData( nodeId != -1 ? nodeId : null, key, value ); } private static char[] readCharArray( ReadableByteChannel channel, ByteBuffer buffer, char[] charArray ) throws IOException { buffer.clear(); int charsLeft = charArray.length; int maxSize = buffer.capacity() / 2; int offset = 0; // offset in chars while ( charsLeft > 0 ) { if ( charsLeft > maxSize ) { buffer.limit( maxSize * 2 ); charsLeft -= maxSize; } else { buffer.limit( charsLeft * 2 ); charsLeft = 0; } if ( channel.read( buffer ) != buffer.limit() ) { return null; } buffer.flip(); int length = buffer.limit() / 2; buffer.asCharBuffer().get( charArray, offset, length ); offset += length; buffer.clear(); } return charArray; } static XaCommand readCommand( ReadableByteChannel channel, ByteBuffer buffer ) throws IOException { buffer.clear(); buffer.limit( 1 ); if ( channel.read( buffer ) != buffer.limit() ) { return null; } buffer.flip(); byte commandType = buffer.get(); CommandData data = readCommandData( channel, buffer ); if ( data == null ) { return null; } switch ( commandType ) { case ADD_COMMAND: return new AddCommand( data ); case REMOVE_COMMAND: return new RemoveCommand( data ); default: return null; } } }
package com.pm.server.repository; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.pm.server.TestTemplate; import com.pm.server.datatype.Coordinate; import com.pm.server.datatype.CoordinateImpl; import com.pm.server.player.Pacman; import com.pm.server.player.PacmanImpl; public class PacmanRepositoryTest extends TestTemplate { private List<Pacman> pacmanList = new ArrayList<Pacman>(); private final static Integer numOfPacmans = 2; private static final List<Integer> randomIdList = Arrays.asList( 95873, 30839, 34918 ); private static final List<Coordinate> randomCoordinateList = Arrays.asList( new CoordinateImpl(45983.39872, 98347.39182), new CoordinateImpl(39487.22889, 90893.32281), new CoordinateImpl(49990.12929, 48982.39489) ); @Autowired private PacmanRepository pacmanRepository; private static final Logger log = LogManager.getLogger(PacmanRepositoryTest.class.getName()); @Before public void setUp() { for(Integer i = 0; i < numOfPacmans; i++) { // Arbitrary decimal values Coordinate coordinate = new CoordinateImpl( (i+12345.6789) / 100, (i-9876.54321) / 100 ); Pacman pacman = new PacmanImpl(); pacman.setId(i); pacman.setLocation(coordinate); pacmanList.add(pacman); } assert(pacmanList.size() == numOfPacmans); } @After public void cleanUp() { pacmanRepository.clearPlayers(); assert(pacmanRepository.getPlayer() == null); pacmanList.clear(); assert(pacmanList.size() == 0); } @Test public void unitTest_addPlayer() { // Given Pacman pacman = pacmanList.get(0); // When addPlayer_failUponException(pacman); // Then Pacman pacmanReturned = pacmanRepository.getPlayer(); assertEquals(pacman.getId(), pacmanReturned.getId()); assertEquals(pacman.getLocation(), pacmanReturned.getLocation()); } @Test public void unitTest_addPlayer_noId() { // Given Pacman pacman = pacmanList.get(0); pacman.setId(null); // When addPlayer_failUponException(pacman); // Then Pacman pacman_returned = pacmanRepository.getPlayer(); assertEquals(pacman.getLocation(), pacman_returned.getLocation()); } @Test public void unitTest_addPlayer_noLocation() { // Given Pacman pacman = pacmanList.get(0); pacman.setLocation(null); // When addPlayer_failUponException(pacman); // Then Pacman pacman_returned = pacmanRepository.getPlayer(); assertEquals(pacman.getId(), pacman_returned.getId()); } @Test public void unitTest_addPlayer_nullPlayer() { // Given // When addPlayer_failUponException(null); // Then assertNull(pacmanRepository.getPlayer()); } @Test(expected = IllegalStateException.class) public void unitTest_addPlayer_pacmanAlreadyExists() throws Exception { // Given Pacman pacman1 = pacmanList.get(0); Pacman pacman2 = pacmanList.get(1); addPlayer_failUponException(pacman1); // When pacmanRepository.addPlayer(pacman2); // Then // Exception thrown above } @Test public void unitTest_deletePlayerById() { // Given addPlayer_failUponException(pacmanList.get(0)); Integer randomId = randomIdList.get(0); // When try { pacmanRepository.deletePlayerById(randomId); } catch(Exception e) { log.error(e.getMessage()); fail(); } // Then assertNull(pacmanRepository.getPlayer()); } @Test public void unitTest_deletePlayerById_noId() { // Given addPlayer_failUponException(pacmanList.get(0)); // When try { pacmanRepository.deletePlayerById(null); } catch(Exception e) { log.error(e.getMessage()); fail(); } // Then assertNull(pacmanRepository.getPlayer()); } @Test(expected = IllegalStateException.class) public void unitTest_deletePlayerById_noPlayer() throws Exception { // Given Integer randomId = randomIdList.get(0); // When pacmanRepository.deletePlayerById(randomId); // Then // Exception thrown above } @Test public void unitTest_clearPlayers() { // Given addPlayer_failUponException(pacmanList.get(0)); // When pacmanRepository.clearPlayers(); // Then assertNull(pacmanRepository.getPlayer()); } @Test public void unitTest_clearPlayers_noPlayer() { // Given // When pacmanRepository.clearPlayers(); // Then assertNull(pacmanRepository.getPlayer()); } @Test public void unitTest_numOfPlayers_0players() { // Given // When Integer numOfPlayers = pacmanRepository.numOfPlayers(); // Then assertEquals((Integer)0, numOfPlayers); } @Test public void unitTest_numofPlayers_1player() { // Given addPlayer_failUponException(pacmanList.get(0)); // When Integer numOfPlayers = pacmanRepository.numOfPlayers(); // Then assertEquals((Integer)1, numOfPlayers); } @Test public void unitTest_getPlayerById() { // Given Pacman pacman = pacmanList.get(0); addPlayer_failUponException(pacman); Integer randomId = randomIdList.get(0); // When Pacman pacmanReturned = pacmanRepository.getPlayerById(randomId); // Then assertSame(pacman.getLocation(), pacmanReturned.getLocation()); } @Test public void unitTest_getPlayerById_nullAddedId() { // Given Pacman pacman = pacmanList.get(0); pacman.setId(null); addPlayer_failUponException(pacman); Integer randomId = randomIdList.get(0); // When Pacman pacmanReturned = pacmanRepository.getPlayerById(randomId); // Then assertSame(pacman.getLocation(), pacmanReturned.getLocation()); } @Test public void unitTest_getPlayerById_nullRequestedId() { // Given Pacman pacman = pacmanList.get(0); addPlayer_failUponException(pacman); // When Pacman pacmanReturned = pacmanRepository.getPlayerById(null); // Then assertSame(pacman.getLocation(), pacmanReturned.getLocation()); } @Test public void unitTest_getPlayerById_noPacman() { // Given Integer randomId = randomIdList.get(0); // When Pacman pacmanReturned = pacmanRepository.getPlayerById(randomId); // Then assertNull(pacmanReturned); } @Test public void unitTest_getPlayer() { // Given Pacman pacman = pacmanList.get(0); addPlayer_failUponException(pacman); // When Pacman pacmanReturned = pacmanRepository.getPlayer(); // Then assertEquals(pacman, pacmanReturned); } @Test public void unitTest_getPlayer_noPacman() { // Given // When Pacman pacmanReturned = pacmanRepository.getPlayer(); // Then assertNull(pacmanReturned); } @Test public void unitTest_getAllPlayers() { // Given Pacman pacman = pacmanList.get(0); addPlayer_failUponException(pacman); // When List<Pacman> pacmanReturnedList = pacmanRepository.getAllPlayers(); // Then assertSame(pacman, pacmanReturnedList.get(0)); } @Test public void unitTest_getAllPlayers_noPacman() { // Given // When List<Pacman> pacmanReturnedList = pacmanRepository.getAllPlayers(); // Then assertNull(pacmanReturnedList); } @Test public void unitTest_setPlayerLocationById() { // Given Pacman pacman = pacmanList.get(0); addPlayer_failUponException(pacman); Coordinate newLocation = randomCoordinateList.get(0); // When pacmanRepository.setPlayerLocationById(pacman.getId(), newLocation); // Then Pacman pacmanReturned = pacmanRepository.getPlayer(); assertSame(newLocation, pacmanReturned.getLocation()); } @Test public void unitTest_setPlayerLocationById_randomId() { // Given Pacman pacman = pacmanList.get(0); addPlayer_failUponException(pacman); Integer randomId = randomIdList.get(0); Coordinate newLocation = randomCoordinateList.get(0); // When pacmanRepository.setPlayerLocationById(randomId, newLocation); // Then Pacman pacmanReturned = pacmanRepository.getPlayer(); assertSame(newLocation, pacmanReturned.getLocation()); } @Test public void unitTest_setPlayerLocationById_nullId() { // Given Pacman pacman = pacmanList.get(0); addPlayer_failUponException(pacman); Coordinate newLocation = randomCoordinateList.get(0); // When pacmanRepository.setPlayerLocationById(null, newLocation); // Then Pacman pacmanReturned = pacmanRepository.getPlayer(); assertSame(newLocation, pacmanReturned.getLocation()); } @Test(expected = NullPointerException.class) public void unitTest_setPlayerLocationById_nullLocation() { // Given Integer randomId = randomIdList.get(0); // When pacmanRepository.setPlayerLocationById(randomId, null); // Then // Exception thrown above } @Test(expected = IllegalArgumentException.class) public void unitTest_setPlayerLocationById_noPacman() throws IllegalArgumentException { // Given Integer randomId = randomIdList.get(0); Coordinate newLocation = randomCoordinateList.get(0); // When pacmanRepository.setPlayerLocationById(randomId, newLocation); // Then // Exception thrown above } @Test public void unitTest_setPlayerLocation() { // Given Pacman pacman = pacmanList.get(0); addPlayer_failUponException(pacman); Coordinate newLocation = randomCoordinateList.get(0); // When pacmanRepository.setPlayerLocation(newLocation); // Then Pacman pacmanReturned = pacmanRepository.getPlayer(); assertSame(newLocation, pacmanReturned.getLocation()); } @Test(expected = NullPointerException.class) public void unitTest_setPlayerLocation_nullLocation() { // Given // When pacmanRepository.setPlayerLocation(null); // Then // Exception thrown above } @Test(expected = IllegalArgumentException.class) public void unitTest_setPlayerLocation_noPacman() throws IllegalArgumentException { // Given Coordinate newLocation = randomCoordinateList.get(0); // When pacmanRepository.setPlayerLocation(newLocation); // Then // Exception thrown above } private void addPlayer_failUponException(Pacman pacman) { try { pacmanRepository.addPlayer(pacman); } catch (Exception e) { log.error(e.getMessage()); fail(); } } }
package org.openforis.users.dao; import static org.openforis.users.jooq.tables.OfUserGroup.OF_USER_GROUP; import org.jooq.Configuration; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.TransactionalRunnable; import org.jooq.impl.DSL; import org.openforis.users.jooq.tables.daos.OfUserGroupDao; import org.openforis.users.model.UserGroup; import org.openforis.users.model.UserGroup.UserGroupRequestStatus; import org.openforis.users.model.UserGroup.UserGroupRole; /** * * @author S. Ricci * */ public class UserGroupDao extends OfUserGroupDao { public UserGroupDao(Configuration configuration) { super(configuration); } public void insert(UserGroup userGroup) { Record record = dsl().newRecord(OF_USER_GROUP, userGroup); runInTransaction(new Runnable() { public void run() { dsl().insertInto(OF_USER_GROUP).set(record).execute(); } }); } public UserGroup findById(long groupId, long userId) { UserGroup userGroup = dsl().selectFrom(OF_USER_GROUP) .where(OF_USER_GROUP.GROUP_ID.eq(groupId) .and(OF_USER_GROUP.USER_ID.eq(userId))) .fetchOneInto(UserGroup.class); return userGroup; } public void deleteByGroupIdAndUserId(long groupId, long userId) { runInTransaction(new Runnable() { public void run() { dsl().deleteFrom(OF_USER_GROUP) .where(OF_USER_GROUP.GROUP_ID.eq(groupId)) .and(OF_USER_GROUP.USER_ID.eq(userId)).execute(); } }); } public void editByGroupIdAndUserId(long groupId, long userId, UserGroupRole role, UserGroupRequestStatus status) { runInTransaction(new Runnable() { public void run() { dsl().update(OF_USER_GROUP) .set(OF_USER_GROUP.STATUS_CODE, status.getCode()) .set(OF_USER_GROUP.ROLE_CODE, role.getCode()) .where(OF_USER_GROUP.GROUP_ID.eq(groupId) .and(OF_USER_GROUP.USER_ID.eq(userId))) .execute(); } }); } public UserGroup fetchByGroupIdAndUserId(long groupId, long userId) { UserGroup result = dsl().selectFrom(OF_USER_GROUP) .where(OF_USER_GROUP.GROUP_ID.eq(groupId) .and(OF_USER_GROUP.USER_ID.eq(userId))) .fetchOneInto(UserGroup.class); return result; } protected void runInTransaction(Runnable runnable) { dsl().transaction(new TransactionalRunnable() { public void run(Configuration configuration) throws Exception { runnable.run(); } }); } private DSLContext dsl() { return DSL.using(configuration()); } }
package com.yahoo.sketches.quantiles; import static com.yahoo.sketches.quantiles.PreambleUtil.*; import static org.testng.Assert.*; import com.yahoo.sketches.quantiles.QuantilesSketch; import org.testng.annotations.Test; public class PreambleUtilTest { @Test public void checkExtracts() { long along = 0XFFL; assertEquals(extractPreLongs(along), (int) along); along = 3L << 8; assertEquals(extractSerVer(along), 3); along = 7L << 16; assertEquals(extractFamilyID(along), 7); along = 0XFFL << 24; assertEquals(extractFlags(along), 0XFF); along = -1L << 32; assertEquals(extractK(along), -1); along = 0XFFFFFFFFL; assertEquals(extractBufAlloc(along), -1); } @Test public void checkInserts() { long v; int shift; v = 0XFFL; shift = 0; assertEquals(insertPreLongs((int)v, ~(v<<shift)), -1L); assertEquals(insertPreLongs((int)v, 0), v<<shift); v = 0XFFL; shift = 8; assertEquals(insertSerVer((int)v, ~(v<<shift)), -1L); assertEquals(insertSerVer((int)v, 0), v<<shift); v = 0XFFL; shift = 16; assertEquals(insertFamilyID((int)v, ~(v<<shift)), -1L); assertEquals(insertFamilyID((int)v, 0), v<<shift); v = 0XFFL; shift = 24; assertEquals(insertFlags((int)v, ~(v<<shift)), -1L); assertEquals(insertFlags((int)v, 0), v<<shift); v = -1L; shift = 32; assertEquals(insertK((int)v, ~(v<<shift)), -1L); assertEquals(insertK((int)v, 0), v<<shift); v = 0XFFFFFFFFL; shift = 0; assertEquals(insertBufAlloc((int)v, ~(v<<shift)), -1L); assertEquals(insertBufAlloc((int)v, 0), v<<shift); } @Test public void checkToString() { int k = 227; int n = 1000000; QuantilesSketch qs = QuantilesSketch.builder().build(k); for (int i=0; i<n; i++) qs.update(i); byte[] byteArr = qs.toByteArray(); println(PreambleUtil.toString(byteArr)); } @Test public void checkToStringEmpty() { int k = 227; QuantilesSketch qs = QuantilesSketch.builder().build(k); byte[] byteArr = qs.toByteArray(); println(PreambleUtil.toString(byteArr)); } @Test public void printlnTest() { println("PRINTING: "+this.getClass().getName()); } /** * @param s value to print */ static void println(String s) { //System.out.println(s); //disable here } }
package mho.wheels.iterables; import mho.wheels.ordering.Ordering; import mho.wheels.random.IsaacPRNG; import mho.wheels.structures.Pair; import mho.wheels.structures.Triple; import org.jetbrains.annotations.NotNull; import org.junit.Test; import java.math.BigInteger; import java.math.RoundingMode; import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; import java.util.function.Supplier; import static mho.wheels.iterables.IterableUtils.*; import static mho.wheels.ordering.Ordering.*; import static mho.wheels.testing.Testing.*; import static org.junit.Assert.*; @SuppressWarnings("ConstantConditions") public class RandomProviderProperties { private static final String RANDOM_PROVIDER_CHARS = " ,-0123456789@PR[]adeimnorv"; private static final int TINY_LIMIT = 20; private static int LIMIT; private static IterableProvider P; private static void initialize(String name) { P.reset(); System.out.println("\t\ttesting " + name + " properties..."); } @Test public void testAllProperties() { List<Triple<IterableProvider, Integer, String>> configs = new ArrayList<>(); configs.add(new Triple<>(ExhaustiveProvider.INSTANCE, 10000, "exhaustively")); configs.add(new Triple<>(RandomProvider.example(), 1000, "randomly")); System.out.println("RandomProvider properties"); for (Triple<IterableProvider, Integer, String> config : configs) { P = config.a; LIMIT = config.b; System.out.println("\ttesting " + config.c); propertiesConstructor(); propertiesConstructor_List_Integer(); propertiesGetScale(); propertiesGetSecondaryScale(); propertiesGetSeed(); propertiesWithScale(); propertiesWithSecondaryScale(); propertiesCopy(); propertiesDeepCopy(); propertiesReset(); propertiesGetId(); propertiesNextInt(); propertiesIntegers(); propertiesNextLong(); propertiesLongs(); propertiesBooleans(); propertiesNextBoolean(); propertiesNextUniformSample_Iterable(); propertiesUniformSample_Iterable(); propertiesNextUniformSample_String(); propertiesUniformSample_String(); propertiesNextOrdering(); propertiesOrderings(); propertiesNextRoundingMode(); propertiesRoundingModes(); propertiesNextPositiveByte(); propertiesPositiveBytes(); propertiesNextPositiveShort(); propertiesPositiveShorts(); propertiesNextPositiveInt(); propertiesPositiveIntegers(); propertiesNextPositiveLong(); propertiesPositiveLongs(); propertiesNextNegativeByte(); propertiesNegativeBytes(); propertiesNextNegativeShort(); propertiesNegativeShorts(); propertiesNextNegativeInt(); propertiesNegativeIntegers(); propertiesNextNegativeLong(); propertiesNegativeLongs(); propertiesNextNaturalByte(); propertiesNaturalBytes(); propertiesNextNaturalShort(); propertiesNaturalShorts(); propertiesNextNaturalInt(); propertiesNaturalIntegers(); propertiesNextNaturalLong(); propertiesNaturalLongs(); propertiesNonzeroBytes(); propertiesNonzeroShorts(); propertiesNonzeroIntegers(); propertiesNonzeroLongs(); propertiesBytes(); propertiesShorts(); propertiesAsciiCharacters(); propertiesCharacters(); propertiesRangeUp_byte(); propertiesRangeUp_short(); propertiesRangeUp_int(); propertiesRangeUp_long(); propertiesRangeUp_char(); propertiesRangeDown_byte(); propertiesRangeDown_short(); propertiesRangeDown_int(); propertiesRangeDown_long(); propertiesRangeDown_char(); propertiesRange_byte_byte(); propertiesRange_short_short(); propertiesRange_int_int(); propertiesRange_long_long(); propertiesRange_BigInteger_BigInteger(); propertiesRange_char_char(); propertiesPositiveIntegersGeometric(); propertiesNegativeIntegersGeometric(); propertiesNaturalIntegersGeometric(); propertiesNonzeroIntegersGeometric(); propertiesIntegersGeometric(); propertiesRangeUpGeometric(); propertiesRangeDownGeometric(); propertiesPositiveBigIntegers(); propertiesNegativeBigIntegers(); propertiesNaturalBigIntegers(); propertiesNonzeroBigIntegers(); propertiesBigIntegers(); propertiesEquals(); propertiesHashCode(); propertiesToString(); } System.out.println("Done"); } private static void propertiesConstructor() { initialize("RandomProvider()"); for (Void v : take(LIMIT, repeat((Void) null))) { RandomProvider rp = new RandomProvider(); rp.validate(); } } private static void propertiesConstructor_List_Integer() { initialize("RandomProvider(List<Integer>)"); for (List<Integer> is : take(LIMIT, P.lists(IsaacPRNG.SIZE, P.integers()))) { RandomProvider rp = new RandomProvider(is); rp.validate(); assertEquals(is.toString(), rp.getScale(), 32); assertEquals(is.toString(), rp.getSecondaryScale(), 8); } for (List<Integer> is : take(LIMIT, filter(js -> js.size() != IsaacPRNG.SIZE, P.lists(P.integers())))) { try { new RandomProvider(is); fail(is.toString()); } catch (IllegalArgumentException ignored) {} } } private static void propertiesGetScale() { initialize("getScale()"); for (RandomProvider rp : take(LIMIT, P.randomProviders())) { int scale = rp.getScale(); assertEquals(rp.toString(), rp.withScale(scale), rp); } } private static void propertiesGetSecondaryScale() { initialize("getSecondaryScale()"); for (RandomProvider rp : take(LIMIT, P.randomProviders())) { int secondaryScale = rp.getSecondaryScale(); assertEquals(rp.toString(), rp.withSecondaryScale(secondaryScale), rp); } } private static void propertiesGetSeed() { initialize("getSeed()"); for (RandomProvider rp : take(LIMIT, P.randomProviders())) { List<Integer> seed = rp.getSeed(); assertEquals(rp.toString(), seed.size(), IsaacPRNG.SIZE); assertEquals( rp.toString(), new RandomProvider(seed).withScale(rp.getScale()).withSecondaryScale(rp.getSecondaryScale()), rp ); } } private static void propertiesWithScale() { initialize("withScale(int)"); for (Pair<RandomProvider, Integer> p : take(LIMIT, P.pairs(P.randomProviders(), P.naturalIntegers()))) { RandomProvider rp = p.a.withScale(p.b); rp.validate(); assertEquals(p.toString(), rp.getScale(), p.b.intValue()); assertEquals(p.toString(), rp.getSecondaryScale(), p.a.getSecondaryScale()); assertEquals(p.toString(), rp.getSeed(), p.a.getSeed()); inverses(x -> x.withScale(p.b), (RandomProvider y) -> y.withScale(p.a.getScale()), p.a); } for (RandomProvider rp : take(LIMIT, P.randomProviders())) { idempotent(x -> x.withScale(rp.getScale()), rp); } } private static void propertiesWithSecondaryScale() { initialize("withSecondaryScale(int)"); for (Pair<RandomProvider, Integer> p : take(LIMIT, P.pairs(P.randomProviders(), P.naturalIntegers()))) { RandomProvider rp = p.a.withSecondaryScale(p.b); rp.validate(); assertEquals(p.toString(), rp.getScale(), p.a.getScale()); assertEquals(p.toString(), rp.getSecondaryScale(), p.b.intValue()); assertEquals(p.toString(), rp.getSeed(), p.a.getSeed()); inverses( x -> x.withSecondaryScale(p.b), (RandomProvider y) -> y.withSecondaryScale(p.a.getSecondaryScale()), p.a ); } for (RandomProvider rp : take(LIMIT, P.randomProviders())) { idempotent(x -> x.withSecondaryScale(rp.getSecondaryScale()), rp); } } private static void propertiesCopy() { initialize("copy()"); for (RandomProvider rp : take(LIMIT, P.randomProviders())) { RandomProvider copy = rp.copy(); assertEquals(rp.toString(), rp, copy); rp.nextInt(); assertEquals(rp.toString(), rp, copy); } } private static void propertiesDeepCopy() { initialize("deepCopy()"); for (RandomProvider rp : take(LIMIT, P.randomProviders())) { RandomProvider copy = rp.deepCopy(); assertEquals(rp.toString(), rp, copy); rp.nextInt(); assertNotEquals(rp.toString(), rp, copy); } } private static void propertiesReset() { initialize("reset()"); for (RandomProvider rp : take(LIMIT, P.randomProviders())) { RandomProvider original = rp.deepCopy(); rp.nextInt(); assertNotEquals(rp, original); rp.reset(); assertEquals(rp, original); } } private static void propertiesGetId() { initialize("getId()"); for (RandomProvider rp : take(LIMIT, P.randomProviders())) { rp.getId(); } } private static <T> void supplierEquivalence( @NotNull RandomProvider rp, @NotNull Iterable<T> xs, @NotNull Supplier<T> s ) { rp.reset(); List<T> iterableSample = toList(take(TINY_LIMIT, xs)); rp.reset(); List<T> supplierSample = toList(take(TINY_LIMIT, fromSupplier(s))); aeqit(rp.toString(), iterableSample, supplierSample); } private static <T> void simpleTestWithNulls( @NotNull RandomProvider rp, @NotNull Iterable<T> xs, @NotNull Predicate<T> predicate ) { rp.reset(); assertTrue(rp.toString(), all(predicate, take(TINY_LIMIT, xs))); rp.reset(); testNoRemove(TINY_LIMIT, xs); } private static <T> void simpleTest( @NotNull RandomProvider rp, @NotNull Iterable<T> xs, @NotNull Predicate<T> predicate ) { simpleTestWithNulls(rp, xs, x -> x != null && predicate.test(x)); } private static void propertiesNextInt() { initialize("nextInt()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { rp.nextInt(); } } private static void propertiesIntegers() { initialize("integers()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Integer> is = rp.integers(); simpleTest(rp, is, i -> true); supplierEquivalence(rp, is, rp::nextInt); } } private static void propertiesNextLong() { initialize("nextLong()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { rp.nextLong(); } } private static void propertiesLongs() { initialize("longs()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Long> ls = rp.longs(); simpleTest(rp, ls, l -> true); supplierEquivalence(rp, ls, rp::nextLong); } } private static void propertiesNextBoolean() { initialize("nextBoolean()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { rp.nextBoolean(); } } private static void propertiesBooleans() { initialize("booleans()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Boolean> bs = rp.booleans(); simpleTest(rp, bs, b -> true); supplierEquivalence(rp, bs, rp::nextBoolean); for (boolean b : ExhaustiveProvider.INSTANCE.booleans()) { rp.reset(); assertTrue(rp.toString(), elem(b, bs)); } } } private static void propertiesNextUniformSample_Iterable() { initialize("nextUniformSample(Iterable<T>)"); Iterable<Pair<RandomProvider, List<Integer>>> ps = P.pairs( P.randomProvidersDefault(), P.listsAtLeast(1, P.withNull(P.integers())) ); for (Pair<RandomProvider, List<Integer>> p : take(LIMIT, ps)) { assertTrue(p.toString(), p.b.contains(p.a.nextUniformSample(p.b))); } } private static void propertiesUniformSample_Iterable() { initialize("uniformSample(Iterable<T>)"); Iterable<Pair<RandomProvider, List<Integer>>> ps = P.pairs( P.randomProvidersDefault(), P.lists(P.withNull(P.integers())) ); for (Pair<RandomProvider, List<Integer>> p : take(LIMIT, ps)) { Iterable<Integer> is = p.a.uniformSample(p.b); simpleTestWithNulls(p.a, is, p.b::contains); if (!p.b.isEmpty()) { supplierEquivalence(p.a, is, () -> p.a.nextUniformSample(p.b)); } p.a.reset(); assertEquals(is.toString(), isEmpty(is), p.b.isEmpty()); } } private static void propertiesNextUniformSample_String() { initialize("nextUniformSample(String)"); for (Pair<RandomProvider, String> p : take(LIMIT, P.pairs(P.randomProvidersDefault(), P.stringsAtLeast(1)))) { assertTrue(p.toString(), elem(p.a.nextUniformSample(p.b), p.b)); } } private static void propertiesUniformSample_String() { initialize("uniformSample(String)"); for (Pair<RandomProvider, String> p : take(LIMIT, P.pairs(P.randomProvidersDefault(), P.strings()))) { Iterable<Character> cs = p.a.uniformSample(p.b); simpleTest(p.a, cs, c -> elem(c, cs)); if (!p.b.isEmpty()) { supplierEquivalence(p.a, cs, () -> p.a.nextUniformSample(p.b)); } p.a.reset(); assertEquals(cs.toString(), isEmpty(cs), p.b.isEmpty()); } } private static void propertiesNextOrdering() { initialize("nextOrdering()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { rp.nextOrdering(); } } private static void propertiesOrderings() { initialize("orderings()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Ordering> os = rp.orderings(); simpleTest(rp, os, o -> true); supplierEquivalence(rp, os, rp::nextOrdering); for (Ordering o : ExhaustiveProvider.INSTANCE.orderings()) { rp.reset(); assertTrue(rp.toString(), elem(o, os)); } } } private static void propertiesNextRoundingMode() { initialize("nextBoolean()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { rp.nextRoundingMode(); } } private static void propertiesRoundingModes() { initialize("roundingModes()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<RoundingMode> rms = rp.roundingModes(); simpleTest(rp, rms, rm -> true); supplierEquivalence(rp, rms, rp::nextRoundingMode); for (RoundingMode rm : ExhaustiveProvider.INSTANCE.roundingModes()) { rp.reset(); assertTrue(rp.toString(), elem(rm, rms)); } } } private static void propertiesNextPositiveByte() { initialize("nextPositiveByte()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { rp.nextPositiveByte(); } } private static void propertiesPositiveBytes() { initialize("positiveBytes()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Byte> bs = rp.positiveBytes(); simpleTest(rp, bs, b -> b > 0); supplierEquivalence(rp, bs, rp::nextPositiveByte); } } private static void propertiesNextPositiveShort() { initialize("nextPositiveShort()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { rp.nextPositiveShort(); } } private static void propertiesPositiveShorts() { initialize("positiveShorts()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Short> ss = rp.positiveShorts(); simpleTest(rp, ss, s -> s > 0); supplierEquivalence(rp, ss, rp::nextPositiveShort); } } private static void propertiesNextPositiveInt() { initialize("nextPositiveInt()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { rp.nextPositiveInt(); } } private static void propertiesPositiveIntegers() { initialize("positiveIntegers()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Integer> is = rp.positiveIntegers(); simpleTest(rp, is, i -> i > 0); supplierEquivalence(rp, is, rp::nextPositiveInt); } } private static void propertiesNextPositiveLong() { initialize("nextPositiveLong()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { rp.nextPositiveLong(); } } private static void propertiesPositiveLongs() { initialize("positiveLongs()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Long> ls = rp.positiveLongs(); simpleTest(rp, ls, l -> l > 0); supplierEquivalence(rp, ls, rp::nextPositiveLong); } } private static void propertiesNextNegativeByte() { initialize("nextNegativeByte()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { rp.nextNegativeByte(); } } private static void propertiesNegativeBytes() { initialize("negativeBytes()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Byte> bs = rp.negativeBytes(); simpleTest(rp, bs, b -> b < 0); supplierEquivalence(rp, bs, rp::nextNegativeByte); } } private static void propertiesNextNegativeShort() { initialize("nextNegativeShort()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { rp.nextNegativeShort(); } } private static void propertiesNegativeShorts() { initialize("negativeShorts()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Short> ss = rp.negativeShorts(); simpleTest(rp, ss, s -> s < 0); supplierEquivalence(rp, ss, rp::nextNegativeShort); } } private static void propertiesNextNegativeInt() { initialize("nextNegativeInt()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { rp.nextNegativeInt(); } } private static void propertiesNegativeIntegers() { initialize("negativeIntegers()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Integer> is = rp.negativeIntegers(); simpleTest(rp, is, i -> i < 0); supplierEquivalence(rp, is, rp::nextNegativeInt); } } private static void propertiesNextNegativeLong() { initialize("nextNegativeLong()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { rp.nextNegativeLong(); } } private static void propertiesNegativeLongs() { initialize("negativeLongs()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Long> ls = rp.negativeLongs(); simpleTest(rp, ls, l -> l < 0); supplierEquivalence(rp, ls, rp::nextNegativeLong); } } private static void propertiesNextNaturalByte() { initialize("nextNaturalByte()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { rp.nextNaturalByte(); } } private static void propertiesNaturalBytes() { initialize("naturalBytes()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Byte> bs = rp.naturalBytes(); simpleTest(rp, bs, b -> b >= 0); supplierEquivalence(rp, bs, rp::nextNaturalByte); } } private static void propertiesNextNaturalShort() { initialize("nextNaturalShort()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { rp.nextNaturalShort(); } } private static void propertiesNaturalShorts() { initialize("naturalShorts()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Short> ss = rp.naturalShorts(); simpleTest(rp, ss, s -> s >= 0); supplierEquivalence(rp, ss, rp::nextNaturalShort); } } private static void propertiesNextNaturalInt() { initialize("nextNaturalInt()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { rp.nextNaturalInt(); } } private static void propertiesNaturalIntegers() { initialize("naturalIntegers()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Integer> is = rp.naturalIntegers(); simpleTest(rp, is, i -> i >= 0); supplierEquivalence(rp, is, rp::nextNaturalInt); } } private static void propertiesNextNaturalLong() { initialize("nextNaturalLong()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { rp.nextNaturalLong(); } } private static void propertiesNaturalLongs() { initialize("naturalLongs()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Long> ls = rp.naturalLongs(); simpleTest(rp, ls, l -> l >= 0); supplierEquivalence(rp, ls, rp::nextNaturalLong); } } private static void propertiesNonzeroBytes() { initialize("nonzeroBytes()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Byte> bs = rp.nonzeroBytes(); Iterable<Byte> tbs = take(TINY_LIMIT, bs); assertTrue(rp.toString(), all(b -> b != null, tbs)); assertTrue(rp.toString(), all(b -> b != 0, tbs)); testNoRemove(TINY_LIMIT, bs); } } private static void propertiesNonzeroShorts() { initialize("nonzeroShorts()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Short> ss = rp.nonzeroShorts(); Iterable<Short> tss = take(TINY_LIMIT, ss); assertTrue(rp.toString(), all(s -> s != null, tss)); assertTrue(rp.toString(), all(s -> s != 0, tss)); testNoRemove(TINY_LIMIT, ss); } } private static void propertiesNonzeroIntegers() { initialize("nonzeroIntegers()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Integer> is = rp.nonzeroIntegers(); Iterable<Integer> tis = take(TINY_LIMIT, is); assertTrue(rp.toString(), all(i -> i != null, tis)); assertTrue(rp.toString(), all(i -> i != 0, tis)); testNoRemove(TINY_LIMIT, is); } } private static void propertiesNonzeroLongs() { initialize("nonzeroLongs()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Long> ls = rp.nonzeroLongs(); Iterable<Long> tls = take(TINY_LIMIT, ls); assertTrue(rp.toString(), all(l -> l != null, tls)); assertTrue(rp.toString(), all(l -> l != 0, tls)); testNoRemove(TINY_LIMIT, ls); } } private static void propertiesBytes() { initialize("bytes()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Byte> bs = rp.bytes(); Iterable<Byte> tbs = take(TINY_LIMIT, bs); assertTrue(rp.toString(), all(b -> b != null, tbs)); testNoRemove(TINY_LIMIT, bs); } } private static void propertiesShorts() { initialize("shorts()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Short> ss = rp.shorts(); Iterable<Short> tss = take(TINY_LIMIT, ss); assertTrue(rp.toString(), all(s -> s != null, tss)); testNoRemove(TINY_LIMIT, ss); } } private static void propertiesAsciiCharacters() { initialize("asciiCharacters()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Character> cs = rp.asciiCharacters(); Iterable<Character> tcs = take(TINY_LIMIT, cs); assertTrue(rp.toString(), all(c -> c != null, tcs)); assertTrue(rp.toString(), all(c -> c < 128, tcs)); testNoRemove(TINY_LIMIT, cs); } } private static void propertiesCharacters() { initialize("characters()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Character> cs = rp.characters(); assertTrue(rp.toString(), all(c -> c != null, take(TINY_LIMIT, cs))); testNoRemove(TINY_LIMIT, cs); } } private static void propertiesRangeUp_byte() { initialize("testing rangeUp(byte)"); for (Pair<RandomProvider, Byte> p : take(LIMIT, P.pairs(P.randomProvidersDefault(), P.bytes()))) { Iterable<Byte> bs = p.a.rangeUp(p.b); Iterable<Byte> tbs = take(TINY_LIMIT, bs); assertTrue(p.toString(), all(b -> b != null, tbs)); testNoRemove(TINY_LIMIT, bs); assertTrue(p.toString(), all(b -> b >= p.b, tbs)); } for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { aeqit(rp.toString(), TINY_LIMIT, rp.rangeUp(Byte.MAX_VALUE), repeat(Byte.MAX_VALUE)); } } private static void propertiesRangeUp_short() { initialize("rangeUp(short)"); for (Pair<RandomProvider, Short> p : take(LIMIT, P.pairs(P.randomProvidersDefault(), P.shorts()))) { Iterable<Short> ss = p.a.rangeUp(p.b); Iterable<Short> tss = take(TINY_LIMIT, ss); assertTrue(p.toString(), all(s -> s != null, tss)); testNoRemove(TINY_LIMIT, ss); assertTrue(p.toString(), all(s -> s >= p.b, tss)); } for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { aeqit(rp.toString(), TINY_LIMIT, rp.rangeUp(Short.MAX_VALUE), repeat(Short.MAX_VALUE)); } } private static void propertiesRangeUp_int() { initialize("rangeUp(int)"); for (Pair<RandomProvider, Integer> p : take(LIMIT, P.pairs(P.randomProvidersDefault(), P.integers()))) { Iterable<Integer> is = p.a.rangeUp(p.b); Iterable<Integer> tis = take(TINY_LIMIT, is); assertTrue(p.toString(), all(i -> i != null, tis)); testNoRemove(TINY_LIMIT, is); assertTrue(p.toString(), all(i -> i >= p.b, tis)); } for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { aeqit(rp.toString(), TINY_LIMIT, rp.rangeUp(Integer.MAX_VALUE), repeat(Integer.MAX_VALUE)); } } private static void propertiesRangeUp_long() { initialize("rangeUp(long)"); for (Pair<RandomProvider, Long> p : take(LIMIT, P.pairs(P.randomProvidersDefault(), P.longs()))) { Iterable<Long> ls = p.a.rangeUp(p.b); Iterable<Long> tls = take(TINY_LIMIT, ls); assertTrue(p.toString(), all(l -> l != null, tls)); testNoRemove(TINY_LIMIT, ls); assertTrue(p.toString(), all(l -> l >= p.b, tls)); } for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { aeqit(rp.toString(), TINY_LIMIT, rp.rangeUp(Long.MAX_VALUE), repeat(Long.MAX_VALUE)); } } private static void propertiesRangeUp_char() { initialize("rangeUp(char)"); Iterable<Pair<RandomProvider, Character>> ps = P.pairs(P.randomProvidersDefault(), P.characters()); for (Pair<RandomProvider, Character> p : take(LIMIT, ps)) { Iterable<Character> cs = p.a.rangeUp(p.b); Iterable<Character> tcs = take(TINY_LIMIT, cs); assertTrue(p.toString(), all(b -> b != null, tcs)); testNoRemove(TINY_LIMIT, cs); assertTrue(p.toString(), all(b -> b >= p.b, tcs)); } for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { aeqit(rp.toString(), TINY_LIMIT, rp.rangeUp(Character.MAX_VALUE), repeat(Character.MAX_VALUE)); } } private static void propertiesRangeDown_byte() { initialize("rangeDown(byte)"); for (Pair<RandomProvider, Byte> p : take(LIMIT, P.pairs(P.randomProvidersDefault(), P.bytes()))) { Iterable<Byte> bs = p.a.rangeDown(p.b); Iterable<Byte> tbs = take(TINY_LIMIT, bs); assertTrue(p.toString(), all(b -> b != null, tbs)); testNoRemove(TINY_LIMIT, bs); assertTrue(p.toString(), all(b -> b <= p.b, tbs)); } for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { aeqit(rp.toString(), TINY_LIMIT, rp.rangeDown(Byte.MIN_VALUE), repeat(Byte.MIN_VALUE)); } } private static void propertiesRangeDown_short() { initialize("rangeDown(short)"); for (Pair<RandomProvider, Short> p : take(LIMIT, P.pairs(P.randomProvidersDefault(), P.shorts()))) { Iterable<Short> ss = p.a.rangeDown(p.b); Iterable<Short> tss = take(TINY_LIMIT, ss); assertTrue(p.toString(), all(s -> s != null, tss)); testNoRemove(TINY_LIMIT, ss); assertTrue(p.toString(), all(s -> s <= p.b, tss)); } for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { aeqit(rp.toString(), TINY_LIMIT, rp.rangeDown(Short.MIN_VALUE), repeat(Short.MIN_VALUE)); } } private static void propertiesRangeDown_int() { initialize("rangeDown(int)"); for (Pair<RandomProvider, Integer> p : take(LIMIT, P.pairs(P.randomProvidersDefault(), P.integers()))) { Iterable<Integer> is = p.a.rangeDown(p.b); Iterable<Integer> tis = take(TINY_LIMIT, is); assertTrue(p.toString(), all(i -> i != null, tis)); testNoRemove(TINY_LIMIT, is); assertTrue(p.toString(), all(i -> i <= p.b, tis)); } for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { aeqit(rp.toString(), TINY_LIMIT, rp.rangeDown(Integer.MIN_VALUE), repeat(Integer.MIN_VALUE)); } } private static void propertiesRangeDown_long() { initialize("rangeDown(long)"); for (Pair<RandomProvider, Long> p : take(LIMIT, P.pairs(P.randomProvidersDefault(), P.longs()))) { Iterable<Long> ls = p.a.rangeDown(p.b); Iterable<Long> tls = take(TINY_LIMIT, ls); assertTrue(p.toString(), all(l -> l != null, tls)); testNoRemove(TINY_LIMIT, ls); assertTrue(p.toString(), all(l -> l <= p.b, tls)); } for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { aeqit(rp.toString(), TINY_LIMIT, rp.rangeDown(Long.MIN_VALUE), repeat(Long.MIN_VALUE)); } } private static void propertiesRangeDown_char() { initialize("rangeDown(char)"); Iterable<Pair<RandomProvider, Character>> ps = P.pairs(P.randomProvidersDefault(), P.characters()); for (Pair<RandomProvider, Character> p : take(LIMIT, ps)) { Iterable<Character> cs = p.a.rangeDown(p.b); Iterable<Character> tcs = take(TINY_LIMIT, cs); assertTrue(p.toString(), all(b -> b != null, tcs)); testNoRemove(TINY_LIMIT, cs); assertTrue(p.toString(), all(b -> b <= p.b, tcs)); } for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { aeqit(rp.toString(), TINY_LIMIT, rp.rangeDown(Character.MIN_VALUE), repeat(Character.MIN_VALUE)); } } private static void propertiesRange_byte_byte() { initialize("range(byte, byte)"); Iterable<Triple<RandomProvider, Byte, Byte>> ts = P.triples(P.randomProvidersDefault(), P.bytes(), P.bytes()); for (Triple<RandomProvider, Byte, Byte> p : take(LIMIT, ts)) { Iterable<Byte> bs = p.a.range(p.b, p.c); Iterable<Byte> tbs = take(TINY_LIMIT, bs); assertTrue(p.toString(), all(b -> b != null, tbs)); testNoRemove(TINY_LIMIT, bs); assertTrue(p.toString(), all(b -> b >= p.b && b <= p.c, tbs)); assertEquals(p.toString(), p.b > p.c, isEmpty(bs)); } for (Pair<RandomProvider, Byte> p : take(LIMIT, P.pairs(P.randomProvidersDefault(), P.bytes()))) { aeqit(p.toString(), TINY_LIMIT, p.a.range(p.b, p.b), repeat(p.b)); } } private static void propertiesRange_short_short() { initialize("range(short, short)"); Iterable<Triple<RandomProvider, Short, Short>> ts = P.triples( P.randomProvidersDefault(), P.shorts(), P.shorts() ); for (Triple<RandomProvider, Short, Short> p : take(LIMIT, ts)) { Iterable<Short> ss = p.a.range(p.b, p.c); Iterable<Short> tss = take(TINY_LIMIT, ss); assertTrue(p.toString(), all(b -> b != null, tss)); testNoRemove(TINY_LIMIT, ss); assertTrue(p.toString(), all(b -> b >= p.b && b <= p.c, tss)); assertEquals(p.toString(), p.b > p.c, isEmpty(ss)); } for (Pair<RandomProvider, Short> p : take(LIMIT, P.pairs(P.randomProvidersDefault(), P.shorts()))) { aeqit(p.toString(), TINY_LIMIT, p.a.range(p.b, p.b), repeat(p.b)); } } private static void propertiesRange_int_int() { initialize("range(int, int)"); Iterable<Triple<RandomProvider, Integer, Integer>> ts = P.triples( P.randomProvidersDefault(), P.integers(), P.integers() ); for (Triple<RandomProvider, Integer, Integer> p : take(LIMIT, ts)) { Iterable<Integer> is = p.a.range(p.b, p.c); Iterable<Integer> tis = take(TINY_LIMIT, is); assertTrue(p.toString(), all(b -> b != null, tis)); testNoRemove(TINY_LIMIT, is); assertTrue(p.toString(), all(b -> b >= p.b && b <= p.c, tis)); assertEquals(p.toString(), p.b > p.c, isEmpty(is)); } for (Pair<RandomProvider, Integer> p : take(LIMIT, P.pairs(P.randomProvidersDefault(), P.integers()))) { aeqit(p.toString(), TINY_LIMIT, p.a.range(p.b, p.b), repeat(p.b)); } } private static void propertiesRange_long_long() { initialize("range(long, long)"); Iterable<Triple<RandomProvider, Long, Long>> ts = P.triples(P.randomProvidersDefault(), P.longs(), P.longs()); for (Triple<RandomProvider, Long, Long> p : take(LIMIT, ts)) { Iterable<Long> ls = p.a.range(p.b, p.c); Iterable<Long> tls = take(TINY_LIMIT, ls); assertTrue(p.toString(), all(b -> b != null, tls)); testNoRemove(TINY_LIMIT, ls); assertTrue(p.toString(), all(b -> b >= p.b && b <= p.c, tls)); assertEquals(p.toString(), p.b > p.c, isEmpty(ls)); } for (Pair<RandomProvider, Long> p : take(LIMIT, P.pairs(P.randomProvidersDefault(), P.longs()))) { aeqit(p.toString(), TINY_LIMIT, p.a.range(p.b, p.b), repeat(p.b)); } } private static void propertiesRange_BigInteger_BigInteger() { initialize("range(BigInteger, BigInteger)"); Iterable<Triple<RandomProvider, BigInteger, BigInteger>> ts = P.triples( P.randomProvidersDefault(), P.bigIntegers(), P.bigIntegers() ); for (Triple<RandomProvider, BigInteger, BigInteger> p : take(LIMIT, ts)) { Iterable<BigInteger> is = p.a.range(p.b, p.c); Iterable<BigInteger> tis = take(TINY_LIMIT, is); assertTrue(p.toString(), all(b -> b != null, tis)); testNoRemove(TINY_LIMIT, is); assertTrue(p.toString(), all(b -> ge(b, p.b) && le(b, p.c), tis)); assertEquals(p.toString(), gt(p.b, p.c), isEmpty(is)); } Iterable<Pair<RandomProvider, BigInteger>> ps = P.pairs(P.randomProvidersDefault(), P.bigIntegers()); for (Pair<RandomProvider, BigInteger> p : take(LIMIT, ps)) { aeqit(p.toString(), TINY_LIMIT, p.a.range(p.b, p.b), repeat(p.b)); } } private static void propertiesRange_char_char() { initialize("range(char, char)"); Iterable<Triple<RandomProvider, Character, Character>> ts = P.triples( P.randomProvidersDefault(), P.characters(), P.characters() ); for (Triple<RandomProvider, Character, Character> p : take(LIMIT, ts)) { Iterable<Character> cs = p.a.range(p.b, p.c); Iterable<Character> tcs = take(TINY_LIMIT, cs); assertTrue(p.toString(), all(b -> b != null, tcs)); testNoRemove(TINY_LIMIT, p.a.range(p.b, p.c)); assertTrue(p.toString(), all(b -> ge(b, p.b) && le(b, p.c), tcs)); assertEquals(p.toString(), gt(p.b, p.c), isEmpty(cs)); } Iterable<Pair<RandomProvider, Character>> ps = P.pairs(P.randomProvidersDefault(), P.characters()); for (Pair<RandomProvider, Character> p : take(LIMIT, ps)) { aeqit(p.toString(), TINY_LIMIT, p.a.range(p.b, p.b), repeat(p.b)); } } private static void propertiesPositiveIntegersGeometric() { initialize("positiveIntegersGeometric()"); Iterable<RandomProvider> rps = filter(x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale()); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<Integer> is = rp.positiveIntegers(); Iterable<Integer> tis = take(TINY_LIMIT, is); assertTrue(rp.toString(), all(i -> i != null, tis)); assertTrue(rp.toString(), all(i -> i > 0, tis)); testNoRemove(TINY_LIMIT, is); } } private static void propertiesNegativeIntegersGeometric() { initialize("negativeIntegersGeometric()"); Iterable<RandomProvider> rps = filter(x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale()); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<Integer> is = rp.negativeIntegersGeometric(); Iterable<Integer> tis = take(TINY_LIMIT, is); assertTrue(rp.toString(), all(i -> i != null, tis)); assertTrue(rp.toString(), all(i -> i < 0, tis)); testNoRemove(TINY_LIMIT, is); } } private static void propertiesNaturalIntegersGeometric() { initialize("naturalIntegersGeometric()"); Iterable<RandomProvider> rps = filter( x -> x.getScale() > 0 && x.getScale() != Integer.MAX_VALUE, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<Integer> is = rp.naturalIntegersGeometric(); Iterable<Integer> tis = take(TINY_LIMIT, is); assertTrue(rp.toString(), all(i -> i != null, tis)); assertTrue(rp.toString(), all(i -> i >= 0, tis)); testNoRemove(TINY_LIMIT, is); } } private static void propertiesNonzeroIntegersGeometric() { initialize("nonzeroIntegersGeometric()"); Iterable<RandomProvider> rps = filter(x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale()); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<Integer> is = rp.nonzeroIntegersGeometric(); Iterable<Integer> tis = take(TINY_LIMIT, is); assertTrue(rp.toString(), all(i -> i != null, tis)); assertTrue(rp.toString(), all(i -> i != 0, tis)); testNoRemove(TINY_LIMIT, is); } } private static void propertiesIntegersGeometric() { initialize("integersGeometric()"); Iterable<RandomProvider> rps = filter( x -> x.getScale() > 0 && x.getScale() != Integer.MAX_VALUE, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<Integer> is = rp.integersGeometric(); Iterable<Integer> tis = take(TINY_LIMIT, is); assertTrue(rp.toString(), all(i -> i != null, tis)); testNoRemove(TINY_LIMIT, is); } } private static void propertiesRangeUpGeometric() { initialize("rangeUpGeometric(int)"); Iterable<Pair<RandomProvider, Integer>> ps = filter( p -> p.a.getScale() > p.b && (p.b >= 1 || p.a.getScale() < Integer.MAX_VALUE + p.b), P.pairs(P.randomProvidersDefaultSecondaryScale(), P.integersGeometric()) ); for (Pair<RandomProvider, Integer> p : take(LIMIT, ps)) { Iterable<Integer> is = p.a.rangeUpGeometric(p.b); Iterable<Integer> tis = take(TINY_LIMIT, is); assertTrue(p.toString(), all(i -> i != null, tis)); testNoRemove(TINY_LIMIT, is); assertTrue(p.toString(), all(i -> i >= p.b, tis)); } Iterable<Pair<RandomProvider, Integer>> psFail = filter( p -> p.a.getScale() <= p.b || p.b < 1 && p.a.getScale() >= Integer.MAX_VALUE + p.b, P.pairs(P.randomProvidersDefaultSecondaryScale(), P.integersGeometric()) ); for (Pair<RandomProvider, Integer> p : take(LIMIT, psFail)) { try { p.a.rangeUpGeometric(p.b); fail(p.toString()); } catch (IllegalStateException ignored) {} } } private static void propertiesRangeDownGeometric() { initialize("rangeDownGeometric(int)"); Iterable<Pair<RandomProvider, Integer>> ps = filter( p -> p.a.getScale() < p.b && (p.b <= -1 || p.a.getScale() > p.b - Integer.MAX_VALUE), P.pairs(P.randomProvidersDefaultSecondaryScale(), P.integersGeometric()) ); for (Pair<RandomProvider, Integer> p : take(LIMIT, ps)) { Iterable<Integer> is = p.a.rangeDownGeometric(p.b); Iterable<Integer> tis = take(TINY_LIMIT, is); assertTrue(p.toString(), all(i -> i != null, tis)); testNoRemove(TINY_LIMIT, is); assertTrue(p.toString(), all(i -> i <= p.b, tis)); } Iterable<Pair<RandomProvider, Integer>> psFail = filter( p -> p.a.getScale() >= p.b || p.b > -1 && p.a.getScale() <= p.b - Integer.MAX_VALUE, P.pairs(P.randomProvidersDefaultSecondaryScale(), P.integersGeometric()) ); for (Pair<RandomProvider, Integer> p : take(LIMIT, psFail)) { try { p.a.rangeDownGeometric(p.b); fail(p.toString()); } catch (IllegalStateException ignored) {} } } private static void propertiesPositiveBigIntegers() { initialize("positiveBigIntegers()"); Iterable<RandomProvider> rps = filter(x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale()); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<BigInteger> is = rp.positiveBigIntegers(); Iterable<BigInteger> tis = take(TINY_LIMIT, is); assertTrue(rp.toString(), all(i -> i != null, tis)); assertTrue(rp.toString(), all(i -> i.signum() == 1, tis)); testNoRemove(TINY_LIMIT, is); } } private static void propertiesNegativeBigIntegers() { initialize("negativeBigIntegers()"); Iterable<RandomProvider> rps = filter(x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale()); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<BigInteger> is = rp.negativeBigIntegers(); Iterable<BigInteger> tis = take(TINY_LIMIT, is); assertTrue(rp.toString(), all(i -> i != null, tis)); assertTrue(rp.toString(), all(i -> i.signum() == -1, tis)); testNoRemove(TINY_LIMIT, is); } } private static void propertiesNaturalBigIntegers() { initialize("naturalBigIntegers()"); Iterable<RandomProvider> rps = filter( x -> x.getScale() > 0 && x.getScale() != Integer.MAX_VALUE, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<BigInteger> is = rp.naturalBigIntegers(); Iterable<BigInteger> tis = take(TINY_LIMIT, is); assertTrue(rp.toString(), all(i -> i != null, tis)); assertTrue(rp.toString(), all(i -> i.signum() != -1, tis)); testNoRemove(TINY_LIMIT, is); } } private static void propertiesNonzeroBigIntegers() { initialize("nonzeroBigIntegers()"); Iterable<RandomProvider> rps = filter(x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale()); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<BigInteger> is = rp.nonzeroBigIntegers(); Iterable<BigInteger> tis = take(TINY_LIMIT, is); assertTrue(rp.toString(), all(i -> i != null, tis)); assertTrue(rp.toString(), all(i -> !i.equals(BigInteger.ZERO), tis)); testNoRemove(TINY_LIMIT, is); } } private static void propertiesBigIntegers() { initialize("bigIntegers()"); Iterable<RandomProvider> rps = filter( x -> x.getScale() > 0 && x.getScale() != Integer.MAX_VALUE, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<BigInteger> is = rp.bigIntegers(); Iterable<BigInteger> tis = take(TINY_LIMIT, is); assertTrue(rp.toString(), all(i -> i != null, tis)); testNoRemove(TINY_LIMIT, is); } } private static void propertiesEquals() { initialize("equals(Object)"); IterableProvider P2; IterableProvider P3; if (P instanceof ExhaustiveProvider) { P2 = ExhaustiveProvider.INSTANCE; P3 = ExhaustiveProvider.INSTANCE; } else { P2 = ((RandomProvider) P).deepCopy(); P3 = ((RandomProvider) P).deepCopy(); } Iterable<Triple<RandomProvider, RandomProvider, RandomProvider>> ts = zip3( P.randomProviders(), P2.randomProviders(), P3.randomProviders() ); for (Triple<RandomProvider, RandomProvider, RandomProvider> t : take(LIMIT, ts)) { //noinspection ConstantConditions,ObjectEqualsNull assertFalse(t.toString(), t.a.equals(null)); assertEquals(t.toString(), t.a, t.b); assertEquals(t.toString(), t.b, t.c); } P.reset(); P2.reset(); P3.reset(); Iterable<Pair<RandomProvider, RandomProvider>> ps = ExhaustiveProvider.INSTANCE.pairs( P.randomProviders(), P2.randomProviders() ); for (Pair<RandomProvider, RandomProvider> p : take(LIMIT, ps)) { symmetric(RandomProvider::equals, p); } P.reset(); P2.reset(); ts = ExhaustiveProvider.INSTANCE.triples(P.randomProviders(), P2.randomProviders(), P3.randomProviders()); for (Triple<RandomProvider, RandomProvider, RandomProvider> t : take(LIMIT, ts)) { transitive(RandomProvider::equals, t); } } private static void propertiesHashCode() { initialize("hashCode()"); IterableProvider P2; if (P instanceof ExhaustiveProvider) { P2 = ExhaustiveProvider.INSTANCE; } else { P2 = ((RandomProvider) P).deepCopy(); } propertiesHashCodeHelper(P.randomProviders(), P2.randomProviders(), LIMIT); } private static void propertiesToString() { initialize("toString()"); for (RandomProvider rp : take(LIMIT, P.randomProviders())) { String s = rp.toString(); assertTrue(rp.toString(), isSubsetOf(s, RANDOM_PROVIDER_CHARS)); } } }
package org.robolectric.res; import org.jetbrains.annotations.NotNull; import org.robolectric.util.PropertiesHelper; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.Arrays; import java.util.Comparator; import java.util.Properties; import static org.robolectric.util.Util.file; public class AndroidSdkFinder { public static final String ANDROID_SDK_HELP_TEXT = "See http://pivotal.github.com/robolectric/resources.html#unable_to_find_android_sdk for more info."; public static final String LOCAL_PROPERTIES_FILE_NAME = "local.properties"; private final File androidSdkBaseDir; public AndroidSdkFinder() { this.androidSdkBaseDir = getPathToAndroidResources(); } private File getPathToAndroidResources() { File file; if ((file = getAndroidResourcePathFromLocalProperties()) != null) { return file; } if ((file = getAndroidResourcePathFromSystemEnvironment()) != null) { return file; } if ((file = getAndroidResourcePathFromSystemProperty()) != null) { return file; } if ((file = getAndroidResourcePathByExecingWhichAndroid()) != null) { return file; } return null; } public ResourcePath findSystemResourcePath() { verifySdkFound(); return getNewestSdkResourcePath(); } public ResourcePath findSystemResourcePath(int version) { verifySdkFound(); return new ResourcePath(android.R.class, file(androidSdkBaseDir, "platforms", "android-" + version, "data", "res"), null); } private void verifySdkFound() { if (androidSdkBaseDir == null) throw new RuntimeException("Unable to find Android SDK. " + ANDROID_SDK_HELP_TEXT); if (!androidSdkBaseDir.isDirectory()) throw new RuntimeException("Unable to find Android SDK: " + androidSdkBaseDir.getAbsolutePath() + " is not a directory. " + ANDROID_SDK_HELP_TEXT); } private File getAndroidResourcePathFromLocalProperties() { File localPropertiesFile = new File(LOCAL_PROPERTIES_FILE_NAME); if (!localPropertiesFile.exists()) { URL resource = AndroidSdkFinder.class.getClassLoader().getResource(LOCAL_PROPERTIES_FILE_NAME); if (resource != null) { localPropertiesFile = new File(resource.getFile()); } } if (localPropertiesFile.exists()) { Properties localProperties = new Properties(); try { localProperties.load(new FileInputStream(localPropertiesFile)); PropertiesHelper.doSubstitutions(localProperties); String sdkPath = localProperties.getProperty("sdk.dir"); if (sdkPath != null) { return new File(sdkPath); } } catch (IOException e) { // fine, we'll try something else } } return null; } private File getAndroidResourcePathFromSystemEnvironment() { // Hand tested String resourcePath = System.getenv().get("ANDROID_HOME"); if (resourcePath != null) { return new File(resourcePath); } return null; } private File getAndroidResourcePathFromSystemProperty() { // this is used by the android-maven-plugin String resourcePath = System.getProperty("android.sdk.path"); if (resourcePath != null) { return new File(resourcePath); } return null; } private File getAndroidResourcePathByExecingWhichAndroid() { File file = shellExec("which", "android"); if (file == null) file = shellExec("bash", "-l", "-c", "which android"); return file; } private File shellExec(String... args) { // Hand tested // Should always work from the command line. Often fails in IDEs because // they don't pass the full PATH in the environment try { Process process = Runtime.getRuntime().exec(args); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String sdkPath; while ((sdkPath = reader.readLine()) != null) { if (sdkPath.endsWith("tools/android")) { String sdkPath1 = sdkPath.substring(0, sdkPath.indexOf("tools/android")); return new File(sdkPath1); } } } catch (IOException e) { // fine we'll try something else } return null; } private Integer extractSdkInt(File file) { String name = file.getName(); int dashIdx = name.lastIndexOf('-'); if (dashIdx == -1) throw new RuntimeException("not an android-XX dir: " + file.getPath()); return Integer.parseInt(name.substring(dashIdx + 1)); } public ResourcePath getNewestSdkResourcePath() { File platformsDir = file(androidSdkBaseDir, "platforms"); if (!platformsDir.exists()) return null; File[] sdkDirs = platformsDir.listFiles(new FilenameFilter() { @Override public boolean accept(@NotNull File dir, @NotNull String name) { return name.matches("android-\\d+"); } }); Arrays.sort(sdkDirs, new Comparator<File>() { @Override public int compare(@NotNull File o1, @NotNull File o2) { return extractSdkInt(o1).compareTo(extractSdkInt(o2)); } }); if (sdkDirs.length == 0) throw new RuntimeException("no android-XX dirs found in " + platformsDir.getPath()); File sdkDir = sdkDirs[sdkDirs.length - 1]; return new ResourcePath(android.R.class, file(sdkDir, "data", "res"), null); } }
package mho.wheels.iterables; import mho.wheels.math.BinaryFraction; import mho.wheels.numberUtils.BigDecimalUtils; import mho.wheels.numberUtils.FloatingPointUtils; import mho.wheels.ordering.Ordering; import mho.wheels.random.IsaacPRNG; import mho.wheels.structures.NullableOptional; import mho.wheels.structures.Pair; import mho.wheels.structures.Triple; import org.jetbrains.annotations.NotNull; import org.junit.Test; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.*; import java.util.function.Function; import java.util.function.Predicate; import static mho.wheels.iterables.IterableUtils.*; import static mho.wheels.ordering.Ordering.*; import static mho.wheels.testing.Testing.*; public class RandomProviderProperties { private static final String RANDOM_PROVIDER_CHARS = " ,-0123456789@PR[]adeimnorv"; private static final int TINY_LIMIT = 20; private static int LIMIT; private static IterableProvider P; private static void initialize(String name) { P.reset(); System.out.println("\t\ttesting " + name + " properties..."); } @Test public void testAllProperties() { List<Triple<IterableProvider, Integer, String>> configs = new ArrayList<>(); configs.add(new Triple<>(ExhaustiveProvider.INSTANCE, 10000, "exhaustively")); configs.add(new Triple<>(RandomProvider.example(), 1000, "randomly")); System.out.println("RandomProvider properties"); for (Triple<IterableProvider, Integer, String> config : configs) { P = config.a; LIMIT = config.b; System.out.println("\ttesting " + config.c); propertiesConstructor(); propertiesConstructor_List_Integer(); propertiesGetScale(); propertiesGetSecondaryScale(); propertiesGetSeed(); propertiesWithScale(); propertiesWithSecondaryScale(); propertiesCopy(); propertiesDeepCopy(); propertiesReset(); propertiesGetId(); propertiesIntegers(); propertiesLongs(); propertiesBooleans(); propertiesUniformSample_Iterable(); propertiesUniformSample_String(); propertiesOrderings(); propertiesRoundingModes(); propertiesPositiveBytes(); propertiesPositiveShorts(); propertiesPositiveIntegers(); propertiesPositiveLongs(); propertiesNegativeBytes(); propertiesNegativeShorts(); propertiesNegativeIntegers(); propertiesNegativeLongs(); propertiesNaturalBytes(); propertiesNaturalShorts(); propertiesNaturalIntegers(); propertiesNaturalLongs(); propertiesNonzeroBytes(); propertiesNonzeroShorts(); propertiesNonzeroIntegers(); propertiesNonzeroLongs(); propertiesBytes(); propertiesShorts(); propertiesAsciiCharacters(); propertiesCharacters(); propertiesRangeUp_byte(); propertiesRangeUp_short(); propertiesRangeUp_int(); propertiesRangeUp_long(); propertiesRangeUp_char(); propertiesRangeDown_byte(); propertiesRangeDown_short(); propertiesRangeDown_int(); propertiesRangeDown_long(); propertiesRangeDown_char(); propertiesRange_byte_byte(); propertiesRange_short_short(); propertiesRange_int_int(); propertiesRange_long_long(); propertiesRange_BigInteger_BigInteger(); propertiesRange_char_char(); propertiesPositiveIntegersGeometric(); propertiesNegativeIntegersGeometric(); propertiesNaturalIntegersGeometric(); propertiesNonzeroIntegersGeometric(); propertiesIntegersGeometric(); propertiesRangeUpGeometric(); propertiesRangeDownGeometric(); propertiesPositiveBigIntegers(); propertiesNegativeBigIntegers(); propertiesNaturalBigIntegers(); propertiesNonzeroBigIntegers(); propertiesBigIntegers(); propertiesRangeUp_BigInteger(); propertiesRangeDown_BigInteger(); propertiesPositiveBinaryFractions(); propertiesNegativeBinaryFractions(); propertiesNonzeroBinaryFractions(); propertiesBinaryFractions(); propertiesRangeUp_BinaryFraction(); propertiesRangeDown_BinaryFraction(); propertiesRange_BinaryFraction_BinaryFraction(); propertiesPositiveFloats(); propertiesNegativeFloats(); propertiesNonzeroFloats(); propertiesFloats(); propertiesPositiveDoubles(); propertiesNegativeDoubles(); propertiesNonzeroDoubles(); propertiesDoubles(); propertiesPositiveFloatsUniform(); propertiesNegativeFloatsUniform(); propertiesNonzeroFloatsUniform(); propertiesFloatsUniform(); propertiesPositiveDoublesUniform(); propertiesNegativeDoublesUniform(); propertiesNonzeroDoublesUniform(); propertiesDoublesUniform(); propertiesRangeUp_float(); propertiesRangeDown_float(); propertiesRange_float_float(); propertiesRangeUp_double(); propertiesRangeDown_double(); propertiesRange_double_double(); propertiesRangeUpUniform_float(); propertiesRangeDownUniform_float(); propertiesRangeUniform_float_float(); propertiesRangeUpUniform_double(); propertiesRangeDownUniform_double(); propertiesRangeUniform_double_double(); propertiesPositiveBigDecimals(); propertiesNegativeBigDecimals(); propertiesNonzeroBigDecimals(); propertiesBigDecimals(); propertiesPositiveCanonicalBigDecimals(); propertiesNegativeCanonicalBigDecimals(); propertiesNonzeroCanonicalBigDecimals(); propertiesCanonicalBigDecimals(); propertiesRangeUp_BigDecimal(); propertiesRangeDown_BigDecimal(); propertiesRange_BigDecimal_BigDecimal(); propertiesRangeUpCanonical_BigDecimal(); propertiesRangeDownCanonical_BigDecimal(); propertiesRangeCanonical_BigDecimal_BigDecimal(); propertiesWithElement(); propertiesWithNull(); propertiesOptionals(); propertiesNullableOptionals(); propertiesEquals(); propertiesHashCode(); propertiesToString(); } System.out.println("Done"); } private static void propertiesConstructor() { initialize("RandomProvider()"); //noinspection unused for (Void v : take(LIMIT, repeat((Void) null))) { RandomProvider rp = new RandomProvider(); rp.validate(); } } private static void propertiesConstructor_List_Integer() { initialize("RandomProvider(List<Integer>)"); for (List<Integer> is : take(LIMIT, P.lists(IsaacPRNG.SIZE, P.integers()))) { RandomProvider rp = new RandomProvider(is); rp.validate(); assertEquals(is, rp.getScale(), 32); assertEquals(is, rp.getSecondaryScale(), 8); } Iterable<List<Integer>> isFail = filterInfinite(js -> js.size() != IsaacPRNG.SIZE, P.lists(P.integers())); for (List<Integer> is : take(LIMIT, isFail)) { try { new RandomProvider(is); fail(is); } catch (IllegalArgumentException ignored) {} } } private static void propertiesGetScale() { initialize("getScale()"); for (RandomProvider rp : take(LIMIT, P.randomProviders())) { int scale = rp.getScale(); assertEquals(rp, rp.withScale(scale), rp); } } private static void propertiesGetSecondaryScale() { initialize("getSecondaryScale()"); for (RandomProvider rp : take(LIMIT, P.randomProviders())) { int secondaryScale = rp.getSecondaryScale(); assertEquals(rp, rp.withSecondaryScale(secondaryScale), rp); } } private static void propertiesGetSeed() { initialize("getSeed()"); for (RandomProvider rp : take(LIMIT, P.randomProviders())) { List<Integer> seed = rp.getSeed(); assertEquals(rp, seed.size(), IsaacPRNG.SIZE); assertEquals( rp, new RandomProvider(seed).withScale(rp.getScale()).withSecondaryScale(rp.getSecondaryScale()), rp ); } } private static void propertiesWithScale() { initialize("withScale(int)"); for (Pair<RandomProvider, Integer> p : take(LIMIT, P.pairs(P.randomProviders(), P.naturalIntegers()))) { RandomProvider rp = p.a.withScale(p.b); rp.validate(); assertEquals(p, rp.getScale(), p.b.intValue()); assertEquals(p, rp.getSecondaryScale(), p.a.getSecondaryScale()); assertEquals(p, rp.getSeed(), p.a.getSeed()); inverses(x -> x.withScale(p.b), (RandomProvider y) -> y.withScale(p.a.getScale()), p.a); } for (RandomProvider rp : take(LIMIT, P.randomProviders())) { idempotent(x -> x.withScale(rp.getScale()), rp); } } private static void propertiesWithSecondaryScale() { initialize("withSecondaryScale(int)"); for (Pair<RandomProvider, Integer> p : take(LIMIT, P.pairs(P.randomProviders(), P.naturalIntegers()))) { RandomProvider rp = p.a.withSecondaryScale(p.b); rp.validate(); assertEquals(p, rp.getScale(), p.a.getScale()); assertEquals(p, rp.getSecondaryScale(), p.b.intValue()); assertEquals(p, rp.getSeed(), p.a.getSeed()); inverses( x -> x.withSecondaryScale(p.b), (RandomProvider y) -> y.withSecondaryScale(p.a.getSecondaryScale()), p.a ); } for (RandomProvider rp : take(LIMIT, P.randomProviders())) { idempotent(x -> x.withSecondaryScale(rp.getSecondaryScale()), rp); } } private static void propertiesCopy() { initialize("copy()"); for (RandomProvider rp : take(LIMIT, P.randomProviders())) { RandomProvider copy = rp.copy(); assertEquals(rp, rp, copy); head(rp.integers()); assertEquals(rp, rp, copy); } } private static void propertiesDeepCopy() { initialize("deepCopy()"); for (RandomProvider rp : take(LIMIT, P.randomProviders())) { RandomProvider copy = rp.deepCopy(); assertEquals(rp, rp, copy); head(rp.integers()); assertNotEquals(rp, rp, copy); } } private static void propertiesReset() { initialize("reset()"); for (RandomProvider rp : take(LIMIT, P.randomProviders())) { RandomProvider rpDependent = rp.withScale(10); RandomProvider original = rp.deepCopy(); RandomProvider dependent = original.withScale(10); assertEquals(rp, rpDependent, dependent); head(rp.integers()); assertNotEquals(rp, rp, original); assertNotEquals(rp, rpDependent, dependent); rp.reset(); assertEquals(rp, rp, original); assertEquals(rp, rpDependent, dependent); } } private static void propertiesGetId() { initialize("getId()"); for (RandomProvider rp : take(LIMIT, P.randomProviders())) { rp.getId(); } } private static <T> void simpleTestWithNulls( @NotNull RandomProvider rp, @NotNull Iterable<T> xs, @NotNull Predicate<T> predicate ) { rp.reset(); assertTrue(rp, all(predicate, take(TINY_LIMIT, xs))); rp.reset(); testNoRemove(TINY_LIMIT, xs); } private static <T> void simpleTest( @NotNull RandomProvider rp, @NotNull Iterable<T> xs, @NotNull Predicate<T> predicate ) { simpleTestWithNulls(rp, xs, x -> x != null && predicate.test(x)); } private static void propertiesIntegers() { initialize("integers()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Integer> is = rp.integers(); simpleTest(rp, is, i -> true); } } private static void propertiesLongs() { initialize("longs()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Long> ls = rp.longs(); simpleTest(rp, ls, l -> true); } } private static void propertiesBooleans() { initialize("booleans()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Boolean> bs = rp.booleans(); simpleTest(rp, bs, b -> true); for (boolean b : ExhaustiveProvider.INSTANCE.booleans()) { assertTrue(rp, elem(b, bs)); } } } private static void propertiesUniformSample_Iterable() { initialize("uniformSample(Iterable<T>)"); Iterable<Pair<RandomProvider, List<Integer>>> ps = P.pairs( P.randomProvidersDefault(), P.lists(P.withNull(P.integers())) ); for (Pair<RandomProvider, List<Integer>> p : take(LIMIT, ps)) { Iterable<Integer> is = p.a.uniformSample(p.b); simpleTestWithNulls(p.a, is, p.b::contains); assertEquals(is, isEmpty(is), p.b.isEmpty()); } } private static void propertiesUniformSample_String() { initialize("uniformSample(String)"); for (Pair<RandomProvider, String> p : take(LIMIT, P.pairs(P.randomProvidersDefault(), P.strings()))) { Iterable<Character> cs = p.a.uniformSample(p.b); simpleTest(p.a, cs, c -> elem(c, cs)); assertEquals(cs, isEmpty(cs), p.b.isEmpty()); } } private static void propertiesOrderings() { initialize("orderings()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Ordering> os = rp.orderings(); simpleTest(rp, os, o -> true); for (Ordering o : ExhaustiveProvider.INSTANCE.orderings()) { assertTrue(rp, elem(o, os)); } } } private static void propertiesRoundingModes() { initialize("roundingModes()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<RoundingMode> rms = rp.roundingModes(); simpleTest(rp, rms, rm -> true); for (RoundingMode rm : ExhaustiveProvider.INSTANCE.roundingModes()) { assertTrue(rp, elem(rm, rms)); } } } private static void propertiesPositiveBytes() { initialize("positiveBytes()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Byte> bs = rp.positiveBytes(); simpleTest(rp, bs, b -> b > 0); } } private static void propertiesPositiveShorts() { initialize("positiveShorts()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Short> ss = rp.positiveShorts(); simpleTest(rp, ss, s -> s > 0); } } private static void propertiesPositiveIntegers() { initialize("positiveIntegers()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Integer> is = rp.positiveIntegers(); simpleTest(rp, is, i -> i > 0); } } private static void propertiesPositiveLongs() { initialize("positiveLongs()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Long> ls = rp.positiveLongs(); simpleTest(rp, ls, l -> l > 0); } } private static void propertiesNegativeBytes() { initialize("negativeBytes()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Byte> bs = rp.negativeBytes(); simpleTest(rp, bs, b -> b < 0); } } private static void propertiesNegativeShorts() { initialize("negativeShorts()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Short> ss = rp.negativeShorts(); simpleTest(rp, ss, s -> s < 0); } } private static void propertiesNegativeIntegers() { initialize("negativeIntegers()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Integer> is = rp.negativeIntegers(); simpleTest(rp, is, i -> i < 0); } } private static void propertiesNegativeLongs() { initialize("negativeLongs()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Long> ls = rp.negativeLongs(); simpleTest(rp, ls, l -> l < 0); } } private static void propertiesNaturalBytes() { initialize("naturalBytes()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Byte> bs = rp.naturalBytes(); simpleTest(rp, bs, b -> b >= 0); } } private static void propertiesNaturalShorts() { initialize("naturalShorts()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Short> ss = rp.naturalShorts(); simpleTest(rp, ss, s -> s >= 0); } } private static void propertiesNaturalIntegers() { initialize("naturalIntegers()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Integer> is = rp.naturalIntegers(); simpleTest(rp, is, i -> i >= 0); } } private static void propertiesNaturalLongs() { initialize("naturalLongs()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Long> ls = rp.naturalLongs(); simpleTest(rp, ls, l -> l >= 0); } } private static void propertiesNonzeroBytes() { initialize("nonzeroBytes()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Byte> bs = rp.nonzeroBytes(); simpleTest(rp, bs, b -> b != 0); } } private static void propertiesNonzeroShorts() { initialize("nonzeroShorts()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Short> ss = rp.nonzeroShorts(); simpleTest(rp, ss, s -> s != 0); } } private static void propertiesNonzeroIntegers() { initialize("nonzeroIntegers()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Integer> is = rp.nonzeroIntegers(); simpleTest(rp, is, i -> i != 0); } } private static void propertiesNonzeroLongs() { initialize("nonzeroLongs()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Long> ls = rp.nonzeroLongs(); simpleTest(rp, ls, l -> l != 0); } } private static void propertiesBytes() { initialize("bytes()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Byte> bs = rp.bytes(); simpleTest(rp, bs, b -> true); } } private static void propertiesShorts() { initialize("shorts()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Short> ss = rp.shorts(); simpleTest(rp, ss, s -> true); } } private static void propertiesAsciiCharacters() { initialize("asciiCharacters()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Character> cs = rp.asciiCharacters(); simpleTest(rp, cs, c -> c < 128); } } private static void propertiesCharacters() { initialize("characters()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Character> cs = rp.characters(); simpleTest(rp, cs, c -> true); } } private static void propertiesRangeUp_byte() { initialize("rangeUp(byte)"); for (Pair<RandomProvider, Byte> p : take(LIMIT, P.pairs(P.randomProvidersDefault(), P.bytes()))) { Iterable<Byte> bs = p.a.rangeUp(p.b); simpleTest(p.a, bs, b -> b >= p.b); } for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { aeqit(rp, TINY_LIMIT, rp.rangeUp(Byte.MAX_VALUE), repeat(Byte.MAX_VALUE)); } } private static void propertiesRangeUp_short() { initialize("rangeUp(short)"); for (Pair<RandomProvider, Short> p : take(LIMIT, P.pairs(P.randomProvidersDefault(), P.shorts()))) { Iterable<Short> ss = p.a.rangeUp(p.b); simpleTest(p.a, ss, s -> s >= p.b); } for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { aeqit(rp, TINY_LIMIT, rp.rangeUp(Short.MAX_VALUE), repeat(Short.MAX_VALUE)); } } private static void propertiesRangeUp_int() { initialize("rangeUp(int)"); for (Pair<RandomProvider, Integer> p : take(LIMIT, P.pairs(P.randomProvidersDefault(), P.integers()))) { Iterable<Integer> is = p.a.rangeUp(p.b); simpleTest(p.a, is, i -> i >= p.b); } for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { aeqit(rp, TINY_LIMIT, rp.rangeUp(Integer.MAX_VALUE), repeat(Integer.MAX_VALUE)); } } private static void propertiesRangeUp_long() { initialize("rangeUp(long)"); for (Pair<RandomProvider, Long> p : take(LIMIT, P.pairs(P.randomProvidersDefault(), P.longs()))) { Iterable<Long> ls = p.a.rangeUp(p.b); simpleTest(p.a, ls, l -> l >= p.b); } for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { aeqit(rp, TINY_LIMIT, rp.rangeUp(Long.MAX_VALUE), repeat(Long.MAX_VALUE)); } } private static void propertiesRangeUp_char() { initialize("rangeUp(char)"); Iterable<Pair<RandomProvider, Character>> ps = P.pairs(P.randomProvidersDefault(), P.characters()); for (Pair<RandomProvider, Character> p : take(LIMIT, ps)) { Iterable<Character> cs = p.a.rangeUp(p.b); simpleTest(p.a, cs, c -> c >= p.b); } for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { aeqit(rp, TINY_LIMIT, rp.rangeUp(Character.MAX_VALUE), repeat(Character.MAX_VALUE)); } } private static void propertiesRangeDown_byte() { initialize("rangeDown(byte)"); for (Pair<RandomProvider, Byte> p : take(LIMIT, P.pairs(P.randomProvidersDefault(), P.bytes()))) { Iterable<Byte> bs = p.a.rangeDown(p.b); simpleTest(p.a, bs, b -> b <= p.b); } for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { aeqit(rp, TINY_LIMIT, rp.rangeDown(Byte.MIN_VALUE), repeat(Byte.MIN_VALUE)); } } private static void propertiesRangeDown_short() { initialize("rangeDown(short)"); for (Pair<RandomProvider, Short> p : take(LIMIT, P.pairs(P.randomProvidersDefault(), P.shorts()))) { Iterable<Short> ss = p.a.rangeDown(p.b); simpleTest(p.a, ss, s -> s <= p.b); } for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { aeqit(rp, TINY_LIMIT, rp.rangeDown(Short.MIN_VALUE), repeat(Short.MIN_VALUE)); } } private static void propertiesRangeDown_int() { initialize("rangeDown(int)"); for (Pair<RandomProvider, Integer> p : take(LIMIT, P.pairs(P.randomProvidersDefault(), P.integers()))) { Iterable<Integer> is = p.a.rangeDown(p.b); simpleTest(p.a, is, i -> i <= p.b); } for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { aeqit(rp, TINY_LIMIT, rp.rangeDown(Integer.MIN_VALUE), repeat(Integer.MIN_VALUE)); } } private static void propertiesRangeDown_long() { initialize("rangeDown(long)"); for (Pair<RandomProvider, Long> p : take(LIMIT, P.pairs(P.randomProvidersDefault(), P.longs()))) { Iterable<Long> ls = p.a.rangeDown(p.b); simpleTest(p.a, ls, l -> l <= p.b); } for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { aeqit(rp, TINY_LIMIT, rp.rangeDown(Long.MIN_VALUE), repeat(Long.MIN_VALUE)); } } private static void propertiesRangeDown_char() { initialize("rangeDown(char)"); Iterable<Pair<RandomProvider, Character>> ps = P.pairs(P.randomProvidersDefault(), P.characters()); for (Pair<RandomProvider, Character> p : take(LIMIT, ps)) { Iterable<Character> cs = p.a.rangeDown(p.b); simpleTest(p.a, cs, b -> b <= p.b); } for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { aeqit(rp, TINY_LIMIT, rp.rangeDown(Character.MIN_VALUE), repeat(Character.MIN_VALUE)); } } private static void propertiesRange_byte_byte() { initialize("range(byte, byte)"); Iterable<Triple<RandomProvider, Byte, Byte>> ts = P.triples(P.randomProvidersDefault(), P.bytes(), P.bytes()); for (Triple<RandomProvider, Byte, Byte> t : take(LIMIT, ts)) { Iterable<Byte> bs = t.a.range(t.b, t.c); simpleTest(t.a, bs, b -> b >= t.b && b <= t.c); assertEquals(t, t.b > t.c, isEmpty(bs)); } for (Pair<RandomProvider, Byte> p : take(LIMIT, P.pairs(P.randomProvidersDefault(), P.bytes()))) { aeqit(p, TINY_LIMIT, p.a.range(p.b, p.b), repeat(p.b)); } } private static void propertiesRange_short_short() { initialize("range(short, short)"); Iterable<Triple<RandomProvider, Short, Short>> ts = P.triples( P.randomProvidersDefault(), P.shorts(), P.shorts() ); for (Triple<RandomProvider, Short, Short> t : take(LIMIT, ts)) { Iterable<Short> ss = t.a.range(t.b, t.c); simpleTest(t.a, ss, s -> s >= t.b && s <= t.c); assertEquals(t, t.b > t.c, isEmpty(ss)); } for (Pair<RandomProvider, Short> p : take(LIMIT, P.pairs(P.randomProvidersDefault(), P.shorts()))) { aeqit(p, TINY_LIMIT, p.a.range(p.b, p.b), repeat(p.b)); } } private static void propertiesRange_int_int() { initialize("range(int, int)"); Iterable<Triple<RandomProvider, Integer, Integer>> ts = P.triples( P.randomProvidersDefault(), P.integers(), P.integers() ); for (Triple<RandomProvider, Integer, Integer> t : take(LIMIT, ts)) { Iterable<Integer> is = t.a.range(t.b, t.c); simpleTest(t.a, is, i -> i >= t.b && i <= t.c); assertEquals(t, t.b > t.c, isEmpty(is)); } for (Pair<RandomProvider, Integer> p : take(LIMIT, P.pairs(P.randomProvidersDefault(), P.integers()))) { aeqit(p, TINY_LIMIT, p.a.range(p.b, p.b), repeat(p.b)); } } private static void propertiesRange_long_long() { initialize("range(long, long)"); Iterable<Triple<RandomProvider, Long, Long>> ts = P.triples(P.randomProvidersDefault(), P.longs(), P.longs()); for (Triple<RandomProvider, Long, Long> t : take(LIMIT, ts)) { Iterable<Long> ls = t.a.range(t.b, t.c); simpleTest(t.a, ls, l -> l >= t.b && l <= t.c); assertEquals(t, t.b > t.c, isEmpty(ls)); } for (Pair<RandomProvider, Long> p : take(LIMIT, P.pairs(P.randomProvidersDefault(), P.longs()))) { aeqit(p, TINY_LIMIT, p.a.range(p.b, p.b), repeat(p.b)); } } private static void propertiesRange_BigInteger_BigInteger() { initialize("range(BigInteger, BigInteger)"); Iterable<Triple<RandomProvider, BigInteger, BigInteger>> ts = P.triples( P.randomProvidersDefault(), P.bigIntegers(), P.bigIntegers() ); for (Triple<RandomProvider, BigInteger, BigInteger> t : take(LIMIT, ts)) { Iterable<BigInteger> is = t.a.range(t.b, t.c); simpleTest(t.a, is, i -> ge(i, t.b) && le(i, t.c)); assertEquals(t, gt(t.b, t.c), isEmpty(is)); } Iterable<Pair<RandomProvider, BigInteger>> ps = P.pairs(P.randomProvidersDefault(), P.bigIntegers()); for (Pair<RandomProvider, BigInteger> p : take(LIMIT, ps)) { aeqit(p, TINY_LIMIT, p.a.range(p.b, p.b), repeat(p.b)); } } private static void propertiesRange_char_char() { initialize("range(char, char)"); Iterable<Triple<RandomProvider, Character, Character>> ts = P.triples( P.randomProvidersDefault(), P.characters(), P.characters() ); for (Triple<RandomProvider, Character, Character> t : take(LIMIT, ts)) { Iterable<Character> cs = t.a.range(t.b, t.c); simpleTest(t.a, cs, c -> c >= t.b && c <= t.c); assertEquals(t, t.b > t.c, isEmpty(cs)); } Iterable<Pair<RandomProvider, Character>> ps = P.pairs(P.randomProvidersDefault(), P.characters()); for (Pair<RandomProvider, Character> p : take(LIMIT, ps)) { aeqit(p, TINY_LIMIT, p.a.range(p.b, p.b), repeat(p.b)); } } private static void propertiesPositiveIntegersGeometric() { initialize("positiveIntegersGeometric()"); Iterable<RandomProvider> rps = filterInfinite( x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<Integer> is = rp.positiveIntegersGeometric(); simpleTest(rp, is, i -> i > 0); } Iterable<RandomProvider> rpsFail = filterInfinite( x -> x.getScale() < 2, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(LIMIT, rpsFail)) { try { rp.positiveIntegersGeometric(); fail(rp); } catch (IllegalStateException ignored) {} } } private static void propertiesNegativeIntegersGeometric() { initialize("negativeIntegersGeometric()"); Iterable<RandomProvider> rps = filterInfinite( x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<Integer> is = rp.negativeIntegersGeometric(); simpleTest(rp, is, i -> i < 0); } Iterable<RandomProvider> rpsFail = filterInfinite( x -> x.getScale() < 2, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(LIMIT, rpsFail)) { try { rp.negativeIntegersGeometric(); fail(rp); } catch (IllegalStateException ignored) {} } } private static void propertiesNaturalIntegersGeometric() { initialize("naturalIntegersGeometric()"); Iterable<RandomProvider> rps = filterInfinite( x -> x.getScale() > 0 && x.getScale() != Integer.MAX_VALUE, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<Integer> is = rp.naturalIntegersGeometric(); simpleTest(rp, is, i -> i >= 0); } Iterable<RandomProvider> rpsFail = filterInfinite( x -> x.getScale() < 1, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(LIMIT, rpsFail)) { try { rp.naturalIntegersGeometric(); fail(rp); } catch (IllegalStateException ignored) {} } for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { try { rp.withScale(Integer.MAX_VALUE).naturalIntegersGeometric(); fail(rp); } catch (IllegalStateException ignored) {} } } private static void propertiesNonzeroIntegersGeometric() { initialize("nonzeroIntegersGeometric()"); Iterable<RandomProvider> rps = filterInfinite( x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<Integer> is = rp.nonzeroIntegersGeometric(); simpleTest(rp, is, i -> i != 0); } Iterable<RandomProvider> rpsFail = filterInfinite( x -> x.getScale() < 2, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(LIMIT, rpsFail)) { try { rp.nonzeroIntegersGeometric(); fail(rp); } catch (IllegalStateException ignored) {} } } private static void propertiesIntegersGeometric() { initialize("integersGeometric()"); Iterable<RandomProvider> rps = filterInfinite( x -> x.getScale() > 0 && x.getScale() != Integer.MAX_VALUE, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<Integer> is = rp.integersGeometric(); simpleTest(rp, is, i -> true); } Iterable<RandomProvider> rpsFail = filterInfinite( x -> x.getScale() < 1, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(LIMIT, rpsFail)) { try { rp.integersGeometric(); fail(rp); } catch (IllegalStateException ignored) {} } for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { try { rp.withScale(Integer.MAX_VALUE).integersGeometric(); fail(rp); } catch (IllegalStateException ignored) {} } } private static void propertiesRangeUpGeometric() { initialize("rangeUpGeometric(int)"); Iterable<Pair<RandomProvider, Integer>> ps = filterInfinite( p -> p.a.getScale() > p.b && (p.b >= 1 || p.a.getScale() < Integer.MAX_VALUE + p.b), P.pairs(P.randomProvidersDefaultSecondaryScale(), P.integersGeometric()) ); for (Pair<RandomProvider, Integer> p : take(LIMIT, ps)) { Iterable<Integer> is = p.a.rangeUpGeometric(p.b); simpleTest(p.a, is, i -> i >= p.b); } Iterable<Pair<RandomProvider, Integer>> psFail = filterInfinite( p -> p.a.getScale() <= p.b || p.b < 1 && p.a.getScale() >= Integer.MAX_VALUE + p.b, P.pairs(P.randomProvidersDefaultSecondaryScale(), P.integersGeometric()) ); for (Pair<RandomProvider, Integer> p : take(LIMIT, psFail)) { try { p.a.rangeUpGeometric(p.b); fail(p); } catch (IllegalStateException ignored) {} } } private static void propertiesRangeDownGeometric() { initialize("rangeDownGeometric(int)"); Iterable<Pair<RandomProvider, Integer>> ps = filterInfinite( p -> p.a.getScale() < p.b && (p.b <= -1 || p.a.getScale() > p.b - Integer.MAX_VALUE), P.pairs(P.randomProvidersDefaultSecondaryScale(), P.integersGeometric()) ); for (Pair<RandomProvider, Integer> p : take(LIMIT, ps)) { Iterable<Integer> is = p.a.rangeDownGeometric(p.b); simpleTest(p.a, is, i -> i <= p.b); } Iterable<Pair<RandomProvider, Integer>> psFail = filterInfinite( p -> p.a.getScale() >= p.b || p.b > -1 && p.a.getScale() <= p.b - Integer.MAX_VALUE, P.pairs(P.randomProvidersDefaultSecondaryScale(), P.integersGeometric()) ); for (Pair<RandomProvider, Integer> p : take(LIMIT, psFail)) { try { p.a.rangeDownGeometric(p.b); fail(p); } catch (IllegalStateException ignored) {} } } private static void propertiesPositiveBigIntegers() { initialize("positiveBigIntegers()"); Iterable<RandomProvider> rps = filterInfinite( x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<BigInteger> is = rp.positiveBigIntegers(); simpleTest(rp, is, i -> i.signum() == 1); } Iterable<RandomProvider> rpsFail = filterInfinite( x -> x.getScale() < 2, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(LIMIT, rpsFail)) { try { rp.positiveBigIntegers(); fail(rp); } catch (IllegalStateException ignored) { } } } private static void propertiesNegativeBigIntegers() { initialize("negativeBigIntegers()"); Iterable<RandomProvider> rps = filterInfinite( x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<BigInteger> is = rp.negativeBigIntegers(); simpleTest(rp, is, i -> i.signum() == -1); } Iterable<RandomProvider> rpsFail = filterInfinite( x -> x.getScale() < 2, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(LIMIT, rpsFail)) { try { rp.negativeBigIntegers(); fail(rp); } catch (IllegalStateException ignored) {} } } private static void propertiesNaturalBigIntegers() { initialize("naturalBigIntegers()"); Iterable<RandomProvider> rps = filterInfinite( x -> x.getScale() > 0 && x.getScale() != Integer.MAX_VALUE, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<BigInteger> is = rp.naturalBigIntegers(); simpleTest(rp, is, i -> i.signum() != -1); } Iterable<RandomProvider> rpsFail = filterInfinite( x -> x.getScale() < 1, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(LIMIT, rpsFail)) { try { rp.naturalBigIntegers(); fail(rp); } catch (IllegalStateException ignored) {} } for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { try { rp.withScale(Integer.MAX_VALUE).naturalBigIntegers(); fail(rp); } catch (IllegalStateException ignored) {} } } private static void propertiesNonzeroBigIntegers() { initialize("nonzeroBigIntegers()"); Iterable<RandomProvider> rps = filterInfinite( x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<BigInteger> is = rp.nonzeroBigIntegers(); simpleTest(rp, is, i -> !i.equals(BigInteger.ZERO)); } Iterable<RandomProvider> rpsFail = filterInfinite( x -> x.getScale() < 2, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(LIMIT, rpsFail)) { try { rp.nonzeroBigIntegers(); fail(rp); } catch (IllegalStateException ignored) {} } } private static void propertiesBigIntegers() { initialize("bigIntegers()"); Iterable<RandomProvider> rps = filterInfinite( x -> x.getScale() > 0 && x.getScale() != Integer.MAX_VALUE, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<BigInteger> is = rp.bigIntegers(); simpleTest(rp, is, i -> true); } Iterable<RandomProvider> rpsFail = filterInfinite( x -> x.getScale() < 1, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(LIMIT, rpsFail)) { try { rp.bigIntegers(); fail(rp); } catch (IllegalStateException ignored) {} } for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { try { rp.withScale(Integer.MAX_VALUE).bigIntegers(); fail(rp); } catch (IllegalStateException ignored) {} } } private static void propertiesRangeUp_BigInteger() { initialize("rangeUp(BigInteger)"); Iterable<Pair<RandomProvider, BigInteger>> ps = filterInfinite( p -> { int minBitLength = p.b.signum() == -1 ? 0 : p.b.bitLength(); return p.a.getScale() > minBitLength && (minBitLength == 0 || p.a.getScale() != Integer.MAX_VALUE); }, P.pairs(P.randomProvidersDefaultSecondaryScale(), P.bigIntegers()) ); for (Pair<RandomProvider, BigInteger> p : take(LIMIT, ps)) { Iterable<BigInteger> is = p.a.rangeUp(p.b); simpleTest(p.a, is, i -> ge(i, p.b)); } Iterable<Pair<RandomProvider, BigInteger>> psFail = filterInfinite( p -> { int minBitLength = p.b.signum() == -1 ? 0 : p.b.bitLength(); return p.a.getScale() <= minBitLength || minBitLength != 0 && p.a.getScale() == Integer.MAX_VALUE; }, P.pairs(P.randomProvidersDefaultSecondaryScale(), P.bigIntegers()) ); for (Pair<RandomProvider, BigInteger> p : take(LIMIT, psFail)) { try { p.a.rangeUp(p.b); fail(p); } catch (IllegalStateException ignored) {} } } private static void propertiesRangeDown_BigInteger() { initialize("rangeDown(BigInteger)"); Iterable<Pair<RandomProvider, BigInteger>> ps = filterInfinite( p -> { int minBitLength = p.b.signum() == 1 ? 0 : p.b.negate().bitLength(); return p.a.getScale() > minBitLength && (minBitLength == 0 || p.a.getScale() != Integer.MAX_VALUE); }, P.pairs(P.randomProvidersDefaultSecondaryScale(), P.bigIntegers()) ); for (Pair<RandomProvider, BigInteger> p : take(LIMIT, ps)) { Iterable<BigInteger> is = p.a.rangeDown(p.b); simpleTest(p.a, is, i -> le(i, p.b)); } Iterable<Pair<RandomProvider, BigInteger>> psFail = filterInfinite( p -> { int minBitLength = p.b.signum() == 1 ? 0 : p.b.negate().bitLength(); return p.a.getScale() <= minBitLength || minBitLength != 0 && p.a.getScale() == Integer.MAX_VALUE; }, P.pairs(P.randomProvidersDefaultSecondaryScale(), P.bigIntegers()) ); for (Pair<RandomProvider, BigInteger> p : take(LIMIT, psFail)) { try { p.a.rangeDown(p.b); fail(p); } catch (IllegalStateException ignored) {} } } private static void propertiesPositiveBinaryFractions() { initialize("positiveBinaryFractions()"); Iterable<RandomProvider> rps = filterInfinite( x -> x.getScale() >= 2 && x.getSecondaryScale() > 0, P.randomProviders() ); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<BinaryFraction> bfs = rp.positiveBinaryFractions(); rp.reset(); take(TINY_LIMIT, bfs).forEach(BinaryFraction::validate); simpleTest(rp, bfs, bf -> bf.signum() == 1); } for (RandomProvider rp : take(LIMIT, filterInfinite(x -> x.getScale() < 2, P.randomProviders()))) { try { rp.positiveBinaryFractions(); fail(rp); } catch (IllegalStateException ignored) {} } for (RandomProvider rp : take(LIMIT, filterInfinite(x -> x.getSecondaryScale() < 1, P.randomProviders()))) { try { rp.positiveBinaryFractions(); fail(rp); } catch (IllegalStateException ignored) {} } } private static void propertiesNegativeBinaryFractions() { initialize("negativeBinaryFractions()"); Iterable<RandomProvider> rps = filterInfinite( x -> x.getScale() >= 2 && x.getSecondaryScale() > 0, P.randomProviders() ); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<BinaryFraction> bfs = rp.negativeBinaryFractions(); rp.reset(); take(TINY_LIMIT, bfs).forEach(BinaryFraction::validate); simpleTest(rp, bfs, bf -> bf.signum() == -1); } for (RandomProvider rp : take(LIMIT, filterInfinite(x -> x.getScale() < 2, P.randomProviders()))) { try { rp.negativeBinaryFractions(); fail(rp); } catch (IllegalStateException ignored) {} } for (RandomProvider rp : take(LIMIT, filterInfinite(x -> x.getSecondaryScale() < 1, P.randomProviders()))) { try { rp.negativeBinaryFractions(); fail(rp); } catch (IllegalStateException ignored) {} } } private static void propertiesNonzeroBinaryFractions() { initialize("nonzeroBinaryFractions()"); Iterable<RandomProvider> rps = filterInfinite( x -> x.getScale() >= 2 && x.getSecondaryScale() > 0, P.randomProviders() ); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<BinaryFraction> bfs = rp.nonzeroBinaryFractions(); rp.reset(); take(TINY_LIMIT, bfs).forEach(BinaryFraction::validate); simpleTest(rp, bfs, bf -> bf != BinaryFraction.ZERO); } for (RandomProvider rp : take(LIMIT, filterInfinite(x -> x.getScale() < 2, P.randomProviders()))) { try { rp.nonzeroBinaryFractions(); fail(rp); } catch (IllegalStateException ignored) {} } for (RandomProvider rp : take(LIMIT, filterInfinite(x -> x.getSecondaryScale() < 1, P.randomProviders()))) { try { rp.nonzeroBinaryFractions(); fail(rp); } catch (IllegalStateException ignored) {} } } private static void propertiesBinaryFractions() { initialize("binaryFractions()"); Iterable<RandomProvider> rps = filterInfinite( x -> x.getScale() > 0 && x.getSecondaryScale() > 0, P.randomProviders() ); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<BinaryFraction> bfs = rp.binaryFractions(); rp.reset(); take(TINY_LIMIT, bfs).forEach(BinaryFraction::validate); simpleTest(rp, bfs, bf -> true); } for (RandomProvider rp : take(LIMIT, filterInfinite(x -> x.getScale() < 1, P.randomProviders()))) { try { rp.binaryFractions(); fail(rp); } catch (IllegalStateException ignored) {} } for (RandomProvider rp : take(LIMIT, filterInfinite(x -> x.getSecondaryScale() < 1, P.randomProviders()))) { try { rp.binaryFractions(); fail(rp); } catch (IllegalStateException ignored) {} } } private static void propertiesRangeUp_BinaryFraction() { initialize("rangeUp(BinaryFraction)"); Iterable<Pair<RandomProvider, BinaryFraction>> ps = P.pairs( filterInfinite(x -> x.getScale() > 0 && x.getSecondaryScale() > 0, P.randomProviders()), P.binaryFractions() ); for (Pair<RandomProvider, BinaryFraction> p : take(LIMIT, ps)) { Iterable<BinaryFraction> bfs = p.a.rangeUp(p.b); simpleTest(p.a, bfs, bf -> ge(bf, p.b)); } Iterable<Pair<RandomProvider, BinaryFraction>> psFail = P.pairs( filterInfinite(x -> x.getScale() < 1, P.randomProviders()), P.binaryFractions() ); for (Pair<RandomProvider, BinaryFraction> p : take(LIMIT, psFail)) { try { p.a.rangeUp(p.b); fail(p); } catch (IllegalStateException ignored) {} } psFail = P.pairs(filterInfinite(x -> x.getSecondaryScale() < 1, P.randomProviders()), P.binaryFractions()); for (Pair<RandomProvider, BinaryFraction> p : take(LIMIT, psFail)) { try { p.a.rangeUp(p.b); fail(p); } catch (IllegalStateException ignored) {} } } private static void propertiesRangeDown_BinaryFraction() { initialize("rangeDown(BinaryFraction)"); Iterable<Pair<RandomProvider, BinaryFraction>> ps = P.pairs( filterInfinite(x -> x.getScale() > 0 && x.getSecondaryScale() > 0, P.randomProviders()), P.binaryFractions() ); for (Pair<RandomProvider, BinaryFraction> p : take(LIMIT, ps)) { Iterable<BinaryFraction> bfs = p.a.rangeDown(p.b); simpleTest(p.a, bfs, bf -> le(bf, p.b)); } Iterable<Pair<RandomProvider, BinaryFraction>> psFail = P.pairs( filterInfinite(x -> x.getScale() < 1, P.randomProviders()), P.binaryFractions() ); for (Pair<RandomProvider, BinaryFraction> p : take(LIMIT, psFail)) { try { p.a.rangeDown(p.b); fail(p); } catch (IllegalStateException ignored) {} } psFail = P.pairs(filterInfinite(x -> x.getSecondaryScale() < 1, P.randomProviders()), P.binaryFractions()); for (Pair<RandomProvider, BinaryFraction> p : take(LIMIT, psFail)) { try { p.a.rangeDown(p.b); fail(p); } catch (IllegalStateException ignored) {} } } private static void propertiesRange_BinaryFraction_BinaryFraction() { initialize("range(BinaryFraction, BinaryFraction)"); Iterable<Triple<RandomProvider, BinaryFraction, BinaryFraction>> ts = P.triples( filterInfinite( x -> x.getScale() > 0 && x.getScale() != Integer.MAX_VALUE, P.randomProvidersDefaultSecondaryScale() ), P.binaryFractions(), P.binaryFractions() ); for (Triple<RandomProvider, BinaryFraction, BinaryFraction> t : take(LIMIT, ts)) { Iterable<BinaryFraction> bfs = t.a.range(t.b, t.c); simpleTest(t.a, bfs, bf -> ge(bf, t.b) && le(bf, t.c)); assertEquals(t, gt(t.b, t.c), isEmpty(bfs)); take(TINY_LIMIT, bfs).forEach(BinaryFraction::validate); } Iterable<Pair<RandomProvider, BinaryFraction>> ps = P.pairs(P.randomProvidersDefault(), P.binaryFractions()); for (Pair<RandomProvider, BinaryFraction> p : take(LIMIT, ps)) { aeqit(p, TINY_LIMIT, p.a.range(p.b, p.b), repeat(p.b)); } Iterable<Triple<RandomProvider, BinaryFraction, BinaryFraction>> tsFail = P.triples( filterInfinite(x -> x.getScale() < 1, P.randomProvidersDefaultSecondaryScale()), P.binaryFractions(), P.binaryFractions() ); for (Triple<RandomProvider, BinaryFraction, BinaryFraction> t : take(LIMIT, tsFail)) { try { t.a.range(t.b, t.c); fail(t); } catch (IllegalStateException ignored) {} } tsFail = P.triples(P.randomProvidersDefault(), P.binaryFractions(), P.binaryFractions()); for (Triple<RandomProvider, BinaryFraction, BinaryFraction> t : take(LIMIT, tsFail)) { try { t.a.withScale(Integer.MAX_VALUE).range(t.b, t.c); fail(t); } catch (IllegalStateException ignored) {} } } private static void propertiesPositiveFloats() { initialize("positiveFloats()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Float> fs = rp.positiveFloats(); simpleTest(rp, fs, f -> f > 0); } } private static void propertiesNegativeFloats() { initialize("negativeFloats()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Float> fs = rp.negativeFloats(); simpleTest(rp, fs, f -> f < 0); } } private static void propertiesNonzeroFloats() { initialize("nonzeroFloats()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Float> fs = rp.nonzeroFloats(); simpleTest(rp, fs, f -> f != 0); } } private static void propertiesFloats() { initialize("floats()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Float> fs = rp.floats(); simpleTest(rp, fs, f -> true); } } private static void propertiesPositiveDoubles() { initialize("positiveDoubles()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Double> ds = rp.positiveDoubles(); simpleTest(rp, ds, d -> d > 0); } } private static void propertiesNegativeDoubles() { initialize("negativeDoubles()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Double> ds = rp.negativeDoubles(); simpleTest(rp, ds, d -> d < 0); } } private static void propertiesNonzeroDoubles() { initialize("nonzeroDoubles()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Double> ds = rp.nonzeroDoubles(); simpleTest(rp, ds, d -> d != 0); } } private static void propertiesDoubles() { initialize("doubles()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Double> ds = rp.doubles(); simpleTest(rp, ds, d -> true); } } private static void propertiesPositiveFloatsUniform() { initialize("positiveFloatsUniform()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Float> fs = rp.positiveFloatsUniform(); simpleTest(rp, fs, f -> f > 0 && Float.isFinite(f)); } } private static void propertiesNegativeFloatsUniform() { initialize("negativeFloatsUniform()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Float> fs = rp.negativeFloatsUniform(); simpleTest(rp, fs, f -> f < 0 && Float.isFinite(f)); } } private static void propertiesNonzeroFloatsUniform() { initialize("nonzeroFloatsUniform()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Float> fs = rp.nonzeroFloatsUniform(); simpleTest(rp, fs, f -> f != 0 && Float.isFinite(f)); } } private static void propertiesFloatsUniform() { initialize("floatsUniform()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Float> fs = rp.floatsUniform(); simpleTest(rp, fs, f -> Float.isFinite(f) && !FloatingPointUtils.isNegativeZero(f)); } } private static void propertiesPositiveDoublesUniform() { initialize("positiveDoublesUniform()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Double> ds = rp.positiveDoublesUniform(); simpleTest(rp, ds, d -> d > 0 && Double.isFinite(d)); } } private static void propertiesNegativeDoublesUniform() { initialize("negativeDoublesUniform()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Double> ds = rp.negativeDoublesUniform(); simpleTest(rp, ds, d -> d < 0 && Double.isFinite(d)); } } private static void propertiesNonzeroDoublesUniform() { initialize("nonzeroDoublesUniform()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Double> ds = rp.nonzeroDoublesUniform(); simpleTest(rp, ds, d -> d != 0 && Double.isFinite(d)); } } private static void propertiesDoublesUniform() { initialize("doublesUniform()"); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { Iterable<Double> ds = rp.doublesUniform(); simpleTest(rp, ds, d -> Double.isFinite(d) && !FloatingPointUtils.isNegativeZero(d)); } } private static void propertiesRangeUp_float() { initialize("rangeUp(float)"); Iterable<Pair<RandomProvider, Float>> ps = P.pairs( P.randomProvidersDefault(), filter(f -> !Float.isNaN(f), P.floats()) ); for (Pair<RandomProvider, Float> p : take(LIMIT, ps)) { Iterable<Float> fs = p.a.rangeUp(p.b); simpleTest(p.a, fs, f -> f >= p.b); } for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { aeqit(rp, TINY_LIMIT, rp.rangeUp(Float.POSITIVE_INFINITY), repeat(Float.POSITIVE_INFINITY)); } } private static void propertiesRangeDown_float() { initialize("rangeDown(float)"); Iterable<Pair<RandomProvider, Float>> ps = P.pairs( P.randomProvidersDefault(), filter(f -> !Float.isNaN(f), P.floats()) ); for (Pair<RandomProvider, Float> p : take(LIMIT, ps)) { Iterable<Float> fs = p.a.rangeDown(p.b); simpleTest(p.a, fs, f -> f <= p.b); } for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { aeqit(rp, TINY_LIMIT, rp.rangeDown(Float.NEGATIVE_INFINITY), repeat(Float.NEGATIVE_INFINITY)); } } private static void propertiesRange_float_float() { initialize("range(float, float)"); Iterable<Triple<RandomProvider, Float, Float>> ts = P.triples( P.randomProvidersDefault(), filter(f -> !Float.isNaN(f), P.floats()), filter(f -> !Float.isNaN(f), P.floats()) ); for (Triple<RandomProvider, Float, Float> t : take(LIMIT, ts)) { Iterable<Float> fs = t.a.range(t.b, t.c); simpleTest(t.a, fs, f -> f >= t.b && f <= t.c); assertEquals(t, t.b > t.c, isEmpty(fs)); } Iterable<Pair<RandomProvider, Float>> ps = P.pairs( P.randomProvidersDefault(), filter(f -> !Float.isNaN(f) && f != 0.0f, P.floats()) ); for (Pair<RandomProvider, Float> p : take(LIMIT, ps)) { aeqit(p, TINY_LIMIT, p.a.range(p.b, p.b), repeat(p.b)); try { p.a.range(Float.NaN, p.b); fail(p); } catch (ArithmeticException ignored) {} try { p.a.range(p.b, Float.NaN); fail(p); } catch (ArithmeticException ignored) {} } } private static void propertiesRangeUp_double() { initialize("rangeUp(double)"); Iterable<Pair<RandomProvider, Double>> ps = P.pairs( P.randomProvidersDefault(), filter(d -> !Double.isNaN(d), P.doubles()) ); for (Pair<RandomProvider, Double> p : take(LIMIT, ps)) { Iterable<Double> ds = p.a.rangeUp(p.b); simpleTest(p.a, ds, d -> d >= p.b); } for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { aeqit(rp, TINY_LIMIT, rp.rangeUp(Double.POSITIVE_INFINITY), repeat(Double.POSITIVE_INFINITY)); } } private static void propertiesRangeDown_double() { initialize("rangeDown(double)"); Iterable<Pair<RandomProvider, Double>> ps = P.pairs( P.randomProvidersDefault(), filter(d -> !Double.isNaN(d), P.doubles()) ); for (Pair<RandomProvider, Double> p : take(LIMIT, ps)) { Iterable<Double> ds = p.a.rangeDown(p.b); simpleTest(p.a, ds, d -> d <= p.b); } for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { aeqit(rp, TINY_LIMIT, rp.rangeDown(Double.NEGATIVE_INFINITY), repeat(Double.NEGATIVE_INFINITY)); } } private static void propertiesRange_double_double() { initialize("range(double, double)"); Iterable<Triple<RandomProvider, Double, Double>> ts = P.triples( P.randomProvidersDefault(), filter(d -> !Double.isNaN(d), P.doubles()), filter(d -> !Double.isNaN(d), P.doubles()) ); for (Triple<RandomProvider, Double, Double> t : take(LIMIT, ts)) { Iterable<Double> ds = t.a.range(t.b, t.c); simpleTest(t.a, ds, f -> f >= t.b && f <= t.c); assertEquals(t, t.b > t.c, isEmpty(ds)); } Iterable<Pair<RandomProvider, Double>> ps = P.pairs( P.randomProvidersDefault(), filter(d -> !Double.isNaN(d) && d != 0.0, P.doubles()) ); for (Pair<RandomProvider, Double> p : take(LIMIT, ps)) { aeqit(p, TINY_LIMIT, p.a.range(p.b, p.b), repeat(p.b)); try { p.a.range(Double.NaN, p.b); fail(p); } catch (ArithmeticException ignored) {} try { p.a.range(p.b, Double.NaN); fail(p); } catch (ArithmeticException ignored) {} } } private static void propertiesRangeUpUniform_float() { initialize("rangeUpUniform(float)"); Iterable<Pair<RandomProvider, Float>> ps = P.pairs( P.randomProvidersDefault(), filter(Float::isFinite, P.floats()) ); for (Pair<RandomProvider, Float> p : take(LIMIT, ps)) { Iterable<Float> fs = p.a.rangeUpUniform(p.b); simpleTest(p.a, fs, f -> f >= p.b && Float.isFinite(f) && !FloatingPointUtils.isNegativeZero(f)); } } private static void propertiesRangeDownUniform_float() { initialize("rangeDownUniform(float)"); Iterable<Pair<RandomProvider, Float>> ps = P.pairs( P.randomProvidersDefault(), filter(Float::isFinite, P.floats()) ); for (Pair<RandomProvider, Float> p : take(LIMIT, ps)) { Iterable<Float> fs = p.a.rangeDownUniform(p.b); simpleTest(p.a, fs, f -> f <= p.b && Float.isFinite(f) && !FloatingPointUtils.isNegativeZero(f)); } } private static void propertiesRangeUniform_float_float() { initialize("rangeUniform(float, float)"); Iterable<Triple<RandomProvider, Float, Float>> ts = P.triples( P.randomProvidersDefault(), filter(Float::isFinite, P.floats()), filter(Float::isFinite, P.floats()) ); for (Triple<RandomProvider, Float, Float> t : take(LIMIT, ts)) { Iterable<Float> fs = t.a.rangeUniform(t.b, t.c); simpleTest( t.a, fs, f -> f >= t.b && f <= t.c && Float.isFinite(f) && !FloatingPointUtils.isNegativeZero(f) ); assertEquals(t, t.b > t.c, isEmpty(fs)); } Iterable<Pair<RandomProvider, Float>> ps = P.pairs( P.randomProvidersDefault(), filter(f -> Float.isFinite(f) && !FloatingPointUtils.isNegativeZero(f), P.floats()) ); for (Pair<RandomProvider, Float> p : take(LIMIT, ps)) { aeqit(p, TINY_LIMIT, p.a.rangeUniform(p.b, p.b), repeat(p.b)); } ps = P.pairs(P.randomProvidersDefault(), filter(Float::isFinite, P.floats())); for (Pair<RandomProvider, Float> p : take(LIMIT, ps)) { try { p.a.rangeUniform(Float.NaN, p.b); fail(p); } catch (ArithmeticException ignored) {} try { p.a.rangeUniform(Float.NEGATIVE_INFINITY, p.b); fail(p); } catch (ArithmeticException ignored) {} try { p.a.rangeUniform(Float.POSITIVE_INFINITY, p.b); fail(p); } catch (ArithmeticException ignored) {} try { p.a.rangeUniform(p.b, Float.NaN); fail(p); } catch (ArithmeticException ignored) {} try { p.a.rangeUniform(p.b, Float.NEGATIVE_INFINITY); fail(p); } catch (ArithmeticException ignored) {} try { p.a.rangeUniform(p.b, Float.POSITIVE_INFINITY); fail(p); } catch (ArithmeticException ignored) {} } } private static void propertiesRangeUpUniform_double() { initialize("rangeUpUniform(double)"); Iterable<Pair<RandomProvider, Double>> ps = P.pairs( P.randomProvidersDefault(), filter(Double::isFinite, P.doubles()) ); for (Pair<RandomProvider, Double> p : take(LIMIT, ps)) { Iterable<Double> ds = p.a.rangeUpUniform(p.b); simpleTest(p.a, ds, d -> d >= p.b && Double.isFinite(d) && !FloatingPointUtils.isNegativeZero(d)); } } private static void propertiesRangeDownUniform_double() { initialize("rangeDownUniform(double)"); Iterable<Pair<RandomProvider, Double>> ps = P.pairs( P.randomProvidersDefault(), filter(Double::isFinite, P.doubles()) ); for (Pair<RandomProvider, Double> p : take(LIMIT, ps)) { Iterable<Double> ds = p.a.rangeDownUniform(p.b); simpleTest(p.a, ds, d -> d <= p.b && Double.isFinite(d) && !FloatingPointUtils.isNegativeZero(d)); } } private static void propertiesRangeUniform_double_double() { initialize("rangeUniform(double, double)"); Iterable<Triple<RandomProvider, Double, Double>> ts = P.triples( P.randomProvidersDefault(), filter(Double::isFinite, P.doubles()), filter(Double::isFinite, P.doubles()) ); for (Triple<RandomProvider, Double, Double> t : take(LIMIT, ts)) { Iterable<Double> ds = t.a.rangeUniform(t.b, t.c); simpleTest( t.a, ds, d -> d >= t.b && d <= t.c && Double.isFinite(d) && !FloatingPointUtils.isNegativeZero(d) ); assertEquals(t, t.b > t.c, isEmpty(ds)); } Iterable<Pair<RandomProvider, Double>> ps = P.pairs( P.randomProvidersDefault(), filter(d -> Double.isFinite(d) && !FloatingPointUtils.isNegativeZero(d), P.doubles()) ); for (Pair<RandomProvider, Double> p : take(LIMIT, ps)) { aeqit(p, TINY_LIMIT, p.a.rangeUniform(p.b, p.b), repeat(p.b)); } ps = P.pairs(P.randomProvidersDefault(), filter(Double::isFinite, P.doubles())); for (Pair<RandomProvider, Double> p : take(LIMIT, ps)) { try { p.a.rangeUniform(Double.NaN, p.b); fail(p); } catch (ArithmeticException ignored) {} try { p.a.rangeUniform(Double.NEGATIVE_INFINITY, p.b); fail(p); } catch (ArithmeticException ignored) {} try { p.a.rangeUniform(Double.POSITIVE_INFINITY, p.b); fail(p); } catch (ArithmeticException ignored) {} try { p.a.rangeUniform(p.b, Double.NaN); fail(p); } catch (ArithmeticException ignored) {} try { p.a.rangeUniform(p.b, Double.NEGATIVE_INFINITY); fail(p); } catch (ArithmeticException ignored) {} try { p.a.rangeUniform(p.b, Double.POSITIVE_INFINITY); fail(p); } catch (ArithmeticException ignored) {} } } private static void propertiesPositiveBigDecimals() { initialize("positiveBigDecimals()"); Iterable<RandomProvider> rps = filterInfinite( x -> x.getScale() >= 2 && x.getSecondaryScale() > 0, P.randomProviders() ); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<BigDecimal> bds = rp.positiveBigDecimals(); rp.reset(); simpleTest(rp, bds, bd -> bd.signum() == 1); } for (RandomProvider rp : take(LIMIT, filterInfinite(x -> x.getScale() < 2, P.randomProviders()))) { try { rp.positiveBigDecimals(); fail(rp); } catch (IllegalStateException ignored) {} } for (RandomProvider rp : take(LIMIT, filterInfinite(x -> x.getSecondaryScale() < 1, P.randomProviders()))) { try { rp.positiveBigDecimals(); fail(rp); } catch (IllegalStateException ignored) {} } } private static void propertiesNegativeBigDecimals() { initialize("negativeBigDecimals()"); Iterable<RandomProvider> rps = filterInfinite( x -> x.getScale() >= 2 && x.getSecondaryScale() > 0, P.randomProviders() ); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<BigDecimal> bds = rp.negativeBigDecimals(); rp.reset(); simpleTest(rp, bds, bd -> bd.signum() == -1); } for (RandomProvider rp : take(LIMIT, filterInfinite(x -> x.getScale() < 2, P.randomProviders()))) { try { rp.negativeBigDecimals(); fail(rp); } catch (IllegalStateException ignored) {} } for (RandomProvider rp : take(LIMIT, filterInfinite(x -> x.getSecondaryScale() < 1, P.randomProviders()))) { try { rp.negativeBigDecimals(); fail(rp); } catch (IllegalStateException ignored) {} } } private static void propertiesNonzeroBigDecimals() { initialize("nonzeroBigDecimals()"); Iterable<RandomProvider> rps = filterInfinite( x -> x.getScale() >= 2 && x.getSecondaryScale() > 0, P.randomProviders() ); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<BigDecimal> bds = rp.nonzeroBigDecimals(); rp.reset(); simpleTest(rp, bds, bd -> ne(bd, BigDecimal.ZERO)); } for (RandomProvider rp : take(LIMIT, filterInfinite(x -> x.getScale() < 2, P.randomProviders()))) { try { rp.nonzeroBigDecimals(); fail(rp); } catch (IllegalStateException ignored) {} } for (RandomProvider rp : take(LIMIT, filterInfinite(x -> x.getSecondaryScale() < 1, P.randomProviders()))) { try { rp.nonzeroBigDecimals(); fail(rp); } catch (IllegalStateException ignored) {} } } private static void propertiesBigDecimals() { initialize("bigDecimals()"); Iterable<RandomProvider> rps = filterInfinite( x -> x.getScale() >= 2 && x.getSecondaryScale() > 0, P.randomProviders() ); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<BigDecimal> bds = rp.bigDecimals(); rp.reset(); simpleTest(rp, bds, bd -> true); } for (RandomProvider rp : take(LIMIT, filterInfinite(x -> x.getScale() < 1, P.randomProviders()))) { try { rp.bigDecimals(); fail(rp); } catch (IllegalStateException ignored) {} } for (RandomProvider rp : take(LIMIT, filterInfinite(x -> x.getSecondaryScale() < 1, P.randomProviders()))) { try { rp.bigDecimals(); fail(rp); } catch (IllegalStateException ignored) {} } } private static void propertiesPositiveCanonicalBigDecimals() { initialize("positiveCanonicalBigDecimals()"); Iterable<RandomProvider> rps = filterInfinite( x -> x.getScale() >= 2 && x.getSecondaryScale() > 0, P.randomProviders() ); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<BigDecimal> bds = rp.positiveCanonicalBigDecimals(); rp.reset(); simpleTest(rp, bds, bd -> bd.signum() == 1 && BigDecimalUtils.isCanonical(bd)); } for (RandomProvider rp : take(LIMIT, filterInfinite(x -> x.getScale() < 2, P.randomProviders()))) { try { rp.positiveCanonicalBigDecimals(); fail(rp); } catch (IllegalStateException ignored) {} } for (RandomProvider rp : take(LIMIT, filterInfinite(x -> x.getSecondaryScale() < 1, P.randomProviders()))) { try { rp.positiveCanonicalBigDecimals(); fail(rp); } catch (IllegalStateException ignored) {} } } private static void propertiesNegativeCanonicalBigDecimals() { initialize("negativeCanonicalBigDecimals()"); Iterable<RandomProvider> rps = filterInfinite( x -> x.getScale() >= 2 && x.getSecondaryScale() > 0, P.randomProviders() ); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<BigDecimal> bds = rp.negativeCanonicalBigDecimals(); rp.reset(); simpleTest(rp, bds, bd -> bd.signum() == -1 && BigDecimalUtils.isCanonical(bd)); } for (RandomProvider rp : take(LIMIT, filterInfinite(x -> x.getScale() < 2, P.randomProviders()))) { try { rp.negativeCanonicalBigDecimals(); fail(rp); } catch (IllegalStateException ignored) {} } for (RandomProvider rp : take(LIMIT, filterInfinite(x -> x.getSecondaryScale() < 1, P.randomProviders()))) { try { rp.negativeCanonicalBigDecimals(); fail(rp); } catch (IllegalStateException ignored) {} } } private static void propertiesNonzeroCanonicalBigDecimals() { initialize("nonzeroCanonicalBigDecimals()"); Iterable<RandomProvider> rps = filterInfinite( x -> x.getScale() >= 2 && x.getSecondaryScale() > 0, P.randomProviders() ); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<BigDecimal> bds = rp.nonzeroCanonicalBigDecimals(); rp.reset(); simpleTest(rp, bds, bd -> ne(bd, BigDecimal.ZERO) && BigDecimalUtils.isCanonical(bd)); } for (RandomProvider rp : take(LIMIT, filterInfinite(x -> x.getScale() < 2, P.randomProviders()))) { try { rp.nonzeroCanonicalBigDecimals(); fail(rp); } catch (IllegalStateException ignored) {} } for (RandomProvider rp : take(LIMIT, filterInfinite(x -> x.getSecondaryScale() < 1, P.randomProviders()))) { try { rp.nonzeroCanonicalBigDecimals(); fail(rp); } catch (IllegalStateException ignored) {} } } private static void propertiesCanonicalBigDecimals() { initialize("canonicalBigDecimals()"); Iterable<RandomProvider> rps = filterInfinite( x -> x.getScale() >= 2 && x.getSecondaryScale() > 0, P.randomProviders() ); for (RandomProvider rp : take(LIMIT, rps)) { Iterable<BigDecimal> bds = rp.canonicalBigDecimals(); rp.reset(); simpleTest(rp, bds, BigDecimalUtils::isCanonical); } for (RandomProvider rp : take(LIMIT, filterInfinite(x -> x.getScale() < 2, P.randomProviders()))) { try { rp.canonicalBigDecimals(); fail(rp); } catch (IllegalStateException ignored) {} } for (RandomProvider rp : take(LIMIT, filterInfinite(x -> x.getSecondaryScale() < 1, P.randomProviders()))) { try { rp.canonicalBigDecimals(); fail(rp); } catch (IllegalStateException ignored) {} } } private static void propertiesRangeUp_BigDecimal() { initialize("rangeUp(BigDecimal)"); Iterable<Pair<RandomProvider, BigDecimal>> ps = P.pairs( filterInfinite(x -> x.getScale() >= 2 && x.getSecondaryScale() > 0, P.randomProviders()), P.bigDecimals() ); for (Pair<RandomProvider, BigDecimal> p : take(LIMIT, ps)) { Iterable<BigDecimal> bds = p.a.rangeUp(p.b); simpleTest(p.a, bds, bd -> ge(bd, p.b)); } Iterable<Pair<RandomProvider, BigDecimal>> psFail = P.pairs( filterInfinite(x -> x.getScale() < 2, P.randomProviders()), P.bigDecimals() ); for (Pair<RandomProvider, BigDecimal> p : take(LIMIT, psFail)) { try { p.a.rangeUp(p.b); fail(p); } catch (IllegalStateException ignored) {} } psFail = P.pairs(filterInfinite(x -> x.getSecondaryScale() < 1, P.randomProviders()), P.bigDecimals()); for (Pair<RandomProvider, BigDecimal> p : take(LIMIT, psFail)) { try { p.a.rangeUp(p.b); fail(p); } catch (IllegalStateException ignored) {} } } private static void propertiesRangeDown_BigDecimal() { initialize("rangeDown(BigDecimal)"); Iterable<Pair<RandomProvider, BigDecimal>> ps = P.pairs( filterInfinite(x -> x.getScale() >= 2 && x.getSecondaryScale() > 0, P.randomProviders()), P.bigDecimals() ); for (Pair<RandomProvider, BigDecimal> p : take(LIMIT, ps)) { Iterable<BigDecimal> bds = p.a.rangeDown(p.b); simpleTest(p.a, bds, bd -> le(bd, p.b)); } Iterable<Pair<RandomProvider, BigDecimal>> psFail = P.pairs( filterInfinite(x -> x.getScale() < 2, P.randomProviders()), P.bigDecimals() ); for (Pair<RandomProvider, BigDecimal> p : take(LIMIT, psFail)) { try { p.a.rangeDown(p.b); fail(p); } catch (IllegalStateException ignored) {} } psFail = P.pairs(filterInfinite(x -> x.getSecondaryScale() < 1, P.randomProviders()), P.bigDecimals()); for (Pair<RandomProvider, BigDecimal> p : take(LIMIT, psFail)) { try { p.a.rangeDown(p.b); fail(p); } catch (IllegalStateException ignored) {} } } private static void propertiesRange_BigDecimal_BigDecimal() { initialize("range(BigDecimal, BigDecimal)"); Iterable<Triple<RandomProvider, BigDecimal, BigDecimal>> ts = P.triples( filterInfinite(x -> x.getScale() > 0 && x.getSecondaryScale() > 0, P.randomProviders()), P.bigDecimals(), P.bigDecimals() ); for (Triple<RandomProvider, BigDecimal, BigDecimal> t : take(LIMIT, ts)) { Iterable<BigDecimal> bds = t.a.range(t.b, t.c); simpleTest(t.a, bds, bd -> ge(bd, t.b) && le(bd, t.c)); assertEquals(t, gt(t.b, t.c), isEmpty(bds)); } Iterable<Pair<RandomProvider, BigDecimal>> ps = P.pairs( filterInfinite(x -> x.getScale() > 0 && x.getSecondaryScale() > 0, P.randomProviders()), P.bigDecimals() ); for (Pair<RandomProvider, BigDecimal> p : take(LIMIT, ps)) { assertTrue(p, all(bd -> eq(bd, p.b), take(TINY_LIMIT, p.a.range(p.b, p.b)))); } Iterable<Triple<RandomProvider, BigDecimal, BigDecimal>> tsFail = P.triples( filterInfinite(x -> x.getScale() < 1, P.randomProviders()), P.bigDecimals(), P.bigDecimals() ); for (Triple<RandomProvider, BigDecimal, BigDecimal> t : take(LIMIT, tsFail)) { try { t.a.range(t.b, t.c); fail(t); } catch (IllegalStateException ignored) {} } tsFail = P.triples( filterInfinite(x -> x.getSecondaryScale() < 1, P.randomProviders()), P.bigDecimals(), P.bigDecimals() ); for (Triple<RandomProvider, BigDecimal, BigDecimal> t : take(LIMIT, tsFail)) { try { t.a.range(t.b, t.c); fail(t); } catch (IllegalStateException ignored) {} } } private static void propertiesRangeUpCanonical_BigDecimal() { initialize("rangeUpCanonical(BigDecimal)"); Iterable<Pair<RandomProvider, BigDecimal>> ps = P.pairs( filterInfinite(x -> x.getScale() >= 2 && x.getSecondaryScale() > 0, P.randomProviders()), P.bigDecimals() ); for (Pair<RandomProvider, BigDecimal> p : take(LIMIT, ps)) { Iterable<BigDecimal> bds = p.a.rangeUpCanonical(p.b); simpleTest(p.a, bds, bd -> ge(bd, p.b) && BigDecimalUtils.isCanonical(bd)); } Iterable<Pair<RandomProvider, BigDecimal>> psFail = P.pairs( filterInfinite(x -> x.getScale() < 2, P.randomProviders()), P.bigDecimals() ); for (Pair<RandomProvider, BigDecimal> p : take(LIMIT, psFail)) { try { p.a.rangeUpCanonical(p.b); fail(p); } catch (IllegalStateException ignored) {} } psFail = P.pairs(filterInfinite(x -> x.getSecondaryScale() < 1, P.randomProviders()), P.bigDecimals()); for (Pair<RandomProvider, BigDecimal> p : take(LIMIT, psFail)) { try { p.a.rangeUpCanonical(p.b); fail(p); } catch (IllegalStateException ignored) {} } } private static void propertiesRangeDownCanonical_BigDecimal() { initialize("rangeDownCanonical(BigDecimal)"); Iterable<Pair<RandomProvider, BigDecimal>> ps = P.pairs( filterInfinite(x -> x.getScale() >= 2 && x.getSecondaryScale() > 0, P.randomProviders()), P.bigDecimals() ); for (Pair<RandomProvider, BigDecimal> p : take(LIMIT, ps)) { Iterable<BigDecimal> bds = p.a.rangeDownCanonical(p.b); simpleTest(p.a, bds, bd -> le(bd, p.b) && BigDecimalUtils.isCanonical(bd)); } Iterable<Pair<RandomProvider, BigDecimal>> psFail = P.pairs( filterInfinite(x -> x.getScale() < 2, P.randomProviders()), P.bigDecimals() ); for (Pair<RandomProvider, BigDecimal> p : take(LIMIT, psFail)) { try { p.a.rangeDownCanonical(p.b); fail(p); } catch (IllegalStateException ignored) {} } psFail = P.pairs(filterInfinite(x -> x.getSecondaryScale() < 1, P.randomProviders()), P.bigDecimals()); for (Pair<RandomProvider, BigDecimal> p : take(LIMIT, psFail)) { try { p.a.rangeDownCanonical(p.b); fail(p); } catch (IllegalStateException ignored) {} } } private static void propertiesRangeCanonical_BigDecimal_BigDecimal() { initialize("rangeCanonical(BigDecimal, BigDecimal)"); Iterable<Triple<RandomProvider, BigDecimal, BigDecimal>> ts = P.triples( filterInfinite(x -> x.getScale() > 0 && x.getSecondaryScale() > 0, P.randomProviders()), P.bigDecimals(), P.bigDecimals() ); for (Triple<RandomProvider, BigDecimal, BigDecimal> t : take(LIMIT, ts)) { Iterable<BigDecimal> bds = t.a.rangeCanonical(t.b, t.c); simpleTest(t.a, bds, bd -> ge(bd, t.b) && le(bd, t.c) && BigDecimalUtils.isCanonical(bd)); assertEquals(t, gt(t.b, t.c), isEmpty(bds)); } Iterable<Pair<RandomProvider, BigDecimal>> ps = P.pairs( filterInfinite(x -> x.getScale() > 0 && x.getSecondaryScale() > 0, P.randomProviders()), P.bigDecimals() ); for (Pair<RandomProvider, BigDecimal> p : take(LIMIT, ps)) { aeqit(p, TINY_LIMIT, p.a.rangeCanonical(p.b, p.b), repeat(BigDecimalUtils.canonicalize(p.b))); } Iterable<Triple<RandomProvider, BigDecimal, BigDecimal>> tsFail = P.triples( filterInfinite(x -> x.getScale() < 1, P.randomProviders()), P.bigDecimals(), P.bigDecimals() ); for (Triple<RandomProvider, BigDecimal, BigDecimal> t : take(LIMIT, tsFail)) { try { t.a.rangeCanonical(t.b, t.c); fail(t); } catch (IllegalStateException ignored) {} } tsFail = P.triples( filterInfinite(x -> x.getSecondaryScale() < 1, P.randomProviders()), P.bigDecimals(), P.bigDecimals() ); for (Triple<RandomProvider, BigDecimal, BigDecimal> t : take(LIMIT, tsFail)) { try { t.a.rangeCanonical(t.b, t.c); fail(t); } catch (IllegalStateException ignored) {} } } private static void propertiesWithElement() { initialize("withElement(Integer, Iterable<Integer>)"); Iterable<Triple<RandomProvider, Integer, Iterable<Integer>>> ts = P.triples( filterInfinite(x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale()), P.withNull(P.integers()), P.repeatingIterables(P.withNull(P.integers())) ); for (Triple<RandomProvider, Integer, Iterable<Integer>> t : take(LIMIT, ts)) { List<Integer> withElement = toList(take(TINY_LIMIT, t.a.withElement(t.b, t.c))); testNoRemove(TINY_LIMIT, t.a.withElement(t.b, t.c)); List<Integer> filteredResult = toList(filter(x -> !Objects.equals(x, t.b), withElement)); assertEquals( t, filteredResult, toList(take(filteredResult.size(), filterInfinite(x -> !Objects.equals(x, t.b), t.c))) ); } Iterable<Triple<RandomProvider, Integer, List<Integer>>> tsFail = P.triples( filterInfinite(x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale()), P.withNull(P.integers()), P.lists(P.withNull(P.integers())) ); for (Triple<RandomProvider, Integer, List<Integer>> t : take(LIMIT, tsFail)) { try { toList(t.a.withElement(t.b, t.c)); fail(t); } catch (IllegalArgumentException ignored) {} } } private static void propertiesWithNull() { initialize("withNull(Iterable<Integer>)"); Iterable<Pair<RandomProvider, Iterable<Integer>>> ps = P.pairs( filterInfinite(x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale()), P.repeatingIterables(P.integers()) ); for (Pair<RandomProvider, Iterable<Integer>> p : take(LIMIT, ps)) { List<Integer> withNull = toList(take(TINY_LIMIT, p.a.withNull(p.b))); testNoRemove(TINY_LIMIT, p.a.withNull(p.b)); List<Integer> filteredResult = toList(filter(x -> x != null, withNull)); assertEquals(p, filteredResult, toList(take(filteredResult.size(), p.b))); } Iterable<Pair<RandomProvider, List<Integer>>> psFail = P.pairs( filterInfinite(x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale()), P.lists(P.integers()) ); for (Pair<RandomProvider, List<Integer>> p : take(LIMIT, psFail)) { try { toList(p.a.withNull(p.b)); fail(p); } catch (IllegalArgumentException ignored) {} } } private static void propertiesOptionals() { initialize("optionals(Iterable<Integer>)"); Iterable<Pair<RandomProvider, Iterable<Integer>>> ps = P.pairs( filterInfinite(x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale()), P.repeatingIterables(P.integers()) ); for (Pair<RandomProvider, Iterable<Integer>> p : take(LIMIT, ps)) { List<Optional<Integer>> os = toList(take(TINY_LIMIT, p.a.optionals(p.b))); testNoRemove(TINY_LIMIT, p.a.optionals(p.b)); List<Integer> filteredResult = toList(optionalMap(Function.identity(), os)); assertEquals(p, filteredResult, toList(take(filteredResult.size(), p.b))); } Iterable<Pair<RandomProvider, List<Integer>>> psFail = P.pairs( filterInfinite(x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale()), P.lists(P.integers()) ); for (Pair<RandomProvider, List<Integer>> p : take(LIMIT, psFail)) { try { toList(p.a.optionals(p.b)); fail(p); } catch (IllegalArgumentException ignored) {} } } private static void propertiesNullableOptionals() { initialize("nullableOptionals(Iterable<Integer>)"); Iterable<Pair<RandomProvider, Iterable<Integer>>> ps = P.pairs( filterInfinite(x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale()), P.repeatingIterables(P.withNull(P.integers())) ); for (Pair<RandomProvider, Iterable<Integer>> p : take(LIMIT, ps)) { List<NullableOptional<Integer>> os = toList(take(TINY_LIMIT, p.a.nullableOptionals(p.b))); testNoRemove(TINY_LIMIT, p.a.nullableOptionals(p.b)); List<Integer> filteredResult = toList(nullableOptionalMap(Function.identity(), os)); assertEquals(p, filteredResult, toList(take(filteredResult.size(), p.b))); } Iterable<Pair<RandomProvider, List<Integer>>> psFail = P.pairs( filterInfinite(x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale()), P.lists(P.withNull(P.integers())) ); for (Pair<RandomProvider, List<Integer>> p : take(LIMIT, psFail)) { try { toList(p.a.nullableOptionals(p.b)); fail(p); } catch (IllegalArgumentException ignored) {} } } private static void propertiesEquals() { initialize("equals(Object)"); propertiesEqualsHelper(LIMIT, P, IterableProvider::randomProviders); } private static void propertiesHashCode() { initialize("hashCode()"); propertiesHashCodeHelper(LIMIT, P, IterableProvider::randomProviders); } private static void propertiesToString() { initialize("toString()"); for (RandomProvider rp : take(LIMIT, P.randomProviders())) { String s = rp.toString(); assertTrue(rp, isSubsetOf(s, RANDOM_PROVIDER_CHARS)); } } }
package org.scribe.builder.api; import org.scribe.extractors.*; import org.scribe.model.*; import org.scribe.oauth.*; import org.scribe.services.*; /** * Default implementation of the OAuth protocol, version 1.0a * * This class is meant to be extended by concrete implementations of the API. * If your Api adheres to the 1.0a protocol correctly, you just need to extend * this class and define the getters for your endpoints. * * @author Pablo Fernandez * */ public abstract class DefaultApi10a implements Api { public AccessTokenExtractor getAccessTokenExtractor() { return new TokenExtractorImpl(); } public BaseStringExtractor getBaseStringExtractor() { return new BaseStringExtractorImpl(); } public HeaderExtractor getHeaderExtractor() { return new HeaderExtractorImpl(); } public RequestTokenExtractor getRequestTokenExtractor() { return new TokenExtractorImpl(); } public SignatureService getSignatureService() { return new HMACSha1SignatureService(); } public TimestampService getTimestampService() { return new TimestampServiceImpl(); } public Verb getAccessTokenVerb() { return Verb.POST; } public Verb getRequestTokenVerb() { return Verb.POST; } /** * Returns the URL that receives the request token requests. * * @return request token URL */ public abstract String getRequestTokenEndpoint(); /** * Returns the URL that receives the access token requests. * * @return access token URL */ public abstract String getAccessTokenEndpoint(); /** * Returns the {@link OAuthService} for this Api * * @param apiKey Key * @param apiSecret Api Secret * @param callback OAuth callback (either URL or 'oob') * @param scope OAuth scope (optional) */ public OAuthService createService(OAuthConfig config, String scope) { OAuthService service = doCreateService(config); service.addScope(scope); return service; } private OAuthService doCreateService(OAuthConfig config) { return new OAuth10aServiceImpl(this, config); } }
package neomcfly.jsoupmapper; import java.io.InputStream; import org.junit.Test; import junit.framework.TestCase; import lombok.Data; import lombok.extern.slf4j.Slf4j; @Slf4j public class JSoupMapperConvertorTest { JSoupMapper mapper = new JSoupMapper(); @Test public void convertorPrimitive1() { InputStream document = read("/convertor/u1.html"); Result result = mapper.map(document, Result.class); TestCase.assertNotNull(result); TestCase.assertEquals(new Integer("3"), result.getInt1()); TestCase.assertEquals(3, result.getInt2()); TestCase.assertEquals(new Boolean("false"), result.getBool1()); TestCase.assertEquals(false, result.getBool2()); TestCase.assertEquals(new Double("5.5"), result.getDouble1()); TestCase.assertEquals(5.5d, result.getDouble2()); TestCase.assertEquals(new Long("6"), result.getLong1()); TestCase.assertEquals(6L, result.getLong2()); TestCase.assertEquals(new Short("7"), result.getShort1()); TestCase.assertEquals(7, result.getShort2()); TestCase.assertEquals(new Float("10.2"), result.getFloat1()); TestCase.assertEquals(10.2f, result.getFloat2()); TestCase.assertEquals(new Character('C'), result.getChar1()); TestCase.assertEquals('C', result.getChar2()); TestCase.assertEquals(new Byte("11"), result.getByte1()); TestCase.assertEquals(0x11, result.getByte2()); log.info(result.toString()); } @Data public static class Result { @JSoupSelect("#intId") @JSoupText public Integer int1; @JSoupSelect("#intId") @JSoupText public int int2; @JSoupSelect("#floatId") @JSoupText public Float float1; @JSoupSelect("#floatId") @JSoupText public float float2; @JSoupSelect("#boolId") @JSoupText public Boolean bool1; @JSoupSelect("#boolId") @JSoupText public float bool2; @JSoupSelect("#doubleId") @JSoupText public Double double1; @JSoupSelect("#doubleId") @JSoupText public double double2; @JSoupSelect("#longId") @JSoupText public Long long1; @JSoupSelect("#longId") @JSoupText public long long2; @JSoupSelect("#shortId") @JSoupText public Short short1; @JSoupSelect("#shortId") @JSoupText public short short2; @JSoupSelect("charId") @JSoupText public Character char1; @JSoupSelect("#charId") @JSoupText public char char2; @JSoupSelect("byteId") @JSoupText public Byte byte1; @JSoupSelect("#byteId") @JSoupText public byte byte2; } private InputStream read(String string) { InputStream resourceAsStream = JSoupMapper.class .getResourceAsStream(string); TestCase.assertNotNull(resourceAsStream); return resourceAsStream; } }
package org.smoothbuild.db.outputs; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.Streams.stream; import static org.smoothbuild.db.outputs.OutputsDbException.corruptedValueException; import static org.smoothbuild.db.outputs.OutputsDbException.ioException; import static org.smoothbuild.lang.message.Message.isValidSeverity; import java.io.IOException; import java.util.List; import javax.inject.Inject; import org.smoothbuild.db.hashed.HashedDb; import org.smoothbuild.db.hashed.Marshaller; import org.smoothbuild.db.hashed.Unmarshaller; import org.smoothbuild.db.values.ValuesDb; import org.smoothbuild.lang.message.Message; import org.smoothbuild.lang.message.Messages; import org.smoothbuild.lang.plugin.Types; import org.smoothbuild.lang.type.ArrayType; import org.smoothbuild.lang.type.ConcreteType; import org.smoothbuild.lang.value.Array; import org.smoothbuild.lang.value.ArrayBuilder; import org.smoothbuild.lang.value.Struct; import org.smoothbuild.lang.value.Value; import org.smoothbuild.task.base.Output; import com.google.common.collect.ImmutableList; import com.google.common.hash.HashCode; public class OutputsDb { private final HashedDb hashedDb; private final ValuesDb valuesDb; private final Types types; @Inject public OutputsDb(@Outputs HashedDb hashedDb, ValuesDb valuesDb, Types types) { this.hashedDb = hashedDb; this.valuesDb = valuesDb; this.types = types; } public void write(HashCode taskHash, Output output) { try (Marshaller marshaller = hashedDb.newMarshaller(taskHash)) { ImmutableList<Message> messageList = output.messages(); marshaller.sink().write(storeMessageArray(messageList).hash().asBytes()); if (!Messages.containsErrors(messageList)) { marshaller.sink().write(output.result().hash().asBytes()); } } catch (IOException e) { throw ioException(e); } } private Array storeMessageArray(ImmutableList<Message> messages) { ArrayBuilder builder = valuesDb.arrayBuilder(types.message()); for (Message message : messages) { builder.add(message.value()); } return builder.build(); } public boolean contains(HashCode taskHash) { return hashedDb.contains(taskHash); } public Output read(HashCode taskHash, ConcreteType type) { try (Unmarshaller unmarshaller = hashedDb.newUnmarshaller(taskHash)) { Value messagesValue = valuesDb.get(unmarshaller.readHash()); ArrayType messageArrayType = types.array(types.message()); if (!messagesValue.type().equals(messageArrayType)) { throw corruptedValueException(taskHash, "Expected " + messageArrayType + " as first child of its merkle root, but got " + messagesValue.type()); } List<Message> messages = stream(((Array) messagesValue).asIterable(Struct.class)) .map(Message::new) .collect(toImmutableList()); messages.forEach(m -> { if (!isValidSeverity(m.severity())) { throw corruptedValueException(taskHash, "One of messages has invalid severity = '" + m.severity() + "'"); } }); if (Messages.containsErrors(messages)) { return new Output(messages); } else { HashCode resultObjectHash = unmarshaller.readHash(); Value value = valuesDb.get(resultObjectHash); if (!type.equals(value.type())) { throw corruptedValueException(taskHash, "Expected value of type " + type + " as second child of its merkle root, but got " + value.type()); } return new Output(value, messages); } } catch (IOException e) { throw ioException(e); } } }
package net.sf.jooreports.templates; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.imageio.ImageIO; import net.sf.jooreports.templates.image.ClasspathImageSource; import net.sf.jooreports.templates.image.FileImageSource; import net.sf.jooreports.templates.image.ImageSource; import net.sf.jooreports.templates.image.RenderedImageSource; public class DynamicImagesTest extends AbstractTemplateTest { public void testOrderForm() throws Exception { File templateFile = getTestFile("order-with-images-template.odt"); ImageSource red = new RenderedImageSource(ImageIO.read(new File("src/test/resources/red.png"))); ImageSource blue = new FileImageSource("src/test/resources/blue.png"); ImageSource blue2 = new ClasspathImageSource("blue.png"); Map model = new HashMap(); List items = new ArrayList(); Map item1 = new HashMap(); item1.put("description", "First Item"); item1.put("quantity", "20"); item1.put("picture", red); items.add(item1); Map item2 = new HashMap(); item2.put("description", "Second Item"); item2.put("quantity", "15"); item2.put("picture", blue); items.add(item2); Map item3 = new HashMap(); item3.put("description", "Third Item"); item3.put("quantity", "50"); item3.put("picture", red); items.add(item3); Map item4 = new HashMap(); item4.put("description", "Fourth Item"); item4.put("quantity", "20"); item4.put("picture", blue2); items.add(item4); model.put("items", items); String content = processTemplate(templateFile, model); String expected = "Order Form\n" + "\n" + "Picture\n" + "Description\n" + "Quantity\n" + "[frame:1.409cm,0.706cm][img:Pictures/dynamic-image-1.png]\n" + "First Item\n" + "20\n" + "[frame:1.409cm,0.706cm][img:Pictures/dynamic-image-2.png]\n" + "Second Item\n" + "15\n" + "[frame:1.409cm,0.706cm][img:Pictures/dynamic-image-1.png]\n" + "Third Item\n" + "50\n" + "[frame:1.409cm,0.706cm][img:Pictures/dynamic-image-3.png]\n" + "Fourth Item\n" + "20"; assertEquals("incorrect output", expected, content); } public void testOldScriptOrderForm() throws Exception { File templateFile = getTestFile("order-with-images-old-script-template.odt"); ImageSource red = new RenderedImageSource(ImageIO.read(new File("src/test/resources/red.png"))); ImageSource blue = new FileImageSource("src/test/resources/blue.png"); ImageSource blue2 = new ClasspathImageSource("blue.png"); Map model = new HashMap(); List items = new ArrayList(); Map item1 = new HashMap(); item1.put("description", "First Item"); item1.put("quantity", "20"); item1.put("picture", red); items.add(item1); Map item2 = new HashMap(); item2.put("description", "Second Item"); item2.put("quantity", "15"); item2.put("picture", blue); items.add(item2); Map item3 = new HashMap(); item3.put("description", "Third Item"); item3.put("quantity", "50"); item3.put("picture", red); items.add(item3); Map item4 = new HashMap(); item4.put("description", "Fourth Item"); item4.put("quantity", "20"); item4.put("picture", blue2); items.add(item4); model.put("items", items); String content = processTemplate(templateFile, model); String expected = "Order Form\n" + "\n" + "Picture\n" + "Description\n" + "Quantity\n" + "[frame:1.409cm,0.706cm][img:Pictures/dynamic-image-1.png]\n" + "First Item\n" + "20\n" + "[frame:1.409cm,0.706cm][img:Pictures/dynamic-image-2.png]\n" + "Second Item\n" + "15\n" + "[frame:1.409cm,0.706cm][img:Pictures/dynamic-image-1.png]\n" + "Third Item\n" + "50\n" + "[frame:1.409cm,0.706cm][img:Pictures/dynamic-image-3.png]\n" + "Fourth Item\n" + "20"; assertEquals("incorrect output", expected, content); } public void testImageSourceWithFileName() throws Exception { File templateFile = getTestFile("order-with-images-template.odt"); ImageSource blue = new FileImageSource("src/test/resources/blue.png"); Map model = new HashMap(); List items = new ArrayList(); Map item1 = new HashMap(); item1.put("description", "First Item"); item1.put("quantity", "20"); item1.put("picture", blue); items.add(item1); Map item2 = new HashMap(); item2.put("description", "Second Item"); item2.put("quantity", "15"); item2.put("picture", "src/test/resources/red.png"); items.add(item2); Map item3 = new HashMap(); item3.put("description", "Third Item"); item3.put("quantity", "50"); item3.put("picture", ""); items.add(item3); Map item4 = new HashMap(); item4.put("description", "Fourth Item"); item4.put("quantity", "20"); item4.put("picture", null); items.add(item4); model.put("items", items); String content = processTemplate(templateFile, model); String expected = "Order Form\n" + "\n" + "Picture\n" + "Description\n" + "Quantity\n" + "[frame:1.409cm,0.706cm][img:Pictures/dynamic-image-1.png]\n" + "First Item\n" + "20\n" + "[frame:1.409cm,0.706cm][img:Pictures/dynamic-image-2.png]\n" + "Second Item\n" + "15\n" + "[frame:1.409cm,0.706cm][img:Pictures/1000000000000028000000145B20E0B1.png]\n" + "Third Item\n" + "50\n" + "[frame:1.409cm,0.706cm][img:Pictures/1000000000000028000000145B20E0B1.png]\n" + "Fourth Item\n" + "20"; assertEquals("incorrect output", expected, content); } public void testOrderFormWithImageResize() throws Exception { File templateFile = getTestFile("order-with-images-resize-template.odt"); ImageSource red = new RenderedImageSource(ImageIO.read(new File("src/test/resources/red.png"))); ImageSource blue = new FileImageSource("src/test/resources/blue.png"); ImageSource blue2 = new ClasspathImageSource("blue.png"); Map model = new HashMap(); List items = new ArrayList(); Map item1 = new HashMap(); item1.put("description", "First Item"); item1.put("quantity", "20"); item1.put("picture", red); items.add(item1); Map item2 = new HashMap(); item2.put("description", "Second Item"); item2.put("quantity", "15"); item2.put("picture", blue); items.add(item2); Map item3 = new HashMap(); item3.put("description", "Third Item"); item3.put("quantity", "50"); item3.put("picture", red); items.add(item3); Map item4 = new HashMap(); item4.put("description", "Fourth Item"); item4.put("quantity", "20"); item4.put("picture", blue2); items.add(item4); model.put("items", items); String content = processTemplate(templateFile, model); String expected = "Order Form\n" + "\n" + "Picture\n" + "Description\n" + "Quantity\n" + "[frame:8.999cm,4.5cm][img:Pictures/dynamic-image-1.png]\n" + "First Item\n" + "20\n" + "[frame:8.999cm,4.5cm][img:Pictures/dynamic-image-2.png]\n" + "Second Item\n" + "15\n" + "[frame:8.999cm,4.5cm][img:Pictures/dynamic-image-1.png]\n" + "Third Item\n" + "50\n" + "[frame:8.999cm,4.5cm][img:Pictures/dynamic-image-3.png]\n" + "Fourth Item\n" + "20"; assertEquals("incorrect output", expected, content); } public void testImageResize() throws Exception { File templateFile = getTestFile("images-resize-template.odt"); Map model = new HashMap(); model.put("coinsV", new FileImageSource("src/test/resources/coinsV.jpg")); model.put("coinsH", new FileImageSource("src/test/resources/coinsH.jpg")); model.put("earthV", new ClasspathImageSource("earthV.jpg")); model.put("earthH", new ClasspathImageSource("earthH.jpg")); String actual = processTemplate(templateFile, model); String expected = "Default\n" + "[frame:2.54cm,2.54cm][img:Pictures/dynamic-image-1.png]\n" + "[frame:2.54cm,2.54cm][img:Pictures/dynamic-image-2.png]\n" + "[frame:2.54cm,2.54cm][img:Pictures/dynamic-image-3.png]\n" + "[frame:2.54cm,2.54cm][img:Pictures/dynamic-image-4.png]\n" + "MaxWidth\n" + "[frame:2.54cm,1.57cm][img:Pictures/dynamic-image-1.png]\n" + "[frame:2.54cm,4.12cm][img:Pictures/dynamic-image-2.png]\n" + "[frame:2.54cm,1.9cm][img:Pictures/dynamic-image-3.png]\n" + "[frame:2.54cm,3.39cm][img:Pictures/dynamic-image-4.png]\n" + "MaxHeight\n" + "[frame:4.12cm,2.54cm][img:Pictures/dynamic-image-1.png]\n" + "[frame:1.57cm,2.54cm][img:Pictures/dynamic-image-2.png]\n" + "[frame:3.39cm,2.54cm][img:Pictures/dynamic-image-3.png]\n" + "[frame:1.9cm,2.54cm][img:Pictures/dynamic-image-4.png]\n" + "Fit\n" + "[frame:2.54cm,1.57cm][img:Pictures/dynamic-image-1.png]\n" + "[frame:1.57cm,2.54cm][img:Pictures/dynamic-image-2.png]\n" + "[frame:2.54cm,1.9cm][img:Pictures/dynamic-image-3.png]\n" + "[frame:1.9cm,2.54cm][img:Pictures/dynamic-image-4.png]"; assertEquals("output content", expected, actual); } }
package org.spongepowered.api.world; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import com.flowpowered.math.vector.Vector3d; import com.flowpowered.math.vector.Vector3i; import com.google.common.base.Objects; import org.spongepowered.api.Sponge; import org.spongepowered.api.block.BlockSnapshot; import org.spongepowered.api.block.BlockState; import org.spongepowered.api.block.BlockType; import org.spongepowered.api.block.BlockTypes; import org.spongepowered.api.block.ScheduledBlockUpdate; import org.spongepowered.api.block.tileentity.TileEntity; import org.spongepowered.api.data.DataContainer; import org.spongepowered.api.data.DataHolder; import org.spongepowered.api.data.DataTransactionResult; import org.spongepowered.api.data.DataView; import org.spongepowered.api.data.Property; import org.spongepowered.api.data.Queries; import org.spongepowered.api.data.key.Key; import org.spongepowered.api.data.manipulator.DataManipulator; import org.spongepowered.api.data.merge.MergeFunction; import org.spongepowered.api.data.persistence.InvalidDataException; import org.spongepowered.api.data.value.BaseValue; import org.spongepowered.api.data.value.immutable.ImmutableValue; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.entity.EntityType; import org.spongepowered.api.event.cause.Cause; import org.spongepowered.api.event.cause.EventContext; import org.spongepowered.api.event.cause.entity.spawn.SpawnType; import org.spongepowered.api.event.entity.SpawnEntityEvent; import org.spongepowered.api.util.Direction; import org.spongepowered.api.world.biome.BiomeType; import org.spongepowered.api.world.extent.EntityUniverse; import org.spongepowered.api.world.extent.Extent; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.Optional; import java.util.Set; import java.util.function.BiFunction; import java.util.function.Function; import javax.annotation.Nullable; /** * A position within a particular {@link Extent}. * * <p>This class is primarily a helper class to represent a location in a * particular {@link Extent}. The methods provided are proxy methods to ones on * {@link Extent}.</p> * * <p>Each instance can be used to either represent a block or a location on a * continuous coordinate system. Internally, positions are stored using doubles. * When a block-related method is used, the components of the position are each * rounded to an integer.</p> * * <p>Locations are immutable. Methods that change the properties of the * location create a new instance.</p> * * @param <E> The type of extent containing this location */ public final class Location<E extends Extent> implements DataHolder { private final WeakReference<E> extent; // Lazily computed, either position or blockPosition is set by the constructor @Nullable private Vector3d position = null; @Nullable private Vector3i blockPosition = null; @Nullable private Vector3i chunkPosition = null; @Nullable private Vector3i biomePosition = null; /** * Create a new instance. * * @param extent The extent * @param position The position */ public Location(E extent, Vector3d position) { this.extent = new WeakReference<>(checkNotNull(extent, "extent")); this.position = checkNotNull(position, "position"); } /** * Create a new instance. * * @param extent The extent * @param x The X-axis position * @param y The Y-axis position * @param z The Z-axis position */ public Location(E extent, double x, double y, double z) { this(extent, new Vector3d(x, y, z)); } /** * Create a new instance. * * @param extent The extent * @param blockPosition The position */ public Location(E extent, Vector3i blockPosition) { this.extent = new WeakReference<>(checkNotNull(extent, "extent")); this.blockPosition = checkNotNull(blockPosition, "blockPosition"); } /** * Create a new instance. * * @param extent The extent * @param x The X-axis position * @param y The Y-axis position * @param z The Z-axis position */ public Location(E extent, int x, int y, int z) { this(extent, new Vector3i(x, y, z)); } public E getExtent() { final E currentExtent = this.extent.get(); if (currentExtent == null) { throw new IllegalStateException(); } return currentExtent; } /** * Gets the underlying position. * * @return The underlying position */ public Vector3d getPosition() { if (this.position == null) { checkState(this.blockPosition != null); this.position = getBlockPosition().toDouble(); } return this.position; } /** * Gets the underlying block position. * * @return The underlying block position */ public Vector3i getBlockPosition() { if (this.blockPosition == null) { checkState(this.position != null); this.blockPosition = getPosition().toInt(); } return this.blockPosition; } /** * Gets the underlying chunk position. * * @return The underlying chunk position */ public Vector3i getChunkPosition() { if (this.chunkPosition == null) { this.chunkPosition = Sponge.getServer().getChunkLayout().forceToChunk(getBlockPosition()); } return this.chunkPosition; } /** * Gets the underlying biome position. * * @return The underlying biome position */ public Vector3i getBiomePosition() { if (this.biomePosition == null) { final Vector3i blockPosition = getBlockPosition(); this.biomePosition = new Vector3i(blockPosition.getX(), 0, blockPosition.getZ()); } return this.biomePosition; } /** * Gets the X component of this instance's position. * * @return The x component */ public double getX() { return getPosition().getX(); } /** * Gets the Y component of this instance's position. * * @return The y component */ public double getY() { return getPosition().getY(); } /** * Gets the Z component of this instance's position. * * @return The z component */ public double getZ() { return getPosition().getZ(); } /** * Gets the floored X component of this instance's position. * * @return The floored x component */ public int getBlockX() { return getBlockPosition().getX(); } /** * Gets the floored Y component of this instance's position. * * @return The floored y component */ public int getBlockY() { return getBlockPosition().getY(); } /** * Gets the floored Z component of this instance's position. * * @return The floored z component */ public int getBlockZ() { return getBlockPosition().getZ(); } /** * Returns true if this location is in the given extent. This is implemented * as an {@link Object#equals(Object)} check. * * @param extent The extent to check * @return Whether this location is in the extent */ public boolean inExtent(Extent extent) { return getExtent().equals(extent); } /** * Returns true if this location has a biome at its * {@link #getBiomePosition()}. * * @return Whether or not there is a biome at this location. */ public boolean hasBiome() { return getExtent().containsBiome(getBiomePosition()); } /** * Returns true if this location has a block at its * {@link #getBlockPosition()} ()}. * * @return Whether or not there is a block at this location. */ public boolean hasBlock() { return getExtent().containsBlock(getBlockPosition()); } /** * Gets a {@link LocatableBlock} if the parent {@link Extent} of this * {@link Location} is a {@link World}. * * @return The locatable block of this location, if available */ public Optional<LocatableBlock> getLocatableBlock() { return getExtent() instanceof World ? Optional.of( LocatableBlock .builder() .world((World) getExtent()) .position(this.getBlockPosition()) .build() ) : Optional.empty(); } /** * Create a new instance with a new extent. * * @param extent The new extent * @return A new instance */ public Location<E> setExtent(E extent) { checkNotNull(extent, "extent"); if (extent == getExtent()) { return this; } return new Location<>(extent, getPosition()); } /** * Create a new instance with a new position. * * @param position The new position * @return A new instance */ public Location<E> setPosition(Vector3d position) { checkNotNull(position, "position"); if (position == getPosition()) { return this; } return new Location<>(getExtent(), position); } /** * Create a new instance with a new block position. * * @param position The new position * @return A new instance */ public Location<E> setBlockPosition(Vector3i position) { checkNotNull(position, "position"); if (position == getBlockPosition()) { return this; } return new Location<>(getExtent(), position); } /** * Subtract another Vector3d to the position on this instance, returning * a new Location instance. * * @param v The vector to subtract * @return A new instance */ public Location<E> sub(Vector3d v) { return sub(v.getX(), v.getY(), v.getZ()); } /** * Subtract another Vector3i to the position on this instance, returning * a new Location instance. * * @param v The vector to subtract * @return A new instance */ public Location<E> sub(Vector3i v) { return sub(v.getX(), v.getY(), v.getZ()); } /** * Subtract vector components to the position on this instance, returning a * new Location instance. * * @param x The x component * @param y The y component * @param z The z component * @return A new instance */ public Location<E> sub(double x, double y, double z) { return setPosition(getPosition().sub(x, y, z)); } /** * Add another Vector3d to the position on this instance, returning a new * Location instance. * * @param v The vector to add * @return A new instance */ public Location<E> add(Vector3d v) { return add(v.getX(), v.getY(), v.getZ()); } /** * Add another Vector3i to the position on this instance, returning a new * Location instance. * * @param v The vector to add * @return A new instance */ public Location<E> add(Vector3i v) { return add(v.getX(), v.getY(), v.getZ()); } /** * Add vector components to the position on this instance, returning a new * Location instance. * * @param x The x component * @param y The y component * @param z The z component * @return A new instance */ public Location<E> add(double x, double y, double z) { return setPosition(getPosition().add(x, y, z)); } /** * Calls the mapper function on the extent and position. * * @param mapper The mapper * @param <T> The return type of the mapper * @return The results of the mapping */ public <T> T map(BiFunction<E, Vector3d, T> mapper) { return mapper.apply(getExtent(), getPosition()); } /** * Calls the mapper function on the extent and block position. * * @param mapper The mapper * @param <T> The return type of the mapper * @return The results of the mapping */ public <T> T mapBlock(BiFunction<E, Vector3i, T> mapper) { return mapper.apply(getExtent(), getBlockPosition()); } /** * Calls the mapper function on the extent and chunk position. * * @param mapper The mapper * @param <T> The return type of the mapper * @return The results of the mapping */ public <T> T mapChunk(BiFunction<E, Vector3i, T> mapper) { return mapper.apply(getExtent(), getChunkPosition()); } /** * Calls the mapper function on the extent and biome position. * * @param mapper The mapper * @param <T> The return type of the mapper * @return The results of the mapping */ public <T> T mapBiome(BiFunction<E, Vector3i, T> mapper) { return mapper.apply(getExtent(), getBiomePosition()); } /** * Gets the location next to this one in the given direction. * Always moves by a unit amount, even diagonally. * * @param direction The direction to move in * @return The location in that direction */ public Location<E> getRelative(Direction direction) { return add(direction.asOffset()); } public Location<E> getBlockRelative(Direction direction) { checkArgument(!direction.isSecondaryOrdinal(), "Secondary cardinal directions can't be used here"); return add(direction.asBlockOffset()); } /** * Gets the block at this location. * * @return The biome at this location */ public BiomeType getBiome() { return getExtent().getBiome(getBiomePosition()); } /** * Gets the base type of block. * * <p>The type does not include block data such as the contents of * inventories.</p> * * @return The type of block */ public BlockType getBlockType() { return getExtent().getBlockType(getBlockPosition()); } /** * Gets the {@link BlockState} for this position. * * @return The block state */ public BlockState getBlock() { return getExtent().getBlock(getBlockPosition()); } /** * Checks for whether the block at this position contains tile entity data. * * @return True if the block at this position has tile entity data, false * otherwise */ public boolean hasTileEntity() { return getExtent().getTileEntity(getBlockPosition()).isPresent(); } /** * Gets the associated {@link TileEntity} on this block. * * @return The associated tile entity, if available */ public Optional<TileEntity> getTileEntity() { return getExtent().getTileEntity(getBlockPosition()); } /** * Replace the block at this position with a new state. * * <p>This will remove any extended block data at the given position.</p> * * @param state The new block state * @return True if the block change was successful */ public boolean setBlock(BlockState state) { return getExtent().setBlock(getBlockPosition(), state); } /** * Replace the block at this position with a new state. * * <p>This will remove any extended block data at the given position.</p> * @param state The new block state * @param flag The various change flags controlling some interactions * @return True if the block change was successful */ public boolean setBlock(BlockState state, BlockChangeFlag flag) { return getExtent().setBlock(getBlockPosition(), state, flag); } /** * Replace the block type at this position by a new type. * * <p>This will remove any extended block data at the given position.</p> * * @param type The new type * @return True if the block change was successful */ public boolean setBlockType(BlockType type) { return getExtent().setBlockType(getBlockPosition(), type); } /** * Replace the block type at this position by a new type. * * <p>This will remove any extended block data at the given position.</p> * @param type The new type * @param flag The various change flags controlling some interactions * @return True if the block change was successful */ public boolean setBlockType(BlockType type, BlockChangeFlag flag) { return getExtent().setBlockType(getBlockPosition(), type, flag); } /** * Replace the block at this position with a copy of the given snapshot. * * <p>Changing the snapshot afterwards will not affect the block that has * been placed at this location.</p> * @param snapshot The snapshot * @param force If true, forces block state to be set even if the * {@link BlockType} does not match the snapshot one. * @param flag The various change flags controlling some interactions * @return True if the snapshot restore was successful */ public boolean restoreSnapshot(BlockSnapshot snapshot, boolean force, BlockChangeFlag flag) { return getExtent().restoreSnapshot(getBlockPosition(), snapshot, force, flag); } /** * Remove the block at this position by replacing it with * {@link BlockTypes#AIR}. * * <p>This will remove any extended block data at the given position.</p> * @return True if the block change was successful */ public boolean removeBlock() { return getExtent().setBlockType(getBlockPosition(), BlockTypes.AIR, BlockChangeFlags.ALL); } public Entity createEntity(EntityType type) { return this.getExtent().createEntity(type, this.getPosition()); } /** * Spawns an {@link Entity} using the already set properties (extent, * position, rotation) and applicable {@link DataManipulator}s with the * specified {@link Cause} for spawning the entity. * * <p>Note that for the {@link Cause} to be useful in the expected * {@link SpawnEntityEvent}, a {@link SpawnType} should be provided in the * {@link EventContext} for other plugins to understand and have finer * control over the event.</p> * * <p>The requirements involve that all necessary setup of states and data * is already preformed on the entity retrieved from the various * {@link EntityUniverse#createEntity(EntityType,Vector3d)} methods. Calling * this will make the now-spawned entity able to be processed by various * systems.</p> * * <p>If the entity was unable to spawn, the entity is not removed, but it * should be taken note that there can be many reasons for a failure.</p> * * @param entity The entity to spawn * @return True if successful, false if not * @see EntityUniverse#spawnEntity(Entity) */ public boolean spawnEntity(Entity entity) { return this.getExtent().spawnEntity(entity); } /** * Similar to {@link #spawnEntity(Entity)} except where multiple * entities can be attempted to be spawned with a customary {@link Cause}. * The recommended use is to easily process the entity spawns without * interference with the cause tracking system. * * @param entities The entities which spawned correctly, or empty if none * @return True if any of the entities were successfully spawned * @see EntityUniverse#spawnEntities(Iterable) */ public Collection<Entity> spawnEntities(Iterable<? extends Entity> entities) { return this.getExtent().spawnEntities(entities); } /** * Gets the highest {@link Location} at this location. * * @return The highest location at this location * @see Extent#getHighestPositionAt(Vector3i) */ public Location<E> asHighestLocation() { return this.setBlockPosition(this.getExtent().getHighestPositionAt(getBlockPosition())); } @Override public DataTransactionResult remove(Class<? extends DataManipulator<?, ?>> containerClass) { return getExtent().remove(getBlockPosition(), containerClass); } @Override public DataTransactionResult remove(BaseValue<?> value) { return getExtent().remove(getBlockPosition(), value.getKey()); } @Override public DataTransactionResult remove(Key<?> key) { return getExtent().remove(getBlockPosition(), key); } /** * Gets a snapshot of this block at the current point in time. * * <p>A snapshot is disconnected from the {@link Extent} that it was taken * from so changes to the original block do not affect the snapshot.</p> * * @return A snapshot */ public BlockSnapshot createSnapshot() { return getExtent().createSnapshot(getBlockPosition()); } /** * Gets a list of {@link ScheduledBlockUpdate}s on this block. * * @return A list of ScheduledBlockUpdates on this block */ public Collection<ScheduledBlockUpdate> getScheduledUpdates() { return getExtent().getScheduledUpdates(getBlockPosition()); } /** * Adds a new {@link ScheduledBlockUpdate} to this block. * * @param priority The priority of the scheduled update * @param ticks The ticks until the scheduled update should be processed * @return The newly created scheduled update */ public ScheduledBlockUpdate addScheduledUpdate(int priority, int ticks) { return getExtent().addScheduledUpdate(getBlockPosition(), priority, ticks); } /** * Removes a {@link ScheduledBlockUpdate} from this block. * * @param update The ScheduledBlockUpdate to remove */ public void removeScheduledUpdate(ScheduledBlockUpdate update) { getExtent().removeScheduledUpdate(getBlockPosition(), update); } @Override public <T extends Property<?, ?>> Optional<T> getProperty(Class<T> propertyClass) { return getExtent().getProperty(getBlockPosition(), propertyClass); } @Override public Collection<Property<?, ?>> getApplicableProperties() { return getExtent().getProperties(getBlockPosition()); } @Override public boolean validateRawData(DataView container) { return getExtent().validateRawData(getBlockPosition(), container); } @Override public void setRawData(DataView container) throws InvalidDataException { getExtent().setRawData(getBlockPosition(), container); } @Override public int getContentVersion() { return 2; } @Override public DataContainer toContainer() { final DataContainer container = DataContainer.createNew(); container.set(Queries.CONTENT_VERSION, getContentVersion()); if (getExtent() instanceof World) { container.set(Queries.WORLD_ID, getExtent().getUniqueId().toString()); } else if (getExtent() instanceof Chunk) { container.set(Queries.CHUNK_X, ((Chunk) getExtent()).getPosition().getX()) .set(Queries.CHUNK_Y, ((Chunk) getExtent()).getPosition().getY()) .set(Queries.CHUNK_Z, ((Chunk) getExtent()).getPosition().getZ()) .set(Queries.WORLD_ID, ((Chunk) getExtent()).getWorld().getUniqueId().toString()); } container .set(Queries.POSITION_X, this.getX()) .set(Queries.POSITION_Y, this.getY()) .set(Queries.POSITION_Z, this.getZ()); return container; } @Override public <T extends DataManipulator<?, ?>> Optional<T> get(Class<T> containerClass) { return getExtent().get(getBlockPosition(), containerClass); } @Override public <T> Optional<T> get(Key<? extends BaseValue<T>> key) { return getExtent().get(getBlockPosition(), key); } @Override public <T extends DataManipulator<?, ?>> Optional<T> getOrCreate(Class<T> containerClass) { return getExtent().getOrCreate(getBlockPosition(), containerClass); } @Override public <T> DataTransactionResult offer(Key<? extends BaseValue<T>> key, T value) { return getExtent().offer(getBlockPosition(), key, value); } @Override public DataTransactionResult offer(Iterable<DataManipulator<?, ?>> valueHolders) { return getExtent().offer(getBlockPosition(), valueHolders); } @Override public DataTransactionResult offer(Iterable<DataManipulator<?, ?>> values, MergeFunction function) { return getExtent().offer(getBlockPosition(), values, function); } @Override public <T> DataTransactionResult offer(BaseValue<T> value) { return getExtent().offer(getBlockPosition(), value); } @Override public DataTransactionResult offer(DataManipulator<?, ?> valueContainer) { return getExtent().offer(getBlockPosition(), valueContainer); } @Override public DataTransactionResult offer(DataManipulator<?, ?> valueContainer, MergeFunction function) { return getExtent().offer(getBlockPosition(), valueContainer, function); } @Override public DataTransactionResult undo(DataTransactionResult result) { return getExtent().undo(getBlockPosition(), result); } @Override public boolean supports(Class<? extends DataManipulator<?, ?>> holderClass) { return getExtent().supports(getBlockPosition(), holderClass); } @Override public boolean supports(Key<?> key) { return getExtent().supports(getBlockPosition(), key); } @Override public <T> DataTransactionResult transform(Key<? extends BaseValue<T>> key, Function<T, T> function) { return getExtent().transform(getBlockPosition(), key, function); } @Override public DataTransactionResult copyFrom(DataHolder that) { return getExtent().copyFrom(getBlockPosition(), that); } @Override public DataTransactionResult copyFrom(DataHolder that, MergeFunction strategy) { return getExtent().copyFrom(getBlockPosition(), that, strategy); } @Override public Collection<DataManipulator<?, ?>> getContainers() { return getExtent().getManipulators(getBlockPosition()); } @Override public <T, V extends BaseValue<T>> Optional<V> getValue(Key<V> key) { return getExtent().getValue(getBlockPosition(), key); } @Override public Location<E> copy() { return new Location<>(getExtent(), getPosition()); } @Override public Set<Key<?>> getKeys() { return getExtent().getKeys(getBlockPosition()); } @Override public Set<ImmutableValue<?>> getValues() { return getExtent().getValues(getBlockPosition()); } @Override public String toString() { return "Location{" + getPosition() + " in " + getExtent() + "}"; } @Override public int hashCode() { return Objects.hashCode(getExtent(), getPosition()); } @Override public boolean equals(Object other) { if (!(other instanceof Location<?>)) { return false; } Location<?> otherLoc = (Location<?>) other; return otherLoc.getExtent().equals(getExtent()) && otherLoc.getPosition().equals(getPosition()); } }
package org.jutils.jprocesses.util; import org.junit.Test; import java.text.ParseException; import java.util.Locale; import static org.junit.Assert.*; @SuppressWarnings("Since15") public class ProcessesUtilsTest { @Test public void getCustomDateFormat() throws Exception { assertEquals("10/23/2016 08:30:00", ProcessesUtils.parseUnixLongTimeToFullDate("oct 23 08:30:00 2016")); try { ProcessesUtils.parseUnixLongTimeToFullDate("23 okt 2016 08:30:00"); fail(); } catch (ParseException e) {} ProcessesUtils.setCustomDateFormat("dd MMM yyyy HH:mm:ss"); ProcessesUtils.setCustomLocale(Locale.forLanguageTag("no")); assertEquals("10/23/2016 08:30:00", ProcessesUtils.parseUnixLongTimeToFullDate("23 okt 2016 08:30:00")); } }
package uk.co.qmunity.lib.tile; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutput; import java.io.DataOutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.network.NetworkManager; import net.minecraft.network.Packet; import net.minecraft.network.play.server.S35PacketUpdateTileEntity; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import uk.co.qmunity.lib.client.renderer.RenderMultipart; import uk.co.qmunity.lib.part.IMicroblock; import uk.co.qmunity.lib.part.IPart; import uk.co.qmunity.lib.part.IPartCollidable; import uk.co.qmunity.lib.part.IPartFace; import uk.co.qmunity.lib.part.IPartInteractable; import uk.co.qmunity.lib.part.IPartOccluding; import uk.co.qmunity.lib.part.IPartRedstone; import uk.co.qmunity.lib.part.IPartSelectable; import uk.co.qmunity.lib.part.IPartSolid; import uk.co.qmunity.lib.part.IPartTicking; import uk.co.qmunity.lib.part.IPartUpdateListener; import uk.co.qmunity.lib.part.ITilePartHolder; import uk.co.qmunity.lib.part.PartRegistry; import uk.co.qmunity.lib.part.compat.OcclusionHelper; import uk.co.qmunity.lib.part.compat.PartUpdateManager; import uk.co.qmunity.lib.raytrace.QMovingObjectPosition; import uk.co.qmunity.lib.raytrace.RayTracer; import uk.co.qmunity.lib.util.QLog; import uk.co.qmunity.lib.vec.Vec3d; import uk.co.qmunity.lib.vec.Vec3dCube; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class TileMultipart extends TileEntity implements ITilePartHolder { private Map<String, IPart> parts = new HashMap<String, IPart>(); private boolean shouldDieInAFire = false; private boolean loaded = false; private final boolean simulated; public TileMultipart(boolean simulated) { this.simulated = simulated; } public TileMultipart() { this(false); } @Override public World getWorld() { return getWorldObj(); } @Override public int getX() { return xCoord; } @Override public int getY() { return yCoord; } @Override public int getZ() { return zCoord; } @Override public List<IPart> getParts() { List<IPart> parts = new ArrayList<IPart>(); for (String s : this.parts.keySet()) { IPart p = this.parts.get(s); if (p.getParent() != null) parts.add(p); } return parts; } @Override public boolean canAddPart(IPart part) { if (part instanceof IPartCollidable) { List<Vec3dCube> cubes = new ArrayList<Vec3dCube>(); ((IPartCollidable) part).addCollisionBoxesToList(cubes, null); for (Vec3dCube c : cubes) if (!getWorld().checkNoEntityCollision(c.clone().add(getX(), getY(), getZ()).toAABB())) return false; } return OcclusionHelper.occlusionTest(this, part); } @Override public void addPart(IPart part) { int before = parts.size(); parts.put(genIdentifier(), part); part.setParent(this); if (!simulated) { if (part instanceof IPartUpdateListener) ((IPartUpdateListener) part).onAdded(); for (IPart p : getParts()) if (p != part && p instanceof IPartUpdateListener) ((IPartUpdateListener) p).onPartChanged(part); if (before > 0) PartUpdateManager.addPart(this, part); markDirty(); getWorld().markBlockRangeForRenderUpdate(getX(), getY(), getZ(), getX(), getY(), getZ()); if (!getWorld().isRemote && before > 0) getWorld().notifyBlocksOfNeighborChange(getX(), getY(), getZ(), blockType); } } @Override public boolean removePart(IPart part) { if (part == null) return false; if (!parts.containsValue(part)) return false; if (part.getParent() == null || part.getParent() != this) return false; if (!simulated) { PartUpdateManager.removePart(this, part); if (part instanceof IPartUpdateListener) ((IPartUpdateListener) part).onRemoved(); } String id = getIdentifier(part); parts.remove(id); part.setParent(null); if (!simulated) { for (IPart p : getParts()) if (p != part && p instanceof IPartUpdateListener) ((IPartUpdateListener) p).onPartChanged(part); markDirty(); getWorld().markBlockRangeForRenderUpdate(getX(), getY(), getZ(), getX(), getY(), getZ()); if (!getWorld().isRemote) getWorld().notifyBlocksOfNeighborChange(getX(), getY(), getZ(), blockType); } return true; } private String genIdentifier() { String s = null; do { s = UUID.randomUUID().toString(); } while (parts.containsKey(s)); return s; } private String getIdentifier(IPart part) { for (String s : parts.keySet()) if (parts.get(s).equals(part)) return s; return null; } private IPart getPart(String id) { for (String s : parts.keySet()) if (s.equals(id)) return parts.get(s); return null; } public int getLightValue() { int val = 0; for (IPart p : getParts()) val = Math.max(val, p.getLightValue()); return val; } @Override public QMovingObjectPosition rayTrace(Vec3d start, Vec3d end) { QMovingObjectPosition closest = null; double dist = Double.MAX_VALUE; for (IPart p : getParts()) { if (p instanceof IPartSelectable) { QMovingObjectPosition mop = ((IPartSelectable) p).rayTrace(start, end); if (mop == null) continue; double d = start.distanceTo(new Vec3d(mop.hitVec)); if (d < dist) { closest = mop; dist = d; } } } return closest; } // Saving/loading/syncing parts @Override public void writeToNBT(NBTTagCompound tag) { super.writeToNBT(tag); NBTTagList l = new NBTTagList(); writeParts(l, false); tag.setTag("parts", l); } @Override public void readFromNBT(NBTTagCompound tag) { super.readFromNBT(tag); NBTTagList l = tag.getTagList("parts", new NBTTagCompound().getId()); readParts(l, false, false); loaded = true; if (getParts().size() == 0) shouldDieInAFire = true; } public void writeUpdateToNBT(NBTTagCompound tag) { NBTTagList l = new NBTTagList(); writeParts(l, true); tag.setTag("parts", l); } public void readUpdateFromNBT(NBTTagCompound tag) { NBTTagList l = tag.getTagList("parts", new NBTTagCompound().getId()); readParts(l, true, true); getWorldObj().markBlockRangeForRenderUpdate(xCoord, yCoord, zCoord, xCoord, yCoord, zCoord); } private void writeParts(NBTTagList l, boolean update) { for (IPart p : getParts()) { String id = getIdentifier(p); NBTTagCompound tag = new NBTTagCompound(); tag.setString("id", id); tag.setString("type", p.getType()); NBTTagCompound data = new NBTTagCompound(); if (update) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutput buffer = new DataOutputStream(baos); try { p.writeUpdateData(buffer, -1); baos.flush(); } catch (Exception ex) { ex.printStackTrace(); } data.setByteArray("data", baos.toByteArray()); } else { p.writeToNBT(data); } tag.setTag("data", data); l.appendTag(tag); } } private void readParts(NBTTagList l, boolean update, boolean client) { for (int i = 0; i < l.tagCount(); i++) { NBTTagCompound tag = l.getCompoundTagAt(i); String id = tag.getString("id"); IPart p = getPart(id); if (p == null) { p = PartRegistry.createPart(tag.getString("type"), client); if (p == null) continue; p.setParent(this); parts.put(id, p); } NBTTagCompound data = tag.getCompoundTag("data"); if (update) { try { p.readUpdateData(new DataInputStream(new ByteArrayInputStream(data.getByteArray("data"))), -1); } catch (Exception ex) { ex.printStackTrace(); } } else { p.readFromNBT(data); } } } @Override public void sendUpdatePacket(IPart part, int channel) { if (getWorld() != null && getParts().contains(part)) PartUpdateManager.sendPartUpdate(this, part, channel); } @Override public Packet getDescriptionPacket() { NBTTagCompound tag = new NBTTagCompound(); writeUpdateToNBT(tag); return new S35PacketUpdateTileEntity(xCoord, yCoord, zCoord, 0, tag); } @Override public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) { readUpdateFromNBT(pkt.func_148857_g()); } public void removePart(EntityPlayer player) { QMovingObjectPosition mop = rayTrace(RayTracer.getStartVector(player), RayTracer.getEndVector(player)); if (mop != null) if (mop.getPart().breakAndDrop(player, mop)) mop.getPart().getParent().removePart(mop.getPart()); } @Override public void addCollisionBoxesToList(List<Vec3dCube> l, AxisAlignedBB bounds, Entity entity) { List<Vec3dCube> boxes = new ArrayList<Vec3dCube>(); for (IPart p : getParts()) { if (p instanceof IPartCollidable) { List<Vec3dCube> boxes_ = new ArrayList<Vec3dCube>(); ((IPartCollidable) p).addCollisionBoxesToList(boxes_, entity); for (Vec3dCube c : boxes_) { Vec3dCube cube = c.clone(); cube.add(getX(), getY(), getZ()); cube.setPart(p); boxes.add(cube); } boxes_.clear(); } } for (Vec3dCube c : boxes) { if (c.toAABB().intersectsWith(bounds)) l.add(c); } } public void onNeighborBlockChange() { if (simulated) return; onUpdate(); for (IPart p : getParts()) if (p instanceof IPartUpdateListener) ((IPartUpdateListener) p).onNeighborBlockChange(); onUpdate(); } public void onNeighborChange() { if (simulated) return; onUpdate(); for (IPart p : getParts()) if (p instanceof IPartUpdateListener) ((IPartUpdateListener) p).onNeighborTileChange(); onUpdate(); } private void onUpdate() { if (simulated) return; if (!getWorldObj().isRemote) { if (getParts().size() == 0) getWorldObj().setBlockToAir(xCoord, yCoord, zCoord); } } public boolean isSideSolid(ForgeDirection face) { for (IPart p : getParts()) if (p instanceof IPartSolid) if (((IPartSolid) p).isSideSolid(face)) return true; return false; } private boolean firstTick = true; @Override public void updateEntity() { if (firstTick && loaded) { for (IPart p : getParts()) { if (p instanceof IPartUpdateListener) ((IPartUpdateListener) p).onLoaded(); } firstTick = false; } for (IPart p : getParts()) if (p instanceof IPartTicking) ((IPartTicking) p).update(); if(parts.size() > 100) { QLog.error("A Qmunitylib part has " + parts.size() + " parts! It has been removed. Dimension: " + getWorld().provider.dimensionId + ", location: " + getX() + ", " + getY() + ", " + getZ()); shouldDieInAFire = true; } if (shouldDieInAFire) getWorld().setBlockToAir(getX(), getY(), getZ()); } public List<Vec3dCube> getOcclusionBoxes() { List<Vec3dCube> boxes = new ArrayList<Vec3dCube>(); for (IPart p : getParts()) if (p instanceof IPartOccluding) boxes.addAll(((IPartOccluding) p).getOcclusionBoxes()); return boxes; } public int getStrongOutput(ForgeDirection direction, ForgeDirection face) { int max = 0; for (IPart p : getParts()) { if (p instanceof IPartRedstone) { if (p instanceof IPartFace) { if (((IPartFace) p).getFace() == face) max = Math.max(max, ((IPartRedstone) p).getStrongPower(direction)); } else { max = Math.max(max, ((IPartRedstone) p).getStrongPower(direction)); } } } return max; } public int getStrongOutput(ForgeDirection direction) { int max = 0; for (ForgeDirection face : ForgeDirection.VALID_DIRECTIONS) max = Math.max(max, getStrongOutput(direction, face)); return max; } public int getWeakOutput(ForgeDirection direction, ForgeDirection face) { int max = 0; for (IPart p : getParts()) { if (p instanceof IPartRedstone) { if (p instanceof IPartFace) { if (((IPartFace) p).getFace() == face) max = Math.max(max, ((IPartRedstone) p).getWeakPower(direction)); } else { max = Math.max(max, ((IPartRedstone) p).getWeakPower(direction)); } } } return max; } public int getWeakOutput(ForgeDirection direction) { int max = 0; for (ForgeDirection face : ForgeDirection.VALID_DIRECTIONS) max = Math.max(max, getWeakOutput(direction, face)); return max; } public boolean canConnect(ForgeDirection direction, ForgeDirection face) { for (IPart p : getParts()) { if (p instanceof IPartRedstone) { if (p instanceof IPartFace) { if (((IPartFace) p).getFace() == face) if (((IPartRedstone) p).canConnectRedstone(direction)) return true; } else { if (((IPartRedstone) p).canConnectRedstone(direction)) return true; } } } return false; } public boolean canConnect(ForgeDirection direction) { for (ForgeDirection face : ForgeDirection.VALID_DIRECTIONS) if (canConnect(direction, face)) return true; return false; } @Override public void onChunkUnload() { if (simulated) return; for (IPart p : getParts()) if (p instanceof IPartUpdateListener) ((IPartUpdateListener) p).onUnloaded(); } @Override @SideOnly(Side.CLIENT) public AxisAlignedBB getRenderBoundingBox() { return AxisAlignedBB.getBoundingBox(xCoord, yCoord, zCoord, xCoord + 1, yCoord + 1, zCoord + 1); } public ItemStack pickUp(EntityPlayer player) { QMovingObjectPosition mop = rayTrace(RayTracer.getStartVector(player), RayTracer.getEndVector(player)); if (mop != null) { return mop.getPart().getPickedItem(mop); } return null; } @Override public Map<String, IPart> getPartMap() { return parts; } public void onClicked(EntityPlayer player) { QMovingObjectPosition mop = rayTrace(RayTracer.getStartVector(player), RayTracer.getEndVector(player)); if (mop != null) if (mop.getPart() instanceof IPartInteractable) ((IPartInteractable) mop.getPart()).onClicked(player, mop, player.getCurrentEquippedItem()); } public boolean onActivated(EntityPlayer player) { QMovingObjectPosition mop = rayTrace(RayTracer.getStartVector(player), RayTracer.getEndVector(player)); if (mop != null) if (mop.getPart() instanceof IPartInteractable) return ((IPartInteractable) mop.getPart()).onActivated(player, mop, player.getCurrentEquippedItem()); return false; } @Override public List<IMicroblock> getMicroblocks() { List<IMicroblock> microblocks = new ArrayList<IMicroblock>(); for (IPart p : getParts()) if (p instanceof IMicroblock) microblocks.add((IMicroblock) p); return microblocks; } @Override public boolean isSimulated() { return simulated; } @Override public boolean shouldRenderInPass(int pass) { RenderMultipart.pass = pass; return true; } }
package util.validator; import http.helpers.Helper; import io.appium.java_client.AppiumDriver; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.ParseException; import org.openqa.selenium.Dimension; import org.openqa.selenium.*; import org.openqa.selenium.Point; import util.driver.PageValidator; import util.general.HtmlReportBuilder; import util.validator.properties.Padding; import javax.imageio.ImageIO; import java.awt.*; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.atomic.AtomicLong; import static environment.EnvironmentFactory.*; import static util.general.SystemHelper.isRetinaDisplay; import static util.validator.Constants.*; import static util.validator.ResponsiveUIValidator.Units.PX; public class ResponsiveUIValidator { static final int MIN_OFFSET = -10000; private final static Logger LOG = Logger.getLogger(ResponsiveUIValidator.class); protected static WebDriver driver; static WebElement rootElement; static long startTime; private static boolean isMobileTopBar = false; private static boolean withReport = false; private static String scenarioName = "Default"; private static Color rootColor = new Color(255, 0, 0, 255); private static Color highlightedElementsColor = new Color(255, 0, 255, 255); private static Color linesColor = Color.ORANGE; private static String currentZoom = "100%"; private static List<String> jsonFiles = new ArrayList<>(); private static File screenshot; private static BufferedImage img; private static Graphics2D g; private static JSONArray errorMessage; boolean drawLeftOffsetLine = false; boolean drawRightOffsetLine = false; boolean drawTopOffsetLine = false; boolean drawBottomOffsetLine = false; String rootElementReadableName = "Root Element"; List<WebElement> rootElements; ResponsiveUIValidator.Units units = PX; int xRoot; int yRoot; int widthRoot; int heightRoot; int pageWidth; int pageHeight; public ResponsiveUIValidator(WebDriver driver) { ResponsiveUIValidator.driver = driver; errorMessage = new JSONArray(); } /** * Set color for main element. This color will be used for highlighting element in results * * @param color */ public void setColorForRootElement(Color color) { rootColor = color; } /** * Set color for compared elements. This color will be used for highlighting elements in results * * @param color */ public void setColorForHighlightedElements(Color color) { highlightedElementsColor = color; } /** * Set color for grid lines. This color will be used for the lines of alignment grid in results * * @param color */ public void setLinesColor(Color color) { linesColor = color; } /** * Set top bar mobile offset. Applicable only for native mobile testing * * @param state */ public void setTopBarMobileOffset(boolean state) { isMobileTopBar = state; } /** * Method that defines start of new validation. Needs to be called each time before calling findElement(), findElements() * * @return ResponsiveUIValidator */ public ResponsiveUIValidator init() { return new ResponsiveUIValidator(driver); } /** * Method that defines start of new validation with specified name of scenario. Needs to be called each time before calling findElement(), findElements() * * @param scenarioName * @return ResponsiveUIValidator */ public ResponsiveUIValidator init(String scenarioName) { ResponsiveUIValidator.scenarioName = scenarioName; return new ResponsiveUIValidator(driver); } /** * Main method to specify which element we want to validate (can be called only findElement() OR findElements() for single validation) * * @param element * @param readableNameOfElement * @return UIValidator */ public UIValidator findElement(WebElement element, String readableNameOfElement) { return new UIValidator(driver, element, readableNameOfElement); } /** * Main method to specify the list of elements that we want to validate (can be called only findElement() OR findElements() for single validation) * * @param elements * @return ResponsiveUIChunkValidator */ public ResponsiveUIChunkValidator findElements(java.util.List<WebElement> elements) { return new ResponsiveUIChunkValidator(driver, elements); } /** * Change units to Pixels or % (Units.PX, Units.PERCENT) * * @param units * @return UIValidator */ public ResponsiveUIValidator changeMetricsUnitsTo(Units units) { this.units = units; return this; } /** * Methods needs to be called to collect all the results in JSON file and screenshots * * @return ResponsiveUIValidator */ public ResponsiveUIValidator drawMap() { withReport = true; return this; } /** * Call method to summarize and validate the results (can be called with drawMap(). In this case result will be only True or False) * * @return boolean */ public boolean validate() { JSONObject jsonResults = new JSONObject(); jsonResults.put(ERROR_KEY, false); if (rootElement != null) { if (!errorMessage.isEmpty()) { jsonResults.put(ERROR_KEY, true); jsonResults.put(DETAILS, errorMessage); if (withReport) { try { screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); img = ImageIO.read(screenshot); } catch (Exception e) { LOG.error("Failed to create screenshot file: " + e.getMessage()); } JSONObject rootDetails = new JSONObject(); rootDetails.put(X, xRoot); rootDetails.put(Y, yRoot); rootDetails.put(WIDTH, widthRoot); rootDetails.put(HEIGHT, heightRoot); jsonResults.put(SCENARIO, scenarioName); jsonResults.put(ROOT_ELEMENT, rootDetails); jsonResults.put(TIME_EXECUTION, String.valueOf(System.currentTimeMillis() - startTime) + " milliseconds"); jsonResults.put(ELEMENT_NAME, rootElementReadableName); jsonResults.put(SCREENSHOT, rootElementReadableName.replace(" ", "") + "-" + screenshot.getName()); long ms = System.currentTimeMillis(); String uuid = Helper.getGeneratedStringWithLength(7); String jsonFileName = rootElementReadableName.replace(" ", "") + "-automotion" + ms + uuid + ".json"; try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(TARGET_AUTOMOTION_JSON + jsonFileName), StandardCharsets.UTF_8))) { writer.write(jsonResults.toJSONString()); } catch (IOException ex) { LOG.error("Cannot create json report: " + ex.getMessage()); } jsonFiles.add(jsonFileName); try { File file = new File(TARGET_AUTOMOTION_JSON + rootElementReadableName.replace(" ", "") + "-automotion" + ms + uuid + ".json"); if (file.getParentFile().mkdirs()) { if (file.createNewFile()) { BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.write(jsonResults.toJSONString()); writer.close(); } } } catch (IOException e) { e.printStackTrace(); } if ((boolean) jsonResults.get(ERROR_KEY)) { drawScreenshot(); } } } } else { jsonResults.put(ERROR_KEY, true); jsonResults.put(DETAILS, "Set root web element"); } return !((boolean) jsonResults.get(ERROR_KEY)); } /** * Call method to generate HTML report */ public void generateReport() { if (withReport && !jsonFiles.isEmpty()) { try { new HtmlReportBuilder().buildReport(jsonFiles); } catch (IOException | ParseException | InterruptedException e) { e.printStackTrace(); } } } /** * Call method to generate HTML report with specified file report name * * @param name */ public void generateReport(String name) { if (withReport && !jsonFiles.isEmpty()) { try { new HtmlReportBuilder().buildReport(name, jsonFiles); } catch (IOException | ParseException | InterruptedException e) { e.printStackTrace(); } } } void drawScreenshot() { if (img != null) { g = img.createGraphics(); drawRoot(rootColor); for (Object obj : errorMessage) { JSONObject det = (JSONObject) obj; JSONObject details = (JSONObject) det.get(REASON); JSONObject numE = (JSONObject) details.get(ELEMENT); if (numE != null) { float x = (float) numE.get(X); float y = (float) numE.get(Y); float width = (float) numE.get(WIDTH); float height = (float) numE.get(HEIGHT); g.setColor(highlightedElementsColor); g.setStroke(new BasicStroke(2)); g.drawRect(retinaValue((int) x), retinaValue(mobileY((int) y)), retinaValue((int) width), retinaValue((int) height)); } } try { ImageIO.write(img, "png", screenshot); File file = new File(TARGET_AUTOMOTION_IMG + rootElementReadableName.replace(" ", "") + "-" + screenshot.getName()); FileUtils.copyFile(screenshot, file); } catch (IOException e) { e.printStackTrace(); } } else { LOG.error("Taking of screenshot was failed for some reason."); } } void validateElementsAreNotOverlapped(List<WebElement> rootElements) { for (WebElement el1 : rootElements) { for (WebElement el2 : rootElements) { if (!el1.equals(el2)) { if (elementsAreOverlapped(el1, el2)) { putJsonDetailsWithElement("Elements are overlapped", el1); break; } } } } } void validateGridAlignment(int columns, int rows) { if (rootElements != null) { ConcurrentSkipListMap<Integer, AtomicLong> map = new ConcurrentSkipListMap<>(); for (WebElement el : rootElements) { Integer y = el.getLocation().y; map.putIfAbsent(y, new AtomicLong(0)); map.get(y).incrementAndGet(); } int mapSize = map.size(); if (rows > 0) { if (mapSize != rows) { putJsonDetailsWithoutElement(String.format("Elements in a grid are not aligned properly. Looks like grid has wrong amount of rows. Expected is %d. Actual is %d", rows, mapSize)); } } if (columns > 0) { int errorLastLine = 0; int rowCount = 1; for (Map.Entry<Integer, AtomicLong> entry : map.entrySet()) { if (rowCount <= mapSize) { int actualInARow = entry.getValue().intValue(); if (actualInARow != columns) { errorLastLine++; if (errorLastLine > 1) { putJsonDetailsWithoutElement(String.format("Elements in a grid are not aligned properly in row #%d. Expected %d elements in a row. Actually it's %d", rowCount, columns, actualInARow)); } } rowCount++; } } } } } void validateRightOffsetForChunk(List<WebElement> elements) { for (int i = 0; i < elements.size() - 1; i++) { if (!elementsHaveEqualRightOffset(elements.get(i), elements.get(i + 1))) { putJsonDetailsWithElement(String.format("Element #%d has not the same right offset as element #%d", i + 1, i + 2), elements.get(i + 1)); } } } void validateLeftOffsetForChunk(List<WebElement> elements) { for (int i = 0; i < elements.size() - 1; i++) { if (!elementsHaveEqualLeftOffset(elements.get(i), elements.get(i + 1))) { putJsonDetailsWithElement(String.format("Element #%d has not the same left offset as element #%d", i + 1, i + 2), elements.get(i + 1)); } } } void validateTopOffsetForChunk(List<WebElement> elements) { for (int i = 0; i < elements.size() - 1; i++) { if (!elementsHaveEqualTopOffset(elements.get(i), elements.get(i + 1))) { putJsonDetailsWithElement(String.format("Element #%d has not the same top offset as element #%d", i + 1, i + 2), elements.get(i + 1)); } } } void validateBottomOffsetForChunk(List<WebElement> elements) { for (int i = 0; i < elements.size() - 1; i++) { if (!elementsHaveEqualBottomOffset(elements.get(i), elements.get(i + 1))) { putJsonDetailsWithElement(String.format("Element #%d has not the same bottom offset as element #%d", i + 1, i + 2), elements.get(i + 1)); } } } void validateRightOffsetForElements(WebElement element, String readableName) { if (!element.equals(rootElement)) { if (!elementsHaveEqualRightOffset(rootElement, element)) { putJsonDetailsWithElement(String.format("Element '%s' has not the same right offset as element '%s'", rootElementReadableName, readableName), element); } } } void validateLeftOffsetForElements(WebElement element, String readableName) { if (!element.equals(rootElement)) { if (!elementsHaveEqualLeftOffset(rootElement, element)) { putJsonDetailsWithElement(String.format("Element '%s' has not the same left offset as element '%s'", rootElementReadableName, readableName), element); } } } void validateTopOffsetForElements(WebElement element, String readableName) { if (!element.equals(rootElement)) { if (!elementsHaveEqualTopOffset(rootElement, element)) { putJsonDetailsWithElement(String.format("Element '%s' has not the same top offset as element '%s'", rootElementReadableName, readableName), element); } } } void validateBottomOffsetForElements(WebElement element, String readableName) { if (!element.equals(rootElement)) { if (!elementsHaveEqualBottomOffset(rootElement, element)) { putJsonDetailsWithElement(String.format("Element '%s' has not the same bottom offset as element '%s'", rootElementReadableName, readableName), element); } } } void validateNotOverlappingWithElements(WebElement element, String readableName) { if (!element.equals(rootElement)) { if (elementsAreOverlapped(rootElement, element)) { putJsonDetailsWithElement(String.format("Element '%s' is overlapped with element '%s' but should not", rootElementReadableName, readableName), element); } } } void validateOverlappingWithElements(WebElement element, String readableName) { if (!element.equals(rootElement)) { if (!elementsAreOverlapped(rootElement, element)) { putJsonDetailsWithElement(String.format("Element '%s' is not overlapped with element '%s' but should be", rootElementReadableName, readableName), element); } } } void validateMaxOffset(int top, int right, int bottom, int left) { int rootElementRightOffset = getRightOffset(rootElement); int rootElementBottomOffset = getBottomOffset(rootElement); if (xRoot > left) { putJsonDetailsWithoutElement(String.format("Expected max left offset of element '%s' is: %spx. Actual left offset is: %spx", rootElementReadableName, left, xRoot)); } if (yRoot > top) { putJsonDetailsWithoutElement(String.format("Expected max top offset of element '%s' is: %spx. Actual top offset is: %spx", rootElementReadableName, top, yRoot)); } if (rootElementRightOffset > right) { putJsonDetailsWithoutElement(String.format("Expected max right offset of element '%s' is: %spx. Actual right offset is: %spx", rootElementReadableName, right, rootElementRightOffset)); } if (rootElementBottomOffset > bottom) { putJsonDetailsWithoutElement(String.format("Expected max bottom offset of element '%s' is: %spx. Actual bottom offset is: %spx", rootElementReadableName, bottom, rootElementBottomOffset)); } } void validateMinOffset(int top, int right, int bottom, int left) { int rootElementRightOffset = getRightOffset(rootElement); int rootElementBottomOffset = getBottomOffset(rootElement); if (xRoot < left) { putJsonDetailsWithoutElement(String.format("Expected min left offset of element '%s' is: %spx. Actual left offset is: %spx", rootElementReadableName, left, xRoot)); } if (yRoot < top) { putJsonDetailsWithoutElement(String.format("Expected min top offset of element '%s' is: %spx. Actual top offset is: %spx", rootElementReadableName, top, yRoot)); } if (rootElementRightOffset < right) { putJsonDetailsWithoutElement(String.format("Expected min top offset of element '%s' is: %spx. Actual right offset is: %spx", rootElementReadableName, right, rootElementRightOffset)); } if (rootElementBottomOffset < bottom) { putJsonDetailsWithoutElement(String.format("Expected min bottom offset of element '%s' is: %spx. Actual bottom offset is: %spx", rootElementReadableName, bottom, rootElementBottomOffset)); } } void validateMaxHeight(int height) { if (heightRoot > height) { putJsonDetailsWithoutElement(String.format("Expected max height of element '%s' is: %spx. Actual height is: %spx", rootElementReadableName, height, heightRoot)); } } void validateMinHeight(int height) { if (heightRoot < height) { putJsonDetailsWithoutElement(String.format("Expected min height of element '%s' is: %spx. Actual height is: %spx", rootElementReadableName, height, heightRoot)); } } void validateSameHeight(WebElement element, String readableName) { if (!element.equals(rootElement)) { int h = element.getSize().getHeight(); if (h != heightRoot) { putJsonDetailsWithElement(String.format("Element '%s' has not the same height as %s. Height of '%s' is %spx. Height of element is %spx", rootElementReadableName, readableName, rootElementReadableName, heightRoot, h), element); } } } void validateMaxWidth(int width) { if (widthRoot > width) { putJsonDetailsWithoutElement(String.format("Expected max width of element '%s' is: %spx. Actual width is: %spx", rootElementReadableName, width, widthRoot)); } } void validateMinWidth(int width) { if (widthRoot < width) { putJsonDetailsWithoutElement(String.format("Expected min width of element '%s' is: %spx. Actual width is: %spx", rootElementReadableName, width, widthRoot)); } } void validateSameWidth(WebElement element, String readableName) { if (!element.equals(rootElement)) { int w = element.getSize().getWidth(); if (w != widthRoot) { putJsonDetailsWithElement(String.format("Element '%s' has not the same width as %s. Width of '%s' is %spx. Width of element is %spx", rootElementReadableName, readableName, rootElementReadableName, widthRoot, w), element); } } } void validateSameSize(WebElement element, String readableName) { if (!element.equals(rootElement)) { int h = element.getSize().getHeight(); int w = element.getSize().getWidth(); if (h != heightRoot || w != widthRoot) { putJsonDetailsWithElement(String.format("Element '%s' has not the same size as %s. Size of '%s' is %spx x %spx. Size of element is %spx x %spx", rootElementReadableName, readableName, rootElementReadableName, widthRoot, heightRoot, w, h), element); } } } void validateSameSize(List<WebElement> elements, int type) { for (int i = 0; i < elements.size() - 1; i++) { int h1 = elements.get(i).getSize().getHeight(); int w1 = elements.get(i).getSize().getWidth(); int h2 = elements.get(i + 1).getSize().getHeight(); int w2 = elements.get(i + 1).getSize().getWidth(); switch (type) { case 0: if (h1 != h2 || w1 != w2) { putJsonDetailsWithElement(String.format("Element #%d has different size. Element size is: [%d, %d]", (i + 1), elements.get(i).getSize().width, elements.get(i).getSize().height), elements.get(i)); putJsonDetailsWithElement(String.format("Element #%d has different size. Element size is: [%d, %d]", (i + 2), elements.get(i + 1).getSize().width, elements.get(i + 1).getSize().height), elements.get(i + 1)); } break; case 1: if (w1 != w2) { putJsonDetailsWithElement(String.format("Element #%d has different width. Element width is: [%d, %d]", (i + 1), elements.get(i).getSize().width, elements.get(i).getSize().height), elements.get(i)); putJsonDetailsWithElement(String.format("Element #%d has different width. Element width is: [%d, %d]", (i + 2), elements.get(i + 1).getSize().width, elements.get(i + 1).getSize().height), elements.get(i + 1)); } break; case 2: if (h1 != h2) { putJsonDetailsWithElement(String.format("Element #%d has different height. Element height is: [%d, %d]", (i + 1), elements.get(i).getSize().width, elements.get(i).getSize().height), elements.get(i)); putJsonDetailsWithElement(String.format("Element #%d has different height. Element height is: [%d, %d]", (i + 2), elements.get(i + 1).getSize().width, elements.get(i + 1).getSize().height), elements.get(i + 1)); } } } } void validateNotSameSize(WebElement element, String readableName) { if (!element.equals(rootElement)) { int h = element.getSize().getHeight(); int w = element.getSize().getWidth(); if (h == heightRoot && w == widthRoot) { putJsonDetailsWithElement(String.format("Element '%s' has the same size as %s. Size of '%s' is %spx x %spx. Size of element is %spx x %spx", rootElementReadableName, readableName, rootElementReadableName, widthRoot, heightRoot, w, h), element); } } } void validateNotSameSize(List<WebElement> elements, int type) { for (int i = 0; i < elements.size() - 1; i++) { int h1 = elements.get(i).getSize().getHeight(); int w1 = elements.get(i).getSize().getWidth(); int h2 = elements.get(i + 1).getSize().getHeight(); int w2 = elements.get(i + 1).getSize().getWidth(); switch (type) { case 0: if (h1 == h2 && w1 == w2) { putJsonDetailsWithElement(String.format("Element #%d has same size. Element size is: [%d, %d]", (i + 1), elements.get(i).getSize().width, elements.get(i).getSize().height), elements.get(i)); putJsonDetailsWithElement(String.format("Element #%d has same size. Element size is: [%d, %d]", (i + 2), elements.get(i + 1).getSize().width, elements.get(i + 1).getSize().height), elements.get(i + 1)); } break; case 1: if (w1 == w2) { putJsonDetailsWithElement(String.format("Element #%d has same width. Element width is: [%d, %d]", (i + 1), elements.get(i).getSize().width, elements.get(i).getSize().height), elements.get(i)); putJsonDetailsWithElement(String.format("Element #%d has same width. Element width is: [%d, %d]", (i + 2), elements.get(i + 1).getSize().width, elements.get(i + 1).getSize().height), elements.get(i + 1)); } break; case 2: if (h1 == h2) { putJsonDetailsWithElement(String.format("Element #%d has same height. Element height is: [%d, %d]", (i + 1), elements.get(i).getSize().width, elements.get(i).getSize().height), elements.get(i)); putJsonDetailsWithElement(String.format("Element #%d has same height. Element height is: [%d, %d]", (i + 2), elements.get(i + 1).getSize().width, elements.get(i + 1).getSize().height), elements.get(i + 1)); } } } } void validateBelowElement(WebElement element, int minMargin, int maxMargin) { int yBelowElement = element.getLocation().y; int marginBetweenRoot = yBelowElement - (yRoot + heightRoot); if (marginBetweenRoot < minMargin || marginBetweenRoot > maxMargin) { putJsonDetailsWithElement(String.format("Below element aligned not properly. Expected margin should be between %spx and %spx. Actual margin is %spx", minMargin, maxMargin, marginBetweenRoot), element); } } void validateBelowElement(WebElement element) { List<WebElement> elements = new ArrayList<>(); elements.add(rootElement); elements.add(element); if (!PageValidator.elementsAreAlignedVertically(elements)) { putJsonDetailsWithoutElement("Below element aligned not properly"); } } void validateAboveElement(WebElement element, int minMargin, int maxMargin) { int yAboveElement = element.getLocation().y; int heightAboveElement = element.getSize().height; int marginBetweenRoot = yRoot - (yAboveElement + heightAboveElement); if (marginBetweenRoot < minMargin || marginBetweenRoot > maxMargin) { putJsonDetailsWithElement(String.format("Above element aligned not properly. Expected margin should be between %spx and %spx. Actual margin is %spx", minMargin, maxMargin, marginBetweenRoot), element); } } void validateAboveElement(WebElement element) { List<WebElement> elements = new ArrayList<>(); elements.add(element); elements.add(rootElement); if (!PageValidator.elementsAreAlignedVertically(elements)) { putJsonDetailsWithoutElement("Above element aligned not properly"); } } void validateRightElement(WebElement element, int minMargin, int maxMargin) { int xRightElement = element.getLocation().x; int marginBetweenRoot = xRightElement - (xRoot + widthRoot); if (marginBetweenRoot < minMargin || marginBetweenRoot > maxMargin) { putJsonDetailsWithElement(String.format("Right element aligned not properly. Expected margin should be between %spx and %spx. Actual margin is %spx", minMargin, maxMargin, marginBetweenRoot), element); } } void validateRightElement(WebElement element) { List<WebElement> elements = new ArrayList<>(); elements.add(rootElement); elements.add(element); if (!PageValidator.elementsAreAlignedHorizontally(elements)) { putJsonDetailsWithoutElement("Right element aligned not properly"); } } void validateLeftElement(WebElement leftElement, int minMargin, int maxMargin) { int xLeftElement = leftElement.getLocation().x; int widthLeftElement = leftElement.getSize().width; int marginBetweenRoot = xRoot - (xLeftElement + widthLeftElement); if (marginBetweenRoot < minMargin || marginBetweenRoot > maxMargin) { putJsonDetailsWithElement(String.format("Left element aligned not properly. Expected margin should be between %spx and %spx. Actual margin is %spx", minMargin, maxMargin, marginBetweenRoot), leftElement); } } void validateLeftElement(WebElement leftElement) { List<WebElement> elements = new ArrayList<>(); elements.add(leftElement); elements.add(rootElement); if (!PageValidator.elementsAreAlignedHorizontally(elements)) { putJsonDetailsWithoutElement("Left element aligned not properly"); } } void validateEqualLeftRightOffset(WebElement element, String rootElementReadableName) { if (!elementHasEqualLeftRightOffset(element)) { putJsonDetailsWithElement(String.format("Element '%s' has not equal left and right offset. Left offset is %dpx, right is %dpx", rootElementReadableName, getLeftOffset(element), getRightOffset(element)), element); } } void validateEqualTopBottomOffset(WebElement element, String rootElementReadableName) { if (!elementHasEqualTopBottomOffset(element)) { putJsonDetailsWithElement(String.format("Element '%s' has not equal top and bottom offset. Top offset is %dpx, bottom is %dpx", rootElementReadableName, getTopOffset(element), getBottomOffset(element)), element); } } void validateEqualLeftRightOffset(List<WebElement> elements) { for (WebElement element : elements) { if (!elementHasEqualLeftRightOffset(element)) { putJsonDetailsWithElement(String.format("Element '%s' has not equal left and right offset. Left offset is %dpx, right is %dpx", getFormattedMessage(element), getLeftOffset(element), getRightOffset(element)), element); } } } void validateEqualTopBottomOffset(List<WebElement> elements) { for (WebElement element : elements) { if (!elementHasEqualTopBottomOffset(element)) { putJsonDetailsWithElement(String.format("Element '%s' has not equal top and bottom offset. Top offset is %dpx, bottom is %dpx", getFormattedMessage(element), getTopOffset(element), getBottomOffset(element)), element); } } } void drawRoot(Color color) { g.setColor(color); g.setStroke(new BasicStroke(2)); g.drawRect(retinaValue(xRoot), retinaValue(mobileY(yRoot)), retinaValue(widthRoot), retinaValue(heightRoot)); //g.fillRect(retinaValue(xRoot), retinaValue((yRoot), retinaValue(widthRoot), retinaValue(heightRoot)); Stroke dashed = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[]{9}, 0); g.setStroke(dashed); g.setColor(linesColor); if (drawLeftOffsetLine) { g.drawLine(retinaValue(xRoot), 0, retinaValue(xRoot), retinaValue(img.getHeight())); } if (drawRightOffsetLine) { g.drawLine(retinaValue(xRoot + widthRoot), 0, retinaValue(xRoot + widthRoot), retinaValue(img.getHeight())); } if (drawTopOffsetLine) { g.drawLine(0, retinaValue(mobileY(yRoot)), retinaValue(img.getWidth()), retinaValue(yRoot)); } if (drawBottomOffsetLine) { g.drawLine(0, retinaValue(mobileY(yRoot + heightRoot)), retinaValue(img.getWidth()), retinaValue(yRoot + heightRoot)); } } void putJsonDetailsWithoutElement(String message) { JSONObject details = new JSONObject(); JSONObject mes = new JSONObject(); mes.put(MESSAGE, message); details.put(REASON, mes); errorMessage.add(details); } private void putJsonDetailsWithElement(String message, WebElement element) { float xContainer = element.getLocation().getX(); float yContainer = element.getLocation().getY(); float widthContainer = element.getSize().getWidth(); float heightContainer = element.getSize().getHeight(); JSONObject details = new JSONObject(); JSONObject elDetails = new JSONObject(); elDetails.put(X, xContainer); elDetails.put(Y, yContainer); elDetails.put(WIDTH, widthContainer); elDetails.put(HEIGHT, heightContainer); JSONObject mes = new JSONObject(); mes.put(MESSAGE, message); mes.put(ELEMENT, elDetails); details.put(REASON, mes); errorMessage.add(details); } int getConvertedInt(int i, boolean horizontal) { if (units.equals(PX)) { return i; } else { if (horizontal) { return (i * pageWidth) / 100; } else { return (i * pageHeight) / 100; } } } String getFormattedMessage(WebElement element) { return String.format("with properties: tag=[%s], id=[%s], class=[%s], text=[%s], coord=[%s,%s], size=[%s,%s]", element.getTagName(), element.getAttribute("id"), element.getAttribute("class"), element.getText().length() < 10 ? element.getText() : element.getText().substring(0, 10) + "...", String.valueOf(element.getLocation().x), String.valueOf(element.getLocation().y), String.valueOf(element.getSize().width), String.valueOf(element.getSize().height)); } int retinaValue(int value) { if (!isMobile()) { int zoom = Integer.parseInt(currentZoom.replace("%", "")); if (zoom > 100) { value = (int) (value + (value * Math.abs(zoom - 100f) / 100f)); } else if (zoom < 100) { value = (int) (value - (value * Math.abs(zoom - 100f) / 100f)); } if (isRetinaDisplay() && isChrome()) { return 2 * value; } else { return value; } } else { if (isIOS()) { String[] iOS_RETINA_DEVICES = { "iPhone 4", "iPhone 4s", "iPhone 5", "iPhone 5s", "iPhone 6", "iPhone 6s", "iPad Mini 2", "iPad Mini 4", "iPad Air 2", "iPad Pro" }; if (Arrays.asList(iOS_RETINA_DEVICES).contains(getDevice())) { return 2 * value; } else { return value; } } else { return value; } } } int mobileY(int value) { if (isMobile() && ((AppiumDriver) driver).getContext().startsWith("WEB")) { if (isIOS()) { if (isMobileTopBar) { return value + 20; } else { return value; } } else if (isAndroid()) { if (isMobileTopBar) { return value + 20; } else { return value; } } else { return value; } } else { return value; } } long getPageWidth() { JavascriptExecutor executor = (JavascriptExecutor) driver; if (!isMobile()) { if (isFirefox()) { currentZoom = (String) executor.executeScript("document.body.style.MozTransform"); } else { currentZoom = (String) executor.executeScript("return document.body.style.zoom;"); } if (currentZoom == null || currentZoom.equals("100%") || currentZoom.equals("")) { currentZoom = "100%"; return (long) executor.executeScript("if (self.innerWidth) {return self.innerWidth;} if (document.documentElement && document.documentElement.clientWidth) {return document.documentElement.clientWidth;}if (document.body) {return document.body.clientWidth;}"); } else { return (long) executor.executeScript("return document.getElementsByTagName('body')[0].offsetWidth"); } } else { if (isNativeMobileContext() || isIOS()) { return driver.manage().window().getSize().width; } else { return (long) executor.executeScript("if (self.innerWidth) {return self.innerWidth;} if (document.documentElement && document.documentElement.clientWidth) {return document.documentElement.clientWidth;}if (document.body) {return document.body.clientWidth;}"); } } } long getPageHeight() { JavascriptExecutor executor = (JavascriptExecutor) driver; if (!isMobile()) { if (isFirefox()) { currentZoom = (String) executor.executeScript("document.body.style.MozTransform"); } else { currentZoom = (String) executor.executeScript("return document.body.style.zoom;"); } if (currentZoom == null || currentZoom.equals("100%") || currentZoom.equals("")) { currentZoom = "100%"; return (long) executor.executeScript("if (self.innerHeight) {return self.innerHeight;} if (document.documentElement && document.documentElement.clientHeight) {return document.documentElement.clientHeight;}if (document.body) {return document.body.clientHeight;}"); } else { return (long) executor.executeScript("return document.getElementsByTagName('body')[0].offsetHeight"); } } else { if (isNativeMobileContext() || isIOS()) { return driver.manage().window().getSize().height; } else { return (long) executor.executeScript("if (self.innerHeight) {return self.innerHeight;} if (document.documentElement && document.documentElement.clientHeight) {return document.documentElement.clientHeight;}if (document.body) {return document.body.clientHeight;}"); } } } private boolean isNativeMobileContext() { return ((AppiumDriver) driver).getContext().contains("NATIVE"); } void validateInsideOfContainer(WebElement containerElement, String readableContainerName) { Rectangle2D.Double elementRectangle = rectangle(containerElement); if (rootElements == null || rootElements.isEmpty()) { Rectangle2D.Double rootRectangle = rectangle(rootElement); if (!elementRectangle.contains(rootRectangle)) { putJsonDetailsWithElement(String.format("Element '%s' is not inside of '%s'", rootElementReadableName, readableContainerName), containerElement); } } else { for (WebElement el : rootElements) { if (!elementRectangle.contains(rectangle(el))) { putJsonDetailsWithElement(String.format("Element is not inside of '%s'", readableContainerName), containerElement); } } } } void validateInsideOfContainer(WebElement element, String readableContainerName, Padding padding) { int top = getConvertedInt(padding.getTop(), false); int right = getConvertedInt(padding.getRight(), true); int bottom = getConvertedInt(padding.getBottom(), false); int left = getConvertedInt(padding.getLeft(), true); Rectangle2D.Double paddedRootRectangle = new Rectangle2D.Double( rootElement.getLocation().getX() - left, rootElement.getLocation().getY() - top, rootElement.getSize().getWidth() + left + right, rootElement.getSize().getHeight() + top + bottom); int paddingTop = rootElement.getLocation().getY() - element.getLocation().getY(); int paddingLeft = rootElement.getLocation().getX() - element.getLocation().getX(); int paddingBottom = (element.getLocation().getY() + element.getSize().getHeight()) - (rootElement.getLocation().getY() + rootElement.getSize().getHeight()); int paddingRight = (element.getLocation().getX() + element.getSize().getWidth()) - (rootElement.getLocation().getX() + rootElement.getSize().getWidth()); if (!rectangle(element).contains(paddedRootRectangle)) { putJsonDetailsWithElement(String.format("Padding of element '%s' is incorrect. Expected padding: top[%d], right[%d], bottom[%d], left[%d]. Actual padding: top[%d], right[%d], bottom[%d], left[%d]", rootElementReadableName, top, right, bottom, left, paddingTop, paddingRight, paddingBottom, paddingLeft), element); } } private Rectangle2D.Double rectangle(WebElement element) { return new Rectangle2D.Double( element.getLocation().getX(), element.getLocation().getY(), element.getSize().getWidth(), element.getSize().getHeight()); } private int getLeftOffset(WebElement element) { return element.getLocation().x; } private int getRightOffset(WebElement element) { return pageWidth - (element.getLocation().x + element.getSize().width); } private int getTopOffset(WebElement element) { return element.getLocation().y; } private int getBottomOffset(WebElement element) { return pageHeight - (element.getLocation().y + element.getSize().height); } private boolean elementsAreOverlapped(WebElement rootElement, WebElement elementOverlapWith) { return rectangle(rootElement).intersects(rectangle(elementOverlapWith)); } private boolean elementsHaveEqualLeftOffset(WebElement element, WebElement elementToCompare) { return element.getLocation().x == elementToCompare.getLocation().getX(); } private boolean elementsHaveEqualRightOffset(WebElement element, WebElement elementToCompare) { return element.getLocation().x + element.getSize().width == elementToCompare.getLocation().getX() + elementToCompare.getSize().getWidth(); } private boolean elementsHaveEqualTopOffset(WebElement element, WebElement elementToCompare) { return element.getLocation().y == elementToCompare.getLocation().getY(); } private boolean elementsHaveEqualBottomOffset(WebElement element, WebElement elementToCompare) { return element.getLocation().y + element.getSize().height == elementToCompare.getLocation().getY() + elementToCompare.getSize().getHeight(); } private boolean elementHasEqualLeftRightOffset(WebElement element) { return getLeftOffset(element) == getRightOffset(element); } private boolean elementHasEqualTopBottomOffset(WebElement element) { return getTopOffset(element) == getBottomOffset(element); } public enum Units { PX, PERCENT } }
package org.apache.commons.collections; import junit.framework.*; import java.util.*; public class TestCollectionUtils extends TestCase { public TestCollectionUtils(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestCollectionUtils.class); } public static void main(String args[]) { String[] testCaseName = { TestCollectionUtils.class.getName() }; junit.textui.TestRunner.main(testCaseName); } private Collection _a = null; private Collection _b = null; public void setUp() { _a = new ArrayList(); _a.add("a"); _a.add("b"); _a.add("b"); _a.add("c"); _a.add("c"); _a.add("c"); _a.add("d"); _a.add("d"); _a.add("d"); _a.add("d"); _b = new LinkedList(); _b.add("e"); _b.add("d"); _b.add("d"); _b.add("c"); _b.add("c"); _b.add("c"); _b.add("b"); _b.add("b"); _b.add("b"); _b.add("b"); } public void testGetCardinalityMap() { Map freq = CollectionUtils.getCardinalityMap(_a); assertEquals(new Integer(1),freq.get("a")); assertEquals(new Integer(2),freq.get("b")); assertEquals(new Integer(3),freq.get("c")); assertEquals(new Integer(4),freq.get("d")); assertNull(freq.get("e")); freq = CollectionUtils.getCardinalityMap(_b); assertNull(freq.get("a")); assertEquals(new Integer(4),freq.get("b")); assertEquals(new Integer(3),freq.get("c")); assertEquals(new Integer(2),freq.get("d")); assertEquals(new Integer(1),freq.get("e")); } public void testCardinality() { assertEquals(1,CollectionUtils.cardinality("a",_a)); assertEquals(2,CollectionUtils.cardinality("b",_a)); assertEquals(3,CollectionUtils.cardinality("c",_a)); assertEquals(4,CollectionUtils.cardinality("d",_a)); assertEquals(0,CollectionUtils.cardinality("e",_a)); assertEquals(0,CollectionUtils.cardinality("a",_b)); assertEquals(4,CollectionUtils.cardinality("b",_b)); assertEquals(3,CollectionUtils.cardinality("c",_b)); assertEquals(2,CollectionUtils.cardinality("d",_b)); assertEquals(1,CollectionUtils.cardinality("e",_b)); } public void testCardinalityOfNull() { List list = new ArrayList(); assertEquals(0,CollectionUtils.cardinality(null,list)); { Map freq = CollectionUtils.getCardinalityMap(list); assertNull(freq.get(null)); } list.add("A"); assertEquals(0,CollectionUtils.cardinality(null,list)); { Map freq = CollectionUtils.getCardinalityMap(list); assertNull(freq.get(null)); } list.add(null); assertEquals(1,CollectionUtils.cardinality(null,list)); { Map freq = CollectionUtils.getCardinalityMap(list); assertEquals(new Integer(1),freq.get(null)); } list.add("B"); assertEquals(1,CollectionUtils.cardinality(null,list)); { Map freq = CollectionUtils.getCardinalityMap(list); assertEquals(new Integer(1),freq.get(null)); } list.add(null); assertEquals(2,CollectionUtils.cardinality(null,list)); { Map freq = CollectionUtils.getCardinalityMap(list); assertEquals(new Integer(2),freq.get(null)); } list.add("B"); assertEquals(2,CollectionUtils.cardinality(null,list)); { Map freq = CollectionUtils.getCardinalityMap(list); assertEquals(new Integer(2),freq.get(null)); } list.add(null); assertEquals(3,CollectionUtils.cardinality(null,list)); { Map freq = CollectionUtils.getCardinalityMap(list); assertEquals(new Integer(3),freq.get(null)); } } public void testContainsAny() { Collection empty = new ArrayList(0); Collection one = new ArrayList(1); one.add("1"); Collection two = new ArrayList(1); two.add("2"); Collection three = new ArrayList(1); three.add("3"); Collection odds = new ArrayList(2); odds.add("1"); odds.add("3"); assertTrue("containsAny({1},{1,3}) should return true.", CollectionUtils.containsAny(one,odds)); assertTrue("containsAny({1,3},{1}) should return true.", CollectionUtils.containsAny(odds,one)); assertTrue("containsAny({3},{1,3}) should return true.", CollectionUtils.containsAny(three,odds)); assertTrue("containsAny({1,3},{3}) should return true.", CollectionUtils.containsAny(odds,three)); assertTrue("containsAny({2},{2}) should return true.", CollectionUtils.containsAny(two,two)); assertTrue("containsAny({1,3},{1,3}) should return true.", CollectionUtils.containsAny(odds,odds)); assertTrue("containsAny({2},{1,3}) should return false.", !CollectionUtils.containsAny(two,odds)); assertTrue("containsAny({1,3},{2}) should return false.", !CollectionUtils.containsAny(odds,two)); assertTrue("containsAny({1},{3}) should return false.", !CollectionUtils.containsAny(one,three)); assertTrue("containsAny({3},{1}) should return false.", !CollectionUtils.containsAny(three,one)); assertTrue("containsAny({1,3},{}) should return false.", !CollectionUtils.containsAny(odds,empty)); assertTrue("containsAny({},{1,3}) should return false.", !CollectionUtils.containsAny(empty,odds)); assertTrue("containsAny({},{}) should return false.", !CollectionUtils.containsAny(empty,empty)); } public void testUnion() { Collection col = CollectionUtils.union(_a,_b); Map freq = CollectionUtils.getCardinalityMap(col); assertEquals(new Integer(1),freq.get("a")); assertEquals(new Integer(4),freq.get("b")); assertEquals(new Integer(3),freq.get("c")); assertEquals(new Integer(4),freq.get("d")); assertEquals(new Integer(1),freq.get("e")); Collection col2 = CollectionUtils.union(_b,_a); Map freq2 = CollectionUtils.getCardinalityMap(col2); assertEquals(new Integer(1),freq2.get("a")); assertEquals(new Integer(4),freq2.get("b")); assertEquals(new Integer(3),freq2.get("c")); assertEquals(new Integer(4),freq2.get("d")); assertEquals(new Integer(1),freq2.get("e")); } public void testIntersection() { Collection col = CollectionUtils.intersection(_a,_b); Map freq = CollectionUtils.getCardinalityMap(col); assertNull(freq.get("a")); assertEquals(new Integer(2),freq.get("b")); assertEquals(new Integer(3),freq.get("c")); assertEquals(new Integer(2),freq.get("d")); assertNull(freq.get("e")); Collection col2 = CollectionUtils.intersection(_b,_a); Map freq2 = CollectionUtils.getCardinalityMap(col2); assertNull(freq2.get("a")); assertEquals(new Integer(2),freq2.get("b")); assertEquals(new Integer(3),freq2.get("c")); assertEquals(new Integer(2),freq2.get("d")); assertNull(freq2.get("e")); } public void testDisjunction() { Collection col = CollectionUtils.disjunction(_a,_b); Map freq = CollectionUtils.getCardinalityMap(col); assertEquals(new Integer(1),freq.get("a")); assertEquals(new Integer(2),freq.get("b")); assertNull(freq.get("c")); assertEquals(new Integer(2),freq.get("d")); assertEquals(new Integer(1),freq.get("e")); Collection col2 = CollectionUtils.disjunction(_b,_a); Map freq2 = CollectionUtils.getCardinalityMap(col2); assertEquals(new Integer(1),freq2.get("a")); assertEquals(new Integer(2),freq2.get("b")); assertNull(freq2.get("c")); assertEquals(new Integer(2),freq2.get("d")); assertEquals(new Integer(1),freq2.get("e")); } public void testDisjunctionAsUnionMinusIntersection() { Collection dis = CollectionUtils.disjunction(_a,_b); Collection un = CollectionUtils.union(_a,_b); Collection inter = CollectionUtils.intersection(_a,_b); assertTrue(CollectionUtils.isEqualCollection(dis,CollectionUtils.subtract(un,inter))); } public void testDisjunctionAsSymmetricDifference() { Collection dis = CollectionUtils.disjunction(_a,_b); Collection amb = CollectionUtils.subtract(_a,_b); Collection bma = CollectionUtils.subtract(_b,_a); assertTrue(CollectionUtils.isEqualCollection(dis,CollectionUtils.union(amb,bma))); } public void testSubtract() { Collection col = CollectionUtils.subtract(_a,_b); Map freq = CollectionUtils.getCardinalityMap(col); assertEquals(new Integer(1),freq.get("a")); assertNull(freq.get("b")); assertNull(freq.get("c")); assertEquals(new Integer(2),freq.get("d")); assertNull(freq.get("e")); Collection col2 = CollectionUtils.subtract(_b,_a); Map freq2 = CollectionUtils.getCardinalityMap(col2); assertEquals(new Integer(1),freq2.get("e")); assertNull(freq2.get("d")); assertNull(freq2.get("c")); assertEquals(new Integer(2),freq2.get("b")); assertNull(freq2.get("a")); } public void testIsSubCollectionOfSelf() { assertTrue(CollectionUtils.isSubCollection(_a,_a)); assertTrue(CollectionUtils.isSubCollection(_b,_b)); } public void testIsSubCollection() { assertTrue(!CollectionUtils.isSubCollection(_a,_b)); assertTrue(!CollectionUtils.isSubCollection(_b,_a)); } public void testIsSubCollection2() { Collection c = new ArrayList(); assertTrue(CollectionUtils.isSubCollection(c,_a)); assertTrue(!CollectionUtils.isSubCollection(_a,c)); c.add("a"); assertTrue(CollectionUtils.isSubCollection(c,_a)); assertTrue(!CollectionUtils.isSubCollection(_a,c)); c.add("b"); assertTrue(CollectionUtils.isSubCollection(c,_a)); assertTrue(!CollectionUtils.isSubCollection(_a,c)); c.add("b"); assertTrue(CollectionUtils.isSubCollection(c,_a)); assertTrue(!CollectionUtils.isSubCollection(_a,c)); c.add("c"); assertTrue(CollectionUtils.isSubCollection(c,_a)); assertTrue(!CollectionUtils.isSubCollection(_a,c)); c.add("c"); assertTrue(CollectionUtils.isSubCollection(c,_a)); assertTrue(!CollectionUtils.isSubCollection(_a,c)); c.add("c"); assertTrue(CollectionUtils.isSubCollection(c,_a)); assertTrue(!CollectionUtils.isSubCollection(_a,c)); c.add("d"); assertTrue(CollectionUtils.isSubCollection(c,_a)); assertTrue(!CollectionUtils.isSubCollection(_a,c)); c.add("d"); assertTrue(CollectionUtils.isSubCollection(c,_a)); assertTrue(!CollectionUtils.isSubCollection(_a,c)); c.add("d"); assertTrue(CollectionUtils.isSubCollection(c,_a)); assertTrue(!CollectionUtils.isSubCollection(_a,c)); c.add("d"); assertTrue(CollectionUtils.isSubCollection(c,_a)); assertTrue(CollectionUtils.isSubCollection(_a,c)); c.add("e"); assertTrue(!CollectionUtils.isSubCollection(c,_a)); assertTrue(CollectionUtils.isSubCollection(_a,c)); } public void testIsEqualCollectionToSelf() { assertTrue(CollectionUtils.isEqualCollection(_a,_a)); assertTrue(CollectionUtils.isEqualCollection(_b,_b)); } public void testIsEqualCollection() { assertTrue(!CollectionUtils.isEqualCollection(_a,_b)); assertTrue(!CollectionUtils.isEqualCollection(_b,_a)); } public void testIsEqualCollection2() { Collection a = new ArrayList(); Collection b = new ArrayList(); assertTrue(CollectionUtils.isEqualCollection(a,b)); assertTrue(CollectionUtils.isEqualCollection(b,a)); a.add("1"); assertTrue(!CollectionUtils.isEqualCollection(a,b)); assertTrue(!CollectionUtils.isEqualCollection(b,a)); b.add("1"); assertTrue(CollectionUtils.isEqualCollection(a,b)); assertTrue(CollectionUtils.isEqualCollection(b,a)); a.add("2"); assertTrue(!CollectionUtils.isEqualCollection(a,b)); assertTrue(!CollectionUtils.isEqualCollection(b,a)); b.add("2"); assertTrue(CollectionUtils.isEqualCollection(a,b)); assertTrue(CollectionUtils.isEqualCollection(b,a)); a.add("1"); assertTrue(!CollectionUtils.isEqualCollection(a,b)); assertTrue(!CollectionUtils.isEqualCollection(b,a)); b.add("1"); assertTrue(CollectionUtils.isEqualCollection(a,b)); assertTrue(CollectionUtils.isEqualCollection(b,a)); } public void testIndex() { Map map = new HashMap(); map.put(new Integer(0), "element"); Object test = CollectionUtils.index(map, 0); assertTrue(test.equals("element")); List list = new ArrayList(); list.add("element"); test = CollectionUtils.index(list, 0); assertTrue(test.equals("element")); Bag bag = new HashBag(); bag.add("element", 1); test = CollectionUtils.index(bag, 0); assertTrue(test.equals("element")); } private static Predicate EQUALS_TWO = new Predicate() { public boolean evaluate(Object input) { return (input.equals("Two")); } }; public void testFilter() { List list = new ArrayList(); list.add("One"); list.add("Two"); list.add("Three"); list.add("Four"); CollectionUtils.filter(list, EQUALS_TWO); assertEquals(1, list.size()); assertEquals("Two", list.get(0)); list = new ArrayList(); list.add("One"); list.add("Two"); list.add("Three"); list.add("Four"); CollectionUtils.filter(list, null); assertEquals(4, list.size()); CollectionUtils.filter(null, EQUALS_TWO); assertEquals(4, list.size()); CollectionUtils.filter(null, null); assertEquals(4, list.size()); } public void testCountMatches() { List list = new ArrayList(); list.add("One"); list.add("Two"); list.add("Three"); list.add("Four"); int count = CollectionUtils.countMatches(list, EQUALS_TWO); assertEquals(4, list.size()); assertEquals(1, count); assertEquals(0, CollectionUtils.countMatches(list, null)); assertEquals(0, CollectionUtils.countMatches(null, EQUALS_TWO)); assertEquals(0, CollectionUtils.countMatches(null, null)); } public void testSelect() { List list = new ArrayList(); list.add("One"); list.add("Two"); list.add("Three"); list.add("Four"); Collection output = CollectionUtils.select(list, EQUALS_TWO); assertEquals(4, list.size()); assertEquals(1, output.size()); assertEquals("Two", output.iterator().next()); } public void testSelectRejected() { List list = new ArrayList(); list.add("One"); list.add("Two"); list.add("Three"); list.add("Four"); Collection output = CollectionUtils.selectRejected(list, EQUALS_TWO); assertEquals(4, list.size()); assertEquals(3, output.size()); assertTrue(output.contains("One")); assertTrue(output.contains("Three")); assertTrue(output.contains("Four")); } Transformer TRANSFORM_TO_INTEGER = new Transformer() { public Object transform(Object input) { return new Integer((String) input); } }; public void testTransform1() { List list = new ArrayList(); list.add("1"); list.add("2"); list.add("3"); CollectionUtils.transform(list, TRANSFORM_TO_INTEGER); assertEquals(3, list.size()); assertEquals(new Integer(1), list.get(0)); assertEquals(new Integer(2), list.get(1)); assertEquals(new Integer(3), list.get(2)); list = new ArrayList(); list.add("1"); list.add("2"); list.add("3"); CollectionUtils.transform(null, TRANSFORM_TO_INTEGER); assertEquals(3, list.size()); CollectionUtils.transform(list, null); assertEquals(3, list.size()); CollectionUtils.transform(null, null); assertEquals(3, list.size()); } public void testTransform2() { Set set = new HashSet(); set.add("1"); set.add("2"); set.add("3"); CollectionUtils.transform(set, new Transformer() { public Object transform(Object input) { return new Integer(4); } }); assertEquals(1, set.size()); assertEquals(new Integer(4), set.iterator().next()); } public BulkTest bulkTestPredicatedCollection1() { return new TestPredicatedCollection("") { public Collection predicatedCollection() { Predicate p = getPredicate(); return CollectionUtils.predicatedCollection(new ArrayList(), p); } public BulkTest bulkTestAll() { return new TestCollection("") { public Collection makeCollection() { return predicatedCollection(); } public Collection makeConfirmedCollection() { return new ArrayList(); } public Collection makeConfirmedFullCollection() { ArrayList list = new ArrayList(); list.addAll(java.util.Arrays.asList(getFullElements())); return list; } public Object[] getFullElements() { return getFullNonNullStringElements(); } public Object[] getOtherElements() { return getOtherNonNullStringElements(); } }; } }; } public void testIsFull() { Set set = new HashSet(); set.add("1"); set.add("2"); set.add("3"); try { CollectionUtils.isFull(null); fail(); } catch (NullPointerException ex) {} assertEquals(false, CollectionUtils.isFull(set)); BoundedFifoBuffer buf = new BoundedFifoBuffer(set); assertEquals(true, CollectionUtils.isFull(buf)); buf.remove("2"); assertEquals(false, CollectionUtils.isFull(buf)); buf.add("2"); assertEquals(true, CollectionUtils.isFull(buf)); Buffer buf2 = BufferUtils.synchronizedBuffer(buf); assertEquals(true, CollectionUtils.isFull(buf2)); buf2.remove("2"); assertEquals(false, CollectionUtils.isFull(buf2)); buf2.add("2"); assertEquals(true, CollectionUtils.isFull(buf2)); } public void testMaxSize() { Set set = new HashSet(); set.add("1"); set.add("2"); set.add("3"); try { CollectionUtils.maxSize(null); fail(); } catch (NullPointerException ex) {} assertEquals(-1, CollectionUtils.maxSize(set)); BoundedFifoBuffer buf = new BoundedFifoBuffer(set); assertEquals(3, CollectionUtils.maxSize(buf)); buf.remove("2"); assertEquals(3, CollectionUtils.maxSize(buf)); buf.add("2"); assertEquals(3, CollectionUtils.maxSize(buf)); Buffer buf2 = BufferUtils.synchronizedBuffer(buf); assertEquals(3, CollectionUtils.maxSize(buf2)); buf2.remove("2"); assertEquals(3, CollectionUtils.maxSize(buf2)); buf2.add("2"); assertEquals(3, CollectionUtils.maxSize(buf2)); } }
// modification, are permitted provided that the following conditions are met: // documentation and/or other materials provided with the distribution. // 3. All advertising materials mentioning features or use of this software // must display the following acknowledgement: // This product includes software developed by CDS Networks, Inc. // 4. The name of CDS Networks, Inc. may not be used to endorse or promote // products derived from this software without specific prior // THIS SOFTWARE IS PROVIDED BY CDS NETWORKS, INC. ``AS IS'' AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL CDS NETWORKS, INC. BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS // OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. package net.sourceforge.jtds.jdbc; import java.sql.*; abstract public class EscapeProcessor { public static final String cvsVersion = "$Id: EscapeProcessor.java,v 1.6 2004-01-27 23:16:22 bheineman Exp $"; private static final String ESCAPE_PREFIX_DATE = "d "; private static final String ESCAPE_PREFIX_TIME = "t "; private static final String ESCAPE_PREFIX_TIMESTAMP = "ts "; private static final String ESCAPE_PREFIX_OUTER_JOIN = "oj "; private static final String ESCAPE_PREFIX_FUNCTION = "fn "; private static final String ESCAPE_PREFIX_CALL = "call "; private static final String ESCAPE_PREFIX_ESCAPE_CHAR = "escape "; private static final int NORMAL = 0; private static final int IN_STRING = 1; private static final int IN_ESCAPE = 2; private String input; public EscapeProcessor(String sql) { input = sql; } abstract public String expandDBSpecificFunction(String escapeSequence) throws SQLException; /** * Is the string made up only of digits? * <p> * <b>Note:</b> Leading/trailing spaces or signs are not considered digits. * * @return true if the string has only digits, false otherwise. */ private static boolean validDigits(String str) { for( int i=0; i<str.length(); i++ ) if( !Character.isDigit(str.charAt(i)) ) return false; return true; } /** * Given a string and an index into that string return the index * of the next non-whitespace character. * * @return index of next non-whitespace character. */ private static int skipWhitespace(String str, int i) { while( i<str.length() && Character.isWhitespace(str.charAt(i)) ) i++; return i; } /** * Given a string and an index into that string, advanvance the index * iff it is on a quote character. * * @return the next position in the string iff the current character is a * quote */ private static int skipQuote(String str, int i) { // skip over the leading quote if it exists if( i<str.length() && (str.charAt(i)=='\'' || str.charAt(i)=='"') ) // XXX Note- The spec appears to prohibit the quote character, // but many drivers allow it. We should probably control this // with a flag. i++; return i; } /** * Convert a JDBC SQL escape date sequence into a datestring recognized by SQLServer. */ private static String getDate(String str) throws SQLException { int i; // skip over the "d " i = 2; // skip any additional spaces i = skipWhitespace(str, i); i = skipQuote(str, i); // i is now up to the point where the date had better start. if( str.length()-i<10 || str.charAt(i+4)!='-' || str.charAt(i+7)!='-' ) throw new SQLException("Malformed date"); String year = str.substring(i, i+4); String month = str.substring(i+5, i+5+2); String day = str.substring(i+5+3, i+5+3+2); // Make sure the year, month, and day are numeric if( !validDigits(year) || !validDigits(month) || !validDigits(day) ) throw new SQLException("Malformed date"); // Make sure there isn't any garbage after the date i = i+10; i = skipWhitespace(str, i); i = skipQuote(str, i); i = skipWhitespace(str, i); if( i<str.length() ) throw new SQLException("Malformed date"); return "'" + year + month + day + "'"; } /** * Convert a JDBC SQL escape time sequence into a time string recognized by SQLServer. */ private static String getTime(String str) throws SQLException { int i; // skip over the "t " i = 2; // skip any additional spaces i = skipWhitespace(str, i); i = skipQuote(str, i); // i is now up to the point where the date had better start. if( str.length()-i<8 || str.charAt(i+2)!=':' || str.charAt(i+5)!=':' ) throw new SQLException("Malformed time"); String hour = str.substring(i, i+2); String minute = str.substring(i+3, i+3+2); String second = str.substring(i+3+3, i+3+3+2); // Make sure the year, month, and day are numeric if( !validDigits(hour) || !validDigits(minute) || !validDigits(second) ) throw new SQLException("Malformed time"); // Make sure there isn't any garbage after the time i = i+8; i = skipWhitespace(str, i); i = skipQuote(str, i); i = skipWhitespace(str, i); if( i<str.length() ) throw new SQLException("Malformed time"); return "'" + hour + ":" + minute + ":" + second + "'"; } /** * Convert a JDBC SQL escape timestamp sequence into a date-time string recognized by SQLServer. */ private static String getTimestamp(String str) throws SQLException { int i; // skip over the "d " i = 2; // skip any additional spaces i = skipWhitespace(str, i); i = skipQuote(str, i); // i is now at the point where the date had better start. if( (str.length()-i)<19 || str.charAt(i+4)!='-' || str.charAt(i+7)!='-' ) throw new SQLException("Malformed date"); String year = str.substring(i, i+4); String month = str.substring(i+5, i+5+2); String day = str.substring(i+5+3, i+5+3+2); // Make sure the year, month, and day are numeric if( !validDigits(year) || !validDigits(month) || !validDigits(day) ) throw new SQLException("Malformed date"); // Make sure there is at least one space between date and time i = i+10; if( !Character.isWhitespace(str.charAt(i)) ) throw new SQLException("Malformed date"); // skip the whitespace i = skipWhitespace(str, i); // see if it could be a time if( str.length()-i<8 || str.charAt(i+2)!=':' || str.charAt(i+5)!=':' ) throw new SQLException("Malformed time"); String hour = str.substring(i, i+2); String minute = str.substring(i+3, i+3+2); String second = str.substring(i+3+3, i+3+3+2); String fraction = "000"; i = i+8; if( str.length()>i && str.charAt(i)=='.' ) { fraction = ""; i++; while( str.length()>i && validDigits(str.substring(i,i+1)) ) fraction = fraction + str.substring(i,++i); if( fraction.length() > 3 ) fraction = fraction.substring(0,3); else while( fraction.length()<3 ) fraction = fraction + "0"; } // Make sure there isn't any garbage after the time i = skipWhitespace(str, i); i = skipQuote(str, i); i = skipWhitespace(str, i); if (i<str.length()) { throw new SQLException("Malformed date"); } return "'" + year + month + day + " " + hour + ":" + minute + ":" + second + "." + fraction + "'"; } public String expandEscape(String escapeSequence) throws SQLException { // XXX Is it always okay to trim leading and trailing blanks? String str = escapeSequence.trim(); String result = null; if( startsWithIgnoreCase(str, ESCAPE_PREFIX_FUNCTION) ) { str = str.substring(ESCAPE_PREFIX_FUNCTION.length()); result = expandCommonFunction(str); if( result == null ) result = expandDBSpecificFunction(str); if( result == null ) result = str; } else if( startsWithIgnoreCase(str, ESCAPE_PREFIX_CALL) || str.startsWith("?") ) { boolean returnsVal = str.startsWith("?"); if (returnsVal) { int i = skipWhitespace(str, 1); if (str.charAt(i) != '=') { throw new SQLException("Malformed procedure call, '=' expected at " + i + ": " + escapeSequence); } i = skipWhitespace(str, i + 1); str = str.substring(i); if (!startsWithIgnoreCase(str, ESCAPE_PREFIX_CALL)) { throw new SQLException("Malformed procedure call, '" + ESCAPE_PREFIX_CALL + "' expected at " + i + ": " + escapeSequence); } } str = str.substring(ESCAPE_PREFIX_CALL.length()).trim(); int pPos = str.indexOf('('); if( pPos >= 0 ) { if( str.charAt(str.length()-1) != ')' ) throw new SQLException("Malformed procedure call, ')' expected at " + (escapeSequence.length() - 1) + ": " + escapeSequence); result = "exec "+(returnsVal ? "?=" : "")+str.substring(0, pPos)+ " "+str.substring(pPos+1, str.length()-1); } else result = "exec "+(returnsVal ? "?=" : "")+str; } else if( startsWithIgnoreCase(str, ESCAPE_PREFIX_DATE) ) result = getDate(str); else if( startsWithIgnoreCase(str, ESCAPE_PREFIX_TIME) ) result = getTime(str); else if( startsWithIgnoreCase(str, ESCAPE_PREFIX_TIMESTAMP) ) result = getTimestamp(str); else if( startsWithIgnoreCase(str, ESCAPE_PREFIX_OUTER_JOIN) ) result = str.substring(ESCAPE_PREFIX_OUTER_JOIN.length()).trim(); else if( startsWithIgnoreCase(str, ESCAPE_PREFIX_ESCAPE_CHAR) ) result = getEscape(str); else throw new SQLException("Unrecognized escape sequence: " + escapeSequence); return result; } /** * Expand functions that are common to both SQLServer and Sybase */ public String expandCommonFunction(String str) throws SQLException { String result = null; int pPos = str.indexOf('('); if( pPos < 0 ) throw new SQLException("Malformed function escape, expected '(': " + str); else if (str.charAt(str.length() - 1) != ')') throw new SQLException("Malformed function escape, expected ')' at" + (str.length() - 1) + ": " + str); String fName = str.substring(0, pPos).trim(); // @todo Implement this in a smarter way // ??Can we use HashMaps or are we trying to be java 1.0 / 1.1 compliant?? if( fName.equalsIgnoreCase("user") ) result = "user_name" + str.substring(pPos); else if( fName.equalsIgnoreCase("database") ) result = "db_name" + str.substring(pPos); else if( fName.equalsIgnoreCase("ifnull") ) result = "isnull" + str.substring(pPos); else if( fName.equalsIgnoreCase("now") ) result = "getdate" + str.substring(pPos); else if( fName.equalsIgnoreCase("atan2") ) result = "atn2" + str.substring(pPos); else if( fName.equalsIgnoreCase("length") ) result = "len" + str.substring(pPos); else if( fName.equalsIgnoreCase("locate") ) result = "charindex" + str.substring(pPos); else if( fName.equalsIgnoreCase("repeat") ) result = "replicate" + str.substring(pPos); else if( fName.equalsIgnoreCase("insert") ) result = "stuff" + str.substring(pPos); else if( fName.equalsIgnoreCase("lcase") ) result = "lower" + str.substring(pPos); else if( fName.equalsIgnoreCase("ucase") ) result = "upper" + str.substring(pPos); else if (fName.equalsIgnoreCase("concat")) result = getConcat(str.substring(pPos)); return result; } private String getConcat(String str) throws SQLException { char[] chars = str.toCharArray(); StringBuffer result = new StringBuffer(chars.length); boolean inString = false; for (int i = 0; i < chars.length; i++ ) { char ch = chars[i]; if (inString) { if (ch == '\'') { // Single quotes must be escaped with another single quote result.append("''"); } else if (ch == '"' && chars[i] + 1 != '"') { // What happens when ch = '"' && chars[i] + 1 == '"' // Is this a case where a double quote is escaping a double quote? result.append("'"); inString = false; } else { result.append(ch); } } else { if (ch == ',') { // {fn CONCAT("Hot", "Java")} // The comma ^ separating the parameters was found, simply // replace if with a '+'. result.append('+'); } else if (ch == '"') { result.append("'"); inString = true; } else if (ch == '(' || ch == ')') { result.append(ch); } else if (Character.isWhitespace(ch)) { // Just ignore whitespace, there is no reason to make the database // parse this data as well. } else { throw new SQLException("Malformed concat function, charcter '" + ch + "' was not expected at " + i + ": " + str); } } } return result.toString(); } /** * Returns ANSI ESCAPE sequence with the specified escape character */ public String getEscape(String str) throws SQLException { String tmpStr = str.substring(ESCAPE_PREFIX_ESCAPE_CHAR.length()).trim(); // Escape string should be 3 characters long unless a single quote is being used // (which is probably a bad idea but the ANSI specification allows it) as an // escape character in which case the length should be 4. The escape // sequence needs to be handled in this manner (with two single quotes) or else // parameters will not be counted properly as the string will remain open. if( !((tmpStr.length()==3 && tmpStr.charAt(1)!='\'') || (tmpStr.length()==4 && tmpStr.charAt(1)=='\'' && tmpStr.charAt(2)=='\'')) || tmpStr.charAt(0)!='\'' || tmpStr.charAt(tmpStr.length() - 1)!='\'' ) throw new SQLException("Malformed escape: " + str); return "ESCAPE " + tmpStr; } /** * Converts JDBC escape syntax to native SQL. * <p> * NOTE: This method is now structured the way it is for optimization purposes. * <p> * if (state==NORMAL) else if (state==IN_STRING) else * replaces the * switch (state) case NORMAL: case IN_STRING * as it is faster when there are few case statements. * <p> * Also, IN_ESCAPE is not checked for and a simple 'else' is used instead as it is the * only other state that can exist. * <p> * char ch = chars[i] is used in conjunction with input.toCharArray() to avoid * getfield opcode. * <p> * If any changes are made to this method, please test the performance of the change * to ensure that there is no degradation. The cost of parsing SQL for JDBC escapes * needs to be as close to zero as possible. */ public String nativeString() throws SQLException { char[] chars = input.toCharArray(); /* avoid getfield opcode */ StringBuffer result = new StringBuffer(chars.length); StringBuffer escape = null; int state = NORMAL; for (int i = 0; i < chars.length; i++ ) { char ch = chars[i]; /* avoid getfield opcode */ if (state == NORMAL) { if (ch == '{') { state = IN_ESCAPE; if (escape == null) { escape = new StringBuffer(); } else { escape.delete(0, escape.length()); } } else { result.append(ch); if (ch == '\'') { state = IN_STRING; } } } else if (state == IN_STRING) { result.append(ch); // NOTE: This works even if a single quote is being used as an escape // character since the next single quote found will force the state // to be == to IN_STRING again. if (ch == '\'') { state = NORMAL; } } else { // state == IN_ESCAPE if (ch == '}') { result.append(expandEscape(escape.toString())); state = NORMAL; } else { escape.append(ch); } } } if (state == IN_ESCAPE) { throw new SQLException("Syntax error in SQL escape syntax"); } return result.toString(); } public static boolean startsWithIgnoreCase(String s, String prefix) { if( s.length() < prefix.length() ) return false; for( int i=prefix.length()-1; i>=0; i if( Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(prefix.charAt(i)) ) return false; return true; } }
// D o t F a c t o r y // // <editor-fold defaultstate="collapsed" desc="hdr"> // This program is free software: you can redistribute it and/or modify it under the terms of the // </editor-fold> package org.audiveris.omr.sheet.symbol; import org.audiveris.omr.classifier.Evaluation; import org.audiveris.omr.constant.ConstantSet; import org.audiveris.omr.glyph.Glyph; import org.audiveris.omr.glyph.Grades; import org.audiveris.omr.glyph.Shape; import org.audiveris.omr.math.GeoOrder; import org.audiveris.omr.math.GeoUtil; import org.audiveris.omr.math.LineUtil; import org.audiveris.omr.math.Rational; import org.audiveris.omr.sheet.Part; import org.audiveris.omr.sheet.PartBarline; import org.audiveris.omr.sheet.Scale; import org.audiveris.omr.sheet.Staff; import org.audiveris.omr.sheet.SystemInfo; import org.audiveris.omr.sheet.note.NotePosition; import org.audiveris.omr.sheet.rhythm.Measure; import org.audiveris.omr.sheet.rhythm.MeasureStack; import org.audiveris.omr.sig.SIGraph; import org.audiveris.omr.sig.inter.ArticulationInter; import org.audiveris.omr.sig.inter.AugmentationDotInter; import org.audiveris.omr.sig.inter.BarlineInter; import org.audiveris.omr.sig.inter.DeletedInterException; import org.audiveris.omr.sig.inter.FermataArcInter; import org.audiveris.omr.sig.inter.FermataDotInter; import org.audiveris.omr.sig.inter.HeadInter; import org.audiveris.omr.sig.inter.Inter; import org.audiveris.omr.sig.inter.Inters; import org.audiveris.omr.sig.inter.RepeatDotInter; import org.audiveris.omr.sig.inter.StaffBarlineInter; import org.audiveris.omr.sig.relation.AugmentationRelation; import org.audiveris.omr.sig.relation.DotFermataRelation; import org.audiveris.omr.sig.relation.Link; import org.audiveris.omr.sig.relation.Relation; import org.audiveris.omr.sig.relation.RepeatDotBarRelation; import org.audiveris.omr.sig.relation.RepeatDotPairRelation; import org.audiveris.omr.util.HorizontalSide; import static org.audiveris.omr.util.HorizontalSide.*; import org.audiveris.omrdataset.api.OmrShape; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.awt.Point; import java.awt.Rectangle; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Set; public class DotFactory { private static final Constants constants = new Constants(); private static final Logger logger = LoggerFactory.getLogger(DotFactory.class); /** The related inter factory. */ private final InterFactory interFactory; /** The related system. */ private final SystemInfo system; private final SIGraph sig; private final Scale scale; /** Dot candidates. Sorted top down, then left to right. */ private final List<Dot> dots = new ArrayList<Dot>(); /** * Creates a new DotFactory object. * * @param interFactory the mother factory * @param system underlying system */ public DotFactory (InterFactory interFactory, SystemInfo system) { this.interFactory = interFactory; this.system = system; sig = system.getSig(); scale = system.getSheet().getScale(); } // instantDotChecks // /** * Run the various initial checks for the provided dot-shaped glyph. * <p> * All symbols may not be available yet, so only instant processing is launched on the dot (as * a repeat dot, as a staccato dot). * <p> * Whatever the role of a dot, it cannot be stuck (or too close) to a staff line or ledger. * <p> * The symbol is also saved as a dot candidate for later processing. * * @param eval evaluation result * @param glyph underlying glyph * @param closestStaff staff closest to the dot */ public void instantDotChecks (Evaluation eval, Glyph glyph, Staff closestStaff) { // Discard glyph too close to staff line or ledger if (!checkDistanceToLine(glyph, closestStaff)) { return; } // Simply record the candidate dot Dot dot = new GlyphDot(eval, glyph); dots.add(dot); // Run instant checks instantCheckRepeat(dot); // Repeat dot (relation between the two repeat dots is postponed) instantCheckStaccato(dot); // Staccato dot // We cannot run augmentation check since rest inters may not have been created yet } // lateDotChecks // /** * Launch all processing that can take place only after all symbols interpretations * have been retrieved for the system. */ public void lateDotChecks () { // Sort dots carefully Collections.sort(dots, Dot.comparator); // Run all late checks lateAugmentationChecks(); // Note-Dot and Note-Dot-Dot configurations lateFermataChecks(); // Dot as part of a fermata sign lateRepeatChecks(); // Dot as part of stack repeat (to say the last word) } // buildRepeatPairs // /** * Try to pair each repeat dot with another repeat dot, once all dot-repeat symbols * have been retrieved. */ private void buildRepeatPairs () { List<Inter> repeatDots = sig.inters(Shape.REPEAT_DOT); Collections.sort(repeatDots, Inters.byAbscissa); for (int i = 0; i < repeatDots.size(); i++) { RepeatDotInter dot = (RepeatDotInter) repeatDots.get(i); int dotPitch = dot.getIntegerPitch(); Rectangle luBox = dot.getBounds(); luBox.y -= (scale.getInterline() * dotPitch); final int xBreak = luBox.x + luBox.width; for (Inter inter : repeatDots.subList(i + 1, repeatDots.size())) { Rectangle otherBox = inter.getBounds(); if (luBox.intersects(otherBox)) { RepeatDotInter other = (RepeatDotInter) inter; logger.debug("Pair {} and {}", dot, other); sig.addEdge(dot, other, new RepeatDotPairRelation()); } else if (otherBox.x >= xBreak) { break; } } } } // checkDistanceToLine // /** * Check that dot glyph is vertically distant from staff line or ledger. * * @param glyph the dot glyph to check * @param staff the closest staff * @return true if OK */ private boolean checkDistanceToLine (Glyph glyph, Staff staff) { final Point center = glyph.getCenter(); final NotePosition notePosition = staff.getNotePosition(center); final double pitch = notePosition.getPitchPosition(); if ((Math.abs(pitch) > staff.getLineCount()) && (notePosition.getLedger() == null)) { if (glyph.isVip()) { logger.info("VIP glyph#{} dot isolated OK", glyph.getId()); } return true; } else { // Distance to line/ledger specified in interline fraction double linePitch = 2 * Math.rint(pitch / 2); double distance = Math.abs(pitch - linePitch) / 2; if (distance >= constants.minDyFromLine.getValue()) { if (glyph.isVip()) { logger.info( "VIP glyph#{} dot distance:{} OK", glyph.getId(), String.format("%.2f", distance)); } return true; } else { if (glyph.isVip()) { logger.info( "VIP glyph#{} dot distance:{} too close", glyph.getId(), String.format("%.2f", distance)); } return false; } } } // checkRepeatPairs // /** * Delete RepeatDotInter instances that are not paired. */ private void checkRepeatPairs () { final List<Inter> repeatDots = sig.inters(RepeatDotInter.class); for (Inter inter : repeatDots) { final RepeatDotInter dot = (RepeatDotInter) inter; // Check if the repeat dot has a sibling dot if (!sig.hasRelation(dot, RepeatDotPairRelation.class)) { if (dot.isVip() || logger.isDebugEnabled()) { logger.info("Deleting repeat dot lacking sibling {}", dot); } dot.remove(); } } } // checkStackRepeats // /** * Check left and right sides of every stack for (dot-based) repeat indication. * If quorum reached, discard all overlapping interpretations (such as augmentation dots). */ private void checkStackRepeats () { for (MeasureStack stack : system.getStacks()) { for (HorizontalSide side : HorizontalSide.values()) { final List<RepeatDotInter> repeatDots = new ArrayList<RepeatDotInter>(); int virtualDotCount = 0; // Virtual dots inferred from StaffBarline shape for (Measure measure : stack.getMeasures()) { final Part part = measure.getPart(); final PartBarline partBarline = measure.getPartBarlineOn(side); if (partBarline == null) { continue; } for (Staff staff : part.getStaves()) { StaffBarlineInter staffBarline = partBarline.getStaffBarline(part, staff); BarlineInter bar = (side == LEFT) ? staffBarline.getRightBar() : staffBarline.getLeftBar(); if (bar != null) { // Use bar members Set<Relation> dRels = sig.getRelations(bar, RepeatDotBarRelation.class); if (dRels.isEmpty()) { continue; } for (Relation rel : dRels) { RepeatDotInter dot = (RepeatDotInter) sig.getOppositeInter( bar, rel); repeatDots.add(dot); logger.debug("Repeat dot for {}", dot); } } else { // Use StaffBarline shape Shape shape = staffBarline.getShape(); if (side == LEFT) { if ((shape == Shape.LEFT_REPEAT_SIGN) || (shape == Shape.BACK_TO_BACK_REPEAT_SIGN)) { virtualDotCount += 2; } } else { if ((shape == Shape.RIGHT_REPEAT_SIGN) || (shape == Shape.BACK_TO_BACK_REPEAT_SIGN)) { virtualDotCount += 2; } } } } } int dotCount = repeatDots.size() + virtualDotCount; int staffCount = system.getStaves().size(); logger.trace("{} {} staves:{} dots:{}", stack, side, staffCount, dotCount); if (dotCount >= staffCount) { // It's a repeat side, delete inters that conflict with repeat dots // This works for real dots only, not for virtual ones List<Inter> toDelete = new ArrayList<Inter>(); for (RepeatDotInter dot : repeatDots) { Rectangle dotBox = dot.getBounds(); for (Inter inter : sig.vertexSet()) { if (inter == dot) { continue; } try { if (dotBox.intersects(inter.getBounds()) && dot.overlaps(inter)) { toDelete.add(inter); } } catch (DeletedInterException ignored) { } } } if (!toDelete.isEmpty()) { for (Inter inter : toDelete) { inter.remove(); } } } } } } // filterMirrorHeads // /** * NO LONGER USED. * If the collection of (dot-related) heads contains mirrored heads, keep only the * head with longer duration * * @param heads the heads looked up near a candidate augmentation dot */ private void filterMirrorHeads (List<Inter> heads) { if (heads.size() < 2) { return; } Collections.sort(heads, Inters.byId); boolean modified; do { modified = false; InterLoop: for (Inter inter : heads) { HeadInter head = (HeadInter) inter; Inter mirrorInter = head.getMirror(); if ((mirrorInter != null) && heads.contains(mirrorInter)) { HeadInter mirror = (HeadInter) mirrorInter; Rational hDur = head.getChord().getDurationSansDotOrTuplet(); Rational mDur = mirror.getChord().getDurationSansDotOrTuplet(); switch (mDur.compareTo(hDur)) { case -1: heads.remove(mirror); modified = true; break InterLoop; case +1: heads.remove(head); modified = true; break InterLoop; case 0: // Same duration (but we don't have flags yet!) // Keep the one with lower ID heads.remove(mirror); modified = true; break InterLoop; } } } } while (modified); } // instantCheckRepeat // /** * Try to interpret the provided dot glyph as a repeat dot. * This method can be called during symbols step since barlines are already available. * <p> * For a dot properly located WRT barlines, this method creates an instance of RepeatDotInter * as well as a RepeatDotBarRelation between the inter and the related barline. * * @param dot the candidate dot */ private void instantCheckRepeat (Dot dot) { // Check vertical pitch position within the staff: close to +1 or -1 final Rectangle dotBounds = dot.getBounds(); final Point dotPt = GeoUtil.centerOf(dotBounds); final double pp = system.estimatedPitch(dotPt); double pitchDif = Math.abs(Math.abs(pp) - 1); double maxDif = RepeatDotBarRelation.getYGapMaximum(false).getValue(); // Rough sanity check if (pitchDif > (2 * maxDif)) { return; } final int maxDx = scale.toPixels(RepeatDotBarRelation.getXOutGapMaximum(false)); final int maxDy = scale.toPixels(RepeatDotBarRelation.getYGapMaximum(false)); final Rectangle luBox = new Rectangle(dotPt); luBox.grow(maxDx, maxDy); final List<Inter> bars = Inters.intersectedInters( interFactory.getSystemBars(), GeoOrder.BY_ABSCISSA, luBox); if (bars.isEmpty()) { return; } RepeatDotBarRelation bestRel = null; Inter bestBar = null; double bestXGap = Double.MAX_VALUE; for (Inter barInter : bars) { BarlineInter bar = (BarlineInter) barInter; Rectangle box = bar.getBounds(); Point barCenter = bar.getCenter(); // Select proper bar reference point (left or right side and proper vertical side) double barY = barCenter.y + ((box.height / 8d) * Integer.signum(dotPt.y - barCenter.y)); double barX = LineUtil.xAtY(bar.getMedian(), barY) + ((bar.getWidth() / 2) * Integer.signum( dotPt.x - barCenter.x)); double xGap = Math.abs(barX - dotPt.x); double yGap = Math.abs(barY - dotPt.y); RepeatDotBarRelation rel = new RepeatDotBarRelation(); rel.setOutGaps(scale.pixelsToFrac(xGap), scale.pixelsToFrac(yGap), false); if (rel.getGrade() >= rel.getMinGrade()) { if ((bestRel == null) || (bestXGap > xGap)) { bestRel = rel; bestBar = bar; bestXGap = xGap; } } } if (bestRel != null) { final Staff staff = system.getClosestStaff(dotPt); // Staff is OK double grade = Grades.intrinsicRatio * dot.getGrade(); double pitch = (pp > 0) ? 1 : (-1); Glyph glyph = dot.getGlyph(); int annId = dot.getAnnotationId(); final RepeatDotInter repeat; if (glyph != null) { repeat = new RepeatDotInter(glyph, grade, staff, pitch); } else { repeat = null; // Placeholder } sig.addVertex(repeat); sig.addEdge(repeat, bestBar, bestRel); if (dot.isVip()) { if (glyph != null) { logger.info("VIP Created {} from glyph#{}", repeat, glyph.getId()); } else { logger.info("VIP Created {} from annotation#{}", repeat, annId); } } } } // instantCheckStaccato // /** * Try to interpret the provided glyph as a staccato sign related to note head. * This method can be called during symbols step, since only head-chords (not rest-chords) are * concerned and head-based chords are already available. * * @param dot the candidate dot */ private void instantCheckStaccato (Dot dot) { Glyph glyph = dot.getGlyph(); if (glyph != null) { ArticulationInter.createValidAdded( glyph, Shape.STACCATO, Grades.intrinsicRatio * dot.getGrade(), system, interFactory.getSystemHeadChords()); // } else { // ArticulationInter.createValidAdded( // dot.getAnnotationId(), // dot.getBounds(), // dot.getOmrShape(), // Grades.intrinsicRatio * dot.getGrade(), // system, // interFactory.getSystemHeadChords()); } } // lateAugmentationChecks // /** * Perform check for augmentation dots, once rests symbols have been retrieved. */ private void lateAugmentationChecks () { // Phase #1: Tests for note augmentation dots for (Dot dot : dots) { lateNoteAugmentationCheck(dot); } // Collect all (first) augmentation dots found so far in this system List<Inter> systemFirsts = sig.inters(Shape.AUGMENTATION_DOT); Collections.sort(systemFirsts, Inters.byAbscissa); // Phase #2: Tests for dot augmentation dots (double dots) for (Dot dot : dots) { lateDotAugmentationCheck(dot, systemFirsts); } } // lateDotAugmentationCheck // /** * Try to interpret the glyph as a second augmentation dot, composing a double dot. * <p> * Candidates are dots left over (too far from note/rest) as well as some dots already * recognized as (single) dots. * * @param dot a candidate for augmentation dot * @param systemFirsts all (first) augmentation dots recognized during phase #1 */ private void lateDotAugmentationCheck (Dot dot, List<Inter> systemFirsts) { if (dot.isVip()) { logger.info("VIP lateDotAugmentationCheck for {}", dot); } double grade = Grades.intrinsicRatio * dot.getGrade(); Glyph glyph = dot.getGlyph(); int annId = dot.getAnnotationId(); AugmentationDotInter second = new AugmentationDotInter(glyph, grade); Link bestDotLink = Link.bestOf(second.lookupDotLinks(systemFirsts, system)); if (bestDotLink != null) { sig.addVertex(second); sig.removeAllEdges(sig.getRelations(second, AugmentationRelation.class)); bestDotLink.applyTo(second); } } // lateFermataChecks // /** * Try to include the dot in a fermata symbol. */ private void lateFermataChecks () { // Collection of fermata arc candidates in the system List<Inter> arcs = sig.inters(FermataArcInter.class); if (arcs.isEmpty()) { return; } for (Dot dot : dots) { Glyph glyph = dot.getGlyph(); if (glyph == null) { continue; } Rectangle dotBox = dot.getBounds(); FermataDotInter dotInter = null; for (Inter arc : arcs) { // Box: use lower half for FERMATA_ARC and upper half for FERMATA_ARC_BELOW Rectangle halfBox = arc.getBounds(); halfBox.height /= 2; if (arc.getShape() == Shape.FERMATA_ARC) { halfBox.y += halfBox.height; } if (halfBox.intersects(dotBox)) { final Point dotCenter = GeoUtil.centerOf(dotBox); double xGap = Math.abs( dotCenter.x - (halfBox.x + (halfBox.width / 2))); double yTarget = (arc.getShape() == Shape.FERMATA_ARC_BELOW) ? (halfBox.y + (halfBox.height * 0.25)) : (halfBox.y + (halfBox.height * 0.75)); double yGap = Math.abs(dotCenter.y - yTarget); DotFermataRelation rel = new DotFermataRelation(); rel.setOutGaps(scale.pixelsToFrac(xGap), scale.pixelsToFrac(yGap), false); if (rel.getGrade() >= rel.getMinGrade()) { if (dotInter == null) { double grade = Grades.intrinsicRatio * dot.getGrade(); dotInter = new FermataDotInter(glyph, grade); sig.addVertex(dotInter); logger.debug("Created {}", dotInter); } sig.addEdge(dotInter, arc, rel); logger.debug("{} matches dot glyph#{}", arc, glyph.getId()); } } } } } // lateNoteAugmentationCheck // /** * Try to interpret the glyph as an augmentation dot. * <p> * An augmentation dot can relate to a note or a rest, therefore this method can be called only * after all notes and rests interpretations have been retrieved, and rests are retrieved during * symbols step. * * @param dot a candidate for augmentation dot */ private void lateNoteAugmentationCheck (Dot dot) { if (dot.isVip()) { logger.info("VIP lateNoteAugmentationCheck for {}", dot); } double grade = Grades.intrinsicRatio * dot.getGrade(); Glyph glyph = dot.getGlyph(); AugmentationDotInter aug = new AugmentationDotInter(glyph, grade); List<Link> links = new ArrayList<Link>(); Link headLink = aug.lookupHeadLink( interFactory.getSystemHeadChords(), system); if (headLink != null) { links.add(headLink); } links.addAll(aug.lookupRestLinks(interFactory.getSystemRests(), system)); if (!links.isEmpty()) { sig.addVertex(aug); aug.setStaff(links.get(0).partner.getStaff()); for (Link link : links) { link.applyTo(aug); // Specific case for mirrored head if (link.partner instanceof HeadInter) { Inter mirror = link.partner.getMirror(); if (mirror != null) { logger.debug( "Edge from {} to mirrored {} and {}", aug, link.partner, mirror); sig.addEdge(aug, mirror, link.relation.duplicate()); } } } } } // lateRepeatChecks // private void lateRepeatChecks () { // Try to establish a relation between the two repeat dots of a barline buildRepeatPairs(); // Purge non-paired repeat dots checkRepeatPairs(); // Assign repeats per stack checkStackRepeats(); } // Constants // private static final class Constants extends ConstantSet { private final Scale.Fraction minDyFromLine = new Scale.Fraction( 0.3, "Minimum vertical distance between dot center and staff line/ledger"); } // Dot // /** * Remember a dot candidate, for late processing. */ private abstract static class Dot { /** * Very specific sorting of dots. * <p> * If the 2 dots overlap vertically, return left one first. * Otherwise, return top one first. * * @param that the other dot * @return order sign */ public static final Comparator<Dot> comparator = new Comparator<Dot>() { @Override public int compare (Dot d1, Dot d2) { if (d1 == d2) { return 0; } final Rectangle b1 = d1.getBounds(); final Rectangle b2 = d2.getBounds(); if (GeoUtil.yOverlap(b1, b2) > 0) { return Integer.compare(b1.x, b2.x); } else { return Integer.compare(b1.y, b2.y); } } }; public abstract int getAnnotationId (); public abstract Rectangle getBounds (); public abstract Glyph getGlyph (); public abstract double getGrade (); public abstract OmrShape getOmrShape (); public abstract boolean isVip (); } // GlyphDot // /** * Glyph-based dot. */ private static class GlyphDot extends Dot { private final Glyph glyph; // Underlying glyph private final Evaluation eval; // Evaluation result public GlyphDot (Evaluation eval, Glyph glyph) { this.eval = eval; this.glyph = glyph; } @Override public int getAnnotationId () { return 0; } @Override public Rectangle getBounds () { return glyph.getBounds(); } @Override public Glyph getGlyph () { return glyph; } @Override public double getGrade () { return eval.grade; } @Override public OmrShape getOmrShape () { return null; } @Override public boolean isVip () { return glyph.isVip(); } @Override public String toString () { StringBuilder sb = new StringBuilder("GlyphDot{"); sb.append("glyph#").append(glyph.getId()); sb.append(" ").append(eval); sb.append("}"); return sb.toString(); } } }
package com.lambdaworks.redis; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import java.util.Set; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class GeoCommandTest extends AbstractCommandTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void geoadd() throws Exception { Long result = redis.geoadd(key, 40.747533, -73.9454966, "lic market"); assertThat(result).isEqualTo(1); Long readd = redis.geoadd(key, 40.747533, -73.9454966, "lic market"); assertThat(readd).isEqualTo(0); } @Test public void geoaddMulti() throws Exception { Long result = redis.geoadd(key, 49.5282537, 8.6638775, "Weinheim", 48.9978127, 8.3796281, "EFS9", 49.553302, 8.665351, "Bahn"); assertThat(result).isEqualTo(3); } @Test(expected = IllegalArgumentException.class) public void geoaddMultiWrongArgument() throws Exception { redis.geoadd(key, 49.528253); } protected void prepareGeo() { redis.geoadd(key, 49.5282537, 8.6638775, "Weinheim", 48.9978127, 8.3796281, "EFS9", 49.553302, 8.665351, "Bahn"); } @Test public void georadius() throws Exception { prepareGeo(); Set<String> georadius = redis.georadius(key, 49.5285695, 8.6582861, 1, GeoArgs.Unit.kilometer); assertThat(georadius).hasSize(1).contains("Weinheim"); Set<String> largerGeoradius = redis.georadius(key, 49.5285695, 8.6582861, 5, GeoArgs.Unit.kilometer); assertThat(largerGeoradius).hasSize(2).contains("Weinheim").contains("Bahn"); } @Test public void georadiusWithArgs() throws Exception { prepareGeo(); GeoArgs geoArgs = new GeoArgs().withHash().withCoordinates().withDistance().noProperties().asc(); List<Object> result = redis.georadius(key, 49.5285695, 8.6582861, 1, GeoArgs.Unit.kilometer, geoArgs); assertThat(result).hasSize(1); List<Object> response = (List) result.get(0); assertThat(response).hasSize(4); result = redis.georadius(key, 49.5285695, 8.6582861, 1, GeoArgs.Unit.kilometer, null); assertThat(result).hasSize(1); } @Test public void georadiusbymember() throws Exception { prepareGeo(); Set<String> empty = redis.georadiusbymember(key, "Bahn", 1, GeoArgs.Unit.kilometer); assertThat(empty).hasSize(1).contains("Bahn"); Set<String> georadiusbymember = redis.georadiusbymember(key, "Bahn", 5, GeoArgs.Unit.kilometer); assertThat(georadiusbymember).hasSize(2).contains("Bahn", "Weinheim"); } @Test public void georadiusbymemberWithArgs() throws Exception { prepareGeo(); GeoArgs geoArgs = new GeoArgs().withHash().withCoordinates().withDistance().desc(); List<Object> empty = redis.georadiusbymember(key, "Bahn", 1, GeoArgs.Unit.kilometer, geoArgs); assertThat(empty).isNotEmpty(); List<Object> georadiusbymember = redis.georadiusbymember(key, "Bahn", 5, GeoArgs.Unit.kilometer, geoArgs); assertThat(georadiusbymember).hasSize(2); List<Object> response = (List) georadiusbymember.get(0); assertThat(response).hasSize(4); } @Test public void geoencode() throws Exception { List<Object> geoencode = redis.geoencode(49.5282537, 8.6638775); assertThat(geoencode).hasSize(4); assertThat(geoencode.get(0)).isEqualTo(3666615932941099L); assertThat(geoencode.get(1)).isInstanceOf(List.class); assertThat(geoencode.get(2)).isInstanceOf(List.class); assertThat(geoencode.get(3)).isInstanceOf(List.class); } @Test public void geoencodeWithDistance() throws Exception { List<Object> result = redis.geoencode(49.5282537, 8.6638775, 1, GeoArgs.Unit.kilometer); assertThat(result).hasSize(4); assertThat(result.get(0)).isEqualTo(3666615929405440L); assertThat(result.get(1)).isInstanceOf(List.class); assertThat(result.get(2)).isInstanceOf(List.class); assertThat(result.get(3)).isInstanceOf(List.class); } @Test public void geodecode() throws Exception { List<Object> result = redis.geodecode(3666615932941099L); assertThat(result).hasSize(3); assertThat(result.get(0)).isInstanceOf(List.class); assertThat(result.get(1)).isInstanceOf(List.class); assertThat(result.get(2)).isInstanceOf(List.class); } }
package com.mangopay.core; import com.mangopay.core.enumerations.CultureCode; import com.mangopay.entities.Mandate; import com.mangopay.entities.Transfer; import com.mangopay.entities.UserNatural; import org.junit.Test; import java.util.List; import static org.junit.Assert.*; /** * MandateApiImpl test methods. */ public class MandateApiImplTest extends BaseTest { @Test public void createMandate() throws Exception { Mandate mandatePost = new Mandate(); mandatePost.setBankAccountId(this.getJohnsAccount().getId()); mandatePost.setReturnUrl("http://test.test"); mandatePost.setCulture(CultureCode.EN); Mandate mandate = this.api.getMandateApi().create(mandatePost); assertNotNull(mandate); assertFalse(mandate.getId().isEmpty()); } @Test public void getMandate() throws Exception { Mandate mandatePost = new Mandate(); mandatePost.setBankAccountId(this.getJohnsAccount().getId()); mandatePost.setReturnUrl("http://test.test"); mandatePost.setCulture(CultureCode.EN); Mandate mandateCreated = this.api.getMandateApi().create(mandatePost); Mandate mandate = this.api.getMandateApi().get(mandateCreated.getId()); assertNotNull(mandate); assertFalse(mandate.getId().isEmpty()); assertEquals(mandateCreated.getId(), mandate.getId()); } @Test public void getAllMandates() throws Exception { FilterMandates filters = new FilterMandates(); List<Mandate> mandates = this.api.getMandateApi().getAll(filters, null, null); assertNotNull(mandates); assertTrue(mandates.size() > 0); } @Test public void getMandatesForUser() throws Exception { UserNatural user = this.getJohn(true); Mandate mandatePost = new Mandate(); mandatePost.setBankAccountId(this.getJohnsAccount(true).getId()); mandatePost.setReturnUrl("http://test.test"); mandatePost.setCulture(CultureCode.EN); Mandate mandateCreated = this.api.getMandateApi().create(mandatePost); List<Mandate> mandates = this.api.getMandateApi().getForUser(user.getId(), new FilterMandates(), new Pagination(1, 1), null); assertNotNull(mandates); assertTrue(mandates.size() > 0); assertNotNull(mandates.get(0)); assertTrue(mandates.get(0).getId().length() > 0); assertEquals(mandateCreated.getId(), mandates.get(0).getId()); } @Test public void getMandatesForBankAccount() throws Exception { UserNatural user = this.getJohn(true); Mandate mandatePost = new Mandate(); mandatePost.setBankAccountId(this.getJohnsAccount(true).getId()); mandatePost.setReturnUrl("http://test.test"); mandatePost.setCulture(CultureCode.EN); Mandate mandateCreated = this.api.getMandateApi().create(mandatePost); List<Mandate> mandates = this.api.getMandateApi().getForBankAccount(user.getId(), mandatePost.getBankAccountId(), new FilterMandates(), new Pagination(1, 1), null); assertNotNull(mandates); assertTrue(mandates.size() > 0); assertNotNull(mandates.get(0)); assertTrue(mandates.get(0).getId().length() > 0); assertEquals(mandateCreated.getId(), mandates.get(0).getId()); } @Test public void getMandateTransfers() throws Exception { String mandateId = "15397886";// synced with mangopay sandbox List<Transfer> transfers = this.api.getMandateApi().getTransfers("15397886", new Pagination(1, 1), null); assertNotNull(transfers); assertTrue(transfers.size() == 1); } }
package com.noveogroup.android.log; import org.junit.Assert; import org.junit.Test; public class UtilsTest { @Test public void shortenClassNameTest() { Assert.assertEquals(null, Utils.shortenClassName(null, 0, 10)); String className = "com.example.android.MainActivity"; Assert.assertEquals("com.example.android.MainActivity", Utils.shortenClassName(className, 0, 0)); Assert.assertEquals("MainActivity", Utils.shortenClassName(className, -3, 0)); Assert.assertEquals("com.example.android", Utils.shortenClassName(className, 3, 0)); Assert.assertEquals("example.android.MainActivity", Utils.shortenClassName(className, -1, 0)); Assert.assertEquals("com.example.android.MainActivity", Utils.shortenClassName(className, 7, 0)); Assert.assertEquals("MainActivity", Utils.shortenClassName(className, -7, 0)); Assert.assertEquals("com.example.android.MainActivity", Utils.shortenClassName(className, Integer.MAX_VALUE, 0)); Assert.assertEquals("MainActivity", Utils.shortenClassName(className, Integer.MIN_VALUE, 0)); Assert.assertEquals("com.*", Utils.shortenClassName(className, 0, 1)); Assert.assertEquals("*.MainActivity", Utils.shortenClassName(className, 0, -1)); Assert.assertEquals("com.example.android.*", Utils.shortenClassName(className, 0, 32)); Assert.assertEquals("com.example.android.MainActivity", Utils.shortenClassName(className, 0, 33)); Assert.assertEquals("*.android.MainActivity", Utils.shortenClassName(className, 0, -25)); Assert.assertEquals("com.example.*", Utils.shortenClassName(className, 0, 15)); Assert.assertEquals("com.example.android.MainActivity", Utils.shortenClassName(className, 0, 40)); Assert.assertEquals("com.example.android.MainActivity", Utils.shortenClassName(className, 0, -40)); Assert.assertEquals("com.example.android.MainActivity", Utils.shortenClassName(className, 0, Integer.MAX_VALUE)); Assert.assertEquals("*.MainActivity", Utils.shortenClassName(className, 0, Integer.MIN_VALUE)); Assert.assertEquals("*.example.android", Utils.shortenClassName(className, 3, -18)); Assert.assertEquals("MainActivity$SubClass", Utils.shortenClassName("com.example.android.MainActivity$SubClass", -3, -10)); Assert.assertEquals("com.example.android.MainActivity$SubClass", Utils.shortenClassName("com.example.android.MainActivity$SubClass", Integer.MAX_VALUE, Integer.MAX_VALUE)); String loggerName = "com...Logger"; Assert.assertEquals("*.Logger", Utils.shortenClassName(loggerName, 0, -1)); Assert.assertEquals("com...Logger", Utils.shortenClassName(loggerName, 0, 0)); Assert.assertEquals("*..Logger", Utils.shortenClassName(loggerName, 0, -9)); Assert.assertEquals("*...Logger", Utils.shortenClassName(loggerName, 0, -10)); Assert.assertEquals("com...Logger", Utils.shortenClassName(loggerName, 0, -12)); Assert.assertEquals("com...Logger", Utils.shortenClassName(loggerName, 0, Integer.MAX_VALUE)); } }
package ezvcard.io.text; import static ezvcard.util.TestUtils.assertIntEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.io.ByteArrayOutputStream; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.nio.charset.Charset; import org.junit.Test; import ezvcard.util.StringUtils; import ezvcard.util.org.apache.commons.codec.net.QuotedPrintableCodec; /** * @author Michael Angstadt */ public class FoldedLineWriterTest { @Test public void write() throws Throwable { StringWriter sw = new StringWriter(); FoldedLineWriter writer = new FoldedLineWriter(sw); writer.setLineLength(10); writer.write("line\r\nThis line should be "); writer.write("new line"); writer.write("aa"); writer.write("line"); writer.write("\r\n0123456789\r\n"); writer.write("0123456789", true, null); writer.write("\r\n"); writer.write("01234567=", true, null); writer.write("\r\n"); writer.write("01234567==", true, null); writer.write("\r\n"); writer.write("short", true, null); writer.write("\r\n"); writer.write("quoted-printable line", true, null); writer.close(); String actual = sw.toString(); //@formatter:off String expected = "line\r\n" + "This line \r\n" + " should be \r\n" + " new linea\r\n" + " aline\r\n" + "0123456789\r\n" + "012345678=\r\n" + " 9\r\n" + "01234567=3D\r\n" + "01234567=3D=\r\n" + " =3D\r\n" + "short\r\n" + "quoted-pr=\r\n" + " intable =\r\n" + " line"; //@formatter:on assertEquals(expected, actual); } @Test public void write_sub_array() throws Throwable { StringWriter sw = new StringWriter(); FoldedLineWriter writer = new FoldedLineWriter(sw); writer.setLineLength(10); String str = "This line should be folded."; writer.write(str, 5, 14); writer.close(); String actual = sw.toString(); //@formatter:off String expected = "line shoul\r\n" + " d be"; //@formatter:on assertEquals(expected, actual); } @Test public void write_charset() throws Throwable { StringWriter sw = new StringWriter(); FoldedLineWriter writer = new FoldedLineWriter(sw); writer.setLineLength(10); String str = "test\n\u00e4\u00f6\u00fc\u00df\ntest"; writer.write(str, true, Charset.forName("ISO-8859-1")); writer.close(); String actual = sw.toString(); //@formatter:off String expected = "test=0A=E4=\r\n" + " =F6=FC=DF=\r\n" + " =0Atest"; //@formatter:on assertEquals(expected, actual); QuotedPrintableCodec codec = new QuotedPrintableCodec("ISO-8859-1"); assertEquals("test\n\u00e4\u00f6\u00fc\u00df\ntest", codec.decode("test=0A=E4=F6=FC=DF=0Atest")); } @Test public void write_surrogate_pair() throws Exception { StringWriter sw = new StringWriter(); FoldedLineWriter writer = new FoldedLineWriter(sw); writer.setLineLength(5); String str = "test\uD83D\uDCF0test"; // should not be split writer.write(str, false, Charset.forName("UTF-8")); writer.close(); String actual = sw.toString(); assertEquals("test\uD83D\uDCF0\r\n test", actual); } @Test public void write_surrogate_pair_end() throws Exception { StringWriter sw = new StringWriter(); FoldedLineWriter writer = new FoldedLineWriter(sw); writer.setLineLength(5); String str = "test\uD83D\uDCF0"; // should not be split writer.write(str, false, Charset.forName("UTF-8")); writer.close(); String actual = sw.toString(); assertEquals("test\uD83D\uDCF0", actual); } @Test public void write_different_newlines() throws Exception { StringWriter sw = new StringWriter(); FoldedLineWriter writer = new FoldedLineWriter(sw); writer.setLineLength(8); writer.write("one\r\ntwo three\rthree\nfour five"); writer.close(); String actual = sw.toString(); //@formatter:off String expected = "one\r\n" + "two thre\r\n" + //folded lines always use the newline sequence defined with writer.setNewline() " e\r" + "three\n" + "four fiv\r\n" + " e"; //@formatter:on assertEquals(expected, actual); } @Test public void getLineLength_default() throws Exception { StringWriter sw = new StringWriter(); FoldedLineWriter writer = new FoldedLineWriter(sw); assertIntEquals(75, writer.getLineLength()); writer.close(); } @Test public void getIndent_default() throws Exception { StringWriter sw = new StringWriter(); FoldedLineWriter writer = new FoldedLineWriter(sw); assertEquals(" ", writer.getIndent()); writer.close(); } @Test public void setLineLength() throws Exception { StringWriter sw = new StringWriter(); FoldedLineWriter writer = new FoldedLineWriter(sw); writer.setLineLength(1); assertIntEquals(1, writer.getLineLength()); writer.close(); } @Test(expected = IllegalArgumentException.class) public void setLineLength_zero() throws Exception { StringWriter sw = new StringWriter(); FoldedLineWriter writer = new FoldedLineWriter(sw); writer.setLineLength(0); writer.close(); } @Test public void setLineLength_null() throws Exception { StringWriter sw = new StringWriter(); FoldedLineWriter writer = new FoldedLineWriter(sw); writer.setLineLength(null); //valid value writer.close(); } @Test public void getEncoding() throws Exception { StringWriter sw = new StringWriter(); FoldedLineWriter writer = new FoldedLineWriter(sw); assertNull(writer.getEncoding()); writer.close(); Charset charset = Charset.availableCharsets().values().iterator().next(); OutputStreamWriter osw = new OutputStreamWriter(new ByteArrayOutputStream(), charset); writer = new FoldedLineWriter(osw); assertEquals(charset, writer.getEncoding()); writer.close(); } @Test public void setIndent() throws Exception { StringWriter sw = new StringWriter(); FoldedLineWriter writer = new FoldedLineWriter(sw); writer.setLineLength(10); String indent = StringUtils.repeat(' ', 5); writer.setIndent(indent); assertEquals(indent, writer.getIndent()); writer.close(); } @Test(expected = IllegalArgumentException.class) public void setIndent_invalid() throws Exception { StringWriter sw = new StringWriter(); FoldedLineWriter writer = new FoldedLineWriter(sw); writer.setLineLength(10); writer.setIndent(StringUtils.repeat(' ', 10)); writer.close(); } }
package intellimate.izou.testHelper; import intellimate.izou.events.Event; import intellimate.izou.events.LocalEventManager; import intellimate.izou.fullplugintesting.TestAddOn; import intellimate.izou.main.Main; import intellimate.izou.system.Context; import intellimate.izou.system.Identifiable; import intellimate.izou.system.Identification; import intellimate.izou.system.IdentificationManager; import java.util.Optional; import static org.junit.Assert.*; /** * Helper class for Unit-testing */ public class IzouTest implements Identifiable{ private static Main staticMain; public Main main; public final String id; private IdentificationManager identificationManager; private static int identificationNumber; private static int eventNumber; private static final class Lock { } private final Object lock = new Lock(); private TestAddOn testAddOn = new TestAddOn(getID()); private Context context; /** * creates a new instance of IzouTest * @param isolated whether the fields (manager etc.) should be Isolated from all the other instances. */ public IzouTest(boolean isolated, String id) { if(isolated) { main = new Main(null, true); } else { if(staticMain == null) { staticMain = new Main(null, true); } this.main = staticMain; } context = new Context(testAddOn, main, "debug"); this.id = id; identificationManager = IdentificationManager.getInstance(); identificationManager.registerIdentification(this); } /** * An ID must always be unique. * A Class like Activator or OutputPlugin can just provide their .class.getCanonicalName() * If you have to implement this interface multiple times, just concatenate unique Strings to * .class.getCanonicalName() * * @return A String containing an ID */ @Override public String getID() { return id; } public Optional<Event> getEvent(String type) { Optional<Identification> id = identificationManager.getIdentification(this); if(!id.isPresent()) return Optional.empty(); return Event.createEvent(type, id.get()); } /** * checks if is working is set everywhere to false, [0] should be reserved for the test here */ public void testListenerTrue(final boolean[] isWorking, Event event) throws InterruptedException { main.getEventDistributor().registerEventListener(event, id -> { isWorking[0] = true; }); try { Identification id = IdentificationManager.getInstance().getIdentification(this).get(); main.getLocalEventManager().registerCaller(id).get().fire(event); } catch (LocalEventManager.MultipleEventsException e) { fail(); } synchronized (lock) { lock.wait(10); while(!main.getLocalEventManager().getEvents().isEmpty()) { lock.wait(2); } } boolean result = false; for (boolean temp : isWorking) { if(temp) result = true; } assertTrue(result); } /** * checks if is working is set everywhere to false, [0] should be reserved for the test here */ public void testListenerFalse(final boolean[] isWorking, Event eventId) throws InterruptedException { main.getEventDistributor().registerEventListener(eventId, id -> isWorking[0] = true); try { Identification id = IdentificationManager.getInstance().getIdentification(this).get(); main.getLocalEventManager().registerCaller(id).get().fire(eventId); } catch (LocalEventManager.MultipleEventsException e) { fail(); } synchronized (lock) { lock.wait(10); while(!main.getLocalEventManager().getEvents().isEmpty()) { lock.wait(2); } } boolean result = false; for (boolean temp : isWorking) { if(temp) result = true; } assertFalse(result); } /** * fires the event * @param event the event to fire */ public void testFireEvent(Event event) { try { Identification id = IdentificationManager.getInstance().getIdentification(this).get(); main.getLocalEventManager().registerCaller(id).get().fire(event); } catch (LocalEventManager.MultipleEventsException e) { fail(); } } /** * waits for multitasking * @throws InterruptedException */ public void waitForMultith() throws InterruptedException { synchronized (lock) { synchronized (lock) { lock.wait(10); while(!main.getLocalEventManager().getEvents().isEmpty()) { lock.wait(2); } } } } public Context getContext() { return context; } public Optional<Identification> getNextIdentification() { Identifiable identifiable = () -> id + identificationNumber; identificationManager.registerIdentification(identifiable); identificationNumber++; return identificationManager.getIdentification(identifiable); } public Optional<Event> getNextEvent() { eventNumber++; return getEvent(id + eventNumber); } }
package link.webarata3.poi; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import java.io.File; import java.nio.file.Files; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; @RunWith(Enclosed.class) public class BenrippoiUtilTest { public static class _getWorkbook { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @Test public void openFileNameTest() throws Exception { Workbook wb = TestUtil.getTempWorkbook(tempFolder, "book1.xlsx"); assertThat(wb, is(notNullValue())); wb.close(); } @Test public void openInputStreamTest() throws Exception { File file = TestUtil.getTempWorkbookFile(tempFolder, "book1.xlsx"); Workbook wb = BenrippoiUtil.open(Files.newInputStream(file.toPath())); assertThat(wb, is(notNullValue())); wb.close(); } } @RunWith(Theories.class) public static class _cellIndexToCellLabelTest { @DataPoints public static Fixture[] PARAMs = { new Fixture(0, 0, "A1"), new Fixture(1, 0, "B1"), new Fixture(2, 0, "C1"), new Fixture(26, 0, "AA1"), new Fixture(27, 0, "AB1"), new Fixture(28, 0, "AC1") }; static class Fixture { int x; int y; String cellLabel; Fixture(int x, int y, String cellLabel) { this.x = x; this.y = y; this.cellLabel = cellLabel; } @Override public String toString() { return "Fixture{" + "x=" + x + ", y=" + y + ", cellLabel='" + cellLabel + '\'' + '}'; } } @Theory public void test(Fixture fixture) { assertThat(fixture.toString(), BenrippoiUtil.cellIndexToCellLabel(fixture.x, fixture.y), is(fixture.cellLabel)); } } @RunWith(Theories.class) public static class _cellIndexToCellLabelTest { @Rule public ExpectedException thrown = ExpectedException.none(); @DataPoints public static Fixture[] PARAMs = { new Fixture(-1, 0), new Fixture(0, -1), new Fixture(-1, -1), new Fixture(-2, 0), new Fixture(0, -2), new Fixture(-2, -2) }; static class Fixture { int x; int y; Fixture(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return "Fixture{" + "x=" + x + ", y=" + y + '}'; } } @Theory public void test(Fixture fixture) { thrown.expect(IllegalArgumentException.class); BenrippoiUtil.cellIndexToCellLabel(fixture.x, fixture.y); } } @RunWith(Theories.class) public static class _getCellLabelToCellIndexTest { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @DataPoints public static Fixture[] PARAMs = { new Fixture("A1", 0, 0), new Fixture("B1", 1, 0), new Fixture("C1", 2, 0), new Fixture("AA1", 26, 0), new Fixture("AB1", 27, 0), new Fixture("AC1", 28, 0) }; static class Fixture { String cellLabel; int x; int y; Fixture(String cellLabel, int x, int y) { this.cellLabel = cellLabel; this.x = x; this.y = y; } @Override public String toString() { return "Fixture{" + "cellLabel='" + cellLabel + '\'' + ", x=" + x + ", y=" + y + '}'; } } @Theory public void test(Fixture fixture) throws Exception { Workbook wb = TestUtil.getTempWorkbook(tempFolder, "book1.xlsx"); Sheet sheet = wb.getSheetAt(0); Cell cell = BenrippoiUtil.getCell(sheet, fixture.cellLabel); assertThat(fixture.toString(), cell, is(notNullValue())); assertThat(fixture.toString(), cell.getAddress().getColumn(), is(fixture.x)); assertThat(fixture.toString(), cell.getAddress().getRow(), is(fixture.y)); } } @RunWith(Theories.class) public static class _getCellLabelToCellIndexTest { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @Rule public ExpectedException thrown = ExpectedException.none(); @DataPoints public static Fixture[] PARAMs = { new Fixture("1"), new Fixture("AA"), new Fixture(""), new Fixture("1"), new Fixture("A") }; static class Fixture { String cellLabel; Fixture(String cellLabel) { this.cellLabel = cellLabel; } @Override public String toString() { return "Fixture{" + "cellLabel='" + cellLabel + '\'' + '}'; } } @Theory public void test(Fixture fixture) throws Exception { Workbook wb = TestUtil.getTempWorkbook(tempFolder, "book1.xlsx"); Sheet sheet = wb.getSheetAt(0); thrown.expect(IllegalArgumentException.class); Cell cell = BenrippoiUtil.getCell(sheet, fixture.cellLabel); } } @RunWith(Theories.class) public static class GetRowByIndex { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @DataPoints public static Fixture[] PARAMs = { new Fixture(0), new Fixture(1), new Fixture(2), new Fixture(3), new Fixture(4) }; static class Fixture { int y; Fixture(int y) { this.y = y; } @Override public String toString() { return "Fixture{" + "y=" + y + '}'; } } @Theory public void test(Fixture fixture) throws Exception { Sheet sheet = TestUtil.getSheet(tempFolder, "book1.xlsx"); assertThat(sheet, is(notNullValue())); Row row = BenrippoiUtil.getRow(sheet, fixture.y); assertThat(row, is(notNullValue())); assertThat(row.getRowNum(), is(fixture.y)); } } @RunWith(Theories.class) public static class _getCellByIndex { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @DataPoints public static Fixture[] PARAMs = { new Fixture(0, 0), new Fixture(1, 1), new Fixture(2, 2), new Fixture(3, 3), new Fixture(4, 4) }; static class Fixture { int x; int y; Fixture(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return "Fixture{" + "x=" + x + ", y=" + y + '}'; } } @Theory public void test(Fixture fixture) throws Exception { Sheet sheet = TestUtil.getSheet(tempFolder, "book1.xlsx"); assertThat(sheet, is(notNullValue())); Cell cell = BenrippoiUtil.getCell(sheet, fixture.x, fixture.y); assertThat(cell, is(notNullValue())); assertThat(cell.getAddress().getColumn(), is(fixture.x)); assertThat(cell.getAddress().getRow(), is(fixture.y)); } } @RunWith(Theories.class) public static class _getCellByCellLabel { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @DataPoints public static Fixture[] PARAMs = { new Fixture("A1", 0, 0), new Fixture("B2", 1, 1), new Fixture("C3", 2, 2), new Fixture("C4", 2, 3), new Fixture("C5", 2, 4) }; static class Fixture { String cellLabel; int x; int y; Fixture(String cellLabel, int x, int y) { this.cellLabel = cellLabel; this.x = x; this.y = y; } @Override public String toString() { return "Fixture{" + "cellLabel='" + cellLabel + '\'' + ", x=" + x + ", y=" + y + '}'; } } @Theory public void test(Fixture fixture) throws Exception { Sheet sheet = TestUtil.getSheet(tempFolder, "book1.xlsx"); assertThat(sheet, is(notNullValue())); Cell cell = BenrippoiUtil.getCell(sheet, fixture.cellLabel); assertThat(cell, is(notNullValue())); assertThat(cell.getAddress().getColumn(), is(fixture.x)); assertThat(cell.getAddress().getRow(), is(fixture.y)); } } @RunWith(Theories.class) public static class _cellToString { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @DataPoints public static Fixture[] PARAMs = { new Fixture("B2", ""), new Fixture("C2", "123"), new Fixture("D2", "150.51"), new Fixture("F2", "true"), new Fixture("G2", "123150.51"), new Fixture("H2", ""), new Fixture("I2", ""), new Fixture("J2", "123") }; static class Fixture { String cellLabel; String expected; Fixture(String cellLabel, String expected) { this.cellLabel = cellLabel; this.expected = expected; } @Override public String toString() { return "Fixture{" + "cellLabel='" + cellLabel + '\'' + ", expected='" + expected + '\'' + '}'; } } @Theory public void test(Fixture fixture) throws Exception { Sheet sheet = TestUtil.getSheet(tempFolder, "book1.xlsx"); assertThat(sheet, is(notNullValue())); Cell cell = BenrippoiUtil.getCell(sheet, fixture.cellLabel); assertThat(cell, is(notNullValue())); assertThat(BenrippoiUtil.cellToString(cell), is(fixture.expected)); } } @RunWith(Theories.class) public static class __cellToString { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @Rule public ExpectedException thrown = ExpectedException.none(); @DataPoints public static Fixture[] PARAMs = { new Fixture("E2") }; static class Fixture { String cellLabel; Fixture(String cellLabel) { this.cellLabel = cellLabel; } @Override public String toString() { return "Fixture{" + "cellLabel='" + cellLabel + '\'' + '}'; } } @Theory public void test(Fixture fixture) throws Exception { Sheet sheet = TestUtil.getSheet(tempFolder, "book1.xlsx"); assertThat(sheet, is(notNullValue())); Cell cell = BenrippoiUtil.getCell(sheet, fixture.cellLabel); assertThat(cell, is(notNullValue())); thrown.expect(UnsupportedOperationException.class); BenrippoiUtil.cellToString(cell); } } @RunWith(Theories.class) public static class _cellToString { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @Rule public ExpectedException thrown = ExpectedException.none(); @DataPoints public static Fixture[] PARAMs = { new Fixture("K2") }; static class Fixture { String cellLabel; Fixture(String cellLabel) { this.cellLabel = cellLabel; } @Override public String toString() { return "Fixture{" + "cellLabel='" + cellLabel + '\'' + '}'; } } @Theory public void test(Fixture fixture) throws Exception { Sheet sheet = TestUtil.getSheet(tempFolder, "book1.xlsx"); assertThat(sheet, is(notNullValue())); Cell cell = BenrippoiUtil.getCell(sheet, fixture.cellLabel); assertThat(cell, is(notNullValue())); thrown.expect(PoiIllegalAccessException.class); BenrippoiUtil.cellToString(cell); } } @RunWith(Theories.class) public static class _cellToInt { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @DataPoints public static Fixture[] PARAMs = { new Fixture("B3", 456), new Fixture("C3", 123), new Fixture("D3", 150), new Fixture("G3", 369), new Fixture("J3", 456123) }; static class Fixture { String cellLabel; int expected; Fixture(String cellLabel, int expected) { this.cellLabel = cellLabel; this.expected = expected; } @Override public String toString() { return "Fixture{" + "cellLabel='" + cellLabel + '\'' + ", expected=" + expected + '}'; } } @Theory public void test(Fixture fixture) throws Exception { Sheet sheet = TestUtil.getSheet(tempFolder, "book1.xlsx"); assertThat(sheet, is(notNullValue())); Cell cell = BenrippoiUtil.getCell(sheet, fixture.cellLabel); assertThat(cell, is(notNullValue())); assertThat(BenrippoiUtil.cellToInt(cell), is(fixture.expected)); } } @RunWith(Theories.class) public static class _cellToInt { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @Rule public ExpectedException thrown = ExpectedException.none(); @DataPoints public static Fixture[] PARAMs = { new Fixture("B2"), new Fixture("E3"), new Fixture("F3"), new Fixture("H3"), new Fixture("I3"), new Fixture("K3") }; static class Fixture { String cellLabel; Fixture(String cellLabel) { this.cellLabel = cellLabel; } @Override public String toString() { return "Fixture{" + "cellLabel='" + cellLabel + '\'' + '}'; } } @Theory public void test(Fixture fixture) throws Exception { Sheet sheet = TestUtil.getSheet(tempFolder, "book1.xlsx"); assertThat(sheet, is(notNullValue())); Cell cell = BenrippoiUtil.getCell(sheet, fixture.cellLabel); assertThat(cell, is(notNullValue())); thrown.expect(PoiIllegalAccessException.class); BenrippoiUtil.cellToInt(cell); } } @RunWith(Theories.class) public static class _cellToDouble { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @DataPoints public static Fixture[] PARAMs = { new Fixture("B4", 123.456), new Fixture("C4", 123), new Fixture("D4", 150.51), new Fixture("G4", 50.17), new Fixture("J4", 123123.456) }; static class Fixture { String cellLabel; double expected; Fixture(String cellLabel, double expected) { this.cellLabel = cellLabel; this.expected = expected; } @Override public String toString() { return "Fixture{" + "cellLabel='" + cellLabel + '\'' + ", expected=" + expected + '}'; } } @Theory public void test(Fixture fixture) throws Exception { Sheet sheet = TestUtil.getSheet(tempFolder, "book1.xlsx"); assertThat(sheet, is(notNullValue())); Cell cell = BenrippoiUtil.getCell(sheet, fixture.cellLabel); assertThat(cell, is(notNullValue())); assertThat(BenrippoiUtil.cellToDouble(cell), is(closeTo(fixture.expected, 0.00001))); } } @RunWith(Theories.class) public static class _cellToDouble { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @Rule public ExpectedException thrown = ExpectedException.none(); @DataPoints public static Fixture[] PARAMs = { new Fixture("B2"), new Fixture("E4"), new Fixture("F4"), new Fixture("H4"), new Fixture("I4"), new Fixture("K4") }; static class Fixture { String cellLabel; Fixture(String cellLabel) { this.cellLabel = cellLabel; } @Override public String toString() { return "Fixture{" + "cellLabel='" + cellLabel + '\'' + '}'; } } @Theory public void test(Fixture fixture) throws Exception { Sheet sheet = TestUtil.getSheet(tempFolder, "book1.xlsx"); assertThat(sheet, is(notNullValue())); Cell cell = BenrippoiUtil.getCell(sheet, fixture.cellLabel); assertThat(cell, is(notNullValue())); thrown.expect(PoiIllegalAccessException.class); BenrippoiUtil.cellToDouble(cell); } } @RunWith(Theories.class) public static class _cellToBoolean { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @DataPoints public static Fixture[] PARAMs = { new Fixture("F5", true), new Fixture("G5", false) }; static class Fixture { String cellLabel; boolean expected; Fixture(String cellLabel, boolean expected) { this.cellLabel = cellLabel; this.expected = expected; } @Override public String toString() { return "Fixture{" + "cellLabel='" + cellLabel + '\'' + ", expected=" + expected + '}'; } } @Theory public void test(Fixture fixture) throws Exception { Sheet sheet = TestUtil.getSheet(tempFolder, "book1.xlsx"); assertThat(sheet, is(notNullValue())); Cell cell = BenrippoiUtil.getCell(sheet, fixture.cellLabel); assertThat(cell, is(notNullValue())); assertThat(BenrippoiUtil.cellToBoolean(cell), is(fixture.expected)); } } @RunWith(Theories.class) public static class _cellToBoolean { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @Rule public ExpectedException thrown = ExpectedException.none(); @DataPoints public static Fixture[] PARAMs = { new Fixture("B5"), new Fixture("C5"), new Fixture("D5"), new Fixture("E5"), new Fixture("K5") }; static class Fixture { String cellLabel; Fixture(String cellLabel) { this.cellLabel = cellLabel; } @Override public String toString() { return "Fixture{" + "cellLabel='" + cellLabel + '\'' + '}'; } } @Theory public void test(Fixture fixture) throws Exception { Sheet sheet = TestUtil.getSheet(tempFolder, "book1.xlsx"); assertThat(sheet, is(notNullValue())); Cell cell = BenrippoiUtil.getCell(sheet, fixture.cellLabel); assertThat(cell, is(notNullValue())); thrown.expect(PoiIllegalAccessException.class); BenrippoiUtil.cellToBoolean(cell); } } }
package link.webarata3.poi; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import java.io.File; import java.nio.file.Files; import java.time.LocalDate; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; @RunWith(Enclosed.class) public class BenrippoiUtilTest { public static class _getWorkbook { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @Test public void openFileNameTest() throws Exception { Workbook wb = TestUtil.getTempWorkbook(tempFolder, "book1.xlsx"); assertThat(wb, is(notNullValue())); wb.close(); } @Test public void openInputStreamTest() throws Exception { File file = TestUtil.getTempWorkbookFile(tempFolder, "book1.xlsx"); Workbook wb = BenrippoiUtil.open(Files.newInputStream(file.toPath())); assertThat(wb, is(notNullValue())); wb.close(); } } @RunWith(Theories.class) public static class _cellIndexToCellLabelTest { @DataPoints public static Fixture[] PARAMs = { new Fixture(0, 0, "A1"), new Fixture(1, 0, "B1"), new Fixture(2, 0, "C1"), new Fixture(26, 0, "AA1"), new Fixture(27, 0, "AB1"), new Fixture(28, 0, "AC1") }; static class Fixture { int x; int y; String cellLabel; Fixture(int x, int y, String cellLabel) { this.x = x; this.y = y; this.cellLabel = cellLabel; } @Override public String toString() { return "Fixture{" + "x=" + x + ", y=" + y + ", cellLabel='" + cellLabel + '\'' + '}'; } } @Theory public void test(Fixture fixture) { assertThat(fixture.toString(), BenrippoiUtil.cellIndexToCellLabel(fixture.x, fixture.y), is(fixture.cellLabel)); } } @RunWith(Theories.class) public static class _cellIndexToCellLabelTest { @Rule public ExpectedException thrown = ExpectedException.none(); @DataPoints public static Fixture[] PARAMs = { new Fixture(-1, 0), new Fixture(0, -1), new Fixture(-1, -1), new Fixture(-2, 0), new Fixture(0, -2), new Fixture(-2, -2) }; static class Fixture { int x; int y; Fixture(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return "Fixture{" + "x=" + x + ", y=" + y + '}'; } } @Theory public void test(Fixture fixture) { thrown.expect(IllegalArgumentException.class); BenrippoiUtil.cellIndexToCellLabel(fixture.x, fixture.y); } } @RunWith(Theories.class) public static class _getCellLabelToCellIndexTest { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @DataPoints public static Fixture[] PARAMs = { new Fixture("A1", 0, 0), new Fixture("B1", 1, 0), new Fixture("C1", 2, 0), new Fixture("AA1", 26, 0), new Fixture("AB1", 27, 0), new Fixture("AC1", 28, 0) }; static class Fixture { String cellLabel; int x; int y; Fixture(String cellLabel, int x, int y) { this.cellLabel = cellLabel; this.x = x; this.y = y; } @Override public String toString() { return "Fixture{" + "cellLabel='" + cellLabel + '\'' + ", x=" + x + ", y=" + y + '}'; } } @Theory public void test(Fixture fixture) throws Exception { Workbook wb = TestUtil.getTempWorkbook(tempFolder, "book1.xlsx"); Sheet sheet = wb.getSheetAt(0); Cell cell = BenrippoiUtil.getCell(sheet, fixture.cellLabel); assertThat(fixture.toString(), cell, is(notNullValue())); assertThat(fixture.toString(), cell.getAddress().getColumn(), is(fixture.x)); assertThat(fixture.toString(), cell.getAddress().getRow(), is(fixture.y)); } } @RunWith(Theories.class) public static class _getCellLabelToCellIndexTest { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @Rule public ExpectedException thrown = ExpectedException.none(); @DataPoints public static Fixture[] PARAMs = { new Fixture("1"), new Fixture("AA"), new Fixture(""), new Fixture("1"), new Fixture("A") }; static class Fixture { String cellLabel; Fixture(String cellLabel) { this.cellLabel = cellLabel; } @Override public String toString() { return "Fixture{" + "cellLabel='" + cellLabel + '\'' + '}'; } } @Theory public void test(Fixture fixture) throws Exception { Workbook wb = TestUtil.getTempWorkbook(tempFolder, "book1.xlsx"); Sheet sheet = wb.getSheetAt(0); thrown.expect(IllegalArgumentException.class); Cell cell = BenrippoiUtil.getCell(sheet, fixture.cellLabel); } } @RunWith(Theories.class) public static class GetRowByIndex { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @DataPoints public static Fixture[] PARAMs = { new Fixture(0), new Fixture(1), new Fixture(2), new Fixture(3), new Fixture(4) }; static class Fixture { int y; Fixture(int y) { this.y = y; } @Override public String toString() { return "Fixture{" + "y=" + y + '}'; } } @Theory public void test(Fixture fixture) throws Exception { Sheet sheet = TestUtil.getSheet(tempFolder, "book1.xlsx"); assertThat(sheet, is(notNullValue())); Row row = BenrippoiUtil.getRow(sheet, fixture.y); assertThat(row, is(notNullValue())); assertThat(row.getRowNum(), is(fixture.y)); } } @RunWith(Theories.class) public static class _getCellByIndex { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @DataPoints public static Fixture[] PARAMs = { new Fixture(0, 0), new Fixture(1, 1), new Fixture(2, 2), new Fixture(3, 3), new Fixture(4, 4) }; static class Fixture { int x; int y; Fixture(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return "Fixture{" + "x=" + x + ", y=" + y + '}'; } } @Theory public void test(Fixture fixture) throws Exception { Sheet sheet = TestUtil.getSheet(tempFolder, "book1.xlsx"); assertThat(sheet, is(notNullValue())); Cell cell = BenrippoiUtil.getCell(sheet, fixture.x, fixture.y); assertThat(cell, is(notNullValue())); assertThat(cell.getAddress().getColumn(), is(fixture.x)); assertThat(cell.getAddress().getRow(), is(fixture.y)); } } @RunWith(Theories.class) public static class _getCellByCellLabel { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @DataPoints public static Fixture[] PARAMs = { new Fixture("A1", 0, 0), new Fixture("B2", 1, 1), new Fixture("C3", 2, 2), new Fixture("C4", 2, 3), new Fixture("C5", 2, 4) }; static class Fixture { String cellLabel; int x; int y; Fixture(String cellLabel, int x, int y) { this.cellLabel = cellLabel; this.x = x; this.y = y; } @Override public String toString() { return "Fixture{" + "cellLabel='" + cellLabel + '\'' + ", x=" + x + ", y=" + y + '}'; } } @Theory public void test(Fixture fixture) throws Exception { Sheet sheet = TestUtil.getSheet(tempFolder, "book1.xlsx"); assertThat(sheet, is(notNullValue())); Cell cell = BenrippoiUtil.getCell(sheet, fixture.cellLabel); assertThat(cell, is(notNullValue())); assertThat(cell.getAddress().getColumn(), is(fixture.x)); assertThat(cell.getAddress().getRow(), is(fixture.y)); } } @RunWith(Theories.class) public static class _cellToString { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @DataPoints public static Fixture[] PARAMs = { new Fixture("B2", ""), new Fixture("C2", "123"), new Fixture("D2", "150.51"), new Fixture("F2", "true"), new Fixture("G2", "123150.51"), new Fixture("H2", ""), new Fixture("I2", ""), new Fixture("J2", "123") }; static class Fixture { String cellLabel; String expected; Fixture(String cellLabel, String expected) { this.cellLabel = cellLabel; this.expected = expected; } @Override public String toString() { return "Fixture{" + "cellLabel='" + cellLabel + '\'' + ", expected='" + expected + '\'' + '}'; } } @Theory public void test(Fixture fixture) throws Exception { Sheet sheet = TestUtil.getSheet(tempFolder, "book1.xlsx"); assertThat(sheet, is(notNullValue())); Cell cell = BenrippoiUtil.getCell(sheet, fixture.cellLabel); assertThat(cell, is(notNullValue())); assertThat(BenrippoiUtil.cellToString(cell), is(fixture.expected)); } } @RunWith(Theories.class) public static class __cellToString { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @Rule public ExpectedException thrown = ExpectedException.none(); @DataPoints public static Fixture[] PARAMs = { new Fixture("E2") }; static class Fixture { String cellLabel; Fixture(String cellLabel) { this.cellLabel = cellLabel; } @Override public String toString() { return "Fixture{" + "cellLabel='" + cellLabel + '\'' + '}'; } } @Theory public void test(Fixture fixture) throws Exception { Sheet sheet = TestUtil.getSheet(tempFolder, "book1.xlsx"); assertThat(sheet, is(notNullValue())); Cell cell = BenrippoiUtil.getCell(sheet, fixture.cellLabel); assertThat(cell, is(notNullValue())); thrown.expect(UnsupportedOperationException.class); BenrippoiUtil.cellToString(cell); } } @RunWith(Theories.class) public static class _cellToString { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @Rule public ExpectedException thrown = ExpectedException.none(); @DataPoints public static Fixture[] PARAMs = { new Fixture("K2") }; static class Fixture { String cellLabel; Fixture(String cellLabel) { this.cellLabel = cellLabel; } @Override public String toString() { return "Fixture{" + "cellLabel='" + cellLabel + '\'' + '}'; } } @Theory public void test(Fixture fixture) throws Exception { Sheet sheet = TestUtil.getSheet(tempFolder, "book1.xlsx"); assertThat(sheet, is(notNullValue())); Cell cell = BenrippoiUtil.getCell(sheet, fixture.cellLabel); assertThat(cell, is(notNullValue())); thrown.expect(PoiIllegalAccessException.class); BenrippoiUtil.cellToString(cell); } } @RunWith(Theories.class) public static class _cellToInt { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @DataPoints public static Fixture[] PARAMs = { new Fixture("B3", 456), new Fixture("C3", 123), new Fixture("D3", 150), new Fixture("G3", 369), new Fixture("J3", 456123) }; static class Fixture { String cellLabel; int expected; Fixture(String cellLabel, int expected) { this.cellLabel = cellLabel; this.expected = expected; } @Override public String toString() { return "Fixture{" + "cellLabel='" + cellLabel + '\'' + ", expected=" + expected + '}'; } } @Theory public void test(Fixture fixture) throws Exception { Sheet sheet = TestUtil.getSheet(tempFolder, "book1.xlsx"); assertThat(sheet, is(notNullValue())); Cell cell = BenrippoiUtil.getCell(sheet, fixture.cellLabel); assertThat(cell, is(notNullValue())); assertThat(BenrippoiUtil.cellToInt(cell), is(fixture.expected)); } } @RunWith(Theories.class) public static class _cellToInt { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @Rule public ExpectedException thrown = ExpectedException.none(); @DataPoints public static Fixture[] PARAMs = { new Fixture("B2"), new Fixture("E3"), new Fixture("F3"), new Fixture("H3"), new Fixture("I3"), new Fixture("K3") }; static class Fixture { String cellLabel; Fixture(String cellLabel) { this.cellLabel = cellLabel; } @Override public String toString() { return "Fixture{" + "cellLabel='" + cellLabel + '\'' + '}'; } } @Theory public void test(Fixture fixture) throws Exception { Sheet sheet = TestUtil.getSheet(tempFolder, "book1.xlsx"); assertThat(sheet, is(notNullValue())); Cell cell = BenrippoiUtil.getCell(sheet, fixture.cellLabel); assertThat(cell, is(notNullValue())); thrown.expect(PoiIllegalAccessException.class); BenrippoiUtil.cellToInt(cell); } } @RunWith(Theories.class) public static class _cellToDouble { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @DataPoints public static Fixture[] PARAMs = { new Fixture("B4", 123.456), new Fixture("C4", 123), new Fixture("D4", 150.51), new Fixture("G4", 50.17), new Fixture("J4", 123123.456) }; static class Fixture { String cellLabel; double expected; Fixture(String cellLabel, double expected) { this.cellLabel = cellLabel; this.expected = expected; } @Override public String toString() { return "Fixture{" + "cellLabel='" + cellLabel + '\'' + ", expected=" + expected + '}'; } } @Theory public void test(Fixture fixture) throws Exception { Sheet sheet = TestUtil.getSheet(tempFolder, "book1.xlsx"); assertThat(sheet, is(notNullValue())); Cell cell = BenrippoiUtil.getCell(sheet, fixture.cellLabel); assertThat(cell, is(notNullValue())); assertThat(BenrippoiUtil.cellToDouble(cell), is(closeTo(fixture.expected, 0.00001))); } } @RunWith(Theories.class) public static class _cellToDouble { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @Rule public ExpectedException thrown = ExpectedException.none(); @DataPoints public static Fixture[] PARAMs = { new Fixture("B2"), new Fixture("E4"), new Fixture("F4"), new Fixture("H4"), new Fixture("I4"), new Fixture("K4") }; static class Fixture { String cellLabel; Fixture(String cellLabel) { this.cellLabel = cellLabel; } @Override public String toString() { return "Fixture{" + "cellLabel='" + cellLabel + '\'' + '}'; } } @Theory public void test(Fixture fixture) throws Exception { Sheet sheet = TestUtil.getSheet(tempFolder, "book1.xlsx"); assertThat(sheet, is(notNullValue())); Cell cell = BenrippoiUtil.getCell(sheet, fixture.cellLabel); assertThat(cell, is(notNullValue())); thrown.expect(PoiIllegalAccessException.class); BenrippoiUtil.cellToDouble(cell); } } @RunWith(Theories.class) public static class _cellToBoolean { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @DataPoints public static Fixture[] PARAMs = { new Fixture("F5", true), new Fixture("G5", false) }; static class Fixture { String cellLabel; boolean expected; Fixture(String cellLabel, boolean expected) { this.cellLabel = cellLabel; this.expected = expected; } @Override public String toString() { return "Fixture{" + "cellLabel='" + cellLabel + '\'' + ", expected=" + expected + '}'; } } @Theory public void test(Fixture fixture) throws Exception { Sheet sheet = TestUtil.getSheet(tempFolder, "book1.xlsx"); assertThat(sheet, is(notNullValue())); Cell cell = BenrippoiUtil.getCell(sheet, fixture.cellLabel); assertThat(cell, is(notNullValue())); assertThat(BenrippoiUtil.cellToBoolean(cell), is(fixture.expected)); } } @RunWith(Theories.class) public static class _cellToBoolean { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @Rule public ExpectedException thrown = ExpectedException.none(); @DataPoints public static Fixture[] PARAMs = { new Fixture("B5"), new Fixture("C5"), new Fixture("D5"), new Fixture("E5"), new Fixture("K5") }; static class Fixture { String cellLabel; Fixture(String cellLabel) { this.cellLabel = cellLabel; } @Override public String toString() { return "Fixture{" + "cellLabel='" + cellLabel + '\'' + '}'; } } @Theory public void test(Fixture fixture) throws Exception { Sheet sheet = TestUtil.getSheet(tempFolder, "book1.xlsx"); assertThat(sheet, is(notNullValue())); Cell cell = BenrippoiUtil.getCell(sheet, fixture.cellLabel); assertThat(cell, is(notNullValue())); thrown.expect(PoiIllegalAccessException.class); BenrippoiUtil.cellToBoolean(cell); } } @RunWith(Theories.class) public static class _cellToLocalDate { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @DataPoints public static Fixture[] PARAMs = { new Fixture("E6", LocalDate.of(2015, 12, 1)), new Fixture("G6", LocalDate.of(2015, 12, 3)) }; static class Fixture { String cellLabel; LocalDate expected; Fixture(String cellLabel, LocalDate expected) { this.cellLabel = cellLabel; this.expected = expected; } @Override public String toString() { return "Fixture{" + "cellLabel='" + cellLabel + '\'' + ", expected=" + expected + '}'; } } @Theory public void test(Fixture fixture) throws Exception { Sheet sheet = TestUtil.getSheet(tempFolder, "book1.xlsx"); assertThat(sheet, is(notNullValue())); Cell cell = BenrippoiUtil.getCell(sheet, fixture.cellLabel); assertThat(cell, is(notNullValue())); assertThat(BenrippoiUtil.cellToLocalDate(cell), is(fixture.expected)); } } @RunWith(Theories.class) public static class _cellToLocalDate { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @Rule public ExpectedException thrown = ExpectedException.none(); @DataPoints public static Fixture[] PARAMs = { new Fixture("A6"), new Fixture("B6"), new Fixture("C6"), new Fixture("D6"), new Fixture("F6"), new Fixture("H6"), new Fixture("I6"), new Fixture("J6"), new Fixture("K6") }; static class Fixture { String cellLabel; Fixture(String cellLabel) { this.cellLabel = cellLabel; } @Override public String toString() { return "Fixture{" + "cellLabel='" + cellLabel + '\'' + '}'; } } @Theory public void test(Fixture fixture) throws Exception { Sheet sheet = TestUtil.getSheet(tempFolder, "book1.xlsx"); assertThat(sheet, is(notNullValue())); Cell cell = BenrippoiUtil.getCell(sheet, fixture.cellLabel); assertThat(cell, is(notNullValue())); thrown.expect(PoiIllegalAccessException.class); BenrippoiUtil.cellToLocalDate(cell); } } }
package net.kullo.javautils; import junit.framework.TestCase; import java.nio.charset.Charset; import java.util.Arrays; public class StrictBase64Test extends TestCase { static void assertBytearrayEquals(byte[] expected, byte[] actual) { assertTrue(Arrays.equals(expected, actual)); } public void testEncodeBinaryEmpty() throws Exception { assertEquals("", StrictBase64.encode(new byte[0])); } public void testEncodeBinaryShort() throws Exception { assertEquals("Zg==", StrictBase64.encode(new byte[]{'f'})); assertEquals("Zm8=", StrictBase64.encode(new byte[]{'f', 'o'})); assertEquals("Zm9v", StrictBase64.encode(new byte[]{'f', 'o', 'o'})); assertEquals("Zm9vYg==", StrictBase64.encode(new byte[]{'f', 'o', 'o', 'b'})); assertEquals("Zm9vYmE=", StrictBase64.encode(new byte[]{'f', 'o', 'o', 'b', 'a'})); assertEquals("Zm9vYmFy", StrictBase64.encode(new byte[]{'f', 'o', 'o', 'b', 'a', 'r'})); } public void testEncodeBinary() throws Exception { // Generated by: cat /dev/urandom | head -c 3 | tee /tmp/mybinary | hexdump -C && cat /tmp/mybinary | base64 byte[] binary1 = {(byte) 0x9b}; assertEquals("mw==", StrictBase64.encode(binary1)); byte[] binary2 = {(byte) 0x1c, (byte) 0x60}; assertEquals("HGA=", StrictBase64.encode(binary2)); byte[] binary3 = {(byte) 0x81, (byte) 0x34, (byte) 0xbd}; assertEquals("gTS9", StrictBase64.encode(binary3)); byte[] binary4 = {(byte) 0x5e, (byte) 0x6c, (byte) 0xff, (byte) 0xde}; assertEquals("Xmz/3g==", StrictBase64.encode(binary4)); byte[] binary5 = {(byte) 0xb2, (byte) 0xcd, (byte) 0xf0, (byte) 0xdc, (byte) 0x7f}; assertEquals("ss3w3H8=", StrictBase64.encode(binary5)); byte[] binary6 = {(byte) 0xfc, (byte) 0x56, (byte) 0x2d, (byte) 0xda, (byte) 0xd4, (byte) 0x0e}; assertEquals("/FYt2tQO", StrictBase64.encode(binary6)); byte[] binary7 = {(byte) 0x29, (byte) 0xb2, (byte) 0x32, (byte) 0x2e, (byte) 0x88, (byte) 0x41, (byte) 0xe8}; assertEquals("KbIyLohB6A==", StrictBase64.encode(binary7)); byte[] binary8 = {(byte) 0x0f, (byte) 0x0f, (byte) 0xce, (byte) 0xd9, (byte) 0x49, (byte) 0x7a, (byte) 0xaf, (byte) 0x92}; assertEquals("Dw/O2Ul6r5I=", StrictBase64.encode(binary8)); byte[] binary9 = {(byte) 0x27, (byte) 0x0f, (byte) 0xb1, (byte) 0x89, (byte) 0x82, (byte) 0x80, (byte) 0x0d, (byte) 0xa6, (byte) 0x40}; assertEquals("Jw+xiYKADaZA", StrictBase64.encode(binary9)); } public void testDecodeEmpty() throws Exception { assertBytearrayEquals(new byte[0], StrictBase64.decode("")); } public void testDecodeShortString() throws Exception { assertBytearrayEquals(new byte[]{'f'}, StrictBase64.decode("Zg==")); assertBytearrayEquals(new byte[]{'f', 'o'}, StrictBase64.decode("Zm8=")); assertBytearrayEquals(new byte[]{'f', 'o', 'o'}, StrictBase64.decode("Zm9v")); } public void testDecodeShortStringIgnoreWhitespace() throws Exception { assertBytearrayEquals(new byte[]{'f'}, StrictBase64.decode(" Zg==", true)); assertBytearrayEquals(new byte[]{'f'}, StrictBase64.decode("Z g==", true)); assertBytearrayEquals(new byte[]{'f'}, StrictBase64.decode("Zg ==", true)); assertBytearrayEquals(new byte[]{'f'}, StrictBase64.decode("Zg= =", true)); assertBytearrayEquals(new byte[]{'f'}, StrictBase64.decode("Zg== ", true)); assertBytearrayEquals(new byte[]{'f'}, StrictBase64.decode("\nZg==", true)); assertBytearrayEquals(new byte[]{'f'}, StrictBase64.decode("Z\ng==", true)); assertBytearrayEquals(new byte[]{'f'}, StrictBase64.decode("Zg\n==", true)); assertBytearrayEquals(new byte[]{'f'}, StrictBase64.decode("Zg=\n=", true)); assertBytearrayEquals(new byte[]{'f'}, StrictBase64.decode("Zg==\n", true)); assertBytearrayEquals(new byte[]{'f'}, StrictBase64.decode("\rZg==", true)); assertBytearrayEquals(new byte[]{'f'}, StrictBase64.decode("Z\rg==", true)); assertBytearrayEquals(new byte[]{'f'}, StrictBase64.decode("Zg\r==", true)); assertBytearrayEquals(new byte[]{'f'}, StrictBase64.decode("Zg=\r=", true)); assertBytearrayEquals(new byte[]{'f'}, StrictBase64.decode("Zg==\r", true)); assertBytearrayEquals(new byte[]{'f'}, StrictBase64.decode("\tZg==", true)); assertBytearrayEquals(new byte[]{'f'}, StrictBase64.decode("Z\tg==", true)); assertBytearrayEquals(new byte[]{'f'}, StrictBase64.decode("Zg\t==", true)); assertBytearrayEquals(new byte[]{'f'}, StrictBase64.decode("Zg=\t=", true)); assertBytearrayEquals(new byte[]{'f'}, StrictBase64.decode("Zg==\t", true)); } public void testDecodeString() throws Exception { // Generated by: echo -n "xyz" | base64 assertBytearrayEquals(new byte[]{'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'}, StrictBase64.decode("aGVsbG8gd29ybGQ=")); assertBytearrayEquals(new byte[]{'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!'}, StrictBase64.decode("aGVsbG8gd29ybGQh")); assertBytearrayEquals(new byte[]{'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '.'}, StrictBase64.decode("SGVsbG8sIHdvcmxkLg==")); assertBytearrayEquals(new byte[]{'T', 'h', 'e', ' ', '1', '2', ' ', 'c', 'h', 'a', 'r', 's'}, StrictBase64.decode("VGhlIDEyIGNoYXJz")); assertBytearrayEquals(new byte[]{'T', 'h', 'e', ' ', '1', '3', ' ', 'c', 'h', 'a', 'r', 's', '.'}, StrictBase64.decode("VGhlIDEzIGNoYXJzLg==")); assertBytearrayEquals(new byte[]{'T', 'h', 'e', ' ', '1', '4', ' ', 'c', 'h', 'a', 'r', 's', '.', '.'}, StrictBase64.decode("VGhlIDE0IGNoYXJzLi4=")); assertBytearrayEquals(new byte[]{'T', 'h', 'e', ' ', '1', '5', ' ', 'c', 'h', 'a', 'r', 's', '.', '.', '.'}, StrictBase64.decode("VGhlIDE1IGNoYXJzLi4u")); } public void testDecodeStringSpecialChars() throws Exception { // Generated by: echo -n "xyz" | base64 // Generated by: echo -n "xyz" | hexdump -C assertBytearrayEquals("ß".getBytes("UTF-8"), StrictBase64.decode("w58=")); assertBytearrayEquals(new byte[]{(byte) 0xC3, (byte) 0x9f}, StrictBase64.decode("w58=")); assertBytearrayEquals("ü".getBytes("UTF-8"), StrictBase64.decode("w7w=")); assertBytearrayEquals(new byte[]{(byte) 0xC3, (byte) 0xBC}, StrictBase64.decode("w7w=")); } public void testDecodeBinary() throws Exception { // Generated by: cat /dev/urandom | head -c 3 | tee /tmp/mybinary | hexdump -C && cat /tmp/mybinary | base64 byte[] binary0 = {}; assertBytearrayEquals(binary0, StrictBase64.decode("")); byte[] binary1 = {(byte) 0x9b}; assertBytearrayEquals(binary1, StrictBase64.decode("mw==")); byte[] binary2 = {(byte) 0x1c, (byte) 0x60}; assertBytearrayEquals(binary2, StrictBase64.decode("HGA=")); byte[] binary3 = {(byte) 0x81, (byte) 0x34, (byte) 0xbd}; assertBytearrayEquals(binary3, StrictBase64.decode("gTS9")); byte[] binary4 = {(byte) 0x5e, (byte) 0x6c, (byte) 0xff, (byte) 0xde}; assertBytearrayEquals(binary4, StrictBase64.decode("Xmz/3g==")); byte[] binary5 = {(byte) 0xb2, (byte) 0xcd, (byte) 0xf0, (byte) 0xdc, (byte) 0x7f}; assertBytearrayEquals(binary5, StrictBase64.decode("ss3w3H8=")); byte[] binary6 = {(byte) 0xfc, (byte) 0x56, (byte) 0x2d, (byte) 0xda, (byte) 0xd4, (byte) 0x0e}; assertBytearrayEquals(binary6, StrictBase64.decode("/FYt2tQO")); byte[] binary7 = {(byte) 0x29, (byte) 0xb2, (byte) 0x32, (byte) 0x2e, (byte) 0x88, (byte) 0x41, (byte) 0xe8}; assertBytearrayEquals(binary7, StrictBase64.decode("KbIyLohB6A==")); byte[] binary8 = {(byte) 0x0f, (byte) 0x0f, (byte) 0xce, (byte) 0xd9, (byte) 0x49, (byte) 0x7a, (byte) 0xaf, (byte) 0x92}; assertBytearrayEquals(binary8, StrictBase64.decode("Dw/O2Ul6r5I=")); byte[] binary9 = {(byte) 0x27, (byte) 0x0f, (byte) 0xb1, (byte) 0x89, (byte) 0x82, (byte) 0x80, (byte) 0x0d, (byte) 0xa6, (byte) 0x40}; assertBytearrayEquals(binary9, StrictBase64.decode("Jw+xiYKADaZA")); } public void testDecodeIllegalWhitespace() throws Exception { { boolean didThrow = false; try { StrictBase64.decode("Zg=="); } catch (StrictBase64.DecodingException e) { didThrow = true; } assertEquals(false, didThrow); } // Space { boolean didThrow = false; try { StrictBase64.decode(" Zg=="); } catch (StrictBase64.DecodingException e) { didThrow = true; } assertEquals(true, didThrow); } { boolean didThrow = false; try { StrictBase64.decode("Z g=="); } catch (StrictBase64.DecodingException e) { didThrow = true; } assertEquals(true, didThrow); } { boolean didThrow = false; try { StrictBase64.decode("Zg =="); } catch (StrictBase64.DecodingException e) { didThrow = true; } assertEquals(true, didThrow); } { boolean didThrow = false; try { StrictBase64.decode("Zg= ="); } catch (StrictBase64.DecodingException e) { didThrow = true; } assertEquals(true, didThrow); } { boolean didThrow = false; try { StrictBase64.decode("Zg== "); } catch (StrictBase64.DecodingException e) { didThrow = true; } assertEquals(true, didThrow); } // Newline { boolean didThrow = false; try { StrictBase64.decode("\nZg=="); } catch (StrictBase64.DecodingException e) { didThrow = true; } assertEquals(true, didThrow); } { boolean didThrow = false; try { StrictBase64.decode("Z\ng=="); } catch (StrictBase64.DecodingException e) { didThrow = true; } assertEquals(true, didThrow); } { boolean didThrow = false; try { StrictBase64.decode("Zg\n=="); } catch (StrictBase64.DecodingException e) { didThrow = true; } assertEquals(true, didThrow); } { boolean didThrow = false; try { StrictBase64.decode("Zg=\n="); } catch (StrictBase64.DecodingException e) { didThrow = true; } assertEquals(true, didThrow); } { boolean didThrow = false; try { StrictBase64.decode("Zg==\n"); } catch (StrictBase64.DecodingException e) { didThrow = true; } assertEquals(true, didThrow); } // Tab { boolean didThrow = false; try { StrictBase64.decode("\tZg=="); } catch (StrictBase64.DecodingException e) { didThrow = true; } assertEquals(true, didThrow); } { boolean didThrow = false; try { StrictBase64.decode("Z\tg=="); } catch (StrictBase64.DecodingException e) { didThrow = true; } assertEquals(true, didThrow); } { boolean didThrow = false; try { StrictBase64.decode("Zg\t=="); } catch (StrictBase64.DecodingException e) { didThrow = true; } assertEquals(true, didThrow); } { boolean didThrow = false; try { StrictBase64.decode("Zg=\t="); } catch (StrictBase64.DecodingException e) { didThrow = true; } assertEquals(true, didThrow); } { boolean didThrow = false; try { StrictBase64.decode("Zg==\t"); } catch (Exception e) { didThrow = true; } assertEquals(true, didThrow); } // Carriage Return { boolean didThrow = false; try { StrictBase64.decode("\rZg=="); } catch (StrictBase64.DecodingException e) { didThrow = true; } assertEquals(true, didThrow); } { boolean didThrow = false; try { StrictBase64.decode("Z\rg=="); } catch (StrictBase64.DecodingException e) { didThrow = true; } assertEquals(true, didThrow); } { boolean didThrow = false; try { StrictBase64.decode("Zg\r=="); } catch (StrictBase64.DecodingException e) { didThrow = true; } assertEquals(true, didThrow); } { boolean didThrow = false; try { StrictBase64.decode("Zg=\r="); } catch (StrictBase64.DecodingException e) { didThrow = true; } assertEquals(true, didThrow); } { boolean didThrow = false; try { StrictBase64.decode("Zg==\r"); } catch (StrictBase64.DecodingException e) { didThrow = true; } assertEquals(true, didThrow); } } public void testDecodeIllegalCharacterWhenWhitespaceAllowed() throws Exception { { boolean didThrow = false; try { StrictBase64.decode(" Zg==", true); } catch (StrictBase64.DecodingException e) { didThrow = true; } assertEquals(false, didThrow); } // Space { boolean didThrow = false; try { StrictBase64.decode(", Zg==", true); } catch (StrictBase64.DecodingException e) { didThrow = true; } assertEquals(true, didThrow); } { boolean didThrow = false; try { StrictBase64.decode("Z ,g==", true); } catch (StrictBase64.DecodingException e) { didThrow = true; } assertEquals(true, didThrow); } { boolean didThrow = false; try { StrictBase64.decode("Zg =?=", true); } catch (StrictBase64.DecodingException e) { didThrow = true; } assertEquals(true, didThrow); } { boolean didThrow = false; try { StrictBase64.decode("Zg= =~", true); } catch (StrictBase64.DecodingException e) { didThrow = true; } assertEquals(true, didThrow); } { boolean didThrow = false; try { StrictBase64.decode("Zg== #", true); } catch (StrictBase64.DecodingException e) { didThrow = true; } assertEquals(true, didThrow); } { // Correct length (8) before remong whitespace boolean didThrow = false; try { StrictBase64.decode("Zg== # ", true); } catch (StrictBase64.DecodingException e) { didThrow = true; } assertEquals(true, didThrow); } { // Correct length (8) after removing whitespace boolean didThrow = false; try { StrictBase64.decode(" 1234567? ", true); } catch (StrictBase64.DecodingException e) { didThrow = true; } assertEquals(true, didThrow); } { // Correct length (8) after removing whitespace boolean didThrow = false; try { StrictBase64.decode(" 123,5678 ", true); } catch (StrictBase64.DecodingException e) { didThrow = true; } assertEquals(true, didThrow); } } }
package org.cfwheels.cfwheels; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.TimeUnit; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** * Integration Tests (IT) to run during Maven integration-test phase * See pom.xml for usage * * @author Singgih * */ @RunWith(Parameterized.class) public class CFWheelsCoreIT { static final private String[] KNOWN_ERRORS={"The data source could not be reached."}; static private CustomHtmlUnitDriver driver; static private String baseUrl; static private boolean testOracleEmulation; private String contextPath; private String packageName; public CFWheelsCoreIT(String contextPath, String packageName) { super(); this.contextPath = contextPath; this.packageName = packageName; } /** * @return scan folder for cfwheels core unit tests and add them as parameterized jUnit tests */ @Parameters(name="package {0}{1}") public static Collection<Object[]> getDirectories() { Collection<Object[]> params = new ArrayList<Object[]>(); addSubDirectories(params, "", "", "wheels/tests"); if ("true".equals(System.getProperty("testSubfolder"))) { addSubDirectories(params, "temp/", "", "wheels/tests"); } return params; } private static boolean addSubDirectories(Collection<Object[]> params, String contextPath, String prefix, String path) { boolean added = false; for (File f : new File(path).listFiles()) { if (f.getName().startsWith("_")) continue; if (!f.isDirectory()) { continue; } if (addSubDirectories(params, contextPath, prefix + f.getName() + ".", f.getPath())) { added = true; continue; } Object[] arr = new Object[] {contextPath, prefix + f.getName() }; params.add(arr); added = true; } return added; } /** * Taking backup of key cfwheels files and initializing test database once (unzip cfwheels only on remote server) * @throws Exception */ @BeforeClass static public void setUpServices() throws Exception { Files.copy(Paths.get("wheels/Connection.cfc"), Paths.get("wheels/Connection.cfc.bak"), StandardCopyOption.REPLACE_EXISTING); Files.copy(Paths.get("wheels/tests/populate.cfm"), Paths.get("wheels/tests/populate.cfm.bak"), StandardCopyOption.REPLACE_EXISTING); Path path = Paths.get("target/failsafe-reports"); if (!Files.exists(path)) Files.createDirectory(path); driver = new CustomHtmlUnitDriver(); baseUrl = "http://localhost:8080/"; if (null != System.getProperty("testServer")) baseUrl = System.getProperty("testServer") + "/"; testOracleEmulation = Boolean.valueOf(System.getProperty("testOracleEmulation")); driver.manage().timeouts().implicitlyWait(30000, TimeUnit.SECONDS); if (null != System.getProperty("deployUrl")) { System.out.println("cfwheels deploy"); driver.get(System.getProperty("deployUrl")); String pageSource = driver.getPageSource(); Files.write(Paths.get("target/failsafe-reports/_deploy.html"), pageSource.getBytes()); } recreateTestDatabase(); } public static void main(String[] args) throws Exception { System.setProperty("testOracleEmulation", "true"); setUpServices(); } private static void recreateTestDatabase() throws IOException { if (testOracleEmulation) { String content = new String(Files.readAllBytes(Paths.get("wheels/Connection.cfc"))); content = content.replace("loc.adapterName = \"H2\"","loc.adapterName = 'Oracle'"); Files.write(Paths.get("wheels/Connection.cfc"), content.getBytes()); content = new String(Files.readAllBytes(Paths.get("src/test/coldfusion/_oracle-emu.cfm"))); content += new String(Files.readAllBytes(Paths.get("wheels/tests/populate.cfm"))); content = content.replace("loc.dbinfo.database_productname","'Oracle'"); content = content.replace("booleanType bit DEFAULT 0 NOT NULL","booleanType number(1) DEFAULT 0 NOT NULL"); content = content.replace("to_timestamp(#loc.dateTimeDefault#,'yyyy-dd-mm hh24:mi:ss.FF')","'2000-01-01 18:26:08.690'"); content = content.replace("CREATE TRIGGER bi_#loc.i# BEFORE INSERT ON #loc.i# FOR EACH ROW BEGIN SELECT #loc.seq#.nextval INTO :NEW.<cfif loc.i IS \"photogalleries\">photogalleryid<cfelseif loc.i IS \"photogalleryphotos\">photogalleryphotoid<cfelse>id</cfif> FROM dual; END;", "ALTER TABLE #loc.i# MODIFY COLUMN <cfif loc.i IS \"photogalleries\">photogalleryid<cfelseif loc.i IS \"photogalleryphotos\">photogalleryphotoid<cfelse>id</cfif> #loc.identityColumnType# DEFAULT #loc.seq#.nextval"); Files.write(Paths.get("wheels/tests/populate.cfm"), content.getBytes()); } System.out.println("test database re-create"); driver.get(baseUrl + "index.cfm?controller=wheels&action=wheels&view=tests&type=core&reload=true&package=controller.caching"); String postfix = ""; String pageSource = driver.getPageSource(); if (!pageSource.contains("Passed")) { System.out.println(driver.getPageSourceAsText()); postfix = "-ERROR"; } Files.write(Paths.get("target/failsafe-reports/_databaseRecreate" + postfix + ".html"), pageSource.getBytes()); } /** * Generic test, to be parameterized per cfwheels app test package and database * @throws IOException */ @Test public void testCFWheels() throws IOException { System.out.print(contextPath); System.out.println(packageName); String packageUrl = baseUrl + contextPath + "index.cfm?controller=wheels&action=wheels&view=tests&type=core&package="+packageName; driver.get(packageUrl); String pageSource = driver.getPageSource(); assertTrue("The page should have results",pageSource.trim().length()>0); String postfix=""; // show error detail on Maven log if needed if (!pageSource.contains("Passed")) { System.out.println(driver.getPageSourceAsText()); postfix = "-ERROR"; } // write error detail on per test html report on failsafe-report folder Files.write(Paths.get("target/failsafe-reports/cfwheels-" + packageName + postfix + ".html"), pageSource.getBytes()); for (String error:KNOWN_ERRORS) { if (pageSource.contains(error)) fail(error + " " + packageUrl); } assertTrue("The page should have passed " + packageUrl,pageSource.contains("Passed")); } /** * closing down the web driver client and restoring key cfwheels files to original state * @throws Exception */ @AfterClass static public void tearDownServices() throws Exception { Files.copy(Paths.get("wheels/Connection.cfc.bak"), Paths.get("wheels/Connection.cfc"), StandardCopyOption.REPLACE_EXISTING); Files.copy(Paths.get("wheels/tests/populate.cfm.bak"), Paths.get("wheels/tests/populate.cfm"), StandardCopyOption.REPLACE_EXISTING); Files.delete(Paths.get("wheels/Connection.cfc.bak")); Files.delete(Paths.get("wheels/tests/populate.cfm.bak")); driver.quit(); } }
package seedu.address.logic; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_PERSON_DISPLAYED_INDEX; import static seedu.address.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.google.common.eventbus.Subscribe; import seedu.address.commons.core.EventsCenter; import seedu.address.commons.events.model.AddressBookChangedEvent; import seedu.address.commons.events.ui.JumpToListRequestEvent; import seedu.address.commons.events.ui.ShowHelpRequestEvent; import seedu.address.logic.commands.AddCommand; import seedu.address.logic.commands.ClearCommand; import seedu.address.logic.commands.Command; import seedu.address.logic.commands.CommandResult; import seedu.address.logic.commands.DeleteCommand; import seedu.address.logic.commands.ExitCommand; import seedu.address.logic.commands.FindCommand; import seedu.address.logic.commands.HelpCommand; import seedu.address.logic.commands.ListCommand; import seedu.address.logic.commands.SelectCommand; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.Model; import seedu.address.model.ModelManager; import seedu.address.model.ReadOnlyTaskList; import seedu.address.model.TaskList; import seedu.address.model.tag.Tag; import seedu.address.model.tag.UniqueTagList; import seedu.address.model.task.Description; import seedu.address.model.task.Email; import seedu.address.model.task.Priority; import seedu.address.model.task.ReadOnlyTask; import seedu.address.model.task.Task; import seedu.address.storage.StorageManager; public class LogicManagerTest { @Rule public TemporaryFolder saveFolder = new TemporaryFolder(); private Model model; private Logic logic; //These are for checking the correctness of the events raised private ReadOnlyTaskList latestSavedAddressBook; private boolean helpShown; private int targetedJumpIndex; @Subscribe private void handleLocalModelChangedEvent(AddressBookChangedEvent abce) { latestSavedAddressBook = new TaskList(abce.data); } @Subscribe private void handleShowHelpRequestEvent(ShowHelpRequestEvent she) { helpShown = true; } @Subscribe private void handleJumpToListRequestEvent(JumpToListRequestEvent je) { targetedJumpIndex = je.targetIndex; } @Before public void setUp() { model = new ModelManager(); String tempAddressBookFile = saveFolder.getRoot().getPath() + "TempAddressBook.xml"; String tempPreferencesFile = saveFolder.getRoot().getPath() + "TempPreferences.json"; logic = new LogicManager(model, new StorageManager(tempAddressBookFile, tempPreferencesFile)); EventsCenter.getInstance().registerHandler(this); latestSavedAddressBook = new TaskList(model.getTaskList()); // last saved assumed to be up to date helpShown = false; targetedJumpIndex = -1; // non yet } @After public void tearDown() { EventsCenter.clearSubscribers(); } @Test public void execute_invalid() { String invalidCommand = " "; assertCommandFailure(invalidCommand, String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } /** * Executes the command, confirms that a CommandException is not thrown and that the result message is correct. * Also confirms that both the 'address book' and the 'last shown list' are as specified. * @see #assertCommandBehavior(boolean, String, String, ReadOnlyTaskList, List) */ private void assertCommandSuccess(String inputCommand, String expectedMessage, ReadOnlyTaskList expectedAddressBook, List<? extends ReadOnlyTask> expectedShownList) { assertCommandBehavior(false, inputCommand, expectedMessage, expectedAddressBook, expectedShownList); } /** * Executes the command, confirms that a CommandException is thrown and that the result message is correct. * Both the 'address book' and the 'last shown list' are verified to be unchanged. * @see #assertCommandBehavior(boolean, String, String, ReadOnlyTaskList, List) */ private void assertCommandFailure(String inputCommand, String expectedMessage) { TaskList expectedAddressBook = new TaskList(model.getTaskList()); List<ReadOnlyTask> expectedShownList = new ArrayList<>(model.getFilteredTaskList()); assertCommandBehavior(true, inputCommand, expectedMessage, expectedAddressBook, expectedShownList); } /** * Executes the command, confirms that the result message is correct * and that a CommandException is thrown if expected * and also confirms that the following three parts of the LogicManager object's state are as expected:<br> * - the internal address book data are same as those in the {@code expectedAddressBook} <br> * - the backing list shown by UI matches the {@code shownList} <br> * - {@code expectedAddressBook} was saved to the storage file. <br> */ private void assertCommandBehavior(boolean isCommandExceptionExpected, String inputCommand, String expectedMessage, ReadOnlyTaskList expectedAddressBook, List<? extends ReadOnlyTask> expectedShownList) { try { CommandResult result = logic.execute(inputCommand); assertFalse("CommandException expected but was not thrown.", isCommandExceptionExpected); assertEquals(expectedMessage, result.feedbackToUser); } catch (CommandException e) { assertTrue("CommandException not expected but was thrown.", isCommandExceptionExpected); assertEquals(expectedMessage, e.getMessage()); } //Confirm the ui display elements should contain the right data assertEquals(expectedShownList, model.getFilteredTaskList()); //Confirm the state of data (saved and in-memory) is as expected assertEquals(expectedAddressBook, model.getTaskList()); assertEquals(expectedAddressBook, latestSavedAddressBook); } @Test public void execute_unknownCommandWord() { String unknownCommand = "uicfhmowqewca"; assertCommandFailure(unknownCommand, MESSAGE_UNKNOWN_COMMAND); } @Test public void execute_help() { assertCommandSuccess("help", HelpCommand.SHOWING_HELP_MESSAGE, new TaskList(), Collections.emptyList()); assertTrue(helpShown); } @Test public void execute_exit() { assertCommandSuccess("exit", ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT, new TaskList(), Collections.emptyList()); } @Test public void execute_clear() throws Exception { TestDataHelper helper = new TestDataHelper(); model.addTask(helper.generatePerson(1)); model.addTask(helper.generatePerson(2)); model.addTask(helper.generatePerson(3)); assertCommandSuccess("clear", ClearCommand.MESSAGE_SUCCESS, new TaskList(), Collections.emptyList()); } @Test public void execute_add_invalidArgsFormat() { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE); assertCommandFailure("add wrong args wrong args", expectedMessage); // assertCommandFailure("add Valid Description 12345 e/valid@email.butNoPhonePrefix a/valid,address", // expectedMessage); // assertCommandFailure("add Valid Description p/1234 valid@email.butNoPrefix a/valid, address", // expectedMessage); // assertCommandFailure("add Valid Description p/12345 e/valid@email.butNoAddressPrefix valid, address", // expectedMessage); } @Test public void execute_add_invalidPersonData() { assertCommandFailure("add []\\[;] p/12345 e/valid@e.mail a/valid, address", Description.MESSAGE_DESCRIPTION_CONSTRAINTS); assertCommandFailure("add Valid Description p/not_numbers e/valid@e.mail a/valid, address", Priority.MESSAGE_PRIORITY_CONSTRAINTS); assertCommandFailure("add Valid Description p/12345 e/notAnEmail a/valid, address", Email.MESSAGE_EMAIL_CONSTRAINTS); assertCommandFailure("add Valid Description p/12345 e/valid@e.mail a/valid, address t/invalid_-[.tag", Tag.MESSAGE_TAG_CONSTRAINTS); } @Test public void execute_add_successful() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.adam(); TaskList expectedAB = new TaskList(); expectedAB.addTask(toBeAdded); // execute command and verify result assertCommandSuccess(helper.generateAddCommand(toBeAdded), String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded), expectedAB, expectedAB.getTaskList()); } @Test public void execute_addDuplicate_notAllowed() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.adam(); // setup starting state model.addTask(toBeAdded); // person already in internal address book // execute command and verify result assertCommandFailure(helper.generateAddCommand(toBeAdded), AddCommand.MESSAGE_DUPLICATE_PERSON); } @Test public void execute_list_showsAllPersons() throws Exception { // prepare expectations TestDataHelper helper = new TestDataHelper(); TaskList expectedAB = helper.generateAddressBook(2); List<? extends ReadOnlyTask> expectedList = expectedAB.getTaskList(); // prepare address book state helper.addToModel(model, 2); assertCommandSuccess("list", ListCommand.MESSAGE_SUCCESS, expectedAB, expectedList); } /** * Confirms the 'invalid argument index number behaviour' for the given command * targeting a single person in the shown list, using visible index. * @param commandWord to test assuming it targets a single person in the last shown list * based on visible index. */ private void assertIncorrectIndexFormatBehaviorForCommand(String commandWord, String expectedMessage) throws Exception { assertCommandFailure(commandWord , expectedMessage); //index missing assertCommandFailure(commandWord + " +1", expectedMessage); //index should be unsigned assertCommandFailure(commandWord + " -1", expectedMessage); //index should be unsigned assertCommandFailure(commandWord + " 0", expectedMessage); //index cannot be 0 assertCommandFailure(commandWord + " not_a_number", expectedMessage); } /** * Confirms the 'invalid argument index number behaviour' for the given command * targeting a single person in the shown list, using visible index. * @param commandWord to test assuming it targets a single person in the last shown list * based on visible index. */ private void assertIndexNotFoundBehaviorForCommand(String commandWord) throws Exception { String expectedMessage = MESSAGE_INVALID_PERSON_DISPLAYED_INDEX; TestDataHelper helper = new TestDataHelper(); List<Task> personList = helper.generatePersonList(2); // set AB state to 2 persons model.resetData(new TaskList()); for (Task p : personList) { model.addTask(p); } assertCommandFailure(commandWord + " 3", expectedMessage); } @Test public void execute_selectInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("select", expectedMessage); } @Test public void execute_selectIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("select"); } @Test public void execute_select_jumpsToCorrectPerson() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threePersons = helper.generatePersonList(3); TaskList expectedAB = helper.generateAddressBook(threePersons); helper.addToModel(model, threePersons); assertCommandSuccess("select 2", String.format(SelectCommand.MESSAGE_SELECT_PERSON_SUCCESS, 2), expectedAB, expectedAB.getTaskList()); assertEquals(1, targetedJumpIndex); assertEquals(model.getFilteredTaskList().get(1), threePersons.get(1)); } @Test public void execute_deleteInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("delete", expectedMessage); } @Test public void execute_deleteIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("delete"); } @Test public void execute_delete_removesCorrectPerson() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threePersons = helper.generatePersonList(3); TaskList expectedAB = helper.generateAddressBook(threePersons); expectedAB.removeTask(threePersons.get(1)); helper.addToModel(model, threePersons); assertCommandSuccess("delete 2", String.format(DeleteCommand.MESSAGE_DELETE_PERSON_SUCCESS, threePersons.get(1)), expectedAB, expectedAB.getTaskList()); } @Test public void execute_find_invalidArgsFormat() { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE); assertCommandFailure("find ", expectedMessage); } @Test public void execute_find_onlyMatchesFullWordsInNames() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generatePersonWithName("bla bla KEY bla"); Task pTarget2 = helper.generatePersonWithName("bla KEY bla bceofeia"); Task p1 = helper.generatePersonWithName("KE Y"); Task p2 = helper.generatePersonWithName("KEYKEYKEY sduauo"); List<Task> fourPersons = helper.generatePersonList(p1, pTarget1, p2, pTarget2); TaskList expectedAB = helper.generateAddressBook(fourPersons); List<Task> expectedList = helper.generatePersonList(pTarget1, pTarget2); helper.addToModel(model, fourPersons); assertCommandSuccess("find KEY", Command.getMessageForPersonListShownSummary(expectedList.size()), expectedAB, expectedList); } @Test public void execute_find_isNotCaseSensitive() throws Exception { TestDataHelper helper = new TestDataHelper(); Task p1 = helper.generatePersonWithName("bla bla KEY bla"); Task p2 = helper.generatePersonWithName("bla KEY bla bceofeia"); Task p3 = helper.generatePersonWithName("key key"); Task p4 = helper.generatePersonWithName("KEy sduauo"); List<Task> fourPersons = helper.generatePersonList(p3, p1, p4, p2); TaskList expectedAB = helper.generateAddressBook(fourPersons); List<Task> expectedList = fourPersons; helper.addToModel(model, fourPersons); assertCommandSuccess("find KEY", Command.getMessageForPersonListShownSummary(expectedList.size()), expectedAB, expectedList); } @Test public void execute_find_matchesIfAnyKeywordPresent() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generatePersonWithName("bla bla KEY bla"); Task pTarget2 = helper.generatePersonWithName("bla rAnDoM bla bceofeia"); Task pTarget3 = helper.generatePersonWithName("key key"); Task p1 = helper.generatePersonWithName("sduauo"); List<Task> fourPersons = helper.generatePersonList(pTarget1, p1, pTarget2, pTarget3); TaskList expectedAB = helper.generateAddressBook(fourPersons); List<Task> expectedList = helper.generatePersonList(pTarget1, pTarget2, pTarget3); helper.addToModel(model, fourPersons); assertCommandSuccess("find key rAnDoM", Command.getMessageForPersonListShownSummary(expectedList.size()), expectedAB, expectedList); } /** * A utility class to generate test data. */ class TestDataHelper { Task adam() throws Exception { Description description = new Description("Adam Brown"); Priority privatePhone = new Priority("111111"); Email email = new Email("adam@gmail.com"); Tag tag1 = new Tag("tag1"); Tag tag2 = new Tag("longertag2"); UniqueTagList tags = new UniqueTagList(tag1, tag2); return new Task(description, privatePhone, email, tags); } /** * Generates a valid person using the given seed. * Running this function with the same parameter values guarantees the returned person will have the same state. * Each unique seed will generate a unique Task object. * * @param seed used to generate the person data field values */ Task generatePerson(int seed) throws Exception { return new Task( new Description("Task " + seed), new Priority("" + Math.abs(seed)), new Email(seed + "@email"), new UniqueTagList(new Tag("tag" + Math.abs(seed)), new Tag("tag" + Math.abs(seed + 1))) ); } /** Generates the correct add command based on the person given */ String generateAddCommand(Task p) { StringBuffer cmd = new StringBuffer(); cmd.append("add "); cmd.append(p.getDescription().toString()); cmd.append(" e/").append(p.getDate()); cmd.append(" p/").append(p.getPriority()); UniqueTagList tags = p.getTags(); for (Tag t: tags) { cmd.append(" t/").append(t.tagName); } return cmd.toString(); } /** * Generates an TaskList with auto-generated persons. */ TaskList generateAddressBook(int numGenerated) throws Exception { TaskList taskList = new TaskList(); addToAddressBook(taskList, numGenerated); return taskList; } /** * Generates an TaskList based on the list of Persons given. */ TaskList generateAddressBook(List<Task> tasks) throws Exception { TaskList taskList = new TaskList(); addToAddressBook(taskList, tasks); return taskList; } /** * Adds auto-generated Task objects to the given TaskList * @param taskList The TaskList to which the Persons will be added */ void addToAddressBook(TaskList taskList, int numGenerated) throws Exception { addToAddressBook(taskList, generatePersonList(numGenerated)); } /** * Adds the given list of Persons to the given TaskList */ void addToAddressBook(TaskList taskList, List<Task> personsToAdd) throws Exception { for (Task p: personsToAdd) { taskList.addTask(p); } } /** * Adds auto-generated Task objects to the given model * @param model The model to which the Persons will be added */ void addToModel(Model model, int numGenerated) throws Exception { addToModel(model, generatePersonList(numGenerated)); } /** * Adds the given list of Persons to the given model */ void addToModel(Model model, List<Task> personsToAdd) throws Exception { for (Task p: personsToAdd) { model.addTask(p); } } /** * Generates a list of Persons based on the flags. */ List<Task> generatePersonList(int numGenerated) throws Exception { List<Task> tasks = new ArrayList<>(); for (int i = 1; i <= numGenerated; i++) { tasks.add(generatePerson(i)); } return tasks; } List<Task> generatePersonList(Task... persons) { return Arrays.asList(persons); } /** * Generates a Task object with given name. Other fields will have some dummy values. */ Task generatePersonWithName(String name) throws Exception { return new Task( new Description(name), new Priority("1"), new Email("1@email"), new UniqueTagList(new Tag("tag")) ); } } }
package net.craftstars.general.command; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import net.craftstars.general.CommandBase; import net.craftstars.general.General; import net.craftstars.general.util.Messaging; import net.craftstars.general.util.Teleport; import net.craftstars.general.util.Toolbox; public class teleportCommand extends CommandBase { @Override public boolean fromPlayer(General plugin, Player sender, Command command, String commandLabel, String[] args) { if(Toolbox.lacksPermission(plugin, sender, "teleport", "general.teleport")) return true; switch(args.length) { case 1: {// /tp <player|world> Player destination = Toolbox.getPlayer(args[0], sender); if(destination == null) { World where = Toolbox.getWorld(args[0], sender); if(where == null) return true; sender.teleport(where.getSpawnLocation()); return true; } if(destination.getName().equals(sender.getName())) { Messaging.send(sender, "&fCongrats! You just teleported yourself to yourself!"); return true; } Teleport.teleportPlayerToPlayer(sender, destination); Messaging.send(sender, "&fTeleported you to &9" + destination.getName() + "&f!"); } break; case 2: { // /tp <player> <to-player|world> Player destination = Toolbox.getPlayer(args[1], sender); if(destination == null) { World where = Toolbox.getWorld(args[1], sender); if(where == null) return true; sender.teleport(where.getSpawnLocation()); return true; } if(args[0].equalsIgnoreCase("*")) { if(Toolbox.lacksPermission(plugin, sender, "teleport many players at once", "general.teleport.other.mass")) return true; Teleport.teleportAllToPlayer(destination); Messaging.send(sender, "&fTeleported all players to &9" + destination.getName() + "&f!"); return true; } if(args[0].contains(",")) { if(Toolbox.lacksPermission(plugin, sender, "teleport many players at once", "general.teleport.other.mass")) return true; Teleport.teleportManyToPlayer(args[0], destination); Messaging.send(sender, "&fTeleported several players to &9" + destination.getName() + "&f!"); return true; } Player who = Toolbox.getPlayer(args[0], sender); if(who == null) return true; if(who.getName().equals(sender.getName()) && destination.getName().equals(sender.getName())) { Messaging.send(sender, "&fCongrats! You just teleported yourself to yourself!"); return true; } else { if(Toolbox.lacksPermission(plugin, sender, "teleport players other than yourself", "general.teleport.other")) return true; Messaging.send(who, "&fYou have been teleported to &9" + destination.getName() + "&f!"); } Teleport.teleportPlayerToPlayer(who, destination); Messaging.send(sender, "&fTeleported &9" + who.getName() + "&f to &9" + destination.getName() + "&f!"); } break; case 3: { // /tp <x> <y> <z> if(Toolbox.lacksPermission(plugin, sender, "teleport to coordinates", "general.teleport.coords")) return true; Location destination = Toolbox.getLocation(sender, sender.getWorld(), args[0], args[1], args[2]); if(destination == null) return true; sender.teleport(destination); Messaging.send(sender, "&fTeleported you to &9(" + args[0] + "," + args[1] + "," + args[2] + ")&f!"); } break; case 4: { // /tp <player> <x> <y> <z> OR /tp <x> <y> <z> <world> if(Toolbox.lacksPermission(plugin, sender, "teleport to coordinates", "general.teleport.coords")) return true; Player who = Toolbox.getPlayer(args[0], sender); Location destination; if(who == null) { World where = Toolbox.getWorld(args[3], sender); if(where == null) return true; destination = Toolbox.getLocation(sender, where, args[0], args[1], args[2]); } else { destination = Toolbox.getLocation(sender, who.getWorld(), args[1], args[2], args[3]); } if(destination == null) return true; if(!who.getName().equals(sender.getName())) { if(Toolbox.lacksPermission(plugin, sender, "teleport players other than yourself", "general.teleport.other")) return true; Messaging.send(who, "&fYou have been teleported to &9(" + args[0] + "," + args[1] + "," + args[2] + ")&f!"); } who.teleport(destination); Messaging.send(sender, "&fTeleported &9" + who.getName() + "&f to &9(" + args[0] + "," + args[1] + "," + args[2] + ")&f!"); } break; case 5: { // /tp <player> <x> <y> <z> <world> if(Toolbox.lacksPermission(plugin, sender, "teleport to coordinates", "general.teleport.coords")) return true; Player who = Toolbox.getPlayer(args[0], sender); if(who == null) return true; World where = Toolbox.getWorld(args[3], sender); if(where == null) return true; Location destination = Toolbox.getLocation(sender, where, args[0], args[1], args[2]); if(destination == null) return true; if(!who.getName().equals(sender.getName())) { if(Toolbox.lacksPermission(plugin, sender, "teleport players other than yourself", "general.teleport.other")) return true; Messaging.send(who, "&fYou have been teleported to &9(" + args[0] + "," + args[1] + "," + args[2] + ")&f!"); } who.teleport(destination); Messaging.send(sender, "&fTeleported &9" + who.getName() + "&f to &9(" + args[0] + "," + args[1] + "," + args[2] + ")&f!"); } default: return Toolbox.SHOW_USAGE; } return true; } @Override public boolean fromConsole(General plugin, CommandSender sender, Command command, String commandLabel, String[] args) { switch(args.length) { case 2: { // tp <player> <to-player|world> Player destination = Toolbox.getPlayer(args[1], sender); World where = null; if(destination == null) { where = Toolbox.getWorld(args[1], sender); if(where == null) return true; } else { if(args[0].equalsIgnoreCase("*")) { Teleport.teleportAllToPlayer(destination); Messaging.send(sender, "&fTeleported all players to &9" + destination.getName() + "&f!"); return true; } if(args[0].contains(",")) { Teleport.teleportManyToPlayer(args[0], destination); Messaging.send(sender, "&fTeleported several players to &9" + destination.getName() + "&f!"); return true; } } Player who = Toolbox.getPlayer(args[0], sender); if(who == null) return true; Messaging.send(who, "&fYou have been teleported to &9" + destination.getName() + "&f!"); if(destination != null) Teleport.teleportPlayerToPlayer(who, destination); else who.teleport(where.getSpawnLocation()); Messaging.send(sender, "&fTeleported &9" + who.getName() + "&f to &9" + destination.getName() + "&f!"); } break; case 4: { // tp <player> <x> <y> <z> Player who = Toolbox.getPlayer(args[0], sender); if(who == null) return true; Location destination = Toolbox.getLocation(sender, who.getWorld(), args[1], args[2], args[3]); if(destination == null) return true; Messaging.send(who, "&fYou have been teleported to &9(" + args[1] + "," + args[2] + "," + args[3] + ")&f!"); who.teleport(destination); Messaging.send(sender, "&fTeleported &9" + who.getName() + "&f to &9(" + args[1] + "," + args[2] + "," + args[3] + ")&f!"); } break; case 5: { // /tp <player> <x> <y> <z> <world> Player who = Toolbox.getPlayer(args[0], sender); if(who == null) return true; World where = Toolbox.getWorld(args[3], sender); if(where == null) return true; Location destination = Toolbox.getLocation(sender, where, args[0], args[1], args[2]); if(destination == null) return true; Messaging.send(who, "&fYou have been teleported to &9(" + args[0] + "," + args[1] + "," + args[2] + ")&f!"); who.teleport(destination); Messaging.send(sender, "&fTeleported &9" + who.getName() + "&f to &9(" + args[0] + "," + args[1] + "," + args[2] + ")&f!"); } default: return Toolbox.SHOW_USAGE; } return true; } }
package nu.nerd.beastmaster.commands; import java.util.Comparator; import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.stream.Collectors; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.EntityType; import nu.nerd.beastmaster.BeastMaster; import nu.nerd.beastmaster.DropSet; import nu.nerd.beastmaster.zones.Zone; // /<command> replace-mob <zone-id> <entity-type> <loot-id> // /<command> list-replacements <zone-id> /** * Executor for the /beast-zone command. */ public class BeastZoneExecutor extends ExecutorBase { /** * Default constructor. */ public BeastZoneExecutor() { super("beast-zone", "help", "add", "remove", "square", "list", "replace-mob", "list-replacements", "add-block", "remove-block", "list-blocks"); } /** * @see org.bukkit.command.CommandExecutor#onCommand(org.bukkit.command.CommandSender, * org.bukkit.command.Command, java.lang.String, java.lang.String[]) */ @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (args.length == 0 || (args.length == 1 && args[0].equals("help"))) { return false; } if (args.length >= 1) { if (args[0].equals("add")) { if (args.length != 3) { Commands.invalidArguments(sender, getName() + " add <zone-id> <world>"); return true; } String zoneArg = args[1]; String worldArg = args[2]; Zone zone = BeastMaster.ZONES.getZone(zoneArg); if (zone != null) { Commands.errorNotNull(sender, "zone", zoneArg); return true; } World world = Bukkit.getWorld(worldArg); if (world == null) { Commands.errorNull(sender, "world", worldArg); return true; } zone = new Zone(zoneArg, world); BeastMaster.ZONES.addZone(zone); BeastMaster.CONFIG.save(); sender.sendMessage(ChatColor.GOLD + "Added new zone " + ChatColor.YELLOW + zone.getId() + ChatColor.GOLD + " in world " + ChatColor.YELLOW + zone.getWorld().getName() + ChatColor.GOLD + "."); return true; } else if (args[0].equals("remove")) { if (args.length != 2) { Commands.invalidArguments(sender, getName() + " remove <zone-id>"); return true; } String zoneArg = args[1]; Zone zone = BeastMaster.ZONES.getZone(zoneArg); if (zone == null) { Commands.errorNull(sender, "zone", zoneArg); return true; } BeastMaster.ZONES.removeZone(zone); BeastMaster.CONFIG.save(); sender.sendMessage(ChatColor.GOLD + "Removed zone " + ChatColor.YELLOW + zone.getId() + ChatColor.GOLD + "."); return true; } else if (args[0].equals("square")) { if (args.length != 5) { Commands.invalidArguments(sender, getName() + " square <zone-id> <x> <z> <radius>"); return true; } String zoneArg = args[1]; Zone zone = BeastMaster.ZONES.getZone(zoneArg); if (zone == null) { Commands.errorNull(sender, "zone", zoneArg); return true; } Integer centreX = Commands.parseNumber(args[2], Commands::parseInt, n -> true, () -> sender.sendMessage(ChatColor.RED + "The X coordinate must be an integer!"), null); if (centreX == null) { return true; } Integer centreZ = Commands.parseNumber(args[3], Commands::parseInt, n -> true, () -> sender.sendMessage(ChatColor.RED + "The Z coordinate must be an integer!"), null); if (centreZ == null) { return true; } Integer radius = Commands.parseNumber(args[4], Commands::parseInt, n -> n >= 0, () -> sender.sendMessage(ChatColor.RED + "The radius must be at least zero!"), () -> sender.sendMessage(ChatColor.RED + "The radius must be a non-negative integer!")); if (radius == null) { return true; } zone.setSquareBounds(centreX, centreZ, radius); BeastMaster.CONFIG.save(); sender.sendMessage(ChatColor.GOLD + "Set bounds for " + zone.getDescription() + ChatColor.GOLD + "."); return true; } else if (args[0].equals("list")) { if (args.length != 1) { Commands.invalidArguments(sender, getName() + " list"); return true; } sender.sendMessage(ChatColor.GOLD + "Zones:"); for (Zone zone : BeastMaster.ZONES.getZones()) { sender.sendMessage(zone.getDescription()); } return true; } else if (args[0].equals("replace-mob")) { if (args.length != 4) { Commands.invalidArguments(sender, getName() + " replace-mob <zone-id> <entity-type> <loot-id>"); return true; } String zoneArg = args[1]; Zone zone = BeastMaster.ZONES.getZone(zoneArg); if (zone == null) { Commands.errorNull(sender, "zone", zoneArg); return true; } String entityTypeArg = args[2]; EntityType entityType; try { entityType = EntityType.valueOf(entityTypeArg.toUpperCase()); } catch (IllegalArgumentException ex) { Commands.errorNull(sender, "entity type", entityTypeArg); return true; } String lootIdArg = args[3]; if (lootIdArg.equalsIgnoreCase("none")) { zone.setMobReplacementDropSetId(entityType, null); sender.sendMessage(ChatColor.GOLD + "Zone " + ChatColor.YELLOW + zoneArg + ChatColor.GOLD + " will no longer replace mobs of type " + ChatColor.YELLOW + entityType + ChatColor.GOLD + "."); } else { zone.setMobReplacementDropSetId(entityType, lootIdArg); boolean lootTableExists = (BeastMaster.LOOTS.getDropSet(lootIdArg) != null); ChatColor lootTableColour = (lootTableExists ? ChatColor.YELLOW : ChatColor.RED); sender.sendMessage(ChatColor.GOLD + "Zone " + ChatColor.YELLOW + zoneArg + ChatColor.GOLD + " will replace mobs of type " + ChatColor.YELLOW + entityType + ChatColor.GOLD + " according to loot table " + lootTableColour + lootIdArg + ChatColor.GOLD + "."); } BeastMaster.CONFIG.save(); return true; } else if (args[0].equals("list-replacements")) { if (args.length != 2) { Commands.invalidArguments(sender, getName() + " list-replacements <zone-id>"); return true; } String zoneArg = args[1]; Zone zone = BeastMaster.ZONES.getZone(zoneArg); if (zone == null) { Commands.errorNull(sender, "zone", zoneArg); return true; } if (zone.getAllReplacedEntityTypes().isEmpty()) { sender.sendMessage(ChatColor.GOLD + "Zone " + ChatColor.YELLOW + zoneArg + ChatColor.GOLD + " doesn't replace any mobs."); } else { sender.sendMessage(ChatColor.GOLD + "Loot tables replacing mobs in zone " + ChatColor.YELLOW + zoneArg + ChatColor.GOLD + ":"); List<EntityType> sortedTypes = zone.getAllReplacedEntityTypes().stream() .sorted(Comparator.comparing(EntityType::name)) .collect(Collectors.toList()); for (EntityType entityType : sortedTypes) { String lootId = zone.getMobReplacementDropSetId(entityType); boolean lootTableExists = (BeastMaster.LOOTS.getDropSet(lootId) != null); ChatColor lootTableColour = (lootTableExists ? ChatColor.YELLOW : ChatColor.RED); sender.sendMessage(ChatColor.YELLOW + entityType.name() + ChatColor.WHITE + " -> " + lootTableColour + lootId); } } return true; } else if (args[0].equals("add-block")) { if (args.length != 4) { Commands.invalidArguments(sender, getName() + " add-block <zone-id> <material> <loot-id>"); return true; } String zoneArg = args[1]; Zone zone = BeastMaster.ZONES.getZone(zoneArg); if (zone == null) { Commands.errorNull(sender, "zone", zoneArg); return true; } // Material name uppercase for Material.getMaterial() later. String materialArg = args[2].toUpperCase(); Material material = Commands.parseMaterial(sender, materialArg); if (material == null) { return true; } // Check that the material is an actual block and not just an // item type. Suggest corrected material. if (!material.isBlock()) { sender.sendMessage(ChatColor.RED + material.name() + " is not a placeable block type."); if (materialArg.equals("POTATO")) { sender.sendMessage(ChatColor.RED + "Did you mean POTATOES instead?"); } else { // General case: CARROT -> CARROTS, etc. material = Material.getMaterial(materialArg + "S"); if (material != null) { sender.sendMessage(ChatColor.RED + "Did you mean " + material + " instead?"); } } return true; } // Allow the loot table for a material to be set even if the // table is not yet defined. String lootArg = args[3]; zone.setMiningDropsId(material, lootArg); BeastMaster.CONFIG.save(); DropSet drops = BeastMaster.LOOTS.getDropSet(lootArg); String dropsDescription = (drops != null) ? drops.getDescription() : ChatColor.RED + lootArg + ChatColor.GOLD + " (not defined)"; sender.sendMessage(ChatColor.GOLD + "When " + ChatColor.YELLOW + material + ChatColor.GOLD + " is broken in zone " + ChatColor.YELLOW + zoneArg + ChatColor.GOLD + " loot will drop from table " + dropsDescription + ChatColor.GOLD + "."); return true; } else if (args[0].equals("remove-block")) { if (args.length != 3) { Commands.invalidArguments(sender, getName() + " remove-block <zone-id> <material>"); return true; } String zoneArg = args[1]; Zone zone = BeastMaster.ZONES.getZone(zoneArg); if (zone == null) { Commands.errorNull(sender, "zone", zoneArg); return true; } Material material = Commands.parseMaterial(sender, args[2]); if (material == null) { return true; } String oldDropsId = zone.getMiningDropsId(material); DropSet drops = BeastMaster.LOOTS.getDropSet(oldDropsId); String dropsDescription = (drops != null) ? drops.getDescription() : ChatColor.RED + oldDropsId + ChatColor.GOLD + " (not defined)"; if (oldDropsId == null) { sender.sendMessage(ChatColor.RED + "Zone " + zoneArg + " has no custom mining drops for " + material + "!"); } else { sender.sendMessage(ChatColor.GOLD + "When " + ChatColor.YELLOW + material + ChatColor.GOLD + " is broken in zone " + ChatColor.YELLOW + zoneArg + ChatColor.GOLD + " loot will no longer drop from table " + dropsDescription + ChatColor.GOLD + "."); } zone.setMiningDropsId(material, null); BeastMaster.CONFIG.save(); return true; } else if (args[0].equals("list-blocks")) { if (args.length != 2) { Commands.invalidArguments(sender, getName() + " list-blocks <zone-id>"); return true; } String zoneArg = args[1]; Zone zone = BeastMaster.ZONES.getZone(zoneArg); if (zone == null) { Commands.errorNull(sender, "zone", zoneArg); return true; } Set<Entry<Material, String>> allMiningDrops = zone.getAllMiningDrops(); if (allMiningDrops.isEmpty()) { sender.sendMessage(ChatColor.GOLD + "Zone " + ChatColor.YELLOW + zoneArg + ChatColor.GOLD + " has no configured block drops."); } else { sender.sendMessage(ChatColor.GOLD + "Block drops in zone " + ChatColor.YELLOW + zoneArg + ChatColor.GOLD + ": "); List<Entry<Material, String>> sortedMiningDrops = allMiningDrops.stream() .sorted(Comparator.comparing(Entry<Material, String>::getKey)) .collect(Collectors.toList()); for (Entry<Material, String> entry : sortedMiningDrops) { Material material = entry.getKey(); String dropsId = entry.getValue(); DropSet drops = BeastMaster.LOOTS.getDropSet(dropsId); String dropsDescription = (drops != null) ? ChatColor.YELLOW + dropsId : ChatColor.RED + dropsId + ChatColor.GOLD + " (not defined)"; sender.sendMessage(ChatColor.WHITE + material.toString() + ": " + dropsDescription); } } return true; } } return false; } // onCommand } // class BeastZoneExecutor
package org.ensembl.healthcheck; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.logging.Handler; import java.util.logging.Level; import org.ensembl.healthcheck.testcase.EnsTestCase; import org.ensembl.healthcheck.util.ConnectionPool; import org.ensembl.healthcheck.util.LogFormatter; import org.ensembl.healthcheck.util.MyStreamHandler; import org.ensembl.healthcheck.util.Utils; /** * Subclass of DatabaseTestRunner optimised for running a single group of tests against * a single set of databases. Intended to be called by ParallelDatabaseTestRunner to * allow parallel running of healthchecks. Same as DatabaseTestRunner but group and * databases are specified on the command-line rather than in the properties file. */ public class NodeDatabaseTestRunner extends DatabaseTestRunner implements Reporter { private boolean debug = true; private boolean deletePrevious = false; private List databaseRegexps; private long sessionID = -1; /** * Main run method. * * @param args * Command-line arguments. */ protected void run(String[] args) { ReportManager.setReporter(this); parseCommandLine(args); setupLogging(); Utils.readPropertiesFileIntoSystem(PROPERTIES_FILE); TestRegistry testRegistry = new TestRegistry(); DatabaseRegistry databaseRegistry = new DatabaseRegistry(databaseRegexps, null, null); if (databaseRegistry.getAll().length == 0) { logger.warning("Warning: no database names matched any of the database regexps given"); } ReportManager.connectToOutputDatabase(); if (deletePrevious) { ReportManager.deletePrevious(); } runAllTests(databaseRegistry, testRegistry, false); ConnectionPool.closeAll(); } // run /** * Command-line entry point. * * @param args * Command line args. */ public static void main(String[] args) { new NodeDatabaseTestRunner().run(args); } // main private void parseCommandLine(String[] args) { for (int i = 0; i < args.length; i++) { if (args[i].equals("-h") || args[i].equals("-help")) { printUsage(); System.exit(0); } else if (args[i].equals("-debug")) { debug = true; logger.finest("Running in debug mode"); } else if (args[i].equals("-group")) { i++; groupsToRun.add(args[i]); logger.finest("Added " + args[i] + " to group"); } else if (args[i].equals("-d")) { i++; databaseRegexps = new ArrayList(); databaseRegexps.add(args[i]); logger.finest("Database regexp: " + args[i]); } else if (args[i].equals("-session")) { i++; sessionID = Integer.parseInt(args[i]); ReportManager.setSessionID(sessionID); logger.finest("Will use session ID " + sessionID); } } } // parseCommandLine private void printUsage() { System.out.println("\nUsage: NodeDatabaseTestRunner {options} \n"); System.out.println("Options:"); System.out.println(" -d {regexp} The databases on which to run the group of tests (required)"); System.out.println(" -group {group} The group of tests to run (required)"); System.out.println(" -session {id} The session ID to use (required)"); System.out.println(" -h This message."); System.out.println(" -debug Print debugging info"); System.out.println(); System.out.println("All configuration information is read from the file database.properties. "); System.out.println("See the comments in that file for information on which options to set."); } // Implementation of Reporter interface /** * Called when a message is to be stored in the report manager. * * @param reportLine * The message to store. */ public void message(ReportLine reportLine) { } /** * Called just before a test case is run. * * @param testCase * The test case about to be run. * @param dbre * The database which testCase is to be run on, or null of no/several * databases. */ public void startTestCase(EnsTestCase testCase, DatabaseRegistryEntry dbre) { // TODO: write start time to database entry ReportManager.info(testCase, dbre.getConnection(), "#Started"); } /** * Should be called just after a test case has been run. * * @param testCase * The test case that was run. * @param result * The result of testCase. * @param dbre * The database which testCase was run on, or null of no/several * databases. */ public void finishTestCase(EnsTestCase testCase, boolean result, DatabaseRegistryEntry dbre) { // TODO: write end time to database ReportManager.info(testCase, dbre.getConnection(), "#Ended"); } protected void setupLogging() { // stop parent logger getting the message logger.setUseParentHandlers(false); Handler myHandler = new MyStreamHandler(System.out, new LogFormatter()); logger.addHandler(myHandler); logger.setLevel(Level.WARNING); if (debug) { logger.setLevel(Level.FINEST); } } // setupLogging } // NodeDatabaseTestRunner
package org.exist.xquery.functions; import org.exist.dom.QName; import org.exist.xquery.BasicFunction; import org.exist.xquery.Cardinality; import org.exist.xquery.Dependency; import org.exist.xquery.FunctionSignature; import org.exist.xquery.Function; import org.exist.xquery.Profiler; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.value.DateValue; import org.exist.xquery.value.DecimalValue; import org.exist.xquery.value.IntegerValue; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.SequenceType; import org.exist.xquery.value.TimeValue; import org.exist.xquery.value.Type; /** * @author wolf */ public class FunGetTimeComponent extends BasicFunction { public final static FunctionSignature fnHoursFromTime = new FunctionSignature( new QName("hours-from-time", Function.BUILTIN_FUNCTION_NS), "Returns an xs:integer between 0 and 23, both inclusive, representing the " + "value of the hours component in the localized value of $arg.", new SequenceType[] { new SequenceType(Type.TIME, Cardinality.ZERO_OR_ONE)}, new SequenceType(Type.INTEGER, Cardinality.ZERO_OR_ONE)); public final static FunctionSignature fnMinutesFromTime = new FunctionSignature( new QName("minutes-from-time", Function.BUILTIN_FUNCTION_NS), "Returns an xs:integer value between 0 to 59, both inclusive, representing the value of " + "the minutes component in the localized value of $arg.", new SequenceType[] { new SequenceType(Type.TIME, Cardinality.ZERO_OR_ONE)}, new SequenceType(Type.INTEGER, Cardinality.ZERO_OR_ONE)); public final static FunctionSignature fnSecondsFromTime = new FunctionSignature( new QName("seconds-from-time", Function.BUILTIN_FUNCTION_NS), "Returns an xs:decimal value between 0 and 60.999..., both inclusive, representing the " + "seconds and fractional seconds in the localized value of $arg. Note that the value can be " + "greater than 60 seconds to accommodate occasional leap seconds used to keep human time " + "synchronized with the rotation of the planet.", new SequenceType[] { new SequenceType(Type.TIME, Cardinality.ZERO_OR_ONE)}, new SequenceType(Type.DECIMAL, Cardinality.ZERO_OR_ONE)); public final static FunctionSignature fnTimezoneFromTime = new FunctionSignature( new QName("timezone-from-time", Function.BUILTIN_FUNCTION_NS), "Returns the timezone component of $arg if any. If $arg has a timezone component, " + "then the result is an xdt:dayTimeDuration that indicates deviation from UTC; its value may " + "range from +14:00 to -14:00 hours, both inclusive. Otherwise, the result is the empty sequence.", new SequenceType[] { new SequenceType(Type.TIME, Cardinality.ZERO_OR_ONE)}, new SequenceType(Type.DAY_TIME_DURATION, Cardinality.ZERO_OR_ONE)); /** * @param context * @param signature */ public FunGetTimeComponent(XQueryContext context, FunctionSignature signature) { super(context, signature); } /* (non-Javadoc) * @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], org.exist.xquery.value.Sequence) */ public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { if (context.getProfiler().isEnabled()) { context.getProfiler().start(this); context.getProfiler().message(this, Profiler.DEPENDENCIES, "DEPENDENCIES", Dependency.getDependenciesName(this.getDependencies())); if (contextSequence != null) context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT SEQUENCE", contextSequence); } Sequence result; Sequence arg = args[0]; if (arg.isEmpty()) result = Sequence.EMPTY_SEQUENCE; else { TimeValue time = (TimeValue) arg.itemAt(0); if (isCalledAs("hours-from-time")) result = new IntegerValue(time.getPart(DateValue.HOUR), Type.INTEGER); else if (isCalledAs("minutes-from-time")) result = new IntegerValue(time.getPart(DateValue.MINUTE), Type.INTEGER); else if (isCalledAs("seconds-from-time")) { long millis = time.getPart(DateValue.SECOND) * 1000L + time.getPart(DateValue.MILLISECOND); result = new DecimalValue(millis / 1000F); } else if (isCalledAs("timezone-from-time")) result = time.getTimezone(); else throw new Error("can't handle function " + mySignature.getName().getLocalName()); } if (context.getProfiler().isEnabled()) context.getProfiler().end(this, "", result); return result; } }
package org.jitsi.impl.neomedia.recording; import org.jitsi.service.neomedia.MediaType; import org.jitsi.service.neomedia.control.*; import org.jitsi.service.neomedia.recording.*; import org.jitsi.util.*; import javax.media.*; import javax.media.datasink.*; import javax.media.format.*; import javax.media.protocol.*; import java.io.*; /** * A <tt>DataSink</tt> implementation which writes output in webm format. * * @author Boris Grozev */ public class WebmDataSink implements DataSink, BufferTransferHandler { /** * The <tt>Logger</tt> used by the <tt>WebmDataSink</tt> class and its * instances for logging output. */ private static final Logger logger = Logger.getLogger(WebmDataSink.class); /** * The <tt>WebmWriter</tt> which we use to write the frames to a file. */ private WebmWriter writer = null; private RecorderEventHandler eventHandler; private long ssrc = -1; /** * Whether this <tt>DataSink</tt> is open and should write to its * <tt>WebmWriter</tt>. */ private boolean open = false; private final Object openCloseSyncRoot = new Object(); /** * Whether we are in a state of waiting for a keyframe and discarding * non-key frames. */ private boolean waitingForKeyframe = true; /** * The height of the video. Initialized on the first received keyframe. */ private int height = 0; /** * The height of the video. Initialized on the first received keyframe. */ private int width = 0; /** * A <tt>Buffer</tt> used to transfer frames. */ private Buffer buffer = new Buffer(); private WebmWriter.FrameDescriptor fd = new WebmWriter.FrameDescriptor(); /** * Our <tt>DataSource</tt>. */ private DataSource dataSource = null; /** * The name of the file into which we will write. */ private String filename; /** * The RTP time stamp of the first frame written to the output webm file. */ private long firstFrameRtpTimestamp = -1; /** * The time as returned by <tt>System.currentTimeMillis()</tt> of the first * frame written to the output webm file. */ private long firstFrameTime = -1; /** * The PTS (presentation timestamp) of the last frame written to the output * file. In milliseconds. */ private long lastFramePts = -1; /** * The <tt>KeyFrameControl</tt> which we will use to request a keyframe. */ private KeyFrameControl keyFrameControl = null; /** * Whether we have already requested a keyframe. */ private boolean keyframeRequested = false; private int framesSinceLastKeyframeRequest = 0; private static int REREQUEST_KEYFRAME_INTERVAL = 100; /** * Initialize a new <tt>WebmDataSink</tt> instance. * @param filename the name of the file into which to write. * @param dataSource the <tt>DataSource</tt> to use. */ public WebmDataSink(String filename, DataSource dataSource) { this.filename = filename; this.dataSource = dataSource; } /** * {@inheritDoc} */ @Override public void addDataSinkListener(DataSinkListener dataSinkListener) { } /** * {@inheritDoc} */ @Override public void close() { synchronized (openCloseSyncRoot) { if (writer != null) writer.close(); if (eventHandler != null && firstFrameTime != -1 && lastFramePts != -1) { RecorderEvent event = new RecorderEvent(); event.setType(RecorderEvent.Type.RECORDING_ENDED); event.setSsrc(ssrc); event.setFilename(filename); // make sure that the difference in the 'instant'-s of the // STARTED and ENDED events matches the duration of the file event.setDuration(lastFramePts); event.setMediaType(MediaType.VIDEO); eventHandler.handleEvent(event); } open = false; } } /** * {@inheritDoc} */ @Override public String getContentType() { return null; } /** * {@inheritDoc} */ @Override public MediaLocator getOutputLocator() { return null; } /** * {@inheritDoc} */ @Override public void open() throws IOException, SecurityException { synchronized (openCloseSyncRoot) { if (dataSource instanceof PushBufferDataSource) { PushBufferDataSource pbds = (PushBufferDataSource) dataSource; PushBufferStream[] streams = pbds.getStreams(); //XXX: should we allow for multiple streams in the data source? for (PushBufferStream stream : streams) { //XXX whats the proper way to check for this? and handle? if (!stream.getFormat().matches(new VideoFormat("VP8"))) throw new IOException("Unsupported stream format"); stream.setTransferHandler(this); } } dataSource.connect(); open = true; } } /** * {@inheritDoc} */ @Override public void removeDataSinkListener(DataSinkListener dataSinkListener) { } /** * {@inheritDoc} */ @Override public void setOutputLocator(MediaLocator mediaLocator) { } /** * {@inheritDoc} */ @Override public void start() throws IOException { writer = new WebmWriter(filename); dataSource.start(); if (logger.isInfoEnabled()) logger.info("Created WebmWriter on " + filename); } /** * {@inheritDoc} */ @Override public void stop() throws IOException { //XXX: should we do something here? reset waitingForKeyframe? } /** * {@inheritDoc} */ @Override public Object getControl(String s) { return null; } /** * {@inheritDoc} */ @Override public Object[] getControls() { return new Object[0]; } /** * {@inheritDoc} */ @Override public void setSource(DataSource dataSource) throws IOException, IncompatibleSourceException { //maybe we should throw an exception here, since we don't support //changing the data source? } /** * {@inheritDoc} */ @Override public void transferData(PushBufferStream stream) { synchronized (openCloseSyncRoot) { if (!open) return; try { stream.read(buffer); } catch (IOException ioe) { ioe.printStackTrace(); } byte[] data = (byte[])buffer.getData(); int offset = buffer.getOffset(); int len = buffer.getLength(); /* * Until an SDES packet is received by FMJ, it doesn't correctly set * the packets' timestamps. To avoid waiting, we use the RTP time stamps * directly. We can do this because VP8 always uses a rate of 90000. */ long rtpTimeStamp = buffer.getRtpTimeStamp(); boolean key = isKeyFrame(data, offset); boolean valid = isKeyFrameValid(data, offset); if (waitingForKeyframe && key) { if (valid) { waitingForKeyframe = false; width = getWidth(data, offset); height = getHeight(data, offset); firstFrameRtpTimestamp = rtpTimeStamp; firstFrameTime = System.currentTimeMillis(); writer.writeWebmFileHeader(width, height); if (logger.isInfoEnabled()) logger.info("Received the first keyframe (width=" + width + "; height=" + height + ")"+" ssrc="+ssrc); if (eventHandler != null) { RecorderEvent event = new RecorderEvent(); event.setType(RecorderEvent.Type.RECORDING_STARTED); event.setSsrc(ssrc); if (height*4 == width*3) event.setAspectRatio( RecorderEvent.AspectRatio.ASPECT_RATIO_4_3); else if (height*16 == width*9) event.setAspectRatio( RecorderEvent.AspectRatio.ASPECT_RATIO_16_9); event.setFilename(filename); event.setInstant(firstFrameTime); event.setRtpTimestamp(rtpTimeStamp); event.setMediaType(MediaType.VIDEO); eventHandler.handleEvent(event); } } else { keyframeRequested = false; if (logger.isInfoEnabled()) logger.info("Received an invalid first keyframe. " + "Requesting a new one."+ssrc); } } framesSinceLastKeyframeRequest++; if (framesSinceLastKeyframeRequest > REREQUEST_KEYFRAME_INTERVAL) keyframeRequested = false; if (waitingForKeyframe && !keyframeRequested) { if (logger.isInfoEnabled()) logger.info("Requesting keyframe. "+ssrc); if (keyFrameControl != null) keyframeRequested = keyFrameControl.requestKeyFrame(false); framesSinceLastKeyframeRequest = 0; } //that's temporary, aimed at debugging a specific issue if (key && logger.isInfoEnabled()) { String s = ""; for (int i = 0; i<10 && i<len; i++) s += String.format("%02x", data[offset+i]); logger.info("Keyframe. First 10 bytes: "+s); } if (!waitingForKeyframe) { if (key) { if (!valid) { if (logger.isInfoEnabled()) logger.info("Dropping an invalid VP8 keyframe."); return; } int oldWidth = width; width = getWidth(data, offset); int oldHeight = height; height = getHeight(data, offset); // TODO generate an event? start writing in a new file? if (width != oldWidth || height != oldHeight) { if (logger.isInfoEnabled()) { logger.info("VP8 stream width/height changed. Old: " + oldWidth + "/" + oldHeight + ". New: " + width + "/" + height + "."); } } } fd.buffer = data; fd.offset = offset; fd.length = len; fd.flags = key ? WebmWriter.FLAG_FRAME_IS_KEY : 0; if (!isShowFrame(data, offset)) fd.flags |= WebmWriter.FLAG_FRAME_IS_INVISIBLE; long diff = rtpTimeStamp - firstFrameRtpTimestamp; if (diff < -(1L<<31)) diff += 1L<<32; //pts is in milliseconds, the VP8 rtp clock rate is 90000 fd.pts = diff / 90; writer.writeFrame(fd); lastFramePts = fd.pts; } } //synchronized } /** * Returns <tt>true</tt> if the VP8 compressed frame contained in * <tt>buf</tt> at offset <tt>offset</tt> is a keyframe. * TODO: move it to a more general class? * * @param buf the buffer containing a compressed VP8 frame. * @param offset the offset in <tt>buf</tt> where the VP8 compressed frame * starts. * * @return <tt>true</tt>if the VP8 compressed frame contained in * <tt>buf</tt> at offset <tt>offset</tt> is a keyframe. */ private boolean isKeyFrame(byte[] buf, int offset) { return (buf[offset] & 0x01) == 0; } /** * Returns <tt>true</tt> if the VP8 compressed keyframe contained in * <tt>buf</tt> at offset <tt>offset</tt> is valid. * TODO: move it to a more general class? * * @param buf the buffer containing a compressed VP8 frame. * @param offset the offset in <tt>buf</tt> where the VP8 compressed frame * starts. * * @return <tt>true</tt>if the VP8 compressed keyframe contained in * <tt>buf</tt> at offset <tt>offset</tt> is valid. */ private boolean isKeyFrameValid(byte[] buf, int offset) { return (buf[offset + 3] == (byte) 0x9d) && (buf[offset + 4] == (byte) 0x01) && (buf[offset + 5] == (byte) 0x2a); } /** * Returns the width of the VP8 compressed frame contained in <tt>buf</tt> * at offset <tt>offset</tt>. See the format defined in RFC6386. * TODO: move it to a more general class? * * @param buf the buffer containing a compressed VP8 frame. * @param offset the offset in <tt>buf</tt> where the VP8 compressed frame * starts. * * @return the width of the VP8 compressed frame contained in <tt>buf</tt> * at offset <tt>offset</tt>. */ private int getWidth(byte[] buf, int offset) { return (((buf[offset+7] & 0xff) << 8) | (buf[offset+6] & 0xff)) & 0x3fff; } /** * Returns the height of the VP8 compressed frame contained in <tt>buf</tt> * at offset <tt>offset</tt>. See the format defined in RFC6386. * TODO: move it to a more general class? * * @param buf the buffer containing a compressed VP8 frame. * @param offset the offset in <tt>buf</tt> where the VP8 compressed frame * starts. * * @return the height of the VP8 compressed frame contained in <tt>buf</tt> * at offset <tt>offset</tt>. */ private int getHeight(byte[] buf, int offset) { return (((buf[offset+9] & 0xff) << 8) | (buf[offset+8] & 0xff)) & 0x3fff; } private boolean isShowFrame(byte[] buf, int offset) { return (buf[offset] & 0x10) == 0; } public void setKeyFrameControl(KeyFrameControl keyFrameControl) { this.keyFrameControl = keyFrameControl; } public RecorderEventHandler getEventHandler() { return eventHandler; } public void setEventHandler(RecorderEventHandler eventHandler) { this.eventHandler = eventHandler; } public void setSsrc(long ssrc) { this.ssrc = ssrc; } }
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; public class TestaEntrada { public static void main(String[] args) throws IOException { // InputStream is = System.in; // Leitura do teclado do sistema // InputStream is = new FileInputStream("arquivo.txt"); // InputStreamReader isr = new InputStreamReader(is); // BufferedReader br = new BufferedReader(isr); BufferedReader br = new BufferedReader( new InputStreamReader( new FileInputStream("arquivo.txt"))); System.out.println("Digite sua mensagem:"); String linha = br.readLine(); while (linha != null) { System.out.println(linha); linha = br.readLine(); } br.close(); } }
package org.loklak.api.search; import java.io.File; import java.io.FileWriter; import java.io.IOException; import org.json.JSONArray; import org.json.JSONObject; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.loklak.server.APIException; import org.loklak.server.APIHandler; import org.loklak.server.AbstractAPIHandler; import org.loklak.server.Authorization; import org.loklak.server.BaseUserRole; import org.loklak.server.Query; import org.loklak.susi.SusiThought; import org.loklak.tools.storage.JSONObjectWithDefault; public class EventBriteCrawlerService extends AbstractAPIHandler implements APIHandler { private static final long serialVersionUID = 7850249510419661716L; @Override public String getAPIPath() { return "/api/eventbritecrawler.json"; } @Override public BaseUserRole getMinimalBaseUserRole() { return BaseUserRole.ANONYMOUS; } @Override public JSONObject getDefaultPermissions(BaseUserRole baseUserRole) { return null; } @Override public JSONObject serviceImpl(Query call, Authorization rights, JSONObjectWithDefault permissions) throws APIException { String url = call.get("url", ""); return crawlEventBrite(url); } public static SusiThought crawlEventBrite(String url) { Document htmlPage = null; try { htmlPage = Jsoup.connect(url).get(); } catch (Exception e) { e.printStackTrace(); } String eventID = null; String eventName = null; String eventDescription = null; // TODO Fetch Event Color String eventColor = null; String imageLink = null; String eventLocation = null; String startingTime = null; String endingTime = null; String ticketURL = null; Elements tagSection = null; Elements tagSpan = null; String[][] tags = new String[5][2]; String topic = null; // By default String closingDateTime = null; String schedulePublishedOn = null; JSONObject creator = new JSONObject(); String email = null; Float latitude = null; Float longitude = null; String privacy = "public"; // By Default String state = "completed"; // By Default String eventType = ""; String temp; Elements t; eventID = htmlPage.getElementsByTag("body").attr("data-event-id"); eventName = htmlPage.getElementsByClass("listing-hero-body").text(); eventDescription = htmlPage.select("div.js-xd-read-more-toggle-view.read-more__toggle-view").text(); eventColor = null; imageLink = htmlPage.getElementsByTag("picture").attr("content"); eventLocation = htmlPage.select("p.listing-map-card-street-address.text-default").text(); temp = htmlPage.getElementsByAttributeValue("property", "event:start_time").attr("content"); if(temp.length() >= 20){ startingTime = htmlPage.getElementsByAttributeValue("property", "event:start_time").attr("content").substring(0,19); }else{ startingTime = htmlPage.getElementsByAttributeValue("property", "event:start_time").attr("content"); } temp = htmlPage.getElementsByAttributeValue("property", "event:end_time").attr("content"); if(temp.length() >= 20){ endingTime = htmlPage.getElementsByAttributeValue("property", "event:end_time").attr("content").substring(0,19); }else{ endingTime = htmlPage.getElementsByAttributeValue("property", "event:end_time").attr("content"); } ticketURL = url + "#tickets"; // TODO Tags to be modified to fit in the format of Open Event "topic" tagSection = htmlPage.getElementsByAttributeValue("data-automation", "ListingsBreadcrumbs"); tagSpan = tagSection.select("span"); topic = ""; int iterator = 0, k = 0; for (Element e : tagSpan) { if (iterator % 2 == 0) { tags[k][1] = "www.eventbrite.com" + e.select("a.js-d-track-link.badge.badge--tag.l-mar-top-2").attr("href"); } else { tags[k][0] = e.text(); k++; } iterator++; } creator.put("email", ""); creator.put("id", "1"); // By Default temp = htmlPage.getElementsByAttributeValue("property", "event:location:latitude").attr("content"); if(temp.length() > 0){ latitude = Float .valueOf(htmlPage.getElementsByAttributeValue("property", "event:location:latitude").attr("content")); } temp = htmlPage.getElementsByAttributeValue("property", "event:location:longitude").attr("content"); if(temp.length() > 0){ longitude = Float .valueOf(htmlPage.getElementsByAttributeValue("property", "event:location:longitude").attr("content")); } // TODO This returns: "events.event" which is not supported by Open // Event Generator // eventType = htmlPage.getElementsByAttributeValue("property", // "og:type").attr("content"); String organizerName = null; String organizerLink = null; String organizerProfileLink = null; String organizerWebsite = null; String organizerContactInfo = null; String organizerDescription = null; String organizerFacebookFeedLink = null; String organizerTwitterFeedLink = null; String organizerFacebookAccountLink = null; String organizerTwitterAccountLink = null; temp = htmlPage.select("a.js-d-scroll-to.listing-organizer-name.text-default").text(); if(temp.length() >= 5){ organizerName = htmlPage.select("a.js-d-scroll-to.listing-organizer-name.text-default").text().substring(4); }else{ organizerName = ""; } organizerLink = url + "#listing-organizer"; organizerProfileLink = htmlPage .getElementsByAttributeValue("class", "js-follow js-follow-target follow-me fx--fade-in is-hidden") .attr("href"); organizerContactInfo = url + "#lightbox_contact"; Document orgProfilePage = null; try { orgProfilePage = Jsoup.connect(organizerProfileLink).get(); } catch (Exception e) { e.printStackTrace(); } if(orgProfilePage != null){ t = orgProfilePage.getElementsByAttributeValue("class", "l-pad-vert-1 organizer-website"); if(t != null){ organizerWebsite = orgProfilePage.getElementsByAttributeValue("class", "l-pad-vert-1 organizer-website").text(); }else{ organizerWebsite = ""; } t = orgProfilePage.select("div.js-long-text.organizer-description"); if(t != null){ organizerDescription = orgProfilePage.select("div.js-long-text.organizer-description").text(); }else{ organizerDescription = ""; } organizerFacebookFeedLink = organizerProfileLink + "#facebook_feed"; organizerTwitterFeedLink = organizerProfileLink + "#twitter_feed"; t = orgProfilePage.getElementsByAttributeValue("class", "fb-page"); if(t != null){ organizerFacebookAccountLink = orgProfilePage.getElementsByAttributeValue("class", "fb-page").attr("data-href"); }else{ organizerFacebookAccountLink = ""; } t = orgProfilePage.getElementsByAttributeValue("class", "twitter-timeline"); if(t != null){ organizerTwitterAccountLink = orgProfilePage.getElementsByAttributeValue("class", "twitter-timeline").attr("href"); }else{ organizerTwitterAccountLink = ""; } } JSONArray socialLinks = new JSONArray(); JSONObject fb = new JSONObject(); fb.put("id", "1"); fb.put("name", "Facebook"); fb.put("link", organizerFacebookAccountLink); socialLinks.put(fb); JSONObject tw = new JSONObject(); tw.put("id", "2"); tw.put("name", "Twitter"); tw.put("link", organizerTwitterAccountLink); socialLinks.put(tw); JSONArray jsonArray = new JSONArray(); JSONObject event = new JSONObject(); event.put("event_url", url); event.put("id", eventID); event.put("name", eventName); event.put("description", eventDescription); event.put("color", eventColor); event.put("background_url", imageLink); event.put("closing_datetime", closingDateTime); event.put("creator", creator); event.put("email", email); event.put("location_name", eventLocation); event.put("latitude", latitude); event.put("longitude", longitude); event.put("start_time", startingTime); event.put("end_time", endingTime); event.put("logo", imageLink); event.put("organizer_description", organizerDescription); event.put("organizer_name", organizerName); event.put("privacy", privacy); event.put("schedule_published_on", schedulePublishedOn); event.put("state", state); event.put("type", eventType); event.put("ticket_url", ticketURL); event.put("social_links", socialLinks); event.put("topic", topic); jsonArray.put(event); JSONObject org = new JSONObject(); org.put("organizer_name", organizerName); org.put("organizer_link", organizerLink); org.put("organizer_profile_link", organizerProfileLink); org.put("organizer_website", organizerWebsite); org.put("organizer_contact_info", organizerContactInfo); org.put("organizer_description", organizerDescription); org.put("organizer_facebook_feed_link", organizerFacebookFeedLink); org.put("organizer_twitter_feed_link", organizerTwitterFeedLink); org.put("organizer_facebook_account_link", organizerFacebookAccountLink); org.put("organizer_twitter_account_link", organizerTwitterAccountLink); jsonArray.put(org); JSONArray microlocations = new JSONArray(); jsonArray.put(microlocations); JSONArray customForms = new JSONArray(); jsonArray.put(customForms); JSONArray sessionTypes = new JSONArray(); jsonArray.put(sessionTypes); JSONArray sessions = new JSONArray(); jsonArray.put(sessions); JSONArray sponsors = new JSONArray(); jsonArray.put(sponsors); JSONArray speakers = new JSONArray(); jsonArray.put(speakers); JSONArray tracks = new JSONArray(); jsonArray.put(tracks); JSONObject eventBriteResult = new JSONObject(); eventBriteResult.put("EventBriteEventDetails", jsonArray); String userHome = System.getProperty("user.home"); String path = userHome + "/Downloads/EventBriteInfo"; new File(path).mkdir(); try (FileWriter file = new FileWriter(path + "/event.json")) { file.write(event.toString()); } catch (IOException e1) { e1.printStackTrace(); } try (FileWriter file = new FileWriter(path + "/org.json")) { file.write(org.toString()); } catch (IOException e1) { e1.printStackTrace(); } try (FileWriter file = new FileWriter(path + "/social_links.json")) { file.write(socialLinks.toString()); } catch (IOException e1) { e1.printStackTrace(); } try (FileWriter file = new FileWriter(path + "/microlocations.json")) { file.write(microlocations.toString()); } catch (IOException e1) { e1.printStackTrace(); } try (FileWriter file = new FileWriter(path + "/custom_forms.json")) { file.write(customForms.toString()); } catch (IOException e1) { e1.printStackTrace(); } try (FileWriter file = new FileWriter(path + "/session_types.json")) { file.write(sessionTypes.toString()); } catch (IOException e1) { e1.printStackTrace(); } try (FileWriter file = new FileWriter(path + "/sessions.json")) { file.write(sessions.toString()); } catch (IOException e1) { e1.printStackTrace(); } try (FileWriter file = new FileWriter(path + "/sponsors.json")) { file.write(sponsors.toString()); } catch (IOException e1) { e1.printStackTrace(); } try (FileWriter file = new FileWriter(path + "/speakers.json")) { file.write(speakers.toString()); } catch (IOException e1) { e1.printStackTrace(); } try (FileWriter file = new FileWriter(path + "/tracks.json")) { file.write(tracks.toString()); } catch (IOException e1) { e1.printStackTrace(); } JSONArray eventBriteResultJSONArray = new JSONArray(); eventBriteResultJSONArray.put(eventBriteResult); SusiThought json = new SusiThought(); json.setData(eventBriteResultJSONArray); return json; } }
package org.objectweb.proactive.core.body; import org.apache.log4j.Logger; import org.objectweb.proactive.Body; import org.objectweb.proactive.core.UniqueID; import org.objectweb.proactive.core.body.future.Future; import org.objectweb.proactive.core.body.future.FuturePool; import org.objectweb.proactive.core.body.future.FutureProxy; import org.objectweb.proactive.core.body.reply.Reply; import org.objectweb.proactive.core.body.request.BlockingRequestQueue; import org.objectweb.proactive.core.body.request.Request; import org.objectweb.proactive.core.exceptions.handler.Handler; import org.objectweb.proactive.core.group.MethodCallControlForGroup; import org.objectweb.proactive.core.group.ProActiveGroup; import org.objectweb.proactive.core.group.ProActiveGroupManager; import org.objectweb.proactive.core.group.ProxyForGroup; import org.objectweb.proactive.core.mop.MethodCall; import org.objectweb.proactive.core.util.ThreadStore; import org.objectweb.proactive.ext.security.Communication; import org.objectweb.proactive.ext.security.CommunicationForbiddenException; import org.objectweb.proactive.ext.security.DefaultProActiveSecurityManager; import org.objectweb.proactive.ext.security.InternalBodySecurity; import org.objectweb.proactive.ext.security.Policy; import org.objectweb.proactive.ext.security.PolicyServer; import org.objectweb.proactive.ext.security.ProActiveSecurity; import org.objectweb.proactive.ext.security.ProActiveSecurityManager; import org.objectweb.proactive.ext.security.Secure; import org.objectweb.proactive.ext.security.SecurityContext; import org.objectweb.proactive.ext.security.crypto.AuthenticationException; import org.objectweb.proactive.ext.security.crypto.ConfidentialityTicket; import org.objectweb.proactive.ext.security.crypto.KeyExchangeException; import org.objectweb.proactive.ext.security.exceptions.RenegotiateSessionException; import org.objectweb.proactive.ext.security.exceptions.SecurityNotAvailableException; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.security.Provider; import java.security.PublicKey; import java.security.Security; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; /** * <i><font size="-1" color="#FF0000">**For internal use only** </font></i><br> * <p> * This class gives a common implementation of the Body interface. It provides all * the non specific behavior allowing sub-class to write the detail implementation. * </p><p> * Each body is identify by an unique identifier. * </p><p> * All active bodies that get created in one JVM register themselves into a table that allows * to tack them done. The registering and deregistering is done by the AbstractBody and * the table is managed here as well using some static methods. * </p><p> * In order to let somebody customize the body of an active object without subclassing it, * AbstractBody delegates lot of tasks to satellite objects that implements a given * interface. Abstract protected methods instantiate those objects allowing subclasses * to create them as they want (using customizable factories or instance). * </p> * * @author ProActive Team * @version 1.0, 2001/10/23 * @since ProActive 0.9 * @see Body * @see UniqueID * */ public abstract class AbstractBody extends AbstractUniversalBody implements Body, java.io.Serializable { private static final String TERMINATED_BODY_EXCEPTION_MESSAGE = "The body has been Terminated"; protected ThreadStore threadStore; // the current implementation of the local view of this body protected LocalBodyStrategy localBodyStrategy; // SECURITY protected ProActiveSecurityManager psm; protected boolean isSecurityOn = false; protected transient InternalBodySecurity internalBodySecurity; protected Hashtable openedSessions; protected static Logger logger = Logger.getLogger(AbstractBody.class.getName()); protected boolean isInterfaceSecureImplemented = false; // GROUP protected ProActiveGroupManager pgm; /** whether the body has an activity done with a active thread */ private transient boolean isActive; /** whether the body has been killed. A killed body has no more activity although stopping the activity thread is not immediate */ private transient boolean isDead; /** table of handlers associated to the body */ private HashMap bodyLevel; /** * Creates a new AbstractBody. * Used for serialization. */ public AbstractBody() { } /** * Creates a new AbstractBody for an active object attached to a given node. * @param reifiedObject the active object that body is for * @param nodeURL the URL of the node that body is attached to * @param factory the factory able to construct new factories for each type of meta objects * needed by this body */ public AbstractBody(Object reifiedObject, String nodeURL, MetaObjectFactory factory, String jobId) { super(nodeURL, factory.newRemoteBodyFactory(), jobId); this.threadStore = factory.newThreadStoreFactory().newThreadStore(); // GROUP this.pgm = factory.newProActiveGroupManagerFactory() .newProActiveGroupManager(); Provider myProvider = new org.bouncycastle.jce.provider.BouncyCastleProvider(); Security.addProvider(myProvider); // SECURITY if (reifiedObject instanceof Secure) { isInterfaceSecureImplemented = true; } psm = new ProActiveSecurityManager(); internalBodySecurity = new InternalBodySecurity(null); // SECURITY /* this.psm = factory.getProActiveSecurityManager(); if (psm != null) { // startDefaultProActiveSecurityManager(); isSecurityOn = (psm != null); logger.debug("Security is " + isSecurityOn); psm.setBody(this); internalBodySecurity = new InternalBodySecurity(null); } */ } /** * Returns a string representation of this object. * @return a string representation of this object */ public String toString() { return "Body for " + localBodyStrategy.getName() + " node=" + nodeURL + " id=" + bodyID; } public void receiveRequest(Request request) throws java.io.IOException, RenegotiateSessionException { //System.out.println(" --> receiveRequest m="+request.getMethodName()); try { this.enterInThreadStore(); if (this.isDead) { throw new java.io.IOException(TERMINATED_BODY_EXCEPTION_MESSAGE); } if (this.isSecurityOn) { /* if (isInterfaceSecureImplemented) { Session session = psm.getSession(request.getSessionId()); ((Secure) getReifiedObject()).receiveRequest(session.getSecurityContext()); } */ try { this.renegociateSessionIfNeeded(request.getSessionId()); if ((this.internalBodySecurity.isLocalBody()) && request.isCiphered()) { request.decrypt(psm); } } catch (SecurityNotAvailableException e) { // do nothing } } this.registerIncomingFutures(); this.internalReceiveRequest(request); } finally { this.exitFromThreadStore(); } } public void receiveReply(Reply reply) throws java.io.IOException { //System.out.println(" --> receiveReply m="+reply.getMethodName()); try { //System.out.println("Body receives Reply on NODE : " + this.nodeURL); enterInThreadStore(); if (isDead) { throw new java.io.IOException(TERMINATED_BODY_EXCEPTION_MESSAGE); } if (isSecurityOn) { try { if ((internalBodySecurity.isLocalBody()) && reply.isCiphered()) { reply.decrypt(psm); } } catch (Exception e) { e.printStackTrace(); } } this.registerIncomingFutures(); internalReceiveReply(reply); } finally { exitFromThreadStore(); } } /** * This method effectively register futures (ie in the futurePool) that arrive in this active * object (by parameter or by result). Incoming futures have been registered in the static table * FuturePool.incomingFutures during their deserialization. This effective registration must be perform * AFTER entering in the ThreadStore. */ private void registerIncomingFutures() { // get list of futures that should be deserialized and registred "behind the ThreadStore" java.util.ArrayList incomingFutures = FuturePool.getIncomingFutures(); if (incomingFutures != null) { // if futurePool is not null, we are in an Active Body if (getFuturePool() != null) { // some futures have to be registred in the local futurePool java.util.Iterator it = incomingFutures.iterator(); while (it.hasNext()) { Future current = (Future) (it.next()); getFuturePool().receiveFuture(current); } FuturePool.removeIncomingFutures(); } else { // we are in a forwarder // some futures have to set their continuation tag java.util.Iterator it = incomingFutures.iterator(); while (it.hasNext()) { FutureProxy current = (FutureProxy) (it.next()); current.setContinuationTag(); } FuturePool.removeIncomingFutures(); } } } public void enableAC() { localBodyStrategy.getFuturePool().enableAC(); } public void disableAC() { localBodyStrategy.getFuturePool().disableAC(); } public void renegociateSessionIfNeeded(long sID) throws IOException, RenegotiateSessionException, SecurityNotAvailableException { try { enterInThreadStore(); if (!internalBodySecurity.isLocalBody() && (openedSessions != null)) { // inside a forwarder Long sessionID; //long sID = request.getSessionId(); if (sID != 0) { sessionID = new Long(sID); if (openedSessions.containsKey(sessionID)) { openedSessions.remove(sessionID); internalBodySecurity.terminateSession(sID); //System.out.println("Object has migrated : Renegotiate Session"); throw new RenegotiateSessionException(internalBodySecurity.getDistantBody()); } } } } finally { exitFromThreadStore(); } } public String getVNName() throws java.io.IOException, SecurityNotAvailableException { try { enterInThreadStore(); if (isSecurityOn) { if (internalBodySecurity.isLocalBody()) { return psm.getVNName(); } else { return internalBodySecurity.getVNName(); } } } finally { exitFromThreadStore(); } return null; } public void initiateSession(int type, UniversalBody body) throws java.io.IOException, CommunicationForbiddenException, org.objectweb.proactive.ext.security.crypto.AuthenticationException, RenegotiateSessionException, SecurityNotAvailableException { try { enterInThreadStore(); if (isSecurityOn) { if (internalBodySecurity.isLocalBody()) { psm.initiateSession(type, body); } else { internalBodySecurity.initiateSession(type, body); } } } finally { exitFromThreadStore(); } throw new SecurityNotAvailableException(); } public void terminateSession(long sessionID) throws java.io.IOException, SecurityNotAvailableException { try { enterInThreadStore(); if (isSecurityOn) { if (internalBodySecurity.isLocalBody()) { psm.terminateSession(sessionID); } else { internalBodySecurity.terminateSession(sessionID); } } throw new SecurityNotAvailableException(); } finally { exitFromThreadStore(); } } public X509Certificate getCertificate() throws java.io.IOException, SecurityNotAvailableException { try { enterInThreadStore(); if (isSecurityOn) { if (internalBodySecurity.isLocalBody()) { // System.out.println(" getCertificate on demande un security manager a " + ProActive.getBodyOnThis()); // if (psm == null) { // startDefaultProActiveSecurityManager(); return psm.getCertificate(); } else { return internalBodySecurity.getCertificate(); } } throw new SecurityNotAvailableException(); } finally { exitFromThreadStore(); } } public ProActiveSecurityManager getProActiveSecurityManager() throws java.io.IOException, SecurityNotAvailableException { try { enterInThreadStore(); if (isSecurityOn) { if (internalBodySecurity.isLocalBody()) { // System.out.println("getProActiveSecurityManager on demande un security manager a " + ProActive.getBodyOnThis()); // if (psm == null) { // startDefaultProActiveSecurityManager(); return psm; } else { ProActiveSecurityManager plop = internalBodySecurity.getProActiveSecurityManager(); return plop; } } else { throw new SecurityNotAvailableException(); } } finally { exitFromThreadStore(); } } public Policy getPolicyFrom(X509Certificate certificate) throws java.io.IOException, SecurityNotAvailableException { try { enterInThreadStore(); if (isSecurityOn) { Policy pol; if (internalBodySecurity.isLocalBody()) { // if (psm == null) { // startDefaultProActiveSecurityManager(); pol = psm.getPolicyTo(certificate); return pol; } else { pol = internalBodySecurity.getPolicyFrom(certificate); return pol; } } throw new SecurityNotAvailableException(); } finally { exitFromThreadStore(); } } public long startNewSession(Communication policy) throws java.io.IOException, RenegotiateSessionException, SecurityNotAvailableException { try { enterInThreadStore(); if (isSecurityOn) { long sessionID; if (internalBodySecurity.isLocalBody()) { //System.out.println("startNewSession on demande un security manager a " + ProActive.getBodyOnThis()); //if (psm == null) { //startDefaultProActiveSecurityManager(); sessionID = psm.startNewSession(policy); return sessionID; } else { sessionID = internalBodySecurity.startNewSession(policy); return sessionID; } } throw new SecurityNotAvailableException(); } finally { exitFromThreadStore(); } } public ConfidentialityTicket negociateKeyReceiverSide( ConfidentialityTicket confidentialityTicket, long sessionID) throws java.io.IOException, KeyExchangeException, SecurityNotAvailableException { try { enterInThreadStore(); ConfidentialityTicket tick; if (internalBodySecurity.isLocalBody()) { //System.out.println("negociateKeyReceiverSide on demande un security manager a " + ProActive.getBodyOnThis()); //if (psm == null) { // startDefaultProActiveSecurityManager(); tick = psm.keyNegociationReceiverSide(confidentialityTicket, sessionID); return tick; } else { tick = internalBodySecurity.negociateKeyReceiverSide(confidentialityTicket, sessionID); return tick; } } finally { exitFromThreadStore(); } } public PublicKey getPublicKey() throws java.io.IOException, SecurityNotAvailableException { try { enterInThreadStore(); if (isSecurityOn) { PublicKey pk; if (internalBodySecurity.isLocalBody()) { // System.out.println("getPublicKey on demande un security manager a " + ProActive.getBodyOnThis()); //if (psm == null) { // startDefaultProActiveSecurityManager(); pk = psm.getPublicKey(); return pk; } else { pk = internalBodySecurity.getPublicKey(); return pk; } } throw new SecurityNotAvailableException(); } finally { exitFromThreadStore(); } } public byte[] randomValue(long sessionID, byte[] cl_rand) throws java.io.IOException, SecurityNotAvailableException, Exception { try { enterInThreadStore(); if (isSecurityOn) { byte[] plop; if (internalBodySecurity.isLocalBody()) { // System.out.println("randomValue on demande un security manager a " + ProActive.getBodyOnThis()); plop = psm.randomValue(sessionID, cl_rand); return plop; } else { plop = internalBodySecurity.randomValue(sessionID, cl_rand); return plop; } } throw new SecurityNotAvailableException(); } finally { exitFromThreadStore(); } } public byte[][] publicKeyExchange(long sessionID, UniversalBody distantBody, byte[] my_pub, byte[] my_cert, byte[] sig_code) throws java.io.IOException, SecurityNotAvailableException, Exception { try { enterInThreadStore(); if (isSecurityOn) { renegociateSessionIfNeeded(sessionID); byte[][] pke; if (internalBodySecurity.isLocalBody()) { pke = psm.publicKeyExchange(sessionID, distantBody, my_pub, my_cert, sig_code); return pke; } else { pke = internalBodySecurity.publicKeyExchange(sessionID, distantBody, my_pub, my_cert, sig_code); return pke; } } throw new SecurityNotAvailableException(); } finally { exitFromThreadStore(); } } public byte[][] secretKeyExchange(long sessionID, byte[] tmp, byte[] tmp1, byte[] tmp2, byte[] tmp3, byte[] tmp4) throws java.io.IOException, Exception, SecurityNotAvailableException { try { enterInThreadStore(); if (!isSecurityOn) { throw new SecurityNotAvailableException(); } renegociateSessionIfNeeded(sessionID); byte[][] ske; renegociateSessionIfNeeded(sessionID); if (internalBodySecurity.isLocalBody()) { // System.out.println("secretKeyExchange demande un security manager a " + ProActive.getBodyOnThis()); ske = psm.secretKeyExchange(sessionID, tmp, tmp1, tmp2, tmp3, tmp4); return ske; } else { ske = internalBodySecurity.secretKeyExchange(sessionID, tmp, tmp1, tmp2, tmp3, tmp4); return ske; } } finally { threadStore.exit(); } } public Communication getPolicyTo(String type, String from, String to) throws SecurityNotAvailableException, java.io.IOException { try { enterInThreadStore(); if (!isSecurityOn) { throw new SecurityNotAvailableException(); } if (internalBodySecurity.isLocalBody()) { return psm.getPolicyTo(type, from, to); } else { return internalBodySecurity.getPolicyTo(type, from, to); } } finally { exitFromThreadStore(); } } public SecurityContext getPolicy(SecurityContext securityContext) throws java.io.IOException, SecurityNotAvailableException { try { enterInThreadStore(); if (!isSecurityOn) { throw new SecurityNotAvailableException(); } if (internalBodySecurity.isLocalBody()) { return psm.getPolicy(securityContext); } else { return internalBodySecurity.getPolicy(securityContext); } } finally { exitFromThreadStore(); } } public byte[] getCertificateEncoded() throws IOException, SecurityNotAvailableException { try { enterInThreadStore(); //if (psm == null) { // startDefaultProActiveSecurityManager(); if (!isSecurityOn || (psm == null)) { throw new SecurityNotAvailableException(); } if (internalBodySecurity.isLocalBody()) { return psm.getCertificate().getEncoded(); } else { return internalBodySecurity.getCertificatEncoded(); } } catch (CertificateEncodingException e) { e.printStackTrace(); } finally { exitFromThreadStore(); } return null; } protected void startDefaultProActiveSecurityManager() { try { // logger.info("starting a new psm "); this.psm = new DefaultProActiveSecurityManager("vide "); isSecurityOn = true; psm.setBody(this); internalBodySecurity = new InternalBodySecurity(null); } catch (Exception e) { System.out.println( "Error when contructing a DefaultProActiveManager"); e.printStackTrace(); } } public ArrayList getEntities() throws SecurityNotAvailableException, IOException { try { enterInThreadStore(); if (!isSecurityOn) { throw new SecurityNotAvailableException(); } if (internalBodySecurity.isLocalBody()) { return psm.getEntities(); } else { return internalBodySecurity.getEntities(); } } finally { exitFromThreadStore(); } } public void terminate() { if (isDead) { return; } isDead = true; activityStopped(); // unblock is thread was block acceptCommunication(); } public void blockCommunication() { threadStore.close(); } public void acceptCommunication() { threadStore.open(); } public void enterInThreadStore() { threadStore.enter(); } public void exitFromThreadStore() { threadStore.exit(); } public boolean isAlive() { return !isDead; } public boolean isActive() { return isActive; } public UniversalBody checkNewLocation(UniqueID bodyID) { //we look in the location table of the current JVM Body body = LocalBodyStore.getInstance().getLocalBody(bodyID); if (body != null) { // we update our table to say that this body is local location.updateBody(bodyID, body); return body; } else { //it was not found in this vm let's try the location table return location.getBody(bodyID); } } public void setPolicyServer(PolicyServer server) { if (server != null) { if ((psm != null) && (psm.getPolicyServer() == null)) { psm = new ProActiveSecurityManager(server); isSecurityOn = true; System.out.println("Security is on " + isSecurityOn); psm.setBody(this); } } } public FuturePool getFuturePool() { return localBodyStrategy.getFuturePool(); } public BlockingRequestQueue getRequestQueue() { return localBodyStrategy.getRequestQueue(); } public Object getReifiedObject() { return localBodyStrategy.getReifiedObject(); } public String getName() { return localBodyStrategy.getName(); } /** Serves the request. The request should be removed from the request queue * before serving, which is correctly done by all methods of the Service class. * However, this condition is not ensured for custom calls on serve. */ public void serve(Request request) { localBodyStrategy.serve(request); } public void sendRequest(MethodCall methodCall, Future future, UniversalBody destinationBody) throws java.io.IOException, RenegotiateSessionException { long sessionID = 0; // logger.debug("send Request Body" + destinationBody); //logger.debug(" bla" + destinationBody.getRemoteAdapter()); try { try { if (!isSecurityOn) { logger.debug("security is off"); } else { if (internalBodySecurity.isLocalBody()) { byte[] certE = destinationBody.getRemoteAdapter() .getCertificateEncoded(); X509Certificate cert = ProActiveSecurity.decodeCertificate(certE); System.out.println("send Request AbstractBody, method " + methodCall.getName() + " cert " + cert.getSubjectDN().getName()); if ((sessionID = psm.getSessionIDTo(cert)) == 0) { psm.initiateSession(SecurityContext.COMMUNICATION_SEND_REQUEST_TO, destinationBody.getRemoteAdapter()); sessionID = psm.getSessionIDTo(cert); } } } } catch (SecurityNotAvailableException e) { // do nothing logger.debug("communication without security"); //e.printStackTrace(); } localBodyStrategy.sendRequest(methodCall, future, destinationBody); } catch (RenegotiateSessionException e) { if (e.getUniversalBody() != null) { updateLocation(destinationBody.getID(), e.getUniversalBody()); } psm.terminateSession(sessionID); sendRequest(methodCall, future, e.getUniversalBody()); } catch (CommunicationForbiddenException e) { logger.warn(e); //e.printStackTrace(); } catch (AuthenticationException e) { e.printStackTrace(); } } /** * Get information about the handlerizable object * @return information about the handlerizable object */ public String getHandlerizableInfo() throws java.io.IOException { return "BODY (URL=" + this.nodeURL + ") of CLASS [" + this.getClass() + "]"; } /** Give a reference to a local map of handlers * @return A reference to a map of handlers */ public HashMap getHandlersLevel() throws java.io.IOException { return bodyLevel; } /** * Clear the local map of handlers */ public void clearHandlersLevel() throws java.io.IOException { bodyLevel.clear(); } /** Set a new handler within the table of the Handlerizable Object * @param handler A handler associated with a class of non functional exception. * @param exception A class of non functional exception. It is a subclass of <code>NonFunctionalException</code>. */ public void setExceptionHandler(Handler handler, Class exception) throws java.io.IOException { // add handler to body level if (bodyLevel == null) { bodyLevel = new HashMap(); } bodyLevel.put(exception, handler); } /** Remove a handler from the table of the Handlerizable Object * @param exception A class of non functional exception. It is a subclass of <code>NonFunctionalException</code>. * @return The removed handler or null */ public Handler unsetExceptionHandler(Class exception) throws java.io.IOException { // remove handler from body level if (bodyLevel != null) { Handler handler = (Handler) bodyLevel.remove(exception); return handler; } else { if (logger.isDebugEnabled()) { logger.debug("[NFE_WARNING] No handler for [" + exception.getName() + "] can be removed from BODY level"); } return null; } } /** * Receives a request for later processing. The call to this method is non blocking * unless the body cannot temporary receive the request. * @param request the request to process * @exception java.io.IOException if the request cannot be accepted */ protected abstract void internalReceiveRequest(Request request) throws java.io.IOException, RenegotiateSessionException; /** * Receives a reply in response to a former request. * @param reply the reply received * @exception java.io.IOException if the reply cannot be accepted */ protected abstract void internalReceiveReply(Reply reply) throws java.io.IOException; protected void setLocalBodyImpl(LocalBodyStrategy localBody) { localBodyStrategy = localBody; } /** * Signals that the activity of this body, managed by the active thread has just stopped. */ protected void activityStopped() { if (!isActive) { return; } isActive = false; //We are no longer an active body LocalBodyStore.getInstance().unregisterBody(this); } //protected void activityStopped2(){ // LocalBodyStore.getInstance().unregisterBody(this); /** * Signals that the activity of this body, managed by the active thread has just started. */ protected void activityStarted() { if (isActive) { return; } isActive = true; // we associated this body to the thread running it LocalBodyStore.getInstance().setCurrentThreadBody(this); // we register in this JVM LocalBodyStore.getInstance().registerBody(this); } /** * Set the SPMD group for the active object * @param o - the new SPMD group */ public void setSPMDGroup(Object o) { this.pgm.setSPMDGroup(o); } /** * Returns the SPMD group of the active object * @return the SPMD group of the active object */ public Object getSPMDGroup() { return this.pgm.getSPMDGroup(); } /** * Returns the size of of the SPMD group * @return the size of of the SPMD group */ public int getSPMDGroupSize() { return ProActiveGroup.size(this.getSPMDGroup()); } /** * Send a call to all member of the SPMD group * @param gmc the control method call for group */ public void sendSPMDGroupCall(MethodCallControlForGroup gmc) { try { ((ProxyForGroup) ProActiveGroup.getGroup(this.pgm.getSPMDGroup())).reify(gmc); } catch (InvocationTargetException e) { System.err.println( "Unable to invoke a method call to control groups"); e.printStackTrace(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { out.defaultWriteObject(); } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { in.defaultReadObject(); logger = Logger.getLogger("AbstractBody"); } }
/** * FIRST Team 1699 * * Abstract Command Class * * @author squirlemaster42, FIRST Team 1699 * * @version v0.2-norobot */ package org.usfirst.frc.team1699.utils.command; public abstract class Command { private String name; private int id; // id is used for commands run in auto. It should be set to an integer // value that corresponds to // the value used when wanting to call the command from the autonomous file. public Command(String name, int id) { this.name = name; this.id = id; // Add code to add name and id to respective lists } public abstract void init(); public abstract void run(); public abstract void outputToDashBoard(); // Output all data to dash board public abstract void zeroAllSensors(); // zeroAllSensors may need to be // looked at and changed // public abstract boolean isFinished(); Not used at this time may change in // the future. public String getName() { return name; } public int getId() { return id; } @Override public String toString() { return "Command [name=" + name + ", id=" + id + "]"; } }
package pt.iscte.lei.pi.firujo.scores; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Collections; public class HighScoreManager { // lista de scores private ArrayList<Score> scores; private static final String HIGHSCORE_FILE = "highscores.dat"; ObjectOutputStream oos = null; ObjectInputStream ois = null; public HighScoreManager() { //se ainda nao existir o ficheiro (1o carregamento) ele cria File scoresdat = new File(HIGHSCORE_FILE); if (!scoresdat.exists()) { try { scoresdat.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } scores = new ArrayList<Score>(); } /* * Retorna uma lista de resultados ordenada do melhor para o pior */ public ArrayList<Score> getScores() { loadScoreFile(); sort(); return scores; } @SuppressWarnings("unchecked") private void loadScoreFile() { try { ois = new ObjectInputStream(new FileInputStream(HIGHSCORE_FILE)); scores = (ArrayList<Score>) ois.readObject(); } catch (EOFException e) { System.out.println("first load"); } catch (Exception e) { e.printStackTrace(); } finally { try { if (oos != null) { oos.flush(); oos.close(); } } catch (IOException e) { e.printStackTrace(); } } } /* * Ordenar a lista de scores, do melhor para o pior */ private void sort() { ScoreComparator comparator = new ScoreComparator(); Collections.sort(scores, comparator); updateScoreFile(); } public void addScore(Score sc) { loadScoreFile(); scores.add(sc); updateScoreFile(); } /* * Escrever a lista de scores actualizada (depois de nova entrada) no ficheiro scores.dat */ private void updateScoreFile() { try { oos = new ObjectOutputStream(new FileOutputStream(HIGHSCORE_FILE)); oos.writeObject(scores); } catch (Exception e) { e.printStackTrace(); } finally { try { if (oos != null) { oos.flush(); oos.close(); } } catch (Exception e) { e.printStackTrace(); } } } /* * Mandar os top scores para a consola */ @Override public String toString() { String highscoreString = ""; int topmax = 3; ArrayList<Score> scores; scores = getScores(); int i = 0; int x = scores.size(); if (x > topmax) { x = topmax; } while (i < x) { highscoreString += (i + 1) + ".\t" + scores.get(i).getName() + "\t\t" + scores.get(i).getScore() + "\n"; i++; } return highscoreString; } }
// MODEL SYNTHESIS // clone: 338318 (using testLRS, default params) // lrs: // AXIOM SYNTHESIS // clone: 32605 (using testLRS, default params) // lrs: import java.util.*; class SuffixArray { // Size of the suffix array int N; // T is the text int[] T; // Suffix array. Contains the indexes of sorted suffixes. int[] sa; // Contains Longest Common Prefix (LCP) count between adjacent suffixes. // lcp[i] = longestCommonPrefixLength( suffixes[i], suffixes[i+1] ). // Also, LCP[len-1] = 0 int [] lcp; // CHANGE public int[] clone(int[] arr) { // int l = {| arr.length, N |}; int l = arr.length; int[] arr_cp = new int[l]; // for(int i=??; i<l; i++) { for(int i=0; i<l; i++) { arr_cp[i] = arr[i]; } return arr_cp; } public SuffixArray(String text) { this(toIntArray(text)); } //CHANGE private static String intArrToString(int [] text) { char[] tmp = new char[text.length]; for (int i=0; i<text.length; i++) { tmp[i] = (char) text[i]; } // Extract part of the suffix we need to compare return new String(tmp, 0, text.length); } private static int[] toIntArray(String s) { int[] text = new int[s.length()]; for(int i=0;i<s.length();i++)text[i] = s.charAt(i); return text; } public SuffixArray(int[] text) { // CHANGE // T = text.clone(); T = clone(text); N = text.length; construct(); kasai(); } // Construct a suffix array in O(nlog^2(n)) public void construct() { sa = new int[N]; // Maintain suffix ranks in both a matrix with two rows containing the // current and last rank information as well as some sortable rank objects // CHANGE // int[][] suffixRanks = new int[2][N]; TwoDArray suffixRanks = new TwoDArray(2, N); SuffixRankTuple[] ranks = new SuffixRankTuple[N]; // Assign a numerical value to each character in the text for (int i = 0; i < N; i++) { // CHANGE // suffixRanks[0][i] = T[i]; suffixRanks.set(0, i, T[i]); ranks[i] = new SuffixRankTuple(); } // O(logn) for(int pos = 1; pos < N; pos *= 2) { for(int i = 0; i < N; i++) { SuffixRankTuple suffixRank = ranks[i]; suffixRank.firstHalf = suffixRanks.get(0, i); // CHANGE // suffixRank.firstHalf = suffixRanks[0][i]; suffixRank.secondHalf = i+pos < N ? suffixRanks.get(0, i+pos) : -1; // CHANGE // suffixRank.secondHalf = i+pos < N ? suffixRanks[0][i+pos] : -1; suffixRank.originalIndex = i; } // O(nlogn) // CHANGE // java.util.Arrays.sort(ranks); ranks = Arrays.sort(ranks, ranks.length); int newRank = 0; suffixRanks.set(1, ranks[0].originalIndex, 0); // CHANGE // suffixRanks[1][ranks[0].originalIndex] = 0; for (int i = 1; i < N; i++ ) { SuffixRankTuple lastSuffixRank = ranks[i-1]; SuffixRankTuple currSuffixRank = ranks[i]; // If the first half differs from the second half if (currSuffixRank.firstHalf != lastSuffixRank.firstHalf || currSuffixRank.secondHalf != lastSuffixRank.secondHalf) newRank++; suffixRanks.set(1, currSuffixRank.originalIndex, newRank); // CHANGE // suffixRanks[1][currSuffixRank.originalIndex] = newRank; } // Place top row (current row) to be the last row suffixRanks.setRow(0, suffixRanks.getRow(1)); // CHANGE // suffixRanks[0] = suffixRanks[1]; // Optimization to stop early // CHANGE // if (newRank == N-1) break; if (newRank == N-1) pos = N; } // Fill suffix array for (int i = 0; i < N; i++) { sa[i] = ranks[i].originalIndex; ranks[i] = null; } // Cleanup suffixRanks = null; // CHANGE // suffixRanks[0] = suffixRanks[1] = null; suffixRanks = null; ranks = null; } // Constructs the LCP (longest common prefix) array in linear time - O(n) private void kasai() { lcp = new int[N]; // Compute inverse index values int [] inv = new int[N]; for (int i = 0; i < N; i++) inv[sa[i]] = i; // Current lcp length int len = 0; for (int i = 0; i < N; i++) { if (inv[i] > 0) { // Get the index of where the suffix below is int k = sa[inv[i]-1]; // Compute lcp length. For most loops this is O(1) while( (i + len < N) && (k + len < N) && T[i+len] == T[k+len] ) len++; lcp[inv[i]-1] = len; if (len > 0) len } } } // // Runs on O(mlog(n)) where m is the length of the substring // // and n is the length of the text. // // NOTE: This is the naive implementation. There exists an // // implementation which runs in O(m + log(n)) time // public boolean contains(String substr) { // if (substr == null) return false; // if (substr.equals("")) return true; // String suffix_str; // int lo = 0, hi = N - 1; // int substr_len = substr.length(); // while( lo <= hi ) { // int mid = (lo + hi) / 2; // int suffix_index = sa[mid]; // int suffix_len = N - suffix_index; // // CHANGE // char[] tmp = new char[T.length]; // for (int i=0; i<T.length; i++) { // tmp[i] = (char) T[i]; // // Extract part of the suffix we need to compare // if (suffix_len <= substr_len) suffix_str = new String(tmp, suffix_index, suffix_len); // else suffix_str = new String(tmp, suffix_index, substr_len); // // CHANGE // // if (suffix_len <= substr_len) suffix_str = new String(T, suffix_index, suffix_len); // // else suffix_str = new String(T, suffix_index, substr_len); // int cmp = suffix_str.compareTo(substr); // // Found a match // if ( cmp == 0 ) { // // To find the first occurrence linear scan up/down // // from here or keep doing binary search // return true; // // Substring is found above // } else if (cmp < 0) { // lo = mid + 1; // // Substring is found below // } else { // hi = mid - 1; // return false; // generator public void forLoop() { // // for (int i = 0; i < blah; i++) // int t = ??; // int i = ??; // boolean b1 = i < ??; // for (int i = ??; i {| |} blah; i=i+??){ public TreeSet <String> lrs() { int[] localInts = new int[10]; Object[] localObjs = new Object[10]; return lrsGen(localInts, localObjs); } generator public int genInt(int[] localInts, Object[] localObjs, int i) { int local = localInts[??]; int i1 = lcp[??]; int i2 = lcp[i]; int i3 = lcp[local]; int i4 = T[??]; int i5 = T[local]; int i6 = T[i]; int i7 = sa[??]; int i8 = sa[i]; int i9 = sa[local]; int p = {| i, i1, i2, i3, i4, i5, i6, i7, i8, i9, local, ??, T.length, N|}; return p; } public void initVars(int[] localInts, int numLocalInts, Object[] localObjs, int numLocalObjs) { // int t = ??; if (numLocalInts < 10) { if (??) { localInts[numLocalInts] = ??; numLocalInts++; } } if (numLocalObjs < 10 && ??) { localObjs[numLocalObjs] = new TreeSet<>(); numLocalObjs++; } if (numLocalObjs < 10 && ??) { localObjs[numLocalObjs] = new Object(); numLocalObjs++; } if (numLocalObjs < 10 && ??) { localObjs[numLocalObjs] = new String(); numLocalObjs++; } } public TreeSet<String> lrsGen(int[] localInts, Object[] localObjs) { char[] tmp; if (??) { initVars(localInts, 0, localObjs, 0); } if (??) { tmp = new char[T.length]; int g1 = genInt(localInts, localObjs, 0); for (int i=0; {| i == g1 | i < g1 | i <= g1 | i > g1 | i >= g1 |}; i++) { char r = (char) genInt(localInts, localObjs, i); if (??) { tmp[??] = r; } if (??) { tmp[i] = r; } } } if (??) { int g1 = genInt(localInts, localObjs, 0); for (int i=0; {| i == g1 | i < g1 | i <= g1 | i > g1 | i >= g1 |}; i++) { boolean comp1 = genGuard(localInts, localObjs, i); boolean comp2 = genGuard(localInts, localObjs, i); if (comp1) { if (comp2) { genStmt(localInts, localObjs, i, tmp); // TreeSet<String> lrss = (TreeSet<String>) localObjs[0]; // lrss.clear(); // genStmts(localInts, localObjs, i, tmp); } // genStmts(localInts, localObjs, i, tmp); TreeSet<String> lrss = (TreeSet<String>) localObjs[0]; localInts[0] = lcp[i]; lrss.add(new String(tmp, sa[i], localInts[0])); } } } if (??) { return (TreeSet<String>) localObjs[??]; } return null; } generator public boolean genGuard(int[] localInts, Object[] localObjs, int i) { int i1 = genInt(localInts, localObjs, i); int i2 = genInt(localInts, localObjs, i); return {| i1 == i2, i1 < i2, i1 <= i2 |}; } generator public void genStmt(int[] localInts, Object[] localObjs, int i, char[] tmp) { if (??) { TreeSet<String> lrss = (TreeSet<String>) localObjs[??]; lrss.clear(); } if (??) { int i1 = genInt(localInts, localObjs, i); localInts[??] = i1; } if (??) { TreeSet<String> lrss = (TreeSet<String>) localObjs[??]; int index1 = genInt(localInts, localObjs, i); int index2 = genInt(localInts, localObjs, i); lrss.add(new String(tmp, index1, index2)); } } generator public void genStmts(int[] localInts, Object[] localObjs, int i, char[] tmp) { if (??) { genStmt(localInts, localObjs, i, tmp); } if (??) { genStmts(localInts, localObjs, i, tmp); } } generator public void forBody(int[] localInts, Object[] localObjs, int i, char[] tmp) { if (??) { boolean comp1 = genGuard(localInts, localObjs, i); boolean comp2 = genGuard(localInts, localObjs, i); if (comp1) { // if (lcp[i] > 0 && lcp[i] >= localInts[0]) { // forBody(localInts, localObjs, i, tmp); // if (lcp[i] > localInts[0]) { if (comp2) { // TreeSet<String> lrss = (TreeSet<String>) localObjs[0]; TreeSet<String> lrss = (TreeSet<String>) localObjs[??]; lrss.clear(); } int local3 = localInts[??]; int i13 = lcp[??]; int i23 = lcp[i]; int i33 = lcp[local3]; int i43 = T[??]; int i53 = T[local3]; int i63 = T[i]; int i73 = sa[??]; int i83 = sa[i]; int i93 = sa[local3]; int p13 = {| i, i13, i23, i33, i43, i53, i63, i73, i83, i93, local3 |}; localInts[??] = p13; TreeSet<String> lrss = (TreeSet<String>) localObjs[??]; int local4 = localInts[??]; int i14 = lcp[??]; int i24 = lcp[i]; int i34 = lcp[local4]; int i44 = T[??]; int i54 = T[local4]; int i64 = T[i]; int i74 = sa[??]; int i84 = sa[i]; int i94 = sa[local4]; int index1 = {| i, i14, i24, i34, i44, i54, i64, i74, i84, i94, local4 |}; int index2 = {| i, i14, i24, i34, i44, i54, i64, i74, i84, i94, local4 |}; lrss.add(new String(tmp, index1, index2)); // TreeSet<String> lrss = (TreeSet<String>) localObjs[0]; // localInts[0] = i2; // lrss.add(new String(tmp, sa[i], localInts[0])); } } if (??) { TreeSet<String> lrss = (TreeSet<String>) localObjs[??]; lrss.clear(); } if (??) { int local = localInts[??]; int i1 = lcp[??]; int i2 = lcp[i]; int i3 = lcp[local]; int i4 = T[??]; int i5 = T[local]; int i6 = T[i]; int i7 = sa[??]; int i8 = sa[i]; int i9 = sa[local]; int p1 = {| i, i1, i2, i3, i4, i5, i6, i7, i8, i9, local |}; // localInts[??] = p1; localInts[0] = i2; } if (??) { // TreeSet<String> lrss = (TreeSet<String>) localObjs[??]; TreeSet<String> lrss = (TreeSet<String>) localObjs[0]; int local = localInts[??]; int i1 = lcp[??]; int i2 = lcp[i]; int i3 = lcp[local]; int i4 = T[??]; int i5 = T[local]; int i6 = T[i]; int i7 = sa[??]; int i8 = sa[i]; int i9 = sa[local]; int index1 = {| i, i1, i2, i3, i4, i5, i6, i7, i8, i9, local |}; int index2 = {| i, i1, i2, i3, i4, i5, i6, i7, i8, i9, local |}; // lrss.add(new String(tmp, index1, index2)); lrss.add(new String(tmp, sa[i], localInts[0])); } if (??) { forBody(localInts, localObjs, i, tmp); } } // Finds the LRS(s) (Longest Repeated Substring) that occurs in a string. // Traditionally we are only interested in substrings that appear at // least twice, so this method returns an empty set if this is the case. // @return an ordered set of longest repeated substrings public TreeSet <String> lrs2() { int[] localInts = new int[10]; Object[] localObjs = new Object[10]; initVars(localInts, 0, localObjs, 0); // int max_len = 0; // TreeSet <String> lrss = new TreeSet<>(); int max_len = localInts[??]; TreeSet <String> lrss = localObjs[??]; char[] tmp = new char[T.length]; // CHANGE // int g1 = {| T.length, N, max_len, ?? |}; // for (int i=??; i<g1; i=i+??) { for (int i=0; i<T.length; i++) { tmp[i] = (char) T[i]; } // int g2 = {| T.length, N, max_len, ?? |}; // for (int i = ??; i < g2; i=i+??) { for (int i = 0; i < N; i++) { // if (lcp[i] > ?? && lcp[i] >= max_len) { if (lcp[i] > 0 && lcp[i] >= max_len) { // We found a longer LRS if ( lcp[i] > max_len ) { lrss.clear(); } // Append substring to the list and update max max_len = lcp[i]; // CHANGE lrss.add( new String(tmp, sa[i], max_len) ); // lrss.add( new String(T, sa[i], max_len) ); } } return lrss; } // // /** // // * Finds the Longest Common Substring (LCS) between a group of strings. // // * The current implementation takes O(nlog(n)) bounded by the suffix array construction. // // * @param strs - The strings you wish to find the longest common substring between // // * @param K - The minimum number of strings to find the LCS between. K must be at least 2. // // **/ // public static TreeSet<String> lcs(String [] strs, int K) { // // CHANGE // if (K <= 1) { // return null; // TreeSet<String> lcss = new TreeSet(); // if (strs == null || strs.length <= 1) return lcss; // // L is the concatenated length of all the strings and the sentinels // int L = 0; // final int NUM_SENTINELS = strs.length, N = strs.length; // for(int i = 0; i < N; i++) L += strs[i].length() + 1; // int[] indexMap = new int[L]; // // CHANGE // int LOWEST_ASCII = 1000; // // int LOWEST_ASCII = Integer.MAX_VALUE; // int k = 0; // // Find the lowest ASCII value within the strings. // // Also construct the index map to know which original // // string a given suffix belongs to. // for (int i = 0; i < strs.length; i++) { // String str = strs[i]; // for (int j = 0; j < str.length(); j++) { // int asciiVal = str.charAt(j); // if (asciiVal < LOWEST_ASCII) LOWEST_ASCII = asciiVal; // indexMap[k] = i; // // Record that the sentinel belongs to string i // indexMap[k] = i; // final int SHIFT = LOWEST_ASCII + NUM_SENTINELS + 1; // int sentinel = 0; // int[] T = new int[L]; // // CHANGE // k = 0; // // Construct the new text with the shifted values and the sentinels // for(int i = 0; i < N; i++) { // // for(int i = 0, k = 0; i < N; i++) { // String str = strs[i]; // for (int j = 0; j < str.length(); j++) { // T[k] = ((int)str.charAt(j)) + SHIFT; // T[k] = sentinel; // sentinel++; // // CHANGE // String tmp = intArrToString(T); // SuffixArray sa = new SuffixArray(tmp); // // // SuffixArray sa = new SuffixArray(T); // ArrayDeque <Integer> deque = new ArrayDeque<>(); // HashMap <Integer, Integer> windowColorCount = new HashMap<>(); // HashSet <Integer> windowColors = new HashSet<>(); // // Start the sliding window at the number of sentinels because those // // all get sorted first and we want to ignore them // int lo = NUM_SENTINELS, hi = NUM_SENTINELS, bestLCSLength = 0; // // Add the first color // int firstColor = indexMap[sa.sa[hi]]; // windowColors.add(new Integer(firstColor)); // windowColorCount.put(new Integer(firstColor), new Integer(1)); // int count = 0; // // Maintain a sliding window between lo and hi // while(hi < L) { // int uniqueColors = windowColors.size(); // // Attempt to update the LCS // if (uniqueColors >= K) { // // CHANGE // Integer deqPeekFirst = deque.peekFirst(); // int deqPeekFirst_int = deqPeekFirst.intValue(); // int windowLCP = sa.lcp[deqPeekFirst_int]; // // int windowLCP = sa.lcp[deque.peekFirst()]; // if (windowLCP > 0 && bestLCSLength < windowLCP) { // bestLCSLength = windowLCP; // lcss.clear(); // if (windowLCP > 0 && bestLCSLength == windowLCP) { // // Construct the current LCS within the window interval // int pos = sa.sa[lo]; // char[] lcs = new char[windowLCP]; // for (int i = 0; i < windowLCP; i++) lcs[i] = (char)(T[pos+i] - SHIFT); // // CHANGE // lcss.add(new String(lcs, 0, lcs.length)); // // lcss.add(new String(lcs)); // // If you wish to find the original strings to which this longest // // common substring belongs to the indexes of those strings can be // // found in the windowColors set, so just use those indexes on the 'strs' array // // Update the colors in our window // int lastColor = indexMap[sa.sa[lo]]; // // CHANGE // Integer colorCount = windowColorCount.get(new Integer(lastColor)); // // Integer colorCount = windowColorCount.get(lastColor); // int check = colorCount.intValue(); // // CHANGE // boolean removed = false; // if (colorCount.intValue() == 1) { // windowColors.remove(new Integer(lastColor)); // removed = true; // // if (colorCount == 1) windowColors.remove(lastColor); // // CHANGE // windowColorCount.put(new Integer(lastColor), new Integer(colorCount.intValue() - 1)); // // windowColorCount.put(lastColor, colorCount - 1); // // CHANGE // if (!deque.isEmpty()) { // // CHANGE // deqPeekFirst = deque.peekFirst(); // boolean deqPeekLessThanLo = deqPeekFirst.intValue() <= lo; // // Remove the head if it's outside the new range: [lo+1, hi) // while (!deque.isEmpty() && deqPeekLessThanLo) { // deque.removeFirst(); // deqPeekFirst = deque.peekFirst(); // if (deqPeekFirst != null) { // deqPeekLessThanLo = deqPeekFirst.intValue() <= lo; // } else { // deqPeekLessThanLo = false; // // Decrease the window size // // Increase the window size because we don't have enough colors // } else if(hi+1 < L) { // int nextColor = indexMap[sa.sa[hi]]; // // CHANGE // Integer nextColor_Int = new Integer(nextColor); // // Update the colors in our window // // CHANGE // windowColors.add(nextColor_Int); // // windowColors.add(nextColor); // // CHANGE // Integer colorCount = windowColorCount.get(nextColor_Int); // // Integer colorCount = windowColorCount.get(nextColor); // // CHANGE // if (colorCount == null) colorCount = new Integer(0); // // if (colorCount == null) colorCount = 0; // // CHANGE // windowColorCount.put(nextColor_Int, new Integer(colorCount.intValue() + 1)); // // windowColorCount.put(nextColor, colorCount + 1); // // CHANGE // if (!deque.isEmpty()) { // // CHANGE // Integer deqPeekLast = deque.peekLast(); // int deqPeekLast_int = deqPeekLast.intValue(); // // CHANGE // // Remove all the worse values in the back of the deque // while(!deque.isEmpty() && sa.lcp[deqPeekLast_int] > sa.lcp[hi-1]) { // // while(!deque.isEmpty() && sa.lcp[deque.peekLast()] > sa.lcp[hi-1]) // deque.removeLast(); // // CHANGE // if (!deque.isEmpty()) { // deqPeekLast = deque.peekLast(); // deqPeekLast_int = deqPeekLast.intValue(); // // CHANGE // deque.addLast(new Integer(hi-1)); // // deque.addLast(hi-1); // count++; // return lcss; // // public void display() { // // for(int i = 0; i < N; i++) { // // int suffixLen = N - sa[i]; // // String suffix = new String(T, sa[i], suffixLen); // // System.out.printf("% 7d % 7d % 7d %s\n", i, sa[i],lcp[i], suffix ); // // CHANGE // // // public static void main(String[] args){ // // harness public static void main() { // // // String[] strs = { "GAGL", "RGAG", "TGAGE" }; // // String[] strs = { "AAGAAGC", "AGAAGT", "CGAAGC" }; // // // String[] strs = { "abca", "bcad", "daca" }; // // // String[] strs = { "abca", "bcad", "daca" }; // // // String[] strs = { "AABC", "BCDC", "BCDE", "CDED" }; // // // String[] strs = { "abcdefg", "bcdefgh", "cdefghi" }; // // // String[] strs = { "xxx", "yyy", "zzz" }; // // TreeSet <String> lcss = SuffixArray.lcs(strs, 2); // // // System.out.println(lcss); // // // SuffixArray sa = new SuffixArray("abracadabra"); // // // System.out.println(sa); // // // System.out.println(java.util.Arrays.toString(sa.sa)); // // // System.out.println(java.util.Arrays.toString(sa.lcp)); // // // SuffixArray sa = new SuffixArray("ababcabaa"); // // // sa.display(); }
package placebooks.client.ui.items; import placebooks.client.model.PlaceBookItem; import placebooks.client.resources.Resources; import placebooks.client.ui.widget.RichTextArea; import com.google.gwt.event.dom.client.BlurEvent; import com.google.gwt.event.dom.client.BlurHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.FocusEvent; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; public class EditableTextItem extends PlaceBookItemWidget { private RichTextArea textPanel = new RichTextArea(""); EditableTextItem(final PlaceBookItem item) { super(item); initWidget(textPanel); textPanel.setStyleName(Resources.INSTANCE.style().textitem()); textPanel.addDomHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { event.stopPropagation(); fireFocusChanged(true); } }, ClickEvent.getType()); textPanel.addFocusHandler(new com.google.gwt.event.dom.client.FocusHandler() { @Override public void onFocus(final FocusEvent event) { fireFocusChanged(true); event.stopPropagation(); } }); textPanel.addBlurHandler(new BlurHandler() { @Override public void onBlur(final BlurEvent event) { fireFocusChanged(false); } }); textPanel.addKeyUpHandler(new KeyUpHandler() { @Override public void onKeyUp(final KeyUpEvent event) { item.setText(textPanel.getElement().getInnerHTML()); fireResized(); fireChanged(); } }); } @Override public void refresh() { textPanel.getElement().setInnerHTML(item.getText()); } @Override public String resize() { super.resize(); if (getParent() != null && getParent().getParent() != null) { final String panelWidthString = getParent().getParent().getElement().getStyle().getWidth(); double panelWidth = 300; if(panelWidthString != null && panelWidthString.endsWith("%")) { double percent = Double.parseDouble(panelWidthString.substring(0,panelWidthString.length() - 1)); panelWidth = (900d * 100d) / percent; } final double scale = getParent().getOffsetWidth() / panelWidth; textPanel.getElement().setAttribute("style", "width: " + panelWidth + "px; -webkit-transform-origin: 0% 0%; -webkit-transform: scale(" + scale + ")"); return (getOffsetHeight() * scale) + "px"; } return null; } }
package com.intellij.diagnostic; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationInfo; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.application.impl.ApplicationInfoImpl; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.Consumer; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.concurrency.AppScheduledExecutorService; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.management.ListenerNotFoundException; import javax.management.Notification; import javax.management.NotificationEmitter; import javax.management.NotificationListener; import javax.swing.*; import java.io.File; import java.io.IOException; import java.lang.management.ManagementFactory; import java.lang.management.MemoryPoolMXBean; import java.lang.management.ThreadMXBean; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Objects; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** * @author yole */ public class PerformanceWatcher implements Disposable { private static final Logger LOG = Logger.getInstance(PerformanceWatcher.class); private static final int TOLERABLE_LATENCY = 100; private static final String THREAD_DUMPS_PREFIX = "threadDumps-"; private ScheduledFuture<?> myThread; private ScheduledFuture<?> myDumpTask; private final ThreadMXBean myThreadMXBean = ManagementFactory.getThreadMXBean(); private final File myLogDir = new File(PathManager.getLogPath()); private List<StackTraceElement> myStacktraceCommonPart; private final IdePerformanceListener myPublisher = ApplicationManager.getApplication().getMessageBus().syncPublisher(IdePerformanceListener.TOPIC); private volatile ApdexData mySwingApdex = ApdexData.EMPTY; private volatile ApdexData myGeneralApdex = ApdexData.EMPTY; private volatile long myLastSampling = System.currentTimeMillis(); private long myLastDumpTime; private long myFreezeStart; private final AtomicInteger myEdtRequestsQueued = new AtomicInteger(0); private static final long ourIdeStart = System.currentTimeMillis(); private long myLastEdtAlive = System.currentTimeMillis(); private final ScheduledExecutorService myExecutor = AppExecutorUtil.createBoundedScheduledExecutorService("EDT Performance Checker", 1); private Future myCurrentEDTEventChecker; private static final boolean PRECISE_MODE = shouldWatch() && Registry.is("performance.watcher.precise"); public static PerformanceWatcher getInstance() { return ApplicationManager.getApplication().getComponent(PerformanceWatcher.class); } public PerformanceWatcher() { if (!shouldWatch()) return; AppScheduledExecutorService service = (AppScheduledExecutorService)AppExecutorUtil.getAppScheduledExecutorService(); service.setNewThreadListener(new Consumer<Thread>() { private final int ourReasonableThreadPoolSize = Registry.intValue("core.pooled.threads"); @Override public void consume(Thread thread) { if (service.getBackendPoolExecutorSize() > ourReasonableThreadPoolSize && ApplicationInfoImpl.getShadowInstance().isEAP()) { File file = dumpThreads("newPooledThread/", true); LOG.info("Not enough pooled threads" + (file != null ? "; dumped threads into file '" + file.getPath() + "'" : "")); } } }); ApplicationManager.getApplication().executeOnPooledThread(() -> { for (MemoryPoolMXBean bean : ManagementFactory.getMemoryPoolMXBeans()) { if ("Code Cache".equals(bean.getName())) { watchCodeCache(bean); break; } } cleanOldFiles(myLogDir, 0); }); myThread = myExecutor.scheduleWithFixedDelay(this::samplePerformance, getSamplingInterval(), getSamplingInterval(), TimeUnit.MILLISECONDS); } private static int getMaxAttempts() { return Registry.intValue("performance.watcher.unresponsive.max.attempts.before.log"); } private void watchCodeCache(final MemoryPoolMXBean bean) { final long threshold = bean.getUsage().getMax() - 5 * 1024 * 1024; if (!bean.isUsageThresholdSupported() || threshold <= 0) return; bean.setUsageThreshold(threshold); final NotificationEmitter emitter = (NotificationEmitter)ManagementFactory.getMemoryMXBean(); emitter.addNotificationListener(new NotificationListener() { @Override public void handleNotification(Notification n, Object hb) { if (bean.getUsage().getUsed() > threshold) { LOG.info("Code Cache is almost full"); dumpThreads("codeCacheFull", true); try { emitter.removeNotificationListener(this); } catch (ListenerNotFoundException e) { LOG.error(e); } } } }, null, null); } private static void cleanOldFiles(File dir, final int level) { File[] children = dir.listFiles((dir1, name) -> level > 0 || name.startsWith(THREAD_DUMPS_PREFIX)); if (children == null) return; Arrays.sort(children); for (int i = 0; i < children.length; i++) { File child = children[i]; if (i < children.length - 100 || ageInDays(child) > 10) { FileUtil.delete(child); } else if (level < 3) { cleanOldFiles(child, level + 1); } } } private static long ageInDays(File file) { return TimeUnit.DAYS.convert(System.currentTimeMillis() - file.lastModified(), TimeUnit.MILLISECONDS); } @Override public void dispose() { if (myThread != null) { myThread.cancel(true); } myExecutor.shutdownNow(); } private static boolean shouldWatch() { return !ApplicationManager.getApplication().isHeadlessEnvironment() && Registry.intValue("performance.watcher.unresponsive.interval.ms") != 0 && getMaxAttempts() != 0; } private void samplePerformance() { long millis = System.currentTimeMillis(); long diff = millis - myLastSampling - getSamplingInterval(); myLastSampling = millis; // an unexpected delay of 3 seconds is considered as several delays: of 3, 2 and 1 seconds, because otherwise // this background thread would be sampled 3 times. while (diff >= 0) { myGeneralApdex = myGeneralApdex.withEvent(TOLERABLE_LATENCY, diff); diff -= getSamplingInterval(); } if (!PRECISE_MODE) { int edtRequests = myEdtRequestsQueued.get(); if (edtRequests >= getMaxAttempts()) { edtFrozen(millis); } else if (edtRequests == 0) { edtResponds(millis); } } myEdtRequestsQueued.incrementAndGet(); //noinspection SSBasedInspection SwingUtilities.invokeLater(new SwingThreadRunnable(millis)); } @NotNull public static String printStacktrace(@NotNull String headerMsg, @NotNull Thread thread, @NotNull StackTraceElement[] stackTrace) { @SuppressWarnings("NonConstantStringShouldBeStringBuffer") String trace = headerMsg + thread + " (" + (thread.isAlive() ? "alive" : "dead") + ") " + thread.getState() + "\n--- its stacktrace:\n"; for (final StackTraceElement stackTraceElement : stackTrace) { trace += " at " + stackTraceElement + "\n"; } trace += " return trace; } private static int getSamplingInterval() { return Registry.intValue("performance.watcher.sampling.interval.ms"); } static int getDumpInterval() { return getSamplingInterval() * getMaxAttempts(); } private void edtFrozen(long currentMillis) { if (currentMillis - myLastDumpTime >= Registry.intValue("performance.watcher.unresponsive.interval.ms")) { myLastDumpTime = currentMillis; if (myFreezeStart == 0) { myFreezeStart = myLastEdtAlive; myPublisher.uiFreezeStarted(); } dumpThreads(); } } private void edtFrozenPrecise(long start) { myFreezeStart = start; myPublisher.uiFreezeStarted(); stopDumping(); myDumpTask = myExecutor.scheduleWithFixedDelay(this::dumpThreads, 0, getDumpInterval(), TimeUnit.MILLISECONDS); } @NotNull private static String getFreezeFolderName(long freezeStartMs) { return THREAD_DUMPS_PREFIX + "freeze-" + formatTime(freezeStartMs) + "-" + buildName(); } private static String buildName() { return ApplicationInfo.getInstance().getBuild().asString(); } private static String formatTime(long timeMs) { return new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date(timeMs)); } private void stopDumping() { if (myDumpTask != null) { myDumpTask.cancel(false); } } private void edtResponds(long currentMillis) { stopDumping(); if (myFreezeStart != 0) { int unresponsiveDuration = (int)(currentMillis - myFreezeStart) / 1000; File dir = new File(myLogDir, getFreezeFolderName(myFreezeStart)); File reportDir = null; if (dir.exists()) { reportDir = new File(myLogDir, dir.getName() + getFreezePlaceSuffix() + "-" + unresponsiveDuration + "sec"); if (!dir.renameTo(reportDir)) { reportDir = null; } } myPublisher.uiFreezeFinished(currentMillis - myFreezeStart, reportDir); myFreezeStart = 0; myStacktraceCommonPart = null; } } public void edtEventStarted(long start) { if (PRECISE_MODE) { if (myCurrentEDTEventChecker != null) { myCurrentEDTEventChecker.cancel(false); } myCurrentEDTEventChecker = myExecutor .schedule(() -> edtFrozenPrecise(start), Registry.intValue("performance.watcher.unresponsive.interval.ms"), TimeUnit.MILLISECONDS); } } public void edtEventFinished() { if (myCurrentEDTEventChecker != null) { if (!myCurrentEDTEventChecker.cancel(false)) { long end = System.currentTimeMillis(); try { myExecutor.submit(() -> edtResponds(end)).get(); } catch (Exception e) { LOG.warn(e); } } myCurrentEDTEventChecker = null; } } private String getFreezePlaceSuffix() { if (myStacktraceCommonPart != null && !myStacktraceCommonPart.isEmpty()) { final StackTraceElement element = myStacktraceCommonPart.get(0); return "-" + StringUtil.getShortName(element.getClassName()) + "." + element.getMethodName(); } return ""; } private void dumpThreads() { dumpThreads(getFreezeFolderName(myFreezeStart) + "/", false); } @Nullable public File dumpThreads(@NotNull String pathPrefix, boolean millis) { if (!shouldWatch()) return null; if (!pathPrefix.contains("/")) { pathPrefix = THREAD_DUMPS_PREFIX + pathPrefix + "-" + formatTime(ourIdeStart) + "-" + buildName() + "/"; } else if (!pathPrefix.startsWith(THREAD_DUMPS_PREFIX)) { pathPrefix = THREAD_DUMPS_PREFIX + pathPrefix; } long now = System.currentTimeMillis(); String suffix = millis ? "-" + now : ""; File file = new File(myLogDir, pathPrefix + "threadDump-" + formatTime(now) + suffix + ".txt"); File dir = file.getParentFile(); if (!(dir.isDirectory() || dir.mkdirs())) { return null; } checkMemoryUsage(file); ThreadDump threadDump = ThreadDumper.getThreadDumpInfo(myThreadMXBean); try { FileUtil.writeToFile(file, threadDump.getRawDump()); StackTraceElement[] edtStack = threadDump.getEDTStackTrace(); if (edtStack != null) { if (myStacktraceCommonPart == null) { myStacktraceCommonPart = ContainerUtil.newArrayList(edtStack); } else { myStacktraceCommonPart = getStacktraceCommonPart(myStacktraceCommonPart, edtStack); } } myPublisher.dumpedThreads(file, threadDump); } catch (IOException e) { LOG.info("failed to write thread dump file: " + e.getMessage()); } return file; } private static void checkMemoryUsage(File file) { Runtime rt = Runtime.getRuntime(); long maxMemory = rt.maxMemory(); long usedMemory = rt.totalMemory() - rt.freeMemory(); long freeMemory = maxMemory - usedMemory; if (freeMemory < maxMemory / 5) { LOG.info("High memory usage (free " + freeMemory / 1024 / 1024 + " of " + maxMemory / 1024 / 1024 + " MB) while dumping threads to " + file); } } @SuppressWarnings("UseOfSystemOutOrSystemErr") public static void dumpThreadsToConsole(String message) { System.err.println(message); System.err.println(ThreadDumper.dumpThreadsToString()); } static List<StackTraceElement> getStacktraceCommonPart(final List<StackTraceElement> commonPart, final StackTraceElement[] stackTraceElements) { for (int i = 0; i < commonPart.size() && i < stackTraceElements.length; i++) { StackTraceElement el1 = commonPart.get(commonPart.size() - i - 1); StackTraceElement el2 = stackTraceElements[stackTraceElements.length - i - 1]; if (!compareStackTraceElements(el1, el2)) { return commonPart.subList(commonPart.size() - i, commonPart.size()); } } return commonPart; } // same as java.lang.StackTraceElement.equals, but do not care about the line number static boolean compareStackTraceElements(StackTraceElement el1, StackTraceElement el2) { if (el1 == el2) { return true; } return el1.getClassName().equals(el2.getClassName()) && Objects.equals(el1.getMethodName(), el2.getMethodName()) && Objects.equals(el1.getFileName(), el2.getFileName()); } private class SwingThreadRunnable implements Runnable { private final long myCreationMillis; SwingThreadRunnable(long creationMillis) { myCreationMillis = creationMillis; } @Override public void run() { myEdtRequestsQueued.decrementAndGet(); myLastEdtAlive = System.currentTimeMillis(); final long latency = System.currentTimeMillis() - myCreationMillis; mySwingApdex = mySwingApdex.withEvent(TOLERABLE_LATENCY, latency); final Application application = ApplicationManager.getApplication(); if (application.isDisposed()) return; application.getMessageBus().syncPublisher(IdePerformanceListener.TOPIC).uiResponded(latency); } } public class Snapshot { private final ApdexData myStartGeneralSnapshot = myGeneralApdex; private final ApdexData myStartSwingSnapshot = mySwingApdex; private final long myStartMillis = System.currentTimeMillis(); private Snapshot() { } public void logResponsivenessSinceCreation(@NotNull String activityName) { LOG.info(activityName + " took " + (System.currentTimeMillis() - myStartMillis) + "ms" + "; general responsiveness: " + myGeneralApdex.summarizePerformanceSince(myStartGeneralSnapshot) + "; EDT responsiveness: " + mySwingApdex.summarizePerformanceSince(myStartSwingSnapshot)); } } @NotNull public static Snapshot takeSnapshot() { return getInstance().new Snapshot(); } ScheduledExecutorService getExecutor() { return myExecutor; } }
package com.intellij.ide.plugins; import com.intellij.core.CoreBundle; import com.intellij.diagnostic.Activity; import com.intellij.diagnostic.LoadingState; import com.intellij.diagnostic.PluginException; import com.intellij.diagnostic.StartUpMeasurer; import com.intellij.ide.plugins.cl.PluginAwareClassLoader; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.application.impl.ApplicationInfoImpl; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.ExtensionsArea; import com.intellij.openapi.extensions.PluginDescriptor; import com.intellij.openapi.extensions.PluginId; import com.intellij.openapi.extensions.impl.ExtensionPointImpl; import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.BuildNumber; import com.intellij.openapi.util.NlsContexts; import com.intellij.openapi.util.NlsSafe; import com.intellij.openapi.util.SystemInfoRt; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.util.text.HtmlChunk; import com.intellij.reference.SoftReference; import com.intellij.util.ArrayUtil; import com.intellij.util.ArrayUtilRt; import com.intellij.util.PlatformUtils; import com.intellij.util.ReflectionUtil; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.execution.ParametersListUtil; import com.intellij.util.graph.DFSTBuilder; import com.intellij.util.graph.GraphGenerator; import com.intellij.util.graph.InboundSemiGraph; import com.intellij.util.lang.UrlClassLoader; import org.jetbrains.annotations.*; import java.io.*; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.lang.ref.Reference; import java.net.URL; import java.nio.file.*; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; // Prefer to use only JDK classes. Any post start-up functionality should be placed in PluginManager class. public final class PluginManagerCore { public static final @NonNls String META_INF = "META-INF/"; public static final String IDEA_IS_INTERNAL_PROPERTY = "idea.is.internal"; public static final PluginId CORE_ID = PluginId.getId("com.intellij"); public static final String CORE_PLUGIN_ID = "com.intellij"; public static final PluginId JAVA_PLUGIN_ID = PluginId.getId("com.intellij.java"); static final PluginId JAVA_MODULE_ID = PluginId.getId("com.intellij.modules.java"); public static final String PLUGIN_XML = "plugin.xml"; public static final String PLUGIN_XML_PATH = META_INF + PLUGIN_XML; static final PluginId ALL_MODULES_MARKER = PluginId.getId("com.intellij.modules.all"); public static final String VENDOR_JETBRAINS = "JetBrains"; public static final String VENDOR_JETBRAINS_SRO = "JetBrains s.r.o."; private static final String MODULE_DEPENDENCY_PREFIX = "com.intellij.module"; private static final PluginId SPECIAL_IDEA_PLUGIN_ID = PluginId.getId("IDEA CORE"); static final String PROPERTY_PLUGIN_PATH = "plugin.path"; public static final @NonNls String DISABLE = "disable"; public static final @NonNls String ENABLE = "enable"; public static final @NonNls String EDIT = "edit"; private static final boolean IGNORE_DISABLED_PLUGINS = Boolean.getBoolean("idea.ignore.disabled.plugins"); private static final MethodType HAS_LOADED_CLASS_METHOD_TYPE = MethodType.methodType(boolean.class, String.class); private static Reference<Map<PluginId, Set<String>>> ourBrokenPluginVersions; private static volatile IdeaPluginDescriptorImpl[] ourPlugins; private static volatile @Nullable Set<IdeaPluginDescriptorImpl> pluginIdentitySetCache; private static volatile List<IdeaPluginDescriptorImpl> ourLoadedPlugins; private static Map<PluginId, PluginLoadingError> ourPluginLoadingErrors; private static Map<String, String[]> ourAdditionalLayoutMap = Collections.emptyMap(); @SuppressWarnings("StaticNonFinalField") public static volatile boolean isUnitTestMode = Boolean.getBoolean("idea.is.unit.test"); @ApiStatus.Internal static final boolean usePluginClassLoader = Boolean.getBoolean("idea.from.sources.plugins.class.loader"); @ApiStatus.Internal private static final List<Supplier<? extends HtmlChunk>> ourPluginErrors = new ArrayList<>(); @SuppressWarnings("StaticNonFinalField") @ApiStatus.Internal public static Set<PluginId> ourPluginsToDisable; @SuppressWarnings("StaticNonFinalField") @ApiStatus.Internal public static Set<PluginId> ourPluginsToEnable; @SuppressWarnings("StaticNonFinalField") @ApiStatus.Internal public static boolean ourDisableNonBundledPlugins; /** * Bundled plugins that were updated. * When we update bundled plugin it becomes not bundled, so it is more difficult for analytics to use that data. */ private static Set<PluginId> ourShadowedBundledPlugins; private static Boolean isRunningFromSources; private static volatile CompletableFuture<DescriptorListLoadingContext> descriptorListFuture; private static BuildNumber ourBuildNumber; @ApiStatus.Internal public static @Nullable String getPluginsCompatibleBuild() { return System.getProperty("idea.plugins.compatible.build"); } /** * Returns list of all available plugin descriptors (bundled and custom, include disabled ones). Use {@link #getLoadedPlugins()} * if you need to get loaded plugins only. * * <p> * Do not call this method during bootstrap, should be called in a copy of PluginManager, loaded by PluginClassLoader. */ public static @NotNull IdeaPluginDescriptor @NotNull[] getPlugins() { IdeaPluginDescriptor[] result = ourPlugins; if (result == null) { loadAndInitializePlugins(null, null); return ourPlugins; } return result; } static @NotNull Collection<IdeaPluginDescriptorImpl> getAllPlugins() { return Arrays.asList(ourPlugins); } static boolean hasDescriptorByIdentity(@NotNull IdeaPluginDescriptorImpl descriptor) { Set<IdeaPluginDescriptorImpl> cache = pluginIdentitySetCache; if (cache == null) { IdeaPluginDescriptorImpl[] allPlugins = ourPlugins; cache = Collections.newSetFromMap(new IdentityHashMap<>(allPlugins.length)); Collections.addAll(cache, allPlugins); pluginIdentitySetCache = cache; } return cache.contains(descriptor); } /** * Returns descriptors of plugins which are successfully loaded into IDE. The result is sorted in a way that if each plugin comes after * the plugins it depends on. */ public static @NotNull List<? extends IdeaPluginDescriptor> getLoadedPlugins() { return getLoadedPlugins(null); } @ApiStatus.Internal public static @NotNull List<IdeaPluginDescriptorImpl> getLoadedPlugins(@Nullable ClassLoader coreClassLoader) { List<IdeaPluginDescriptorImpl> result = ourLoadedPlugins; if (result == null) { loadAndInitializePlugins(null, coreClassLoader); return ourLoadedPlugins; } return result; } @ApiStatus.Internal public static @NotNull List<HtmlChunk> getAndClearPluginLoadingErrors() { synchronized (ourPluginErrors) { List<HtmlChunk> errors = ContainerUtil.map(ourPluginErrors, Supplier::get); ourPluginErrors.clear(); return errors; } } private static void registerPluginErrors(List<? extends Supplier<? extends HtmlChunk>> errors) { synchronized (ourPluginErrors) { ourPluginErrors.addAll(errors); } } @ApiStatus.Internal public static boolean arePluginsInitialized() { return ourPlugins != null; } static synchronized void doSetPlugins(@NotNull IdeaPluginDescriptorImpl @Nullable [] value) { ourPlugins = value; ourLoadedPlugins = value == null ? null : Collections.unmodifiableList(getOnlyEnabledPlugins(value)); pluginIdentitySetCache = null; } public static boolean isDisabled(@NotNull PluginId pluginId) { return DisabledPluginsState.isDisabled(pluginId); } public static boolean isBrokenPlugin(@NotNull IdeaPluginDescriptor descriptor) { PluginId pluginId = descriptor.getPluginId(); if (pluginId == null) { return true; } Set<String> set = getBrokenPluginVersions().get(pluginId); return set != null && set.contains(descriptor.getVersion()); } public static void updateBrokenPlugins(Map<PluginId, Set<String>> brokenPlugins) { ourBrokenPluginVersions = new java.lang.ref.SoftReference<>(brokenPlugins); } private static @NotNull Map<PluginId, Set<String>> getBrokenPluginVersions() { if (IGNORE_DISABLED_PLUGINS) { return Collections.emptyMap(); } Map<PluginId, Set<String>> result = SoftReference.dereference(ourBrokenPluginVersions); if (result == null) { result = readBrokenPluginFile(); ourBrokenPluginVersions = new SoftReference<>(result); } return result; } private static @NotNull Map<PluginId, Set<String>> readBrokenPluginFile() { Path distDir = Paths.get(PathManager.getHomePath()); Path dbFile = (SystemInfoRt.isMac ? distDir.resolve("Resources") : distDir).resolve("brokenPlugins.db"); try (DataInputStream stream = new DataInputStream(new BufferedInputStream(Files.newInputStream(dbFile), 32_000))) { int version = stream.readUnsignedByte(); if (version != 1) { getLogger().error("Unsupported version of " + dbFile + "(fileVersion=" + version + ", supportedVersion=1)"); return Collections.emptyMap(); } int count = stream.readInt(); Map<PluginId, Set<String>> result = new HashMap<>(count); for (int i = 0; i < count; i++) { PluginId pluginId = PluginId.getId(stream.readUTF()); String[] versions = new String[stream.readUnsignedShort()]; for (int j = 0; j < versions.length; j++) { versions[j] = stream.readUTF(); } //noinspection SSBasedInspection result.put(pluginId, versions.length == 1 ? Collections.singleton(versions[0]) : new HashSet<>(Arrays.asList(versions))); } return result; } catch (NoSuchFileException ignore) { } catch (IOException e) { getLogger().error("Failed to read " + dbFile, e); } return Collections.emptyMap(); } public static void writePluginsList(@NotNull Collection<PluginId> ids, @NotNull Writer writer) throws IOException { List<PluginId> sortedIds = new ArrayList<>(ids); sortedIds.sort(null); for (PluginId id : sortedIds) { writer.write(id.getIdString()); writer.write('\n'); } } public static boolean disablePlugin(@NotNull PluginId id) { return DisabledPluginsState.disablePlugin(id); } public static boolean enablePlugin(@NotNull PluginId id) { return DisabledPluginsState.enablePlugin(id); } public static boolean isModuleDependency(@NotNull PluginId dependentPluginId) { return dependentPluginId.getIdString().startsWith(MODULE_DEPENDENCY_PREFIX); } /** * This is an internal method, use {@link PluginException#createByClass(String, Throwable, Class)} instead. */ @ApiStatus.Internal public static @NotNull PluginException createPluginException(@NotNull String errorMessage, @Nullable Throwable cause, @NotNull Class<?> pluginClass) { ClassLoader classLoader = pluginClass.getClassLoader(); PluginId pluginId; if (classLoader instanceof PluginAwareClassLoader) { pluginId = ((PluginAwareClassLoader)classLoader).getPluginId(); } else { pluginId = getPluginByClassName(pluginClass.getName()); } return new PluginException(errorMessage, cause, pluginId); } public static @Nullable PluginId getPluginByClassName(@NotNull String className) { PluginId id = getPluginOrPlatformByClassName(className); return (id == null || CORE_ID == id) ? null : id; } public static @Nullable PluginId getPluginOrPlatformByClassName(@NotNull String className) { PluginDescriptor result = getPluginDescriptorOrPlatformByClassName(className); return result == null ? null : result.getPluginId(); } @ApiStatus.Internal public static @Nullable PluginDescriptor getPluginDescriptorOrPlatformByClassName(@NotNull @NonNls String className) { List<IdeaPluginDescriptorImpl> loadedPlugins = ourLoadedPlugins; if (loadedPlugins == null || className.startsWith("java.") || className.startsWith("javax.") || className.startsWith("kotlin.") || className.startsWith("groovy.") || !className.contains(".")) { return null; } IdeaPluginDescriptor result = null; for (IdeaPluginDescriptorImpl o : loadedPlugins) { ClassLoader classLoader = o.getPluginClassLoader(); if (!hasLoadedClass(className, classLoader)) { continue; } result = o; break; } if (result == null) { return null; } // return if the found plugin is not "core" or the package is obviously "core" if (result.getPluginId() != CORE_ID || className.startsWith("com.jetbrains.") || className.startsWith("org.jetbrains.") || className.startsWith("com.intellij.") || className.startsWith("org.intellij.") || className.startsWith("com.android.") || className.startsWith("git4idea.") || className.startsWith("org.angularjs.")) { return result; } // otherwise we need to check plugins with use-idea-classloader="true" String root = null; for (IdeaPluginDescriptorImpl o : loadedPlugins) { if (!o.isUseIdeaClassLoader()) { continue; } if (root == null) { root = PathManager.getResourceRoot(result.getPluginClassLoader(), className.replace('.', '/') + ".class"); if (root == null) { return null; } } Path path = o.getPluginPath(); if (root.startsWith(FileUtilRt.toSystemIndependentName(path.toString()))) { return o; } } return null; } private static boolean hasLoadedClass(@NotNull String className, @NotNull ClassLoader loader) { if (loader instanceof UrlClassLoader) { return ((UrlClassLoader)loader).hasLoadedClass(className); } // it can be an UrlClassLoader loaded by another class loader, so instanceof doesn't work Class<?> aClass = loader.getClass(); if (aClass.isAnonymousClass() || aClass.isMemberClass()) { aClass = aClass.getSuperclass(); } try { return (boolean)MethodHandles.publicLookup().findVirtual(aClass, "hasLoadedClass", HAS_LOADED_CLASS_METHOD_TYPE) .invoke(loader, className); } catch (NoSuchMethodError | IllegalAccessError ignore) { } catch (Throwable e) { getLogger().error(e); } return false; } /** * In 191.* and earlier builds Java plugin was part of the platform, so any plugin installed in IntelliJ IDEA might be able to use its * classes without declaring explicit dependency on the Java module. This method is intended to add implicit dependency on the Java plugin * for such plugins to avoid breaking compatibility with them. */ static @Nullable IdeaPluginDescriptorImpl getImplicitDependency(@NotNull IdeaPluginDescriptorImpl descriptor, @NotNull Supplier<IdeaPluginDescriptorImpl> javaDepGetter) { // skip our plugins as expected to be up-to-date whether bundled or not if (descriptor.isBundled() || descriptor.getPluginId() == CORE_ID || descriptor.getPluginId() == JAVA_PLUGIN_ID || VENDOR_JETBRAINS.equals(descriptor.getVendor())) { return null; } IdeaPluginDescriptorImpl javaDep = javaDepGetter.get(); if (javaDep == null) { return null; } // If a plugin does not include any module dependency tags in its plugin.xml, it's assumed to be a legacy plugin // and is loaded only in IntelliJ IDEA, so it may use classes from Java plugin. return hasModuleDependencies(descriptor) ? null : javaDep; } static boolean hasModuleDependencies(@NotNull IdeaPluginDescriptorImpl descriptor) { for (PluginDependency dependency : descriptor.getPluginDependencies()) { PluginId depId = dependency.id; if (depId == JAVA_PLUGIN_ID || depId == JAVA_MODULE_ID || isModuleDependency(depId)) { return true; } } return false; } public static synchronized void invalidatePlugins() { doSetPlugins(null); DisabledPluginsState.invalidate(); ourShadowedBundledPlugins = null; } private static void logPlugins(@NotNull IdeaPluginDescriptorImpl @NotNull [] plugins, Collection<IdeaPluginDescriptorImpl> incompletePlugins) { StringBuilder bundled = new StringBuilder(); StringBuilder disabled = new StringBuilder(); StringBuilder custom = new StringBuilder(); Set<PluginId> disabledPlugins = new HashSet<>(); for (IdeaPluginDescriptor descriptor : plugins) { StringBuilder target; if (!descriptor.isEnabled()) { if (!DisabledPluginsState.isDisabled(descriptor.getPluginId())) { // plugin will be logged as part of "Problems found loading plugins" continue; } disabledPlugins.add(descriptor.getPluginId()); target = disabled; } else if (descriptor.isBundled() || descriptor.getPluginId() == SPECIAL_IDEA_PLUGIN_ID) { target = bundled; } else { target = custom; } appendPlugin(descriptor, target); } for (IdeaPluginDescriptorImpl plugin : incompletePlugins) { // log only explicitly disabled plugins if (DisabledPluginsState.isDisabled(plugin.getPluginId()) && !disabledPlugins.contains(plugin.getPluginId())) { appendPlugin(plugin, disabled); } } Logger logger = getLogger(); logger.info("Loaded bundled plugins: " + bundled); if (custom.length() > 0) { logger.info("Loaded custom plugins: " + custom); } if (disabled.length() > 0) { logger.info("Disabled plugins: " + disabled); } } private static void appendPlugin(IdeaPluginDescriptor descriptor, StringBuilder target) { if (target.length() > 0) { target.append(", "); } target.append(descriptor.getName()); String version = descriptor.getVersion(); if (version != null) { target.append(" (").append(version).append(')'); } } public static boolean isRunningFromSources() { Boolean result = isRunningFromSources; if (result == null) { result = Files.isDirectory(Paths.get(PathManager.getHomePath(), Project.DIRECTORY_STORE_FOLDER)); isRunningFromSources = result; } return result; } private static void prepareLoadingPluginsErrorMessage(@NotNull Map<PluginId, PluginLoadingError> pluginErrors, @NotNull List<? extends Supplier<@NlsContexts.DetailedDescription String>> globalErrors, @NotNull List<? extends Supplier<? extends HtmlChunk>> actions) { ourPluginLoadingErrors = pluginErrors; // Log includes all messages, not only those which need to be reported to the user String logMessage; if (!pluginErrors.isEmpty() || !globalErrors.isEmpty()) { logMessage = "Problems found loading plugins:\n " + Stream.concat(globalErrors.stream().map(Supplier::get), pluginErrors.entrySet().stream() .sorted(Map.Entry.comparingByKey()) .map(e -> e.getValue().getInternalMessage())) .collect(Collectors.joining("\n ")); } else { logMessage = null; } Application app = ApplicationManager.getApplication(); if (app == null || !app.isHeadlessEnvironment() || isUnitTestMode) { List<Supplier<HtmlChunk>> errorsList = Stream.<Supplier<HtmlChunk>>concat( globalErrors.stream().map(message -> () -> HtmlChunk.text(message.get())), pluginErrors.entrySet().stream() .sorted(Map.Entry.comparingByKey()).map(Map.Entry::getValue) .filter(PluginLoadingError::isNotifyUser) .map(error -> () -> HtmlChunk.text(error.getDetailedMessage())) ).collect(Collectors.toList()); if (!errorsList.isEmpty()) { registerPluginErrors(ContainerUtil.concat(errorsList, actions)); } // as warn in tests if (logMessage != null) { getLogger().warn(logMessage); } } else if (logMessage != null) { getLogger().error(logMessage); } } public static @Nullable @NlsContexts.Label String getShortLoadingErrorMessage(@NotNull IdeaPluginDescriptor pluginDescriptor) { PluginLoadingError error = ourPluginLoadingErrors.get(pluginDescriptor.getPluginId()); if (error != null) { return error.getShortMessage(); } return null; } public static @Nullable PluginId getFirstDisabledDependency(@NotNull IdeaPluginDescriptor pluginDescriptor) { PluginLoadingError error = ourPluginLoadingErrors.get(pluginDescriptor.getPluginId()); if (error != null) { return error.getDisabledDependency(); } return null; } static @NotNull CachingSemiGraph<IdeaPluginDescriptorImpl> createPluginIdGraph(@NotNull Collection<IdeaPluginDescriptorImpl> descriptors, @NotNull Function<? super PluginId, IdeaPluginDescriptorImpl> idToDescriptorMap, boolean withOptional, boolean hasAllModules) { Supplier<IdeaPluginDescriptorImpl> javaDep = () -> idToDescriptorMap.apply(JAVA_MODULE_ID); Set<IdeaPluginDescriptorImpl> uniqueCheck = new HashSet<>(); Map<IdeaPluginDescriptorImpl, List<IdeaPluginDescriptorImpl>> in = new HashMap<>(descriptors.size()); for (IdeaPluginDescriptorImpl descriptor : descriptors) { List<IdeaPluginDescriptorImpl> list = getDirectDependencies(descriptor, idToDescriptorMap, withOptional, hasAllModules, javaDep, uniqueCheck); if (!list.isEmpty()) { in.put(descriptor, list); } } return new CachingSemiGraph<>(descriptors, in); } private static @NotNull List<IdeaPluginDescriptorImpl> getDirectDependencies(@NotNull IdeaPluginDescriptorImpl rootDescriptor, @NotNull Function<? super PluginId, IdeaPluginDescriptorImpl> idToDescriptorMap, boolean withOptional, boolean hasAllModules, @NotNull Supplier<IdeaPluginDescriptorImpl> javaDep, @NotNull Set<? super IdeaPluginDescriptorImpl> uniqueCheck) { List<PluginDependency> dependencies = rootDescriptor.pluginDependencies; List<PluginId> incompatibleModuleIds = rootDescriptor.incompatibilities == null ? Collections.emptyList() : rootDescriptor.incompatibilities; if (dependencies == null) { dependencies = Collections.emptyList(); } IdeaPluginDescriptorImpl implicitDep = hasAllModules ? getImplicitDependency(rootDescriptor, javaDep) : null; int capacity = dependencies.size() + incompatibleModuleIds.size(); if (!withOptional) { for (PluginDependency dependency : dependencies) { if (dependency.isOptional) { capacity } } } if (capacity == 0) { return implicitDep == null ? Collections.emptyList() : Collections.singletonList(implicitDep); } uniqueCheck.clear(); List<IdeaPluginDescriptorImpl> plugins = new ArrayList<>(capacity + (implicitDep == null ? 0 : 1)); if (implicitDep != null) { if (rootDescriptor == implicitDep) { getLogger().error("Plugin " + rootDescriptor + " depends on self"); } else { uniqueCheck.add(implicitDep); plugins.add(implicitDep); } } for (PluginDependency dependency : dependencies) { if (!withOptional && dependency.isOptional) { continue; } // check for missing optional dependency IdeaPluginDescriptorImpl dep = idToDescriptorMap.apply(dependency.id); // if 'dep' refers to a module we need to check the real plugin containing this module only if it's still enabled, // otherwise the graph will be inconsistent if (dep == null) { continue; } // ultimate plugin it is combined plugin, where some included XML can define dependency on ultimate explicitly and for now not clear, // can be such requirements removed or not if (rootDescriptor == dep) { if (rootDescriptor.getPluginId() != CORE_ID) { getLogger().error("Plugin " + rootDescriptor + " depends on self"); } } else if (uniqueCheck.add(dep)) { plugins.add(dep); } } for (PluginId moduleId : incompatibleModuleIds) { IdeaPluginDescriptorImpl dep = idToDescriptorMap.apply(moduleId); if (dep != null && uniqueCheck.add(dep)) { plugins.add(dep); } } return plugins; } private static void checkPluginCycles(@NotNull List<IdeaPluginDescriptorImpl> descriptors, @NotNull Map<PluginId, IdeaPluginDescriptorImpl> idToDescriptorMap, @NotNull List<Supplier<@Nls String>> errors) { CachingSemiGraph<IdeaPluginDescriptorImpl> graph = createPluginIdGraph(descriptors, idToDescriptorMap::get, true, idToDescriptorMap.containsKey(ALL_MODULES_MARKER)); DFSTBuilder<IdeaPluginDescriptorImpl> builder = new DFSTBuilder<>(GraphGenerator.generate(graph)); if (builder.isAcyclic()) { return; } for (Collection<IdeaPluginDescriptorImpl> component : builder.getComponents()) { if (component.size() < 2) { continue; } for (IdeaPluginDescriptor descriptor : component) { descriptor.setEnabled(false); } String pluginsString = component.stream().map(it -> "'" + it.getName() + "'").collect(Collectors.joining(", ")); errors.add(message("plugin.loading.error.plugins.cannot.be.loaded.because.they.form.a.dependency.cycle", pluginsString)); } } public static void getDescriptorsToMigrate(@NotNull Path dir, @Nullable BuildNumber compatibleBuildNumber, @Nullable Path bundledPluginsPath, @Nullable Map<PluginId, Set<String>> brokenPluginVersions, List<? super IdeaPluginDescriptorImpl> pluginsToMigrate, List<? super IdeaPluginDescriptorImpl> incompatiblePlugins) throws ExecutionException, InterruptedException { PluginLoadingResult loadingResult = new PluginLoadingResult( brokenPluginVersions != null ? brokenPluginVersions : getBrokenPluginVersions(), () -> compatibleBuildNumber == null ? getBuildNumber() : compatibleBuildNumber ); int flags = DescriptorListLoadingContext.IGNORE_MISSING_SUB_DESCRIPTOR | DescriptorListLoadingContext.IGNORE_MISSING_INCLUDE; DescriptorListLoadingContext context = new DescriptorListLoadingContext(flags, Collections.emptySet(), loadingResult); Path effectiveBundledPluginPath; if (bundledPluginsPath != null || isUnitTestMode) { effectiveBundledPluginPath = bundledPluginsPath; } else { effectiveBundledPluginPath = Paths.get(PathManager.getPreInstalledPluginsPath()); } PluginDescriptorLoader.loadBundledDescriptorsAndDescriptorsFromDir(context, dir, effectiveBundledPluginPath); for (IdeaPluginDescriptorImpl descriptor : loadingResult.idMap.values()) { if (!descriptor.isBundled()) { if (loadingResult.isBroken(descriptor.getPluginId())) { incompatiblePlugins.add(descriptor); } else { pluginsToMigrate.add(descriptor); } } } for (IdeaPluginDescriptorImpl descriptor : loadingResult.incompletePlugins.values()) { if (!descriptor.isBundled()) { incompatiblePlugins.add(descriptor); } } } private static void prepareLoadingPluginsErrorMessage(@NotNull Map<PluginId, String> disabledIds, @NotNull Set<PluginId> disabledRequiredIds, @NotNull Map<PluginId, ? extends IdeaPluginDescriptor> idMap, @NotNull Map<PluginId, PluginLoadingError> pluginErrors, @NotNull List<? extends Supplier<String>> globalErrors) { List<Supplier<HtmlChunk>> actions = new ArrayList<>(); if (!disabledIds.isEmpty()) { @NlsSafe String nameToDisable; if (disabledIds.size() == 1) { PluginId id = disabledIds.keySet().iterator().next(); nameToDisable = idMap.containsKey(id) ? idMap.get(id).getName() : id.getIdString(); } else { nameToDisable = null; } actions.add(() -> HtmlChunk.link(DISABLE, CoreBundle.message("link.text.disable.plugin.or.plugins", nameToDisable, nameToDisable != null ? 0 : 1))); if (!disabledRequiredIds.isEmpty()) { String nameToEnable = disabledRequiredIds.size() == 1 && idMap.containsKey(disabledRequiredIds.iterator().next()) ? idMap.get(disabledRequiredIds.iterator().next()).getName() : null; actions.add(() -> HtmlChunk.link(ENABLE, CoreBundle.message("link.text.enable.plugin.or.plugins", nameToEnable, nameToEnable != null ? 0 : 1))); } actions.add(() -> HtmlChunk.link(EDIT, CoreBundle.message("link.text.open.plugin.manager"))); } prepareLoadingPluginsErrorMessage(pluginErrors, globalErrors, actions); } @TestOnly public static @NotNull List<? extends IdeaPluginDescriptor> testLoadDescriptorsFromClassPath(@NotNull ClassLoader loader) throws ExecutionException, InterruptedException { Map<URL, String> urlsFromClassPath = new LinkedHashMap<>(); PluginDescriptorLoader.collectPluginFilesInClassPath(loader, urlsFromClassPath); BuildNumber buildNumber = BuildNumber.fromString("2042.42"); DescriptorListLoadingContext context = new DescriptorListLoadingContext(0, Collections.emptySet(), new PluginLoadingResult(Collections.emptyMap(), () -> buildNumber, false)); try (DescriptorLoadingContext loadingContext = new DescriptorLoadingContext(context, true, true, new ClassPathXmlPathResolver(loader))) { PluginDescriptorLoader.loadDescriptorsFromClassPath(urlsFromClassPath, loadingContext, null); } context.result.finishLoading(); return context.result.getEnabledPlugins(); } public static void scheduleDescriptorLoading() { getOrScheduleLoading(); } private static synchronized @NotNull CompletableFuture<DescriptorListLoadingContext> getOrScheduleLoading() { CompletableFuture<DescriptorListLoadingContext> future = descriptorListFuture; if (future != null) { return future; } future = CompletableFuture.supplyAsync(() -> { Activity activity = StartUpMeasurer.startActivity("plugin descriptor loading"); DescriptorListLoadingContext context = PluginDescriptorLoader.loadDescriptors(); activity.end(); return context; }, AppExecutorUtil.getAppExecutorService()); descriptorListFuture = future; return future; } /** * Think twice before use and get approve from core team. Returns enabled plugins only. */ @ApiStatus.Internal public static @NotNull List<IdeaPluginDescriptorImpl> getEnabledPluginRawList() { return getOrScheduleLoading().join().result.getEnabledPlugins(); } @ApiStatus.Internal public static @NotNull CompletionStage<List<IdeaPluginDescriptorImpl>> initPlugins(@NotNull ClassLoader coreClassLoader) { CompletableFuture<DescriptorListLoadingContext> future = descriptorListFuture; if (future == null) { future = CompletableFuture.completedFuture(null); } return future.thenApply(context -> { loadAndInitializePlugins(context, coreClassLoader); return ourLoadedPlugins; }); } static @NotNull PluginLoadingResult createLoadingResult(@Nullable BuildNumber buildNumber) { return new PluginLoadingResult(getBrokenPluginVersions(), () -> buildNumber == null ? getBuildNumber() : buildNumber); } private static @NotNull Map<String, String[]> loadAdditionalLayoutMap() { Path fileWithLayout = usePluginClassLoader ? Paths.get(PathManager.getSystemPath(), PlatformUtils.getPlatformPrefix() + ".txt") : null; if (fileWithLayout == null || !Files.exists(fileWithLayout)) { return Collections.emptyMap(); } Map<String, String[]> additionalLayoutMap = new LinkedHashMap<>(); try (BufferedReader bufferedReader = Files.newBufferedReader(fileWithLayout)) { String line; while ((line = bufferedReader.readLine()) != null) { List<String> parameters = ParametersListUtil.parse(line.trim()); if (parameters.size() < 2) { continue; } additionalLayoutMap.put(parameters.get(0), ArrayUtilRt.toStringArray(parameters.subList(1, parameters.size()))); } } catch (Exception ignored) { } return additionalLayoutMap; } /** * not used by plugin manager - only for dynamic plugin reloading. * Building plugin graph and using `getInList` as it is done for regular loading is not required - all that magic and checks * are not required here because only regular plugins maybe dynamically reloaded. * @return */ @ApiStatus.Internal public static @NotNull ClassLoaderConfigurator createClassLoaderConfiguratorForDynamicPlugin(@NotNull IdeaPluginDescriptorImpl pluginDescriptor) { Map<PluginId, IdeaPluginDescriptorImpl> idMap = buildPluginIdMap(ContainerUtil.concat(getLoadedPlugins(null), Collections.singletonList(pluginDescriptor))); return new ClassLoaderConfigurator(true, PluginManagerCore.class.getClassLoader(), idMap, ourAdditionalLayoutMap); } public static @NotNull BuildNumber getBuildNumber() { BuildNumber result = ourBuildNumber; if (result == null) { result = BuildNumber.fromString(getPluginsCompatibleBuild()); if (result == null) { if (isUnitTestMode) { result = BuildNumber.currentVersion(); } else { try { result = ApplicationInfoImpl.getShadowInstance().getApiVersionAsNumber(); } catch (RuntimeException ignore) { // no need to log error - ApplicationInfo is required in production in any case, so, will be logged if really needed result = BuildNumber.currentVersion(); } } } ourBuildNumber = result; } return result; } private static void disableIncompatiblePlugins(@NotNull List<IdeaPluginDescriptorImpl> descriptors, @NotNull Map<PluginId, IdeaPluginDescriptorImpl> idMap, @NotNull Map<PluginId, PluginLoadingError> errors) { boolean isNonBundledPluginDisabled = ourDisableNonBundledPlugins; if (isNonBundledPluginDisabled) { getLogger().info("Running with disableThirdPartyPlugins argument, third-party plugins will be disabled"); } String selectedIds = System.getProperty("idea.load.plugins.id"); String selectedCategory = System.getProperty("idea.load.plugins.category"); IdeaPluginDescriptorImpl coreDescriptor = idMap.get(CORE_ID); Set<IdeaPluginDescriptorImpl> explicitlyEnabled = null; if (selectedIds != null) { Set<PluginId> set = new HashSet<>(); for (String it : selectedIds.split(",")) { set.add(PluginId.getId(it)); } set.addAll(ApplicationInfoImpl.getShadowInstance().getEssentialPluginsIds()); explicitlyEnabled = new LinkedHashSet<>(set.size()); for (PluginId id : set) { IdeaPluginDescriptorImpl descriptor = idMap.get(id); if (descriptor != null) { explicitlyEnabled.add(descriptor); } } } else if (selectedCategory != null) { explicitlyEnabled = new LinkedHashSet<>(); for (IdeaPluginDescriptorImpl descriptor : descriptors) { if (selectedCategory.equals(descriptor.getCategory())) { explicitlyEnabled.add(descriptor); } } } if (explicitlyEnabled != null) { // add all required dependencies Set<IdeaPluginDescriptorImpl> finalExplicitlyEnabled = explicitlyEnabled; Set<IdeaPluginDescriptor> depProcessed = new HashSet<>(); for (IdeaPluginDescriptorImpl descriptor : new ArrayList<>(explicitlyEnabled)) { processAllDependencies(descriptor, false, idMap, depProcessed, (id, dependency) -> { finalExplicitlyEnabled.add(dependency); return FileVisitResult.CONTINUE; }); } } Map<PluginId, Set<String>> brokenPluginVersions = getBrokenPluginVersions(); boolean shouldLoadPlugins = Boolean.parseBoolean(System.getProperty("idea.load.plugins", "true")); for (IdeaPluginDescriptorImpl descriptor : descriptors) { if (descriptor == coreDescriptor) { continue; } Set<String> set = brokenPluginVersions.get(descriptor.getPluginId()); if (set != null && set.contains(descriptor.getVersion())) { descriptor.setEnabled(false); PluginLoadingError.create(descriptor, message("plugin.loading.error.long.marked.as.broken", descriptor.getName(), descriptor.getVersion()), message("plugin.loading.error.short.marked.as.broken")).register(errors); } else if (explicitlyEnabled != null) { if (!explicitlyEnabled.contains(descriptor)) { descriptor.setEnabled(false); getLogger().info("Plugin '" + descriptor.getName() + "' " + (selectedIds != null ? "is not in 'idea.load.plugins.id' system property" : "category doesn't match 'idea.load.plugins.category' system property")); } } else if (!shouldLoadPlugins) { descriptor.setEnabled(false); PluginLoadingError.create(descriptor, message("plugin.loading.error.long.plugin.loading.disabled", descriptor.getName()), message("plugin.loading.error.short.plugin.loading.disabled")).register(errors); } else if (isNonBundledPluginDisabled && !descriptor.isBundled()) { descriptor.setEnabled(false); PluginLoadingError.create(descriptor, message("plugin.loading.error.long.custom.plugin.loading.disabled", descriptor.getName()), message("plugin.loading.error.short.custom.plugin.loading.disabled"), false).register(errors); } } } public static boolean isCompatible(@NotNull IdeaPluginDescriptor descriptor) { return !isIncompatible(descriptor); } public static boolean isCompatible(@NotNull IdeaPluginDescriptor descriptor, @Nullable BuildNumber buildNumber) { return !isIncompatible(descriptor, buildNumber); } public static boolean isIncompatible(@NotNull IdeaPluginDescriptor descriptor) { return isIncompatible(descriptor, getBuildNumber()); } public static boolean isIncompatible(@NotNull IdeaPluginDescriptor descriptor, @Nullable BuildNumber buildNumber) { if (buildNumber == null) { buildNumber = getBuildNumber(); } return checkBuildNumberCompatibility(descriptor, buildNumber) != null; } @Nullable public static PluginLoadingError checkBuildNumberCompatibility(@NotNull IdeaPluginDescriptor descriptor, @NotNull BuildNumber ideBuildNumber) { return checkBuildNumberCompatibility(descriptor, ideBuildNumber, null); } @Nullable public static PluginLoadingError checkBuildNumberCompatibility(@NotNull IdeaPluginDescriptor descriptor, @NotNull BuildNumber ideBuildNumber, @Nullable Runnable beforeCreateErrorCallback) { String sinceBuild = descriptor.getSinceBuild(); String untilBuild = descriptor.getUntilBuild(); try { BuildNumber sinceBuildNumber = sinceBuild == null ? null : BuildNumber.fromString(sinceBuild, null, null); if (sinceBuildNumber != null && sinceBuildNumber.compareTo(ideBuildNumber) > 0) { if (beforeCreateErrorCallback != null) beforeCreateErrorCallback.run(); return PluginLoadingError.create(descriptor, message("plugin.loading.error.long.incompatible.since.build", descriptor.getName(), descriptor.getVersion(), sinceBuild, ideBuildNumber), message("plugin.loading.error.short.incompatible.since.build", sinceBuild)); } BuildNumber untilBuildNumber = untilBuild == null ? null : BuildNumber.fromString(untilBuild, null, null); if (untilBuildNumber != null && untilBuildNumber.compareTo(ideBuildNumber) < 0) { if (beforeCreateErrorCallback != null) beforeCreateErrorCallback.run(); return PluginLoadingError.create(descriptor, message("plugin.loading.error.long.incompatible.until.build", descriptor.getName(), descriptor.getVersion(), untilBuild, ideBuildNumber), message("plugin.loading.error.short.incompatible.until.build", untilBuild)); } return null; } catch (Exception e) { getLogger().error(e); return PluginLoadingError.create(descriptor, message("plugin.loading.error.long.failed.to.load.requirements.for.ide.version", descriptor.getName()), message("plugin.loading.error.short.failed.to.load.requirements.for.ide.version")); } } private static void checkEssentialPluginsAreAvailable(@NotNull Map<PluginId, IdeaPluginDescriptorImpl> idMap) { List<PluginId> required = ApplicationInfoImpl.getShadowInstance().getEssentialPluginsIds(); List<String> missing = null; for (PluginId id : required) { IdeaPluginDescriptorImpl descriptor = idMap.get(id); if (descriptor == null || !descriptor.isEnabled()) { if (missing == null) { missing = new ArrayList<>(); } missing.add(id.getIdString()); } } if (missing != null) { throw new EssentialPluginMissingException(missing); } } static @NotNull PluginManagerState initializePlugins(@NotNull DescriptorListLoadingContext context, @NotNull ClassLoader coreLoader, boolean checkEssentialPlugins) { PluginLoadingResult loadingResult = context.result; Map<PluginId, PluginLoadingError> pluginErrors = new HashMap<>(loadingResult.getPluginErrors()); @NotNull List<Supplier<String>> globalErrors = loadingResult.getGlobalErrors(); if (loadingResult.duplicateModuleMap != null) { for (Map.Entry<PluginId, List<IdeaPluginDescriptorImpl>> entry : loadingResult.duplicateModuleMap.entrySet()) { globalErrors.add(() -> { return CoreBundle.message("plugin.loading.error.module.declared.by.multiple.plugins", entry.getKey(), entry.getValue().stream().map(IdeaPluginDescriptorImpl::toString).collect(Collectors.joining("\n "))); }); } } Map<PluginId, IdeaPluginDescriptorImpl> idMap = loadingResult.idMap; IdeaPluginDescriptorImpl coreDescriptor = idMap.get(CORE_ID); if (checkEssentialPlugins && coreDescriptor == null) { throw new EssentialPluginMissingException(Collections.singletonList(CORE_ID + " (platform prefix: " + System.getProperty(PlatformUtils.PLATFORM_PREFIX_KEY) + ")")); } List<IdeaPluginDescriptorImpl> descriptors = loadingResult.getEnabledPlugins(); disableIncompatiblePlugins(descriptors, idMap, pluginErrors); checkPluginCycles(descriptors, idMap, globalErrors); // topological sort based on required dependencies only IdeaPluginDescriptorImpl[] sortedRequired = getTopologicallySorted(createPluginIdGraph(descriptors, idMap::get, false, idMap.containsKey(ALL_MODULES_MARKER))); Set<PluginId> enabledPluginIds = new LinkedHashSet<>(); Set<PluginId> enabledModuleIds = new LinkedHashSet<>(); Map<PluginId, String> disabledIds = new LinkedHashMap<>(); Set<PluginId> disabledRequiredIds = new LinkedHashSet<>(); for (IdeaPluginDescriptorImpl descriptor : sortedRequired) { boolean wasEnabled = descriptor.isEnabled(); if (wasEnabled && computePluginEnabled(descriptor, enabledPluginIds, enabledModuleIds, idMap, disabledRequiredIds, context.disabledPlugins, pluginErrors)) { enabledPluginIds.add(descriptor.getPluginId()); enabledModuleIds.addAll(descriptor.getModules()); } else { descriptor.setEnabled(false); if (wasEnabled) { disabledIds.put(descriptor.getPluginId(), descriptor.getName()); } } } prepareLoadingPluginsErrorMessage(disabledIds, disabledRequiredIds, idMap, pluginErrors, globalErrors); // topological sort based on all (required and optional) dependencies CachingSemiGraph<IdeaPluginDescriptorImpl> graph = createPluginIdGraph(Arrays.asList(sortedRequired), idMap::get, true, idMap.containsKey(ALL_MODULES_MARKER)); IdeaPluginDescriptorImpl[] sortedAll = getTopologicallySorted(graph); List<IdeaPluginDescriptorImpl> enabledPlugins = getOnlyEnabledPlugins(sortedAll); for (IdeaPluginDescriptorImpl plugin : enabledPlugins) { if (plugin.pluginDependencies != null) { checkOptionalDescriptors(plugin.pluginDependencies, idMap); } } Map<String, String[]> additionalLayoutMap = loadAdditionalLayoutMap(); ourAdditionalLayoutMap = additionalLayoutMap; ClassLoaderConfigurator classLoaderConfigurator = new ClassLoaderConfigurator(context.usePluginClassLoader, coreLoader, idMap, additionalLayoutMap); enabledPlugins.forEach(classLoaderConfigurator::configure); if (checkEssentialPlugins) { checkEssentialPluginsAreAvailable(idMap); } Set<PluginId> effectiveDisabledIds = disabledIds.isEmpty() ? Collections.emptySet() : new HashSet<>(disabledIds.keySet()); return new PluginManagerState(sortedAll, enabledPlugins, disabledRequiredIds, effectiveDisabledIds, idMap); } private static void checkOptionalDescriptors(@NotNull List<PluginDependency> pluginDependencies, @NotNull Map<PluginId, IdeaPluginDescriptorImpl> idMap) { for (PluginDependency dependency : pluginDependencies) { IdeaPluginDescriptorImpl subDescriptor = dependency.subDescriptor; if (subDescriptor == null || dependency.isDisabledOrBroken) { continue; } IdeaPluginDescriptorImpl dependencyDescriptor = idMap.get(dependency.id); if (dependencyDescriptor == null || !dependencyDescriptor.isEnabled()) { dependency.isDisabledOrBroken = true; continue; } // check that plugin doesn't depend on unavailable plugin List<PluginDependency> childDependencies = subDescriptor.pluginDependencies; if (childDependencies != null && !checkChildDeps(childDependencies, idMap)) { dependency.isDisabledOrBroken = true; } } } // multiple dependency condition is not supported, so, // jsp-javaee.xml depends on com.intellij.javaee.web, and included file in turn define jsp-css.xml that depends on com.intellij.css // that's why nesting level is more than one private static boolean checkChildDeps(@NotNull List<PluginDependency> childDependencies, @NotNull Map<PluginId, IdeaPluginDescriptorImpl> idMap) { for (PluginDependency dependency : childDependencies) { if (dependency.isDisabledOrBroken) { if (dependency.isOptional) { continue; } return false; } IdeaPluginDescriptorImpl dependentDescriptor = idMap.get(dependency.id); if (dependentDescriptor == null || !dependentDescriptor.isEnabled()) { dependency.isDisabledOrBroken = true; if (dependency.isOptional) { continue; } return false; } if (dependency.subDescriptor != null) { List<PluginDependency> list = dependency.subDescriptor.pluginDependencies; if (list != null && !checkChildDeps(list, idMap)) { dependency.isDisabledOrBroken = true; if (dependency.isOptional) { continue; } return false; } } } return true; } private static @NotNull IdeaPluginDescriptorImpl @NotNull [] getTopologicallySorted(@NotNull InboundSemiGraph<IdeaPluginDescriptorImpl> graph) { DFSTBuilder<IdeaPluginDescriptorImpl> requiredOnlyGraph = new DFSTBuilder<>(GraphGenerator.generate(graph)); IdeaPluginDescriptorImpl[] sortedRequired = graph.getNodes().toArray(IdeaPluginDescriptorImpl.EMPTY_ARRAY); Comparator<IdeaPluginDescriptorImpl> comparator = requiredOnlyGraph.comparator(); // there is circular reference between core and implementation-detail plugin, as not all such plugins extracted from core, // so, ensure that core plugin is always first (otherwise not possible to register actions - parent group not defined) Arrays.sort(sortedRequired, (o1, o2) -> { if (o1.getPluginId() == CORE_ID) { return -1; } else if (o2.getPluginId() == CORE_ID) { return 1; } else { return comparator.compare(o1, o2); } }); return sortedRequired; } public static @NotNull List<IdeaPluginDescriptorImpl> getPluginsSortedByDependency(@NotNull List<IdeaPluginDescriptorImpl> plugins, boolean enabled) { for (IdeaPluginDescriptorImpl descriptor : plugins) { descriptor.setEnabled(enabled); } InboundSemiGraph<IdeaPluginDescriptorImpl> graph = createPluginIdGraph(plugins, id -> (IdeaPluginDescriptorImpl)getPlugin(id), true, findPluginByModuleDependency(ALL_MODULES_MARKER) != null); return Arrays.asList(getTopologicallySorted(graph)); } @ApiStatus.Internal public static @NotNull Map<PluginId, IdeaPluginDescriptorImpl> buildPluginIdMap(@NotNull List<IdeaPluginDescriptorImpl> descriptors) { Map<PluginId, IdeaPluginDescriptorImpl> idMap = new LinkedHashMap<>(descriptors.size()); Map<PluginId, List<IdeaPluginDescriptorImpl>> duplicateMap = null; for (IdeaPluginDescriptorImpl descriptor : descriptors) { Map<PluginId, List<IdeaPluginDescriptorImpl>> newDuplicateMap = checkAndPut(descriptor, descriptor.getPluginId(), idMap, duplicateMap); if (newDuplicateMap != null) { duplicateMap = newDuplicateMap; continue; } for (PluginId module : descriptor.getModules()) { newDuplicateMap = checkAndPut(descriptor, module, idMap, duplicateMap); if (newDuplicateMap != null) { duplicateMap = newDuplicateMap; } } } return idMap; } @SuppressWarnings("DuplicatedCode") private static @Nullable Map<PluginId, List<IdeaPluginDescriptorImpl>> checkAndPut(@NotNull IdeaPluginDescriptorImpl descriptor, @NotNull PluginId id, @NotNull Map<PluginId, IdeaPluginDescriptorImpl> idMap, @Nullable Map<PluginId, List<IdeaPluginDescriptorImpl>> duplicateMap) { if (duplicateMap != null) { List<IdeaPluginDescriptorImpl> duplicates = duplicateMap.get(id); if (duplicates != null) { duplicates.add(descriptor); return duplicateMap; } } IdeaPluginDescriptorImpl existingDescriptor = idMap.put(id, descriptor); if (existingDescriptor == null) { return null; } // if duplicated, both are removed idMap.remove(id); if (duplicateMap == null) { duplicateMap = new LinkedHashMap<>(); } List<IdeaPluginDescriptorImpl> list = new ArrayList<>(); list.add(existingDescriptor); list.add(descriptor); duplicateMap.put(id, list); return duplicateMap; } private static boolean computePluginEnabled(@NotNull IdeaPluginDescriptorImpl descriptor, @NotNull Set<PluginId> loadedPluginIds, @NotNull Set<PluginId> loadedModuleIds, @NotNull Map<PluginId, IdeaPluginDescriptorImpl> idMap, @NotNull Set<? super PluginId> disabledRequiredIds, @NotNull Set<PluginId> disabledPlugins, @NotNull Map<PluginId, PluginLoadingError> errors) { if (descriptor.getPluginId() == CORE_ID) { return true; } boolean notifyUser = !descriptor.isImplementationDetail(); boolean result = true; for (PluginId incompatibleId : (descriptor.incompatibilities == null ? Collections.<PluginId>emptyList() : descriptor.incompatibilities)) { if (!loadedModuleIds.contains(incompatibleId) || disabledPlugins.contains(incompatibleId)) { continue; } result = false; String presentableName = incompatibleId.getIdString(); PluginLoadingError.create(descriptor, message("plugin.loading.error.long.ide.contains.conflicting.module", descriptor.getName(), presentableName), message("plugin.loading.error.short.ide.contains.conflicting.module", presentableName), notifyUser).register(errors); } // no deps at all if (descriptor.pluginDependencies == null) { return result; } for (PluginDependency dependency : descriptor.pluginDependencies) { PluginId depId = dependency.id; if (dependency.isOptional || loadedPluginIds.contains(depId) || loadedModuleIds.contains(depId)) { continue; } result = false; IdeaPluginDescriptor dep = idMap.get(depId); if (dep != null && disabledPlugins.contains(depId)) { // broken/incompatible plugins can be updated, add them anyway disabledRequiredIds.add(dep.getPluginId()); } String depName = dep == null ? null : dep.getName(); if (depName == null) { @NlsSafe String depPresentableId = depId.getIdString(); if (errors.containsKey(depId)) { PluginLoadingError.create(descriptor, message("plugin.loading.error.long.depends.on.failed.to.load.plugin", descriptor.getName(), depPresentableId), message("plugin.loading.error.short.depends.on.failed.to.load.plugin", depPresentableId), notifyUser).register(errors); } else { PluginLoadingError.create(descriptor, message("plugin.loading.error.long.depends.on.not.installed.plugin", descriptor.getName(), depPresentableId), message("plugin.loading.error.short.depends.on.not.installed.plugin", depPresentableId), notifyUser).register(errors); } } else { PluginLoadingError error = PluginLoadingError.create(descriptor, message("plugin.loading.error.long.depends.on.disabled.plugin", descriptor.getName(), depName), message("plugin.loading.error.short.depends.on.disabled.plugin", depName), notifyUser); error.setDisabledDependency(dep.getPluginId()); error.register(errors); } } return result; } private static @NotNull @Nls Supplier<String> message(@NotNull @PropertyKey(resourceBundle = CoreBundle.BUNDLE) String key, Object @NotNull ... params) { //noinspection Convert2Lambda return new Supplier<String>() { @Override public String get() { return CoreBundle.message(key, params); } }; } /** * Load extensions points and extensions from a configuration file in plugin.xml format * <p> * Use it only for CoreApplicationEnvironment. Do not use otherwise. For IntelliJ Platform application and tests plugins are loaded in parallel * (including other optimizations). * * @param pluginRoot jar file or directory which contains the configuration file * @param fileName name of the configuration file located in 'META-INF' directory under {@code pluginRoot} * @param area area which extension points and extensions should be registered */ public static void registerExtensionPointAndExtensions(@NotNull Path pluginRoot, @NotNull String fileName, @NotNull ExtensionsArea area) { IdeaPluginDescriptorImpl descriptor; DescriptorListLoadingContext parentContext = DescriptorListLoadingContext.createSingleDescriptorContext( DisabledPluginsState.disabledPlugins()); try (DescriptorLoadingContext context = new DescriptorLoadingContext(parentContext, true, true, PathBasedJdomXIncluder.DEFAULT_PATH_RESOLVER)) { if (Files.isDirectory(pluginRoot)) { descriptor = PluginDescriptorLoader.loadDescriptorFromDir(pluginRoot, META_INF + fileName, null, context); } else { descriptor = PluginDescriptorLoader.loadDescriptorFromJar(pluginRoot, fileName, PathBasedJdomXIncluder.DEFAULT_PATH_RESOLVER, context, null); } } if (descriptor == null) { getLogger().error("Cannot load " + fileName + " from " + pluginRoot); return; } List<ExtensionPointImpl<?>> extensionPoints = descriptor.appContainerDescriptor.extensionPoints; if (extensionPoints != null) { ((ExtensionsAreaImpl)area).registerExtensionPoints(extensionPoints, false); } descriptor.registerExtensions((ExtensionsAreaImpl)area, descriptor.appContainerDescriptor, null); } @SuppressWarnings("NonPrivateFieldAccessedInSynchronizedContext") private static synchronized void loadAndInitializePlugins(@Nullable DescriptorListLoadingContext context, @Nullable ClassLoader coreLoader) { if (coreLoader == null) { Class<?> callerClass = ReflectionUtil.findCallerClass(1); assert callerClass != null; coreLoader = callerClass.getClassLoader(); } try { if (context == null) { context = PluginDescriptorLoader.loadDescriptors(); } Activity activity = StartUpMeasurer.startActivity("plugin initialization"); PluginManagerState initResult = initializePlugins(context, coreLoader, !isUnitTestMode); ourPlugins = initResult.sortedPlugins; PluginLoadingResult result = context.result; if (!result.incompletePlugins.isEmpty()) { int oldSize = initResult.sortedPlugins.length; IdeaPluginDescriptorImpl[] all = Arrays.copyOf(initResult.sortedPlugins, oldSize + result.incompletePlugins.size()); ArrayUtil.copy(result.incompletePlugins.values(), all, oldSize); ourPlugins = all; } ourPluginsToDisable = initResult.effectiveDisabledIds; ourPluginsToEnable = initResult.disabledRequiredIds; ourLoadedPlugins = initResult.sortedEnabledPlugins; ourShadowedBundledPlugins = result.getShadowedBundledIds(); activity.end(); activity.setDescription("plugin count: " + ourLoadedPlugins.size()); logPlugins(initResult.sortedPlugins, result.incompletePlugins.values()); } catch (RuntimeException e) { getLogger().error(e); throw e; } } @SuppressWarnings("RedundantSuppression") public static @NotNull Logger getLogger() { // do not use class reference here //noinspection SSBasedInspection return Logger.getInstance("#com.intellij.ide.plugins.PluginManager"); } public static final class EssentialPluginMissingException extends RuntimeException { public final List<String> pluginIds; EssentialPluginMissingException(@NotNull List<String> ids) { super("Missing essential plugins: " + String.join(", ", ids)); pluginIds = ids; } } public static @Nullable IdeaPluginDescriptor getPlugin(@Nullable PluginId id) { if (id != null) { for (IdeaPluginDescriptor plugin : getPlugins()) { if (id == plugin.getPluginId()) { return plugin; } } } return null; } public static @Nullable IdeaPluginDescriptor findPluginByModuleDependency(@NotNull PluginId id) { for (IdeaPluginDescriptorImpl descriptor : ourPlugins) { if (descriptor.getModules().contains(id)) { return descriptor; } } return null; } public static boolean isPluginInstalled(PluginId id) { return getPlugin(id) != null; } @ApiStatus.Internal public static @NotNull Map<PluginId, IdeaPluginDescriptorImpl> buildPluginIdMap() { LoadingState.COMPONENTS_REGISTERED.checkOccurred(); return buildPluginIdMap(Arrays.asList(ourPlugins)); } /** * You must not use this method in cycle, in this case use {@link #processAllDependencies(IdeaPluginDescriptorImpl, boolean, Map, Function)} instead * (to reuse result of {@link #buildPluginIdMap()}). * * {@link FileVisitResult#SKIP_SIBLINGS} is not supported. * * Returns {@code false} if processing was terminated because of {@link FileVisitResult#TERMINATE}, and {@code true} otherwise. */ @SuppressWarnings("UnusedReturnValue") @ApiStatus.Internal public static boolean processAllDependencies(@NotNull IdeaPluginDescriptorImpl rootDescriptor, boolean withOptionalDeps, @NotNull Function<? super IdeaPluginDescriptor, FileVisitResult> consumer) { return processAllDependencies(rootDescriptor, withOptionalDeps, buildPluginIdMap(), consumer); } @ApiStatus.Internal public static boolean processAllDependencies(@NotNull IdeaPluginDescriptorImpl rootDescriptor, boolean withOptionalDeps, @NotNull Map<PluginId, IdeaPluginDescriptorImpl> idToMap, @NotNull Function<? super IdeaPluginDescriptor, FileVisitResult> consumer) { return processAllDependencies(rootDescriptor, withOptionalDeps, idToMap, new HashSet<>(), (id, descriptor) -> descriptor != null ? consumer.apply(descriptor) : FileVisitResult.SKIP_SUBTREE); } @SuppressWarnings("UnusedReturnValue") @ApiStatus.Internal public static boolean processAllDependencies(@NotNull IdeaPluginDescriptorImpl rootDescriptor, boolean withOptionalDeps, @NotNull Map<PluginId, IdeaPluginDescriptorImpl> idToMap, @NotNull BiFunction<? super @NotNull PluginId, ? super @Nullable IdeaPluginDescriptor, FileVisitResult> consumer) { return processAllDependencies(rootDescriptor, withOptionalDeps, idToMap, new HashSet<>(), consumer); } @ApiStatus.Internal private static boolean processAllDependencies(@NotNull IdeaPluginDescriptorImpl rootDescriptor, boolean withOptionalDeps, @NotNull Map<PluginId, IdeaPluginDescriptorImpl> idToMap, @NotNull Set<? super IdeaPluginDescriptor> depProcessed, @NotNull BiFunction<? super PluginId, ? super IdeaPluginDescriptorImpl, FileVisitResult> consumer) { if (rootDescriptor.pluginDependencies == null) { return true; } for (PluginDependency dependency : rootDescriptor.pluginDependencies) { if (!withOptionalDeps && dependency.isOptional) { continue; } IdeaPluginDescriptorImpl descriptor = idToMap.get(dependency.id); PluginId pluginId = descriptor == null ? dependency.id : descriptor.getPluginId(); switch (consumer.apply(pluginId, descriptor)) { case TERMINATE: return false; case CONTINUE: if (descriptor != null && depProcessed.add(descriptor)) { processAllDependencies(descriptor, withOptionalDeps, idToMap, depProcessed, consumer); } break; case SKIP_SUBTREE: break; case SKIP_SIBLINGS: throw new UnsupportedOperationException("FileVisitResult.SKIP_SIBLINGS is not supported"); } } return true; } private static @NotNull List<IdeaPluginDescriptorImpl> getOnlyEnabledPlugins(@NotNull IdeaPluginDescriptorImpl @NotNull[] sortedAll) { List<IdeaPluginDescriptorImpl> enabledPlugins = new ArrayList<>(sortedAll.length); for (IdeaPluginDescriptorImpl descriptor : sortedAll) { if (descriptor.isEnabled()) { enabledPlugins.add(descriptor); } } return enabledPlugins; } public static synchronized boolean isUpdatedBundledPlugin(@NotNull PluginDescriptor plugin) { return ourShadowedBundledPlugins != null && ourShadowedBundledPlugins.contains(plugin.getPluginId()); } //<editor-fold desc="Deprecated stuff."> /** @deprecated Use {@link #isDisabled(PluginId)} */ @Deprecated public static boolean isDisabled(@NotNull String pluginId) { return isDisabled(PluginId.getId(pluginId)); } /** @deprecated Use {@link #disablePlugin(PluginId)} */ @Deprecated public static boolean disablePlugin(@NotNull String id) { return disablePlugin(PluginId.getId(id)); } /** @deprecated Use {@link #enablePlugin(PluginId)} */ @Deprecated public static boolean enablePlugin(@NotNull String id) { return enablePlugin(PluginId.getId(id)); } /** @deprecated Use {@link DisabledPluginsState#addDisablePluginListener} directly */ @Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.2") public static void addDisablePluginListener(@NotNull Runnable listener) { DisabledPluginsState.addDisablePluginListener(listener); } //</editor-fold> }
package melnorme.lang.tests; import melnorme.lang.tooling.LANG_SPECIFIC; import melnorme.utilbox.misc.Location; @LANG_SPECIFIC public class LangCoreTests_Actual { public static Location SAMPLE_SDK_PATH = LangToolingTestResources.getTestResourceLoc("mock_sdk"); }
/* * $Id: TestSimulatedUrlCacher.java,v 1.9 2003-02-26 21:32:24 troberts Exp $ */ package org.lockss.plugin.simulated; import java.util.Properties; import org.lockss.test.*; import org.lockss.daemon.*; import org.lockss.repository.TestLockssRepositoryImpl; import org.lockss.plugin.*; /** * This is the test class for org.lockss.plugin.simulated.SimulatedUrlCacher * * @author Emil Aalto * @version 0.0 */ public class TestSimulatedUrlCacher extends LockssTestCase { private MockLockssDaemon theDaemon = new MockLockssDaemon(null); public TestSimulatedUrlCacher(String msg) { super(msg); } public void setUp() throws Exception { TestLockssRepositoryImpl.configCacheLocation("null"); theDaemon.getLockssRepository(new MockArchivalUnit()); } public void testHtmlProperties() throws Exception { String testStr = "http: SimulatedUrlCacher suc = new SimulatedUrlCacher( new MockCachedUrlSet(), testStr, ""); Properties prop = suc.getUncachedProperties(); assertEquals("text/html", prop.getProperty("content-type")); assertEquals(testStr, prop.getProperty("content-url")); } public void testTextProperties() throws Exception { String testStr = "http: SimulatedUrlCacher suc = new SimulatedUrlCacher( new MockCachedUrlSet(), testStr, ""); Properties prop = suc.getUncachedProperties(); assertEquals("text/plain", prop.getProperty("content-type")); assertEquals(testStr, prop.getProperty("content-url")); } public void testPdfProperties() throws Exception { String testStr = "http: SimulatedUrlCacher suc = new SimulatedUrlCacher( new MockCachedUrlSet(), testStr, ""); Properties prop = suc.getUncachedProperties(); assertEquals("application/pdf", prop.getProperty("content-type")); assertEquals(testStr, prop.getProperty("content-url")); } public void testJpegProperties() throws Exception { String testStr = "http: SimulatedUrlCacher suc = new SimulatedUrlCacher( new MockCachedUrlSet(), testStr, ""); Properties prop = suc.getUncachedProperties(); assertEquals("image/jpeg", prop.getProperty("content-type")); assertEquals(testStr, prop.getProperty("content-url")); } }
package me.thekey.android.core; import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; import android.net.Uri; import android.net.Uri.Builder; import android.support.annotation.AnyThread; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RestrictTo; import android.support.annotation.WorkerThread; import android.text.TextUtils; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.net.ssl.HttpsURLConnection; import me.thekey.android.Attributes; import me.thekey.android.EventsManager; import me.thekey.android.TheKey; import me.thekey.android.TheKeyInvalidSessionException; import me.thekey.android.TheKeySocketException; import me.thekey.android.lib.LocalBroadcastManagerEventsManager; import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP; import static android.support.annotation.RestrictTo.Scope.SUBCLASSES; import static java.net.HttpURLConnection.HTTP_OK; import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; import static me.thekey.android.core.Constants.CAS_SERVER; import static me.thekey.android.core.Constants.OAUTH_PARAM_ACCESS_TOKEN; import static me.thekey.android.core.Constants.OAUTH_PARAM_CLIENT_ID; import static me.thekey.android.core.Constants.OAUTH_PARAM_CODE; import static me.thekey.android.core.Constants.OAUTH_PARAM_REDIRECT_URI; import static me.thekey.android.core.Constants.OAUTH_PARAM_RESPONSE_TYPE; import static me.thekey.android.core.Constants.OAUTH_PARAM_STATE; import static me.thekey.android.core.Constants.OAUTH_PARAM_THEKEY_GUID; import static me.thekey.android.core.Constants.OAUTH_RESPONSE_TYPE_CODE; import static me.thekey.android.core.PkceUtils.encodeS256Challenge; import static me.thekey.android.core.PkceUtils.generateUrlSafeBase64String; import static me.thekey.android.core.PkceUtils.generateVerifier; /** * The Key interaction library, handles all interactions with The Key OAuth API * endpoints and correctly stores/utilizes OAuth access_tokens locally */ public abstract class TheKeyImpl implements TheKey { private static final String PREFFILE_THEKEY = "me.thekey"; private static final String PREF_DEFAULT_GUID = "default_guid"; private static final Object INSTANCE_LOCK = new Object(); @Nullable private static Configuration sInstanceConfig = null; @SuppressLint("StaticFieldLeak") private static TheKeyImpl sInstance = null; private final Map<String, Object> mLockAuth = new HashMap<>(); @NonNull @RestrictTo(SUBCLASSES) final Context mContext; @NonNull @RestrictTo(SUBCLASSES) final EventsManager mEventsManager; @NonNull @RestrictTo(SUBCLASSES) final Configuration mConfig; @Nullable private TheKeyImpl mMigrationSource; @NonNull private final Uri mServer; private final long mClientId; @NonNull private final Uri mDefaultRedirectUri; @Nullable private String mDefaultGuid; TheKeyImpl(@NonNull final Context context, @NonNull final Configuration config) { mContext = context; mConfig = config; mServer = mConfig.mServer; mClientId = mConfig.mClientId; if (mClientId == INVALID_CLIENT_ID) { throw new IllegalStateException("client_id is invalid or not provided"); } mDefaultGuid = getPrefs().getString(PREF_DEFAULT_GUID, null); mDefaultRedirectUri = mConfig.mDefaultRedirectUri != null ? mConfig.mDefaultRedirectUri : getCasUri("oauth", "client", "public"); mEventsManager = new LocalBroadcastManagerEventsManager(mContext); if (mConfig.mMigrationSource != null) { mMigrationSource = createInstance(mContext, mConfig.mMigrationSource); } } @NonNull private static TheKeyImpl createInstance(@NonNull final Context context, @NonNull final Configuration config) { final TheKeyImpl instance; if (TextUtils.isEmpty(config.mAccountType)) { instance = new PreferenceTheKeyImpl(context, config); } else { // dynamically look for AccountManager implementation try { instance = (TheKeyImpl) Class.forName("me.thekey.android.core.AccountManagerTheKeyImpl") .getDeclaredConstructor(Context.class, Configuration.class) .newInstance(context, config); } catch (final Exception e) { throw new RuntimeException("Unable to find AccountManagerTheKeyImpl, " + "make sure thekey-accountmanager library is loaded", e); } } // trigger account migration for this instance instance.migrateAccounts(); return instance; } public static void configure(@NonNull final Configuration config) { synchronized (INSTANCE_LOCK) { if (sInstance == null) { sInstanceConfig = config; } else if (sInstanceConfig == null) { throw new IllegalStateException("Strange, we have an instance, but no instance config"); } else if (!sInstanceConfig.equals(config)) { throw new IllegalArgumentException("Configuration cannot be changed after TheKeyImpl is initialized"); } } } @NonNull public static TheKeyImpl getInstance(@NonNull final Context context) { synchronized (INSTANCE_LOCK) { // initialize the instance if we haven't already and we have configuration if (sInstance == null && sInstanceConfig != null) { sInstance = createInstance(context.getApplicationContext(), sInstanceConfig); } if (sInstance != null) { return sInstance; } } throw new IllegalStateException("TheKeyImpl has not been configured yet!"); } @NonNull public static TheKeyImpl getInstance(@NonNull final Context context, @NonNull final Configuration config) { configure(config); return getInstance(context); } @NonNull private SharedPreferences getPrefs() { return mContext.getSharedPreferences(PREFFILE_THEKEY, Context.MODE_PRIVATE); } @Override public final void setDefaultSession(@NonNull final String guid) throws TheKeyInvalidSessionException { if (!isValidSession(guid)) { throw new TheKeyInvalidSessionException(); } final String oldGuid = mDefaultGuid; // persist updated default guid mDefaultGuid = guid; getPrefs().edit() .putString(PREF_DEFAULT_GUID, guid) .apply(); // broadcast that the default session changed if (!TextUtils.equals(oldGuid, mDefaultGuid)) { mEventsManager.changeDefaultSessionEvent(mDefaultGuid); } } @Nullable @Override public final String getDefaultSessionGuid() { // reset an invalid session String guid = mDefaultGuid; if (!isValidSession(guid)) { resetDefaultSession(guid); } // return the default session return mDefaultGuid; } private void initDefaultSession() { for (final String guid : getSessions()) { try { setDefaultSession(guid); return; } catch (final TheKeyInvalidSessionException ignored) { } } } @RestrictTo(SUBCLASSES) final void resetDefaultSession(@Nullable final String guid) { if (TextUtils.equals(mDefaultGuid, guid)) { // remove persisted default guid mDefaultGuid = null; getPrefs().edit() .remove(PREF_DEFAULT_GUID) .apply(); // reinitialize the default guid initDefaultSession(); } } @NonNull @Override public final Attributes getAttributes() { return getAttributes(getDefaultSessionGuid()); } @Override public final boolean loadAttributes() throws TheKeySocketException { return loadAttributes(getDefaultSessionGuid()); } @Nullable @Override @WorkerThread public final String getTicket(@NonNull final String service) throws TheKeySocketException { final String guid = getDefaultSessionGuid(); return guid != null ? getTicket(guid, service) : null; } @Override @AnyThread public final void logout() { final String guid = getDefaultSessionGuid(); if (guid != null) { logout(guid); } } @AnyThread @RestrictTo(LIBRARY_GROUP) public final Uri getCasUri(final String... segments) { final Builder uri = mServer.buildUpon(); for (final String segment : segments) { uri.appendPath(segment); } return uri.build(); } @NonNull @Override public Uri getDefaultRedirectUri() { return mDefaultRedirectUri; } @RestrictTo(LIBRARY_GROUP) public final Uri getAuthorizeUri() { return getAuthorizeUri(getDefaultRedirectUri(), null); } private Uri getAuthorizeUri(@NonNull final Uri redirectUri, @Nullable String state) { if (state == null) { state = generateUrlSafeBase64String(16); } final String challenge = encodeS256Challenge(generateAndStoreCodeVerifier(state)); // build oauth authorize url final Builder uri = getCasUri("login").buildUpon() .appendQueryParameter(OAUTH_PARAM_RESPONSE_TYPE, OAUTH_RESPONSE_TYPE_CODE) .appendQueryParameter(OAUTH_PARAM_CLIENT_ID, Long.toString(mClientId)) .appendQueryParameter(OAUTH_PARAM_REDIRECT_URI, redirectUri.toString()) .appendQueryParameter(OAUTH_PARAM_STATE, state) .appendQueryParameter(PARAM_CODE_CHALLENGE_METHOD, CODE_CHALLENGE_METHOD_S256) .appendQueryParameter(PARAM_CODE_CHALLENGE, challenge); return uri.build(); } @Override @WorkerThread public final boolean loadAttributes(@Nullable final String guid) throws TheKeySocketException { if (guid == null) { return false; } String accessToken; while ((accessToken = getValidAccessToken(guid, 0)) != null) { // request the attributes from CAS HttpsURLConnection conn = null; try { // generate & send request final Uri attrsUri = this.getCasUri("api", "oauth", "attributes").buildUpon() .appendQueryParameter(OAUTH_PARAM_ACCESS_TOKEN, accessToken).build(); conn = (HttpsURLConnection) new URL(attrsUri.toString()).openConnection(); if (conn.getResponseCode() == HTTP_OK) { // parse the json response final JSONObject json = this.parseJsonResponse(conn.getInputStream()); storeAttributes(guid, json); // broadcast that we just loaded the attributes mEventsManager.attributesUpdatedEvent(guid); // return that attributes were loaded return true; } else if (conn.getResponseCode() == HTTP_UNAUTHORIZED) { // parse the Authenticate header final String auth = conn.getHeaderField("WWW-Authenticate"); if (auth != null) { final HttpHeaderUtils.Challenge challenge = HttpHeaderUtils.parseChallenge(auth); // OAuth Bearer auth if ("BEARER".equals(challenge.getScheme())) { // extract the error encountered final String error = challenge.getParameterValue("error"); if ("insufficient_scope".equals(error)) { removeAttributes(guid); return false; } else if ("invalid_token".equals(error)) { removeAccessToken(guid, accessToken); continue; } } } } } catch (final MalformedURLException e) { throw new RuntimeException("malformed CAS URL", e); } catch (final IOException e) { throw new TheKeySocketException("connect error", e); } finally { if (conn != null) { conn.disconnect(); } } // the access token didn't work, remove it and restart processing removeAccessToken(guid, accessToken); } return false; } @RestrictTo(SUBCLASSES) abstract void storeAttributes(@NonNull String guid, @NonNull JSONObject json); @RestrictTo(SUBCLASSES) abstract void removeAttributes(@NonNull String guid); @Nullable @Override @WorkerThread public final String getTicket(@NonNull final String guid, @NonNull final String service) throws TheKeySocketException { String accessToken; while ((accessToken = getValidAccessToken(guid, 0)) != null) { // fetch a ticket final String ticket = getTicketWithAccessToken(accessToken, service); if (ticket != null) { return ticket; } // the access token didn't work, remove it and restart processing removeAccessToken(guid, accessToken); } // the user needs to authenticate before a ticket can be retrieved return null; } @Nullable @WorkerThread private String getTicketWithAccessToken(@NonNull final String accessToken, @NonNull final String service) throws TheKeySocketException { HttpsURLConnection conn = null; try { // generate & send request final Uri ticketUri = getCasUri("api", "oauth", "ticket").buildUpon() .appendQueryParameter(OAUTH_PARAM_ACCESS_TOKEN, accessToken) .appendQueryParameter(PARAM_SERVICE, service).build(); conn = (HttpsURLConnection) new URL(ticketUri.toString()).openConnection(); // parse the json response if we have a valid response if (conn.getResponseCode() == 200) { final JSONObject json = parseJsonResponse(conn.getInputStream()); return json.optString(JSON_TICKET, null); } } catch (final MalformedURLException e) { throw new RuntimeException("malformed CAS URL", e); } catch (final IOException e) { throw new TheKeySocketException("connect error", e); } finally { if (conn != null) { conn.disconnect(); } } return null; } @Nullable @RestrictTo(SUBCLASSES) abstract String getAccessToken(@NonNull String guid); @Nullable @RestrictTo(SUBCLASSES) abstract String getRefreshToken(@NonNull String guid); @Nullable @WorkerThread private String getValidAccessToken(@NonNull final String guid, final int depth) throws TheKeySocketException { // prevent infinite recursion if (depth > 2) { return null; } synchronized (getLock(mLockAuth, guid)) { // check for an existing accessToken final String accessToken = getAccessToken(guid); if (accessToken != null) { return accessToken; } // try fetching a new access_token using a refresh_token final String refreshToken = getRefreshToken(guid); if (refreshToken != null) { if (processRefreshTokenGrant(guid, refreshToken)) { return getValidAccessToken(guid, depth + 1); } // the refresh_token isn't valid anymore removeRefreshToken(guid, refreshToken); } // no valid access_token was found, clear auth state clearAuthState(guid, true); } return null; } @Override @AnyThread public final void logout(@NonNull final String guid) { // clearAuthState() may block on synchronization, so process the call on a background thread new Thread(new Runnable() { @Override public void run() { clearAuthState(guid, true); } }).start(); } @RestrictTo(SUBCLASSES) abstract void removeAccessToken(@NonNull String guid, @NonNull String token); @RestrictTo(SUBCLASSES) abstract void removeRefreshToken(@NonNull String guid, @NonNull String token); @WorkerThread @RestrictTo(SUBCLASSES) abstract void clearAuthState(@NonNull String guid, boolean sendBroadcast); @Override @WorkerThread public String processCodeGrant(@NonNull final String code, @NonNull final Uri redirectUri, @Nullable final String state) throws TheKeySocketException { // build the request params final Map<String, String> params = new HashMap<>(); params.put(PARAM_GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); params.put(OAUTH_PARAM_CLIENT_ID, Long.toString(mClientId)); params.put(OAUTH_PARAM_REDIRECT_URI, redirectUri.toString()); params.put(OAUTH_PARAM_CODE, code); final String verifier = lookupCodeVerifier(state); if (verifier != null) { params.put(PARAM_CODE_VERIFIER, verifier); } // perform the token api request and process the response final JSONObject resp = sendTokenApiRequest(params); if (resp != null) { final String guid = resp.optString(OAUTH_PARAM_THEKEY_GUID, null); if (guid != null) { if (storeGrants(guid, resp)) { // clear any dangling code verifiers clearCodeVerifiers(); // return the guid this grant was for return guid; } } } return null; } @WorkerThread private boolean processRefreshTokenGrant(@NonNull final String guid, @NonNull final String refreshToken) throws TheKeySocketException { // build the request params final Map<String, String> params = new HashMap<>(); params.put(PARAM_GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); params.put(OAUTH_PARAM_CLIENT_ID, Long.toString(mClientId)); params.put(PARAM_REFRESH_TOKEN, refreshToken); // perform the token api request and process the response final JSONObject resp = sendTokenApiRequest(params); if (resp != null) { return storeGrants(guid, resp); } return false; } @Nullable private JSONObject sendTokenApiRequest(@NonNull final Map<String, String> params) throws TheKeySocketException { final Uri tokenUri = getCasUri("api", "oauth", "token"); HttpsURLConnection conn = null; try { // convert params into request data final Uri.Builder dataBuilder = new Uri.Builder(); for (final Map.Entry<String, String> entry : params.entrySet()) { dataBuilder.appendQueryParameter(entry.getKey(), entry.getValue()); } final byte[] data = dataBuilder.build().getQuery().getBytes("UTF-8"); // connect & send request conn = (HttpsURLConnection) new URL(tokenUri.toString()).openConnection(); conn.setDoOutput(true); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setFixedLengthStreamingMode(data.length); conn.getOutputStream().write(data); // if it's a successful request, return the parsed JSON if (conn.getResponseCode() == HTTP_OK) { return parseJsonResponse(conn.getInputStream()); } } catch (final MalformedURLException e) { throw new RuntimeException("invalid CAS URL", e); } catch (final UnsupportedEncodingException e) { throw new RuntimeException("Unsupported encoding??? this shouldn't happen", e); } catch (final IOException e) { throw new TheKeySocketException(e); } finally { if (conn != null) { conn.disconnect(); } } return null; } @RestrictTo(SUBCLASSES) abstract boolean storeGrants(@NonNull String guid, @NonNull JSONObject json); private void migrateAccounts() { if (mMigrationSource != null) { for (final MigratingAccount account : mMigrationSource.getMigratingAccounts()) { if (!account.isValid() || createMigratingAccount(account)) { mMigrationSource.removeMigratingAccount(account); } } mMigrationSource = null; } } @NonNull private Collection<MigratingAccount> getMigratingAccounts() { final List<MigratingAccount> accounts = new ArrayList<>(); for (final String guid : getSessions()) { accounts.add(getMigratingAccount(guid)); } return accounts; } @NonNull @RestrictTo(SUBCLASSES) final MigratingAccount getMigratingAccount(@NonNull final String guid) { final MigratingAccount account = new MigratingAccount(guid); account.accessToken = getAccessToken(guid); account.refreshToken = getRefreshToken(guid); account.attributes = getAttributes(guid); return account; } private void removeMigratingAccount(@NonNull final MigratingAccount account) { removeAttributes(account.guid); clearAuthState(account.guid, false); } @RestrictTo(SUBCLASSES) abstract boolean createMigratingAccount(@NonNull MigratingAccount account); @NonNull private String codeVerifierKey(@NonNull final String state) { return "code_verifier-" + state; } @NonNull private String generateAndStoreCodeVerifier(@NonNull final String state) { final String verifier = generateVerifier(); getPrefs().edit().putString(codeVerifierKey(state), verifier).apply(); return verifier; } @Nullable private String lookupCodeVerifier(@Nullable final String state) { if (state == null) { return null; } final String key = codeVerifierKey(state); final String verifier = getPrefs().getString(key, null); getPrefs().edit().remove(key).apply(); return verifier; } private void clearCodeVerifiers() { final SharedPreferences prefs = getPrefs(); final SharedPreferences.Editor editor = prefs.edit(); for (final String key : prefs.getAll().keySet()) { if (key.startsWith("code_verifier-")) { editor.remove(key); } } editor.apply(); } @SuppressWarnings("deprecation") private String encodeParam(final String name, final String value) { try { return URLEncoder.encode(name, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8"); } catch (final UnsupportedEncodingException e) { // we should never get here, but if for some odd reason we do, use // the default encoder which should be UTF-8 return URLEncoder.encode(name) + "=" + URLEncoder.encode(value); } } @NonNull private JSONObject parseJsonResponse(final InputStream response) throws IOException { // read response into string builder final BufferedReader reader = new BufferedReader(new InputStreamReader(response, "UTF-8")); final StringBuilder json = new StringBuilder(); String buffer; while ((buffer = reader.readLine()) != null) { json.append(buffer); } // parse response as JSON try { return new JSONObject(json.toString()); } catch (final JSONException e) { // return an empty object on error return new JSONObject(); } } @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") private static <K> Object getLock(@NonNull final Map<K, Object> locks, @NonNull final K key) { synchronized (locks) { if (!locks.containsKey(key)) { locks.put(key, new Object()); } return locks.get(key); } } @RestrictTo(LIBRARY_GROUP) static final class MigratingAccount { @NonNull @RestrictTo(SUBCLASSES) final String guid; @Nullable @RestrictTo(SUBCLASSES) String accessToken; @Nullable @RestrictTo(SUBCLASSES) String refreshToken; @NonNull @RestrictTo(SUBCLASSES) Attributes attributes; MigratingAccount(@NonNull final String guid) { this.guid = guid; } boolean isValid() { return accessToken != null || refreshToken != null; } } public static final class Configuration { @NonNull final Uri mServer; final long mClientId; @Nullable @RestrictTo(SUBCLASSES) final String mAccountType; @Nullable @RestrictTo(SUBCLASSES) final Uri mDefaultRedirectUri; @Nullable final Configuration mMigrationSource; private Configuration(@Nullable final Uri server, final long id, @Nullable final String accountType, @Nullable final Uri redirectUri, @Nullable final Configuration migrationSource) { mServer = server != null ? server : CAS_SERVER; mClientId = id; mAccountType = accountType; mDefaultRedirectUri = redirectUri; mMigrationSource = migrationSource; } @NonNull public static Configuration base() { return new Configuration(null, INVALID_CLIENT_ID, null, null, null); } @NonNull public Configuration server(@Nullable final String uri) { return server(uri != null ? Uri.parse(uri + (uri.endsWith("/") ? "" : "/")) : null); } @NonNull public Configuration server(@Nullable final Uri uri) { return new Configuration(uri, mClientId, mAccountType, mDefaultRedirectUri, mMigrationSource); } @NonNull public Configuration accountType(@Nullable final String type) { return new Configuration(mServer, mClientId, type, mDefaultRedirectUri, mMigrationSource); } @NonNull public Configuration clientId(final long id) { return new Configuration(mServer, id, mAccountType, mDefaultRedirectUri, mMigrationSource); } @NonNull public Configuration redirectUri(@Nullable final String uri) { return redirectUri(uri != null ? Uri.parse(uri) : null); } @NonNull public Configuration redirectUri(@Nullable final Uri uri) { return new Configuration(mServer, mClientId, mAccountType, uri, mMigrationSource); } @NonNull public Configuration migrationSource(@Nullable final Configuration source) { return new Configuration(mServer, mClientId, mAccountType, mDefaultRedirectUri, source); } @Override public boolean equals(@Nullable final Object o) { if (o == this) { return true; } if (!(o instanceof Configuration)) { return false; } final Configuration that = (Configuration) o; return mClientId == that.mClientId && mServer.equals(that.mServer) && TextUtils.equals(mAccountType, that.mAccountType); } @Override public int hashCode() { return Arrays.hashCode(new Object[] {mServer, mClientId, mAccountType}); } } }
package ru.job4j.set; import ru.job4j.generics.DynamicList; import java.util.Arrays; public class SetHashtable<E> { int length = (int) Math.pow(2, 14); int size = 0; Object[] container = new Object[length]; boolean add(E e) { if (!this.contains(e)) { if ((size > 0.75 * length)) { Object[] exchange = container; container = new Object[length = 2 * length]; for (Object object : exchange) { if (object != null) container[object.hashCode() & (length - 1)] = object; } } container[e.hashCode() & (length - 1)] = e; size++; return true; } return false; } boolean contains(E e) { return container[e.hashCode() & (length - 1)] != null; } boolean remove(E e) { if (this.contains(e)) { container[e.hashCode() & (length - 1)] = null; return true; } return false; } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); for (Object element : container) { if (element != null) { stringBuilder.append(element); stringBuilder.append(" "); } } return stringBuilder.toString(); } }
package org.uli.logging; import java.io.File; import java.util.regex.Pattern; import org.apache.log4j.xml.DOMConfigurator; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.Ignore; import static org.junit.Assert.*; @Ignore public class EverySecondTest { @BeforeClass static public void setUp() { setLog4jXml("src/test/resources/log4j-every-second.xml"); } @AfterClass static public void tearDown() { setLog4jXml("src/test/resources/log4j.xml"); } private static final void setLog4jXml(final String filename) { DOMConfigurator.configure(filename); } @Test public void testEcho() { try { final int LOOP_COUNT = 5; EchoServer echoServer = new EchoServer(); String echo = echoServer.echo("UliWasHere!"); assertEquals("UliWasHere!", echo); for (int i = 0; i < LOOP_COUNT; i++) { try { Thread.sleep(1000); } catch (Exception e) { ; } echoServer.echo("This is a log message, i=" + i); } int count = glob(".", "logging-every-second.*"); assertTrue(count > LOOP_COUNT - 2); assertTrue(count < LOOP_COUNT + 2); } finally { //delete(".", "logging-every-second.*"); } } private final int glob(String folderName, String stringPattern) { Pattern pattern = Pattern.compile(stringPattern); File folder = new File(folderName); int count = 0; for (File file : folder.listFiles()) { if (pattern.matcher(file.getName()).matches()) { ++count; } } return count; } private final void delete(String folderName, String stringPattern) { Pattern pattern = Pattern.compile(stringPattern); File folder = new File(folderName); for (File file : folder.listFiles()) { if (pattern.matcher(file.getName()).matches()) { file.delete(); } } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package stallone.mc.sampling; import cern.jet.random.Beta; import cern.jet.random.Exponential; import cern.jet.random.Uniform; import cern.jet.random.engine.MersenneTwister; import stallone.api.doubles.IDoubleArray; import stallone.api.mc.IReversibleSamplingStep; /** * * Implements the reversible element quadruple shift described in Trendelkamp-Schroer and Noe JCP 2013 * * TODO: This does not yet work in combination with the row shift. The proposal probability needs to corrected when mixing these steps * See Noe JCP 2008 * * @author trendelkamp, noe */ public class Step_Rev_Quad_Trendelkamp implements IReversibleSamplingStep { private int n; private IDoubleArray C; private IDoubleArray T; private IDoubleArray mu; // random number generator private MersenneTwister rand = new MersenneTwister(); // various random generators for the reversible element shift. private Uniform randU = new Uniform(0.0, 1.0, rand); private Exponential randE = new Exponential(1.0, rand); private Beta randB = new Beta(1.0, 1.0, rand); private double Tii_backup, Tij_backup, Tji_backup, Tjj_backup; public Step_Rev_Quad_Trendelkamp() {} @Override public void init(IDoubleArray _C, IDoubleArray _T, IDoubleArray _mu) { this.n = _C.rows(); this.C = _C; this.T = _T; this.mu = _mu; } /** * Gibbs sampling step of a random quadruple of four elements (i,j), (i,i), (j,j), (j,i) * according to the method described in Trendelkamp+Noe JCP 2013 * @return */ public void sampleQuad(int i, int j) { //Ensure that the element is only updated if all counts are non-negative //This ensures that the quad step can handle negative counts //resulting from a prior with negative entries if(i<j && C.get(i, j)+C.get(j, i)>=0.0 && C.get(i,i)>=0.0 && C.get(j, j)>=0.0){ //Compute parameters double a=C.get(i,j)+C.get(j,i); double delta=T.get(i,i)+T.get(i,j); double lambda=mu.get(j)/mu.get(i)*(T.get(j,j)+T.get(j,i)); double b,c,d; //Ensure that d won't grow out of bounds if(delta>1e-15 && lambda>1e-15) { //Assign parameters according to ordering of delta and lambda if(delta<=lambda){ b=C.get(i,i); c=C.get(j,j); d=lambda/delta; } else{ b=C.get(j,j); c=C.get(i,i); d=delta/lambda; } //Generate random variate double x=ScaledElementSampler.sample(randU, randE, randB, a, b, c, d); //Update T T.set(i,j, x*Math.min(delta,lambda)); T.set(i,i, delta-T.get(i,j)); T.set(j,i, mu.get(i)/mu.get(j)*T.get(i,j)); T.set(j,j, mu.get(i)/mu.get(j)*lambda-T.get(j,i)); } //Else do nothing. } //Else do noting } @Override public boolean step() { //Draw (i,j) uniformly from {0,..,n-1}x{0,...,n-1} subject to i<j int k=randU.nextIntFromTo(0, n-1); int l=randU.nextIntFromTo(0, n-1); //Exclude i=j while(k==l){ k=randU.nextIntFromTo(0, n-1); l=randU.nextIntFromTo(0, n-1); } //Enforce i<j int i=Math.min(k,l); int j=Math.max(k,l); sampleQuad(i,j); return true; } }
package info.tregmine.listeners; import info.tregmine.Tregmine; import info.tregmine.api.TregminePlayer; import info.tregmine.database.ConnectionPool; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.Date; //import java.util.Random; import java.util.TimeZone; import java.util.List; import java.util.ArrayList; import java.util.Comparator; import java.util.Collections; import java.util.Set; import java.util.HashSet; import org.bukkit.ChatColor; import org.bukkit.GameMode; //import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Item; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.player.PlayerBucketEmptyEvent; import org.bukkit.event.player.PlayerBucketFillEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerItemHeldEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.event.player.PlayerLoginEvent.Result; import org.bukkit.event.player.PlayerMoveEvent; //import org.bukkit.event.player.PlayerPreLoginEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.ocpsoft.pretty.time.PrettyTime; public class TregminePlayerListener implements Listener { private static class RankComparator implements Comparator<TregminePlayer> { private int order; public RankComparator() { this.order = 1; } public RankComparator(boolean reverseOrder) { this.order = reverseOrder ? -1 : 1; } @Override public int compare(TregminePlayer a, TregminePlayer b) { return order * (a.getGuardianRank() - b.getGuardianRank()); } } /* private final static String[] quitMessages = new String[] { ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " deserted from the battlefield with a hearty good bye!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " stole the cookies and ran!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " was eaten by a teenage mutant ninja platypus!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " parachuted of the plane and into the unknown!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " stole the cookies and ran!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " was eaten by a teenage mutant ninja creeper!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " jumped off the plane with a cobble stone parachute!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " built Rome in one day and now deserves a break!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " will come back soon because Tregmine is awesome!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " leaves the light and enter darkness.", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " disconnects from a better life.", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " already miss the best friends in the world!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " will build something epic next time.", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " is not banned yet!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " has left our world!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " went to browse Tregmine's forums instead!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " was scared away by einand! :(", ChatColor.YELLOW + "Quit - " + "%s" + "'s" + ChatColor.YELLOW + " CPU was killed by the Rendermen!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " fell off the map!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " logged out on accident!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " found the IRL warp!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " left the game due to IRL chunk error issues!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " left the Matrix. Say hi to Morpheus!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " <reserved space for ads. Contact a Senior Admin. Only 200k!>", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " disconnected? What is this!? Impossibru!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " Be sure to visit the rifton general store! Follow the red line at /warp rifton", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " Come to Exon (Near sunspot)" }; */ private final Tregmine plugin; public TregminePlayerListener(Tregmine instance) { plugin = instance; plugin.getServer(); } @EventHandler public void onPlayerBucketFill(PlayerBucketFillEvent event) { if (event.getPlayer().getWorld().getName().matches("alpha")) { event.setCancelled(true); } } @EventHandler public void onPlayerItemHeld(InventoryClickEvent event){ Player player = (Player) event.getWhoClicked(); player.sendMessage("TEST"); if (player.getGameMode() == GameMode.CREATIVE) { ItemStack item = player.getItemOnCursor(); ItemMeta meta = item.getItemMeta(); // if (!meta.hasDisplayName()) { meta.setDisplayName("Spawnd by " + player.getName()); item.setItemMeta(meta); } } @EventHandler public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event){ if (event.getBucket() == Material.LAVA_BUCKET) { event.setCancelled(true); } } @EventHandler public void onPlayerInteract(PlayerInteractEvent event) { info.tregmine.api.TregminePlayer tregminePlayer = this.plugin.tregminePlayer.get(event.getPlayer().getName()); if (!tregminePlayer.isTrusted()) { event.setCancelled(true); } if (tregminePlayer.isAdmin()) { event.setCancelled(false); } if (tregminePlayer.getWorld().getName().matches("alpha")) { event.setCancelled(true); } if (event.getPlayer().getItemInHand().getTypeId() == Material.PAPER.getId() && event.getAction() == Action.RIGHT_CLICK_BLOCK ) { Location block = event.getClickedBlock().getLocation(); java.util.zip.CRC32 crc32 = new java.util.zip.CRC32(); String pos = block.getX() + "," + block.getY() + "," + block.getZ(); crc32.update(pos.getBytes()); long checksum = crc32.getValue(); String timezone = tregminePlayer.getTimezone(); SimpleDateFormat dfm = new SimpleDateFormat("dd/MM/yy hh:mm:ss a"); dfm.setTimeZone(TimeZone.getTimeZone(timezone)); Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = ConnectionPool.getConnection(); stmt = conn.prepareStatement("SELECT * FROM stats_blocks WHERE checksum = ? " + "ORDER BY time DESC LIMIT 5"); stmt.setLong(1, checksum); stmt.execute(); rs = stmt.getResultSet(); //TODO : Reverse the sorting order while (rs.next()) { Date date = new Date(rs.getLong("time")); PrettyTime p = new PrettyTime(); long blockid = rs.getLong("blockid"); String player = rs.getString("player"); boolean placed = rs.getBoolean("status"); Material mat = Material.getMaterial((int) blockid); if (placed == true) { // event.getPlayer().sendMessage(ChatColor.DARK_AQUA + mat.name().toLowerCase() + // " placed by " + player + " at " + dfm.format(date)); event.getPlayer().sendMessage(ChatColor.DARK_AQUA + mat.name().toLowerCase() + " placed by " + player + " " + p.format(date)); event.getPlayer().sendMessage(ChatColor.DARK_AQUA + timezone + ": " + dfm.format(date)); } else { event.getPlayer().sendMessage(ChatColor.DARK_AQUA + mat.name().toLowerCase() + " delete by " + player + " " + p.format(date)); event.getPlayer().sendMessage(ChatColor.DARK_AQUA + timezone + ": " + dfm.format(date)); } } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) {} } if (stmt != null) { try { stmt.close(); } catch (SQLException e) {} } if (conn != null) { try { conn.close(); } catch (SQLException e) {} } } } } @EventHandler public void onPreCommand(PlayerCommandPreprocessEvent event) { this.plugin.log.info("COMMAND: " + event.getPlayer().getName() + "::" + event.getMessage()); } @EventHandler public void onPlayerJoin(PlayerJoinEvent event) { event.setJoinMessage(null); if (!this.plugin.tregminePlayer.containsKey(event.getPlayer().getName())) { event.getPlayer().kickPlayer("error loading profile!"); } activateGuardians(); } @EventHandler public void onPlayerLogin(PlayerLoginEvent event) { Player player = event.getPlayer(); String playerName = player.getName(); TregminePlayer tregPlayer = new TregminePlayer(player, playerName); if (player.getLocation().getWorld().getName().matches("world_the_end")) { player.teleport(this.plugin.getServer().getWorld("world").getSpawnLocation()); } if(tregPlayer.exists()) { tregPlayer.load(); } else { tregPlayer.create(); tregPlayer.load(); } if (tregPlayer.isBanned()) { // event.setKickMessage("You are not allowed on this server!"); event.disallow(Result.KICK_BANNED, "You shall not pass!"); } else { this.plugin.tregminePlayer.put(playerName, tregPlayer); } if (tregPlayer.getMetaString("keyword") != null) { String keyword = tregPlayer.getMetaString("keyword") + ".mc.tregmine.info:25565".toLowerCase(); this.plugin.log.warning("host: " + event.getHostname() ); this.plugin.log.warning("keyword:" + keyword ); if (keyword.equals(event.getHostname().toLowerCase()) || keyword.matches("mc.tregmine.info")) { this.plugin.log.warning(tregPlayer.getName() + " keyword :: success" ); } else { this.plugin.log.warning(tregPlayer.getName() + " keyword :: faild" ); event.disallow(Result.KICK_BANNED, "Wrong keyword!"); } } else { this.plugin.log.warning(tregPlayer.getName() + " keyword :: notset" ); } if (tregPlayer.isGuardian()) { tregPlayer.setGuardianState(TregminePlayer.GuardianState.QUEUED); } } @EventHandler public void onPlayerQuit(PlayerQuitEvent event) { event.setQuitMessage(null); // TregminePlayer tregP = this.plugin.tregminePlayer.get(event.getPlayer().getName()); // if(!event.getPlayer().isOp()) { // Random rand = new Random(); // int msgIndex = rand.nextInt(quitMessages.length); // String message = String.format(quitMessages[msgIndex], tregP.getChatName()); // this.plugin.getServer().broadcastMessage(message); this.plugin.tregminePlayer.remove(event.getPlayer().getName()); this.plugin.log.info("Unloaded settings for " + event.getPlayer().getName() + "."); activateGuardians(); } // @EventHandler // public void onPlayerPreLogin(PlayerPreLoginEvent event) { // Player player = this.plugin.getServer().getPlayer(event.getName()); // if (player != null) { // player.kickPlayer("Sorry, we don't allow clones on this server."); @EventHandler public void onPlayerMove(PlayerMoveEvent event) { // if player move if (!this.plugin.tregminePlayer.containsKey(event.getPlayer().getName())) { event.getPlayer().kickPlayer("error loading profile!"); } } public void onPlayerTeleport(PlayerMoveEvent event) { // if player teleport } @EventHandler public void onPlayerPickupItem(PlayerPickupItemEvent event){ TregminePlayer tregminePlayer; try { tregminePlayer = this.plugin.tregminePlayer.get(event.getPlayer().getName()); } catch (Exception e) { e.printStackTrace(); event.setCancelled(true); return; } if (tregminePlayer.isAdmin()) { return; } if (!tregminePlayer.isTrusted()) { event.setCancelled(true); return; } if (event.getPlayer().getWorld().getName().matches("alpha")) { event.setCancelled(true); } } @EventHandler public void onPlayerDropItem(PlayerDropItemEvent event) { TregminePlayer tregminePlayer = this.plugin.tregminePlayer.get(event.getPlayer().getName()); if (tregminePlayer.isAdmin()) { return; } if (!tregminePlayer.isTrusted()) { event.setCancelled(true); return; } if (event.getPlayer().getWorld().getName().matches("alpha")) { event.setCancelled(true); } } @EventHandler public void onPlayerKick(PlayerKickEvent event) { event.setLeaveMessage(null); } private void activateGuardians() { // Identify all guardians and categorize them based on their current state Player[] players = plugin.getServer().getOnlinePlayers(); Set<TregminePlayer> guardians = new HashSet<TregminePlayer>(); List<TregminePlayer> activeGuardians = new ArrayList<TregminePlayer>(); List<TregminePlayer> inactiveGuardians = new ArrayList<TregminePlayer>(); List<TregminePlayer> queuedGuardians = new ArrayList<TregminePlayer>(); for (Player srvPlayer : players) { TregminePlayer guardian = plugin.getPlayer(srvPlayer.getName()); if (guardian == null || !guardian.isGuardian()) { continue; } TregminePlayer.GuardianState state = guardian.getGuardianState(); if (state == null) { state = TregminePlayer.GuardianState.QUEUED; } switch (state) { case ACTIVE: activeGuardians.add(guardian); break; case INACTIVE: inactiveGuardians.add(guardian); break; case QUEUED: queuedGuardians.add(guardian); break; } guardian.setGuardianState(TregminePlayer.GuardianState.QUEUED); guardians.add(guardian); } Collections.sort(activeGuardians, new RankComparator()); Collections.sort(inactiveGuardians, new RankComparator(true)); Collections.sort(queuedGuardians, new RankComparator()); int idealCount = (int)Math.ceil(Math.sqrt(players.length)/2); // There are not enough guardians active, we need to activate a few more if (activeGuardians.size() <= idealCount) { // Make a pool of every "willing" guardian currently online List<TregminePlayer> activationList = new ArrayList<TregminePlayer>(); activationList.addAll(activeGuardians); activationList.addAll(queuedGuardians); // If the pool isn't large enough to satisfy demand, we add the guardians // that have made themselves inactive as well. if (activationList.size() < idealCount) { int diff = idealCount - activationList.size(); // If there aren't enough of these to satisfy demand, we add all of them if (diff >= inactiveGuardians.size()) { activationList.addAll(inactiveGuardians); } // Otherwise we just add the lowest ranked of the inactive else { activationList.addAll(inactiveGuardians.subList(0, diff)); } } // If there are more than necessarry guardians online, only activate // the most highly ranked. Set<TregminePlayer> activationSet; if (activationList.size() > idealCount) { Collections.sort(activationList, new RankComparator()); activationSet = new HashSet<TregminePlayer>(activationList.subList(0, idealCount)); } else { activationSet = new HashSet<TregminePlayer>(activationList); } // Perform activation StringBuffer globalMessage = new StringBuffer(); String delim = ""; for (TregminePlayer guardian : activationSet) { guardian.setGuardianState(TregminePlayer.GuardianState.ACTIVE); globalMessage.append(delim); globalMessage.append(guardian.getName()); delim = ", "; } Set<TregminePlayer> oldActiveGuardians = new HashSet<TregminePlayer>(activeGuardians); if (!activationSet.containsAll(oldActiveGuardians) || activationSet.size() != oldActiveGuardians.size()) { plugin.getServer().broadcastMessage(ChatColor.BLUE + "Active guardians are: " + globalMessage + ". Please contact any of them if you need help."); // Notify previously active guardian of their state change for (TregminePlayer guardian : activeGuardians) { if (!activationSet.contains(guardian)) { guardian.sendMessage(ChatColor.BLUE + "You are no longer on active duty, and should not respond to help requests, unless asked by an admin or active guardian."); } } // Notify previously inactive guardians of their state change for (TregminePlayer guardian : inactiveGuardians) { if (activationSet.contains(guardian)) { guardian.sendMessage(ChatColor.BLUE + "You have been restored to active duty and should respond to help requests."); } } // Notify previously queued guardians of their state change for (TregminePlayer guardian : queuedGuardians) { if (activationSet.contains(guardian)) { guardian.sendMessage(ChatColor.BLUE + "You are now on active duty and should respond to help requests."); } } } } } }
package ch.poole.openinghoursparser; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.junit.Before; import org.junit.Test; /** * Tests for the OpeningHoursParser * * @author Simon Poole * */ public class UnitTest { @Before public void setUp() { I18n.setLocale(Locale.ROOT); } @Test public void holidaysVsWeekdays() { try { OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream("PH,Su 10:00-12:00; PH Su 11:00-13:00".getBytes())); List<Rule> rules = parser.rules(false); assertEquals(2, rules.size()); } catch (ParseException pex) { fail(pex.getMessage()); } try { OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream("Su,PH 10:00-12:00".getBytes())); List<Rule> rules = parser.rules(true); assertEquals(1, rules.size()); } catch (ParseException pex) { fail(pex.getMessage()); } try { OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream("Su,PH,Mo 10:00-12:00".getBytes())); List<Rule> rules = parser.rules(true); fail("this should have thrown an exception"); } catch (ParseException pex) { assertEquals("Holiday in weekday range at line 1, column 10", pex.getMessage()); } } @Test public void holidays() { try { OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream("PH Su 10:00-12:00".getBytes())); List<Rule> rules = parser.rules(false); assertEquals(1, rules.size()); assertEquals("PH Su 10:00-12:00", rules.get(0).toString()); } catch (ParseException pex) { fail(pex.getMessage()); } } @Test public void equalsTests() { DateWithOffset dwo1 = new DateWithOffset(); dwo1.day = 1; dwo1.dayOffset = 1; try { dwo1.setMonth("bla"); fail("This should have caused an exception"); } catch (IllegalArgumentException ex) { assertEquals("bla is not a valid month", ex.getMessage()); } dwo1.setMonth("Jan"); // dwo1.nth = 1; dwo1.openEnded = true; try { dwo1.setVarDate("bla"); fail("This should have caused an exception"); } catch (IllegalArgumentException ex) { assertEquals("bla is not a valid variable date", ex.getMessage()); } dwo1.setVarDate("easter"); // try { // dwo1.setWeekDay("bla"); // fail("This should have caused an exception"); // dwo1.setWeekDay("Mo"); dwo1.setWeekDayOffset("Mo"); dwo1.weekDayOffsetPositive = true; try { dwo1.setYear(1899); fail("This should have caused an exception"); } catch (IllegalArgumentException ex) { assertEquals("1899 is earlier than 1900", ex.getMessage()); } dwo1.setYear(1999); assertEquals(dwo1, dwo1); DateWithOffset dwo2 = new DateWithOffset(); dwo2.day = 1; dwo2.dayOffset = 1; dwo2.setMonth("Jan"); // dwo2.nth = 1; dwo2.openEnded = true; dwo2.setVarDate("easter"); // dwo2.setWeekDay("Mo"); dwo2.setWeekDayOffset("Mo"); dwo2.weekDayOffsetPositive = true; dwo2.setYear(1999); assertEquals(dwo1, dwo2); assertEquals(dwo1.hashCode(), dwo2.hashCode()); dwo2.day = 2; assertNotEquals(dwo1, dwo2); dwo2.day = 1; assertEquals(dwo1, dwo2); dwo2.dayOffset = 2; assertNotEquals(dwo1, dwo2); dwo2.dayOffset = 1; assertEquals(dwo1, dwo2); dwo2.setMonth("Feb"); assertNotEquals(dwo1, dwo2); dwo2.setMonth("Jan"); assertEquals(dwo1, dwo2); // dwo2.nth=2; // assertFalse(dwo1.equals(dwo2)); // dwo2.nth=1; assertEquals(dwo1, dwo2); dwo2.openEnded = false; assertNotEquals(dwo1, dwo2); dwo2.openEnded = true; assertEquals(dwo1, dwo2); dwo2.varDate = null; assertNotEquals(dwo1, dwo2); dwo2.setVarDate("easter"); assertEquals(dwo1, dwo2); // dwo2.setWeekDay("Tu"); // assertFalse(dwo1.equals(dwo2)); // dwo2.setWeekDay("Mo"); assertEquals(dwo1, dwo2); dwo2.setWeekDayOffset("Tu"); assertNotEquals(dwo1, dwo2); dwo2.setWeekDayOffset("Mo"); assertEquals(dwo1, dwo2); dwo2.weekDayOffsetPositive = false; assertNotEquals(dwo1, dwo2); dwo2.weekDayOffsetPositive = true; assertEquals(dwo1, dwo2); dwo2.setYear(2000); assertNotEquals(dwo1, dwo2); TimeSpan ts1 = new TimeSpan(); ts1.start = 1; VariableTime vt1 = new VariableTime(); vt1.setEvent("sunrise"); vt1.offset = 0; assertEquals(vt1, vt1); ts1.startEvent = vt1; ts1.end = 3; ts1.endEvent = null; ts1.openEnded = true; ts1.interval = 0; assertEquals(ts1, ts1); TimeSpan ts2 = new TimeSpan(); ts2.start = 1; VariableTime vt2 = new VariableTime(); vt2.setEvent("sunrise"); vt2.offset = 0; ts2.startEvent = vt2; ts2.end = 3; ts1.endEvent = null; ts2.openEnded = true; ts2.interval = 0; assertEquals(vt1, vt2); assertEquals(vt1.hashCode(), vt2.hashCode()); assertEquals(ts1, ts2); assertEquals(ts1.hashCode(), ts2.hashCode()); assertEquals(ts1, ts2); ts2.start = 2; assertNotEquals(ts1, ts2); ts2.start = 1; assertEquals(ts1, ts2); vt2.setEvent("sunset"); assertNotEquals(ts1, ts2); vt2.setEvent("sunrise"); assertEquals(ts1, ts2); ts2.end = 4; assertNotEquals(ts1, ts2); ts2.end = 3; assertEquals(ts1, ts2); ts2.openEnded = false; assertNotEquals(ts1, ts2); ts2.openEnded = true; assertEquals(ts1, ts2); ts2.interval = 1; assertNotEquals(ts1, ts2); try { OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream("2010-2011 PH Mo,Tu 10:00-11:00".getBytes())); List<Rule> rules1 = parser.rules(false); parser = new OpeningHoursParser(new ByteArrayInputStream("2010-2011 PH Mo,Tu 10:00-11:00".getBytes())); List<Rule> rules2 = parser.rules(false); assertEquals(1, rules1.size()); assertEquals(1, rules2.size()); assertEquals(rules1.get(0), rules1.get(0)); assertEquals(rules1.get(0), rules2.get(0)); assertEquals(rules1.get(0).hashCode(), rules2.get(0).hashCode()); parser = new OpeningHoursParser(new ByteArrayInputStream("2010-2011 SH Mo,Tu 10:00-11:00".getBytes())); List<Rule> rules3 = parser.rules(false); assertNotEquals(rules1.get(0), rules3.get(0)); } catch (ParseException pex) { fail(pex.getMessage()); } } @Test public void mergeRulesTest() { OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream("2010-2011 Mo,Tu 10:00-11:00;2010-2011 Th,Fr 13:00-14:00".getBytes())); try { List<Rule> rules = parser.rules(false); assertEquals(2, rules.size()); List<List<Rule>> mergeableRules = Util.getMergeableRules(rules); assertEquals(1, mergeableRules.size()); } catch (ParseException pex) { fail(pex.getMessage()); } } @Test public void twentyFourSeven() { OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream("2010-2011 Mo,Tu 10:00-11:00, 24/7".getBytes())); try { List<Rule> rules = parser.rules(false); assertEquals(2, rules.size()); } catch (ParseException pex) { fail(pex.getMessage()); } } @Test public void dateWithOffset() { OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream("Dec 25 off".getBytes())); try { List<Rule> rules = parser.rules(false); assertEquals(1, rules.size()); } catch (ParseException pex) { fail(pex.getMessage()); } // parser = new OpeningHoursParser(new ByteArrayInputStream("Dec Mo[1]-Jan Tu[1],Mar Fr[2]".getBytes())); // try { // List<Rule>rules = parser.rules(false); // assertEquals(1,rules.size()); // assertEquals(2,rules.get(0).getDates().size()); // } catch (ParseException pex) { // fail(pex.getMessage()); } @Test public void openEndedDateRange() { OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream("Jan 31+ Mo".getBytes())); try { List<Rule> rules = parser.rules(false); assertEquals(1, rules.size()); List<DateRange> dateRanges = rules.get(0).getDates(); assertEquals(1, dateRanges.size()); assertTrue(dateRanges.get(0).getStartDate().isOpenEnded()); } catch (ParseException pex) { fail(pex.getMessage()); } } @Test /** * This doesn't seem to turn up in our test data */ public void dateRangeWithInterval() { OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream("Jan-Mar/8".getBytes())); try { List<Rule> rules = parser.rules(false); assertEquals(1, rules.size()); ; Rule r = rules.get(0); List<DateRange> list = r.getDates(); assertEquals(1, list.size()); DateRange range = list.get(0); assertEquals(8, range.getInterval()); } catch (ParseException pex) { fail(pex.getMessage()); } parser = new OpeningHoursParser(new ByteArrayInputStream("Jan-Mar 7/8".getBytes())); try { List<Rule> rules = parser.rules(false); fail("should throw a ParseException"); } catch (ParseException pex) { assertEquals("Interval not allowed here at line 1, column 11", pex.getMessage()); } } @Test public void ampm() { // 12:01pm to 12:59pm is 12:01 to 12:59 // 13:00pm and later is considered to be mistyped and in the 24:00 system // 12:00 pm is 12:00 // 12:01am to 12:59am is 00:01 to 00:59 // 12:00am is 00:00 // 13:00am and later is considered to be mistyped and in the 24:00 system OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream("00:01 am".getBytes())); try { List<Rule> rules = parser.rules(false); Rule r = rules.get(0); List<TimeSpan> times = r.getTimes(); TimeSpan span = times.get(0); assertEquals(1, span.getStart()); parser = new OpeningHoursParser(new ByteArrayInputStream("12:01 pm".getBytes())); rules = parser.rules(false); r = rules.get(0); times = r.getTimes(); span = times.get(0); assertEquals(12 * 60 + 1, span.getStart()); parser = new OpeningHoursParser(new ByteArrayInputStream("12:00 pm".getBytes())); rules = parser.rules(false); r = rules.get(0); times = r.getTimes(); span = times.get(0); assertEquals(12 * 60, span.getStart()); parser = new OpeningHoursParser(new ByteArrayInputStream("13:00 pm".getBytes())); rules = parser.rules(false); r = rules.get(0); times = r.getTimes(); span = times.get(0); assertEquals(13 * 60, span.getStart()); parser = new OpeningHoursParser(new ByteArrayInputStream("12:00 am".getBytes())); rules = parser.rules(false); r = rules.get(0); times = r.getTimes(); span = times.get(0); assertEquals(0, span.getStart()); parser = new OpeningHoursParser(new ByteArrayInputStream("12:01 am".getBytes())); rules = parser.rules(false); r = rules.get(0); times = r.getTimes(); span = times.get(0); assertEquals(1, span.getStart()); parser = new OpeningHoursParser(new ByteArrayInputStream("13:00 am".getBytes())); rules = parser.rules(false); r = rules.get(0); times = r.getTimes(); span = times.get(0); assertEquals(13 * 60, span.getStart()); } catch (ParseException pex) { fail(pex.getMessage()); } } static String LONG_TEST = "Mo[2] -2 days 10:00-12:00;24/7;week 4-40 PH+2days dawn-09:00;dawn-25:00/25;2010-2100/4 12:01-13:02, 14:00, 10:00-(sunset+02:00), 13:00+, 11:01-45:00/46, dawn-dusk, sunrise+; 12-16 closed \"ein test\"; Mo, We 12:01-13:02; Apr-Sep 10:01-13:03, Dec 13:03-21:01"; @Test public void copyTest() { OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream(LONG_TEST.getBytes())); try { List<Rule> rules = parser.rules(false); for (Rule r : rules) { Rule copied = r.copy(); assertEquals(r.toDebugString(), copied.toDebugString()); } } catch (ParseException pex) { fail(pex.getMessage()); } } @Test public void collectionTimes() { // common values from https://taginfo.openstreetmap.org/keys/collection_times#values try { new OpeningHoursParser(new ByteArrayInputStream("Mo-Fr 09:00; Sa 07:00".getBytes())).rules(true); new OpeningHoursParser(new ByteArrayInputStream("Mo-Sa 09:00".getBytes())).rules(true); } catch (ParseException pex) { fail(pex.getMessage()); } } @Test public void serviceTimes() { // common values from https://taginfo.openstreetmap.org/keys/service_times#values try { new OpeningHoursParser(new ByteArrayInputStream("Su 10:00".getBytes())).rules(true); new OpeningHoursParser(new ByteArrayInputStream("Su 08:00-10:00".getBytes())).rules(true); new OpeningHoursParser(new ByteArrayInputStream("sunset,sunrise".getBytes())).rules(true); } catch (ParseException pex) { fail(pex.getMessage()); } } @Test public void weekdayThree() { try { new OpeningHoursParser(new ByteArrayInputStream("Tue-Thu 09:00-18:00".getBytes())).rules(false); } catch (ParseException pex) { fail(pex.getMessage()); } try { new OpeningHoursParser(new ByteArrayInputStream("Tue-Thu 09:00-18:00".getBytes())).rules(true); fail("should throw a ParseException"); } catch (ParseException pex) { assertEquals("Three character weekday at line 1, column 4", pex.getMessage()); } } @Test public void weekdayDe() { try { new OpeningHoursParser(new ByteArrayInputStream("Di-Do 09:00-18:00".getBytes())).rules(false); } catch (ParseException pex) { fail(pex.getMessage()); } try { new OpeningHoursParser(new ByteArrayInputStream("Di-Do 09:00-18:00".getBytes())).rules(true); fail("should throw a ParseException"); } catch (ParseException pex) { assertEquals("German weekday abbreviation at line 1, column 3", pex.getMessage()); } } @Test public void weekRangeTest() { OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream("10:00-12:00".getBytes())); try { List<Rule> rules = parser.rules(false); Rule r = rules.get(0); WeekRange wr = new WeekRange(); wr.setStartWeek(1); wr.setEndWeek(52); wr.setInterval(1); List<WeekRange> weeks = new ArrayList<WeekRange>(); weeks.add(wr); r.setWeeks(weeks); assertEquals(1, wr.getStartWeek()); assertEquals(52, wr.getEndWeek()); assertEquals(1, wr.getInterval()); assertEquals("week 01-52/1 10:00-12:00", r.toString()); try { wr.setStartWeek(-1); fail("Should throw an exception"); } catch (IllegalArgumentException ex) { assertEquals("-1 is outside of the 1-53 range", ex.getMessage()); } try { wr.setEndWeek(55); fail("Should throw an exception"); } catch (IllegalArgumentException ex) { assertEquals("55 is outside of the 1-53 range", ex.getMessage()); } } catch (ParseException pex) { fail(pex.getMessage()); } } @Test public void extendedTimeTest() { OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream("02:00-01:00".getBytes())); try { List<Rule> rules = parser.rules(false); Rule r = rules.get(0); List<TimeSpan> spans = r.getTimes(); assertEquals(120, spans.get(0).getStart()); assertEquals(24 * 60 + 60, spans.get(0).getEnd()); assertEquals("02:00-01:00", spans.get(0).toString()); } catch (ParseException pex) { fail(pex.getMessage()); } parser = new OpeningHoursParser(new ByteArrayInputStream("01:00-26:00".getBytes())); try { List<Rule> rules = parser.rules(false); Rule r = rules.get(0); List<TimeSpan> spans = r.getTimes(); assertEquals(60, spans.get(0).getStart()); assertEquals(24 * 60 + 120, spans.get(0).getEnd()); assertEquals("01:00-26:00", spans.get(0).toString()); } catch (ParseException pex) { fail(pex.getMessage()); } } @Test public void timeTest() { OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream("Sa-Su 10.00-20.00".getBytes())); try { assertEquals("Sa-Su 10:00-20:00", Util.rulesToOpeningHoursString(parser.rules(false))); } catch (ParseException pex) { fail(pex.getMessage()); } parser = new OpeningHoursParser(new ByteArrayInputStream("Sa-Su 10.00-20.00".getBytes())); try { Util.rulesToOpeningHoursString(parser.rules(true)); fail("Should throw an exception"); } catch (ParseException pex) { assertEquals("Invalid minutes at line 1, column 12", pex.getMessage()); } parser = new OpeningHoursParser(new ByteArrayInputStream("Mo,Tu 04-17".getBytes())); try { assertEquals("Mo,Tu 04:00-17:00", Util.rulesToOpeningHoursString(parser.rules(false))); } catch (ParseException pex) { fail(pex.getMessage()); } parser = new OpeningHoursParser(new ByteArrayInputStream("Mo,Tu 04-17".getBytes())); try { assertEquals("Mo,Tu 04:00-17:00", Util.rulesToOpeningHoursString(parser.rules(true))); fail("Should throw an exception"); } catch (ParseException pex) { assertEquals("Hours without minutes", pex.getMessage()); } } @Test public void translationSupport() { I18n.setLocale(Locale.GERMAN); try { OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream("Su,PH,Mo 10:00-12:00".getBytes())); List<Rule> rules = parser.rules(true); fail("this should have thrown an exception"); } catch (ParseException pex) { assertEquals("Feiertag in Wochentagbereich in Zeile 1, Zeichen 10", pex.getMessage()); } try { OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream("10:00-12:00 Su".getBytes())); List<Rule> rules = parser.rules(true); fail("this should have thrown an exception"); } catch (ParseException pex) { assertEquals("Vorgefunden wurde: <WEEKDAY> \"Su \" in Zeile 1, Zeichen 10" + System.lineSeparator() + "Erwartet wurde: <EOF>", pex.getMessage()); } } @Test public void modifiers() { try { OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream("Su,PH closed \"test\"".getBytes())); List<Rule> rules = parser.rules(true); assertEquals(1, rules.size()); RuleModifier modifier = rules.get(0).getModifier(); assertNotNull(modifier); assertEquals(RuleModifier.Modifier.CLOSED, modifier.getModifier()); assertEquals("test", modifier.getComment()); parser = new OpeningHoursParser(new ByteArrayInputStream("Su,PH \"test\"".getBytes())); rules = parser.rules(true); assertEquals(1, rules.size()); modifier = rules.get(0).getModifier(); assertNotNull(modifier); assertNull(modifier.getModifier()); assertEquals("test", modifier.getComment()); parser = new OpeningHoursParser(new ByteArrayInputStream("Su,PH unknown".getBytes())); rules = parser.rules(true); assertEquals(1, rules.size()); modifier = rules.get(0).getModifier(); assertNotNull(modifier); assertEquals(RuleModifier.Modifier.UNKNOWN, modifier.getModifier()); assertNull(modifier.getComment()); } catch (ParseException pex) { fail(pex.getMessage()); } } /** * Check that restarting and reporting more than just the first error worked */ @Test public void multipleErrorsReporting() { OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream("Fx-Sa 02:00-01.00".getBytes())); try { List<Rule> rules = parser.rules(true); fail("this should have thrown an exception"); } catch (ParseException pex) { assertTrue(pex instanceof OpeningHoursParseException); assertEquals(2, ((OpeningHoursParseException) pex).getExceptions().size()); OpeningHoursParseException ex = ((OpeningHoursParseException) pex).getExceptions().get(0); assertTrue(ex.getMessage().startsWith("Encountered: <UNEXPECTED_CHAR> \"F \" at line 0, column 0")); assertEquals(0, ex.getLine()); assertEquals(0, ex.getColumn()); ex = ((OpeningHoursParseException) pex).getExceptions().get(1); assertEquals(1, ex.getLine()); assertEquals(17, ex.getColumn()); assertEquals("Invalid minutes at line 1, column 17", ex.getMessage()); } } @Test public void noSpaceAfterColon() { OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream("Oct-Mar:07:00-20:00; Apr:07:00-22:00; May-Sep:07:00-23:00".getBytes())); try { List<Rule> rules = parser.rules(true); } catch (ParseException pex) { fail(pex.getMessage()); } } @Test public void dateRangeWithOccurance() { OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream("Jan 1-Mar Mo[1], Jun 1-Jul Tu[1]".getBytes())); try { List<Rule> rules = parser.rules(true); assertEquals(1, rules.size()); } catch (ParseException pex) { fail(pex.getMessage()); } } @Test public void intervalMinutesOnly() { OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream("07:00-20:00/99".getBytes())); try { List<Rule> rules = parser.rules(true); assertEquals(1, rules.size()); Rule r = rules.get(0); assertEquals(1, r.times.size()); TimeSpan ts = r.times.get(0); assertEquals(99, ts.getInterval()); } catch (ParseException pex) { fail(pex.getMessage()); } } @Test public void intervalHourMinutes() { OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream("07:00-20:00/01:39".getBytes())); try { List<Rule> rules = parser.rules(true); assertEquals(1, rules.size()); Rule r = rules.get(0); assertEquals(1, r.times.size()); TimeSpan ts = r.times.get(0); assertEquals(99, ts.getInterval()); } catch (ParseException pex) { fail(pex.getMessage()); } } @Test public void intervalHourMinutesNoLeading0() { OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream("07:00-20:00/1:39".getBytes())); try { List<Rule> rules = parser.rules(true); assertEquals(1, rules.size()); Rule r = rules.get(0); assertEquals(1, r.times.size()); TimeSpan ts = r.times.get(0); assertEquals(99, ts.getInterval()); } catch (ParseException pex) { fail(pex.getMessage()); } } @Test public void yearRange() { OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream("1999-2001".getBytes())); try { List<Rule> rules = parser.rules(true); assertEquals(1, rules.size()); Rule r = rules.get(0); assertEquals(1, r.years.size()); YearRange range = r.years.get(0); assertEquals(1999, range.getStartYear()); assertEquals(2001, range.getEndYear()); } catch (ParseException pex) { fail(pex.getMessage()); } parser = new OpeningHoursParser(new ByteArrayInputStream("1999-2001 Mo 07:00-20:00".getBytes())); try { List<Rule> rules = parser.rules(true); assertEquals(1, rules.size()); Rule r = rules.get(0); assertEquals(1, r.years.size()); YearRange range = r.years.get(0); assertEquals(1999, range.getStartYear()); assertEquals(2001, range.getEndYear()); assertEquals("1999-2001 Mo 07:00-20:00", Util.rulesToOpeningHoursString(rules)); } catch (ParseException pex) { fail(pex.getMessage()); } } @Test public void yearRangeOpenEnded() { OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream("1999+".getBytes())); try { List<Rule> rules = parser.rules(true); assertEquals(1, rules.size()); Rule r = rules.get(0); assertEquals(1, r.years.size()); YearRange range = r.years.get(0); assertEquals(1999, range.getStartYear()); assertTrue(range.isOpenEnded()); assertEquals(YearRange.UNDEFINED_YEAR, range.getEndYear()); } catch (ParseException pex) { fail(pex.getMessage()); } parser = new OpeningHoursParser(new ByteArrayInputStream("1999+ Mo 07:00-20:00".getBytes())); try { List<Rule> rules = parser.rules(true); assertEquals(1, rules.size()); Rule r = rules.get(0); assertEquals(1, r.years.size()); YearRange range = r.years.get(0); assertEquals(1999, range.getStartYear()); assertTrue(range.isOpenEnded()); assertEquals(YearRange.UNDEFINED_YEAR, range.getEndYear()); assertEquals("1999+ Mo 07:00-20:00", Util.rulesToOpeningHoursString(rules)); } catch (ParseException pex) { fail(pex.getMessage()); } } @Test public void dateRange() { OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream("1999 Jun 1-2001 Jul 2".getBytes())); try { List<Rule> rules = parser.rules(true); assertEquals(1, rules.size()); Rule r = rules.get(0); assertEquals(1, r.dates.size()); DateRange range = r.dates.get(0); DateWithOffset start = range.getStartDate(); assertNotNull(start); assertEquals(1999, start.getYear()); assertEquals(Month.JUN, start.getMonth()); assertEquals(1, start.getDay()); DateWithOffset end = range.getEndDate(); assertNotNull(end); assertEquals(2001, end.getYear()); assertEquals(Month.JUL, end.getMonth()); assertEquals(2, end.getDay()); } catch (ParseException pex) { fail(pex.getMessage()); } } @Test public void invalidDateRange() { OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream("1999 Jun 1+-2001 Jul 2".getBytes())); try { List<Rule> rules = parser.rules(true); fail("this should have thrown an exception"); } catch (ParseException pex) { assertEquals("Encountered: <HYPHEN> \"- \" at line 1, column 11" + System.lineSeparator() + "Was expecting: <EOF>", pex.getMessage()); } } @Test public void timeStrict() { OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream("07:00-06:00".getBytes())); try { List<Rule> rules = parser.rules(true); fail("this should have thrown an exception"); } catch (ParseException pex) { assertEquals("End time earlier than start time at line 1, column 11", pex.getMessage()); } parser = new OpeningHoursParser(new ByteArrayInputStream("07:00-06:00".getBytes())); try { List<Rule> rules = parser.rules(true, false); assertEquals(1, rules.size()); Rule r = rules.get(0); List<TimeSpan> spans = r.getTimes(); assertEquals(1, spans.size()); assertEquals(7 * 60, spans.get(0).getStart()); assertEquals(30 * 60, spans.get(0).getEnd()); assertEquals("07:00-06:00", Util.rulesToOpeningHoursString(rules)); } catch (ParseException pex) { fail(pex.getMessage()); } } @Test public void midnight() { OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream("07:00-24:00".getBytes())); try { List<Rule> rules = parser.rules(true, true); assertEquals(1, rules.size()); Rule r = rules.get(0); List<TimeSpan> spans = r.getTimes(); assertEquals(1, spans.size()); assertEquals(7 * 60, spans.get(0).getStart()); assertEquals(24 * 60, spans.get(0).getEnd()); assertEquals("07:00-24:00", Util.rulesToOpeningHoursString(rules)); } catch (ParseException pex) { fail(pex.getMessage()); } parser = new OpeningHoursParser(new ByteArrayInputStream("07:00-24:00".getBytes())); try { List<Rule> rules = parser.rules(true, false); assertEquals(1, rules.size()); Rule r = rules.get(0); List<TimeSpan> spans = r.getTimes(); assertEquals(1, spans.size()); assertEquals(7 * 60, spans.get(0).getStart()); assertEquals(24 * 60, spans.get(0).getEnd()); assertEquals("07:00-24:00", Util.rulesToOpeningHoursString(rules)); } catch (ParseException pex) { fail(pex.getMessage()); } parser = new OpeningHoursParser(new ByteArrayInputStream("07:00-00:00".getBytes())); try { List<Rule> rules = parser.rules(true, false); assertEquals(1, rules.size()); Rule r = rules.get(0); List<TimeSpan> spans = r.getTimes(); assertEquals(1, spans.size()); assertEquals(7 * 60, spans.get(0).getStart()); assertEquals(24 * 60, spans.get(0).getEnd()); assertEquals("07:00-24:00", Util.rulesToOpeningHoursString(rules)); } catch (ParseException pex) { fail(pex.getMessage()); } } }
package com.alibaba.json.bvt; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.parser.SymbolTable; public class SymbolTableTest extends TestCase { protected String[] symbols = new String[] { "EffectedRowCount", "DataSource", "BatchSizeMax", "BatchSizeTotal", "ConcurrentMax", "ErrorCount", "ExecuteCount", "FetchRowCount", "File", "ID", "LastError", "LastTime", "MaxTimespan", "MaxTimespanOccurTime", "Name", "RunningCount", "SQL", "TotalTime" }; char[][] symbols_char = new char[symbols.length][]; final int COUNT = 1000 * 1000; protected void setUp() throws Exception { for (int i = 0; i < symbols.length; ++i) { symbols_char[i] = symbols[i].toCharArray(); } } public void test_symbol() throws Exception { char[][] symbols_char = new char[symbols.length][]; for (int i = 0; i < symbols.length; ++i) { symbols_char[i] = symbols[i].toCharArray(); } SymbolTable table = new SymbolTable(512); for (int i = 0; i < symbols.length; ++i) { String symbol = symbols[i]; char[] charArray = symbol.toCharArray(); table.addSymbol(charArray, 0, charArray.length); //System.out.println((table.hash(symbol) & table.getIndexMask()) + "\t\t:" + symbol + "\t\t" + table.hash(symbol)); } String symbol = "name"; table.addSymbol(symbol.toCharArray(), 0, symbol.length()); table.addSymbol(symbol.toCharArray(), 0, symbol.length()); Assert.assertTrue(symbol == table.addSymbol("name".toCharArray(), 0, 4)); Assert.assertTrue(symbol == table.addSymbol(" name".toCharArray(), 1, 4)); Assert.assertTrue(symbol == table.addSymbol(" name ".toCharArray(), 1, 4)); Assert.assertTrue(symbol != table.addSymbol(" namf ".toCharArray(), 1, 4)); } }
package imagej.updater.gui; import imagej.updater.core.FileObject; import imagej.updater.core.FileObject.Action; import imagej.updater.core.FileObject.Status; import imagej.updater.core.FilesCollection; import imagej.updater.core.FilesCollection.UpdateSite; import imagej.updater.core.Installer; import imagej.updater.core.UploaderService; import imagej.updater.util.UpdaterUserInterface; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.swing.DefaultCellEditor; import javax.swing.JComboBox; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.event.TableModelEvent; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellEditor; import javax.swing.table.TableColumn; /** * This class's role is to be in charge of how the Table should be displayed. * * @author Johannes Schindelin */ @SuppressWarnings("serial") public class FileTable extends JTable { protected UpdaterFrame updaterFrame; protected UploaderService uploaderService; protected FilesCollection files; protected List<FileObject> row2file; private FileTableModel fileTableModel; protected Font plain, bold; public FileTable(final UpdaterFrame updaterFrame) { this.updaterFrame = updaterFrame; this.uploaderService = updaterFrame.getUploaderService(); files = updaterFrame.files; row2file = new ArrayList<FileObject>(); for (final FileObject file : files) { row2file.add(file); } // Set appearance of table setShowGrid(false); setIntercellSpacing(new Dimension(0, 0)); setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); setRequestFocusEnabled(false); // set up the table properties and other settings setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); setCellSelectionEnabled(true); setColumnSelectionAllowed(false); setRowSelectionAllowed(true); fileTableModel = new FileTableModel(files); setModel(fileTableModel); getModel().addTableModelListener(this); setColumnWidths(250, 100); setDefaultRenderer(Object.class, new DefaultTableCellRenderer() { @Override public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) { final Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); setStyle(comp, row, column); return comp; } }); addMouseListener(new MouseAdapter() { @Override public void mousePressed(final MouseEvent e) { maybeShowPopupMenu(e); } }); } /* * This sets the font to bold when the user selected an action for * this file, or when it is locally modified. * * It also warns loudly when the file is obsolete, but locally * modified. */ protected void setStyle(final Component comp, final int row, final int column) { if (plain == null) { plain = comp.getFont(); bold = plain.deriveFont(Font.BOLD); } final FileObject file = getFile(row); if (file == null) return; comp.setFont(file.actionSpecified() || file.isLocallyModified() ? bold : plain); comp.setForeground(file.getStatus() == Status.OBSOLETE_MODIFIED ? Color.red : Color.black); } private void setColumnWidths(final int col1Width, final int col2Width) { final TableColumn col1 = getColumnModel().getColumn(0); final TableColumn col2 = getColumnModel().getColumn(1); col1.setPreferredWidth(col1Width); col1.setMinWidth(col1Width); col1.setResizable(false); col2.setPreferredWidth(col2Width); col2.setMinWidth(col2Width); col2.setResizable(true); } public FilesCollection getAllFiles() { return files; } public void setFiles(final Iterable<FileObject> files) { fileTableModel.setFiles(files); } @Override public TableCellEditor getCellEditor(final int row, final int col) { final FileObject file = getFile(row); // As we follow FileTableModel, 1st column is filename if (col == 0) return super.getCellEditor(row, col); final Action[] actions = files.getActions(file); return new DefaultCellEditor(new JComboBox(actions)); } public void maybeShowPopupMenu(final MouseEvent e) { if (!e.isPopupTrigger() && (files.util.isMacOSX() || (e.getModifiers() & InputEvent.META_MASK) == 0)) return; final Iterable<FileObject> selected = getSelectedFiles(e.getY() / getRowHeight()); if (!selected.iterator().hasNext()) return; final JPopupMenu menu = new JPopupMenu(); int count = 0; for (final FileObject.Action action : files.getActions(selected)) { final JMenuItem item = new JMenuItem(action.toString()); item.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { if (action == Action.UPLOAD) { String missing = protocolsMissingUploaders(selected); if (missing != null && missing.equals("ssh") && getSSHUploader()) missing = null; if (missing != null) { UpdaterUserInterface.get().error("Missing uploaders: " + missing); return; } } for (final FileObject file : selected) setFileAction(file, action); } }); menu.add(item); count++; } if (count == 0) { final JMenuItem noActions = new JMenuItem("<No common actions>"); noActions.setEnabled(false); menu.add(noActions); } menu.show(e.getComponent(), e.getX(), e.getY()); } protected String protocolsMissingUploaders(final Iterable<FileObject> selected) { Set<String> protocols = new LinkedHashSet<String>(); for (final FileObject file : selected) { final UpdateSite site = files.getUpdateSite(file.updateSite); if (site != null) { if (site.sshHost == null) protocols.add("unknown(" + file.filename + ")"); else protocols.add(site.getUploadProtocol()); } } String result = null; for (String protocol : protocols) if (!uploaderService.hasUploader(protocol)) { if (result == null) result = protocol; else result = result + ", " + protocol; } return result; } protected boolean getSSHUploader() { final FileObject sshUploader = files.get("jars/ij-updater-ssh.jar"); if (sshUploader.getStatus() != Status.NOT_INSTALLED) return false; final Set<URL> urls = new LinkedHashSet<URL>(); final FilesCollection toInstall = new FilesCollection(files.prefix("")); for (final FileObject file : sshUploader.getFileDependencies(files, true)) switch (file.getStatus()) { case NOT_INSTALLED: toInstall.add(file); file.setAction(toInstall, Action.INSTALL); case INSTALLED: try { urls.add(toInstall.prefix(file.filename).toURI().toURL()); } catch (MalformedURLException e) { return false; } break; default: return false; } final Installer installer = new Installer(toInstall, updaterFrame.getProgress("Installing ssh uploader")); try { installer.start(); installer.moveUpdatedIntoPlace(); URLClassLoader loader = new URLClassLoader(urls.toArray(new URL[urls.size()]), Thread.currentThread().getContextClassLoader()); Thread.currentThread().setContextClassLoader(loader); return true; } catch (IOException e) { return false; } } public FileObject getFile(final int row) { final FileObject.LabeledFile file = (FileObject.LabeledFile) getValueAt(row, 0); return file == null ? null : file.getFile(); } public Iterable<FileObject> getSelectedFiles() { return getSelectedFiles(-1); } public Iterable<FileObject> getSelectedFiles(final int fallbackRow) { int[] rows = getSelectedRows(); if (fallbackRow >= 0 && getFile(fallbackRow) != null && (rows.length == 0 || indexOf(rows, fallbackRow) < 0)) rows = new int[] { fallbackRow }; final FileObject[] result = new FileObject[rows.length]; for (int i = 0; i < rows.length; i++) result[i] = getFile(rows[i]); return Arrays.asList(result); } protected int indexOf(final int[] array, final int value) { for (int i = 0; i < array.length; i++) { if (array[i] == value) return i; } return -1; } public boolean areAllSelectedFilesUploadable() { if (getSelectedRows().length == 0) return false; for (final FileObject file : getSelectedFiles()) if (!file.isUploadable(updaterFrame.files)) return false; return true; } public boolean chooseUpdateSite(final FilesCollection files, final FileObject file) { final List<String> list = new ArrayList<String>(); for (final String name : files.getUpdateSiteNames()) { final UpdateSite site = files.getUpdateSite(name); if (site.isUploadable()) list.add(name); } if (list.size() == 0) { error("No upload site available"); return false; } if (list.size() == 1 && list.get(0).equals(FilesCollection.DEFAULT_UPDATE_SITE)) { file.updateSite = FilesCollection.DEFAULT_UPDATE_SITE; return true; } final String updateSite = SwingTools.getChoice(updaterFrame, list, "To which upload site do you want to upload " + file.filename + "?", "Upload site"); if (updateSite == null) return false; file.updateSite = updateSite; return true; } protected void setFileAction(final FileObject file, final Action action) { if (!file.getStatus().isValid(action)) return; if (action == Action.UPLOAD) { final Collection<String> sitesWithUploads = updaterFrame.files.getSiteNamesToUpload(); if (sitesWithUploads.size() > 1) { error("Internal error: multiple upload sites selected"); return; } final boolean isNew = file.getStatus() == Status.LOCAL_ONLY; if (sitesWithUploads.size() == 0) { if (isNew && !chooseUpdateSite(updaterFrame.files, file)) return; String protocol = updaterFrame.files.getUpdateSite(file.updateSite).getUploadProtocol(); if (!uploaderService.hasUploader(protocol) && (!protocol.equals("ssh") || !getSSHUploader())) { UpdaterUserInterface.get().error("Missing uploader for protocol " + protocol); return; } } else { final String siteName = sitesWithUploads.iterator().next(); if (isNew) file.updateSite = siteName; else if (!file.updateSite.equals(siteName)) { error("Already have uploads for site '" + siteName + "', cannot upload to '" + file.updateSite + "', too!"); return; } } } file.setAction(updaterFrame.files, action); fireFileChanged(file); } protected class FileTableModel extends AbstractTableModel { private FilesCollection files; protected Map<FileObject, Integer> fileToRow; protected List<FileObject> rowToFile; public FileTableModel(final FilesCollection files) { this.files = files; } public void setFiles(final Iterable<FileObject> files) { setFiles(this.files.clone(files)); } public void setFiles(final FilesCollection files) { this.files = files; fileToRow = null; rowToFile = null; fireTableChanged(new TableModelEvent(fileTableModel)); } @Override public int getColumnCount() { return 2; // Name of file, status } @Override public Class<?> getColumnClass(final int columnIndex) { switch (columnIndex) { case 0: return String.class; // filename case 1: return String.class; // status/action default: return Object.class; } } @Override public String getColumnName(final int column) { switch (column) { case 0: return "Name"; case 1: return "Status/Action"; default: throw new Error("Column out of range"); } } public FileObject getEntry(final int rowIndex) { return rowToFile.get(rowIndex); } @Override public int getRowCount() { return files.size(); } @Override public Object getValueAt(final int row, final int column) { updateMappings(); if (row < 0 || row >= files.size()) return null; return rowToFile.get(row).getLabeledFile(column); } @Override public boolean isCellEditable(final int rowIndex, final int columnIndex) { return columnIndex == 1; } @Override public void setValueAt(final Object value, final int row, final int column) { if (column == 1) { final Action action = (Action) value; final FileObject file = getFile(row); setFileAction(file, action); } } public void fireRowChanged(final int row) { fireTableRowsUpdated(row, row); } public void fireFileChanged(final FileObject file) { updateMappings(); final Integer row = fileToRow.get(file); if (row != null) fireRowChanged(row.intValue()); } protected void updateMappings() { if (fileToRow != null) return; fileToRow = new HashMap<FileObject, Integer>(); rowToFile = new ArrayList<FileObject>(); // the table may be sorted, and we need the model's row int i = 0; for (final FileObject f : files) { fileToRow.put(f, new Integer(i++)); rowToFile.add(f); } } } public void fireFileChanged(final FileObject file) { fileTableModel.fireFileChanged(file); } protected void error(final String message) { SwingTools.showMessageBox(updaterFrame, message, JOptionPane.ERROR_MESSAGE); } }
package com.jcabi.github; import com.rexsl.test.Request; import com.rexsl.test.request.ApacheRequest; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Assume; import org.junit.Test; /** * Integration case for {@link RepoCommits}. * @author Alexander Sinyagin (sinyagin.alexander@gmail.com) * @version $Id$ */ public class RtRepoCommitsITCase { public final transient String requestUrl = "https://api.github.com/"; public final transient String user = "jcabi"; public final transient String repo = "jcabi-github"; /** * RtRepoCommits can fetch commits. */ @Test public void fetchCommits() { final Request request = new ApacheRequest(requestUrl); final Coordinates coordinates = new Coordinates.Simple(user, repo); RepoCommits repoCommits = new RtRepoCommits(request, coordinates); Iterator<Commit> iterator = repoCommits.iterate().iterator(); final List<String> shas = new ArrayList<String>(); shas.add("1aa4af45aa2c56421c3d911a0a06da513a7316a0"); shas.add("940dd5081fada0ead07762933036bf68a005cc40"); shas.add("05940dbeaa6124e4a87d9829fb2fce80b713dcbe"); shas.add("51cabb8e759852a6a40a7a2a76ef0afd4beef96d"); shas.add("11bd4d527236f9cb211bc6667df06fde075beded"); int existsCount = 0; while (iterator.hasNext()) { if (shas.contains(iterator.next().sha())) { existsCount++; } } MatcherAssert.assertThat(existsCount, Matchers.equalTo(shas.size()) ); } /** * RtRepoCommits can get commit. */ @Test public void getCommit() throws IOException { final Request request = new ApacheRequest(requestUrl); final Coordinates coordinates = new Coordinates.Simple(user, repo); final RepoCommits repoCommits = new RtRepoCommits(request, coordinates); final String sha = "51cabb8e759852a6a40a7a2a76ef0afd4beef96d"; final String expectedName = "\"Alexander Sinyagin\""; final Commit commit = repoCommits.get(sha); MatcherAssert.assertThat(commit.json() .getJsonObject("author") .get("name") .toString(), Matchers.equalTo(expectedName) ); } }
package com.angcyo.uiview.utils; import android.app.Activity; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.support.annotation.DrawableRes; import android.support.v7.app.NotificationCompat; import android.widget.RemoteViews; import com.angcyo.library.utils.L; import com.angcyo.uiview.R; import com.angcyo.uiview.RApplication; import com.angcyo.uiview.github.utilcode.utils.IntentUtils; import java.io.File; import java.util.Random; public class ProgressNotify { private final int NOTIFICATION_ID; private final NotificationCompat.Builder mBuilder; private final RemoteViews mProgressRemoteViews; private final RemoteViews mFinishRemoteViews; NotificationManager mNotificationManager; private Context mContext; private Class<?> clickActivity; private int requestCode = 10011; private String targetFilePath = ""; private ProgressNotify() { mContext = RApplication.getApp(); this.NOTIFICATION_ID = new Random(System.currentTimeMillis()).nextInt(10_000); mNotificationManager = (NotificationManager) mContext .getSystemService(Activity.NOTIFICATION_SERVICE); mBuilder = new NotificationCompat.Builder(mContext); mBuilder.setPriority(NotificationCompat.PRIORITY_MAX); //activityPendingIntent.getActivitygetService mProgressRemoteViews = new RemoteViews(mContext.getPackageName(), R.layout.base_progress_notify_layout); mFinishRemoteViews = new RemoteViews(mContext.getPackageName(), R.layout.base_progress_finish_notify_layout); } public static ProgressNotify instance() { return Holder.holder; } public ProgressNotify setClickActivity(Class<?> clickActivity) { this.clickActivity = clickActivity; return this; } public ProgressNotify setTargetFilePath(String targetFilePath) { this.targetFilePath = targetFilePath; return this; } public int show(String title, @DrawableRes int logo, int progress) { if (clickActivity != null) { Intent intent = new Intent(mContext, clickActivity); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); //intent.setFlags(Intent.FLAG_ACTIVITY_TASK_ON_HOME); mBuilder.setContentIntent(PendingIntent.getActivity(mContext, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT));// Intent } RemoteViews remoteViews; if (progress >= 100) { remoteViews = mFinishRemoteViews; File targetFile = new File(targetFilePath); if (targetFile.exists()) { L.e("-> " + targetFile.getAbsolutePath()); mBuilder.setContentIntent(PendingIntent.getActivity(mContext, requestCode, IntentUtils.getInstallAppIntent(targetFile), PendingIntent.FLAG_UPDATE_CURRENT));// Intent } else { L.e("-> " + targetFile.getAbsolutePath()); } } else { mProgressRemoteViews.setProgressBar(R.id.progressBar, 100, progress, false); remoteViews = mProgressRemoteViews; } remoteViews.setImageViewResource(R.id.image_view, logo); remoteViews.setTextViewText(R.id.text_view, title); mBuilder.setOngoing(true); mBuilder.setSmallIcon(logo); mBuilder.setContent(remoteViews); mBuilder.setWhen(System.currentTimeMillis()); mNotificationManager.notify(this.getClass().getSimpleName(), NOTIFICATION_ID, mBuilder.build()); return NOTIFICATION_ID; } static class Holder { static ProgressNotify holder = new ProgressNotify(); } }
package com.uwetrottmann.trakt5; import com.uwetrottmann.trakt5.entities.AccessToken; import com.uwetrottmann.trakt5.entities.BaseEpisode; import com.uwetrottmann.trakt5.entities.BaseMovie; import com.uwetrottmann.trakt5.entities.BaseRatedEntity; import com.uwetrottmann.trakt5.entities.BaseSeason; import com.uwetrottmann.trakt5.entities.BaseShow; import com.uwetrottmann.trakt5.entities.CastMember; import com.uwetrottmann.trakt5.entities.Credits; import com.uwetrottmann.trakt5.entities.CrewMember; import com.uwetrottmann.trakt5.entities.Ratings; import com.uwetrottmann.trakt5.entities.Stats; import com.uwetrottmann.trakt5.entities.TraktError; import com.uwetrottmann.trakt5.enums.Type; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import org.junit.BeforeClass; import retrofit2.Call; import retrofit2.Response; import javax.annotation.Nullable; import java.io.IOException; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; public class BaseTestCase { protected static final String TEST_CLIENT_ID = "35a671df22d3d98b09aab1c0bc52977e902e696a7704cab94f4d12c2672041e4"; public static final String TEST_ACCESS_TOKEN = "d579c8118878c114fe86c0e6fb779c53be7676dd89e17f2f63ce1d5445f26f88"; // "sgtest" on production public static final String TEST_REFRESH_TOKEN = "5ad78506d0c7d0e53f805fd120ce2a149c98c429229dc84170c0e37f0fa563e5"; // "sgtest" on production private static final boolean DEBUG = true; private static final TraktV2 trakt = new TestTraktV2(TEST_CLIENT_ID); protected static final Integer DEFAULT_PAGE_SIZE = 10; static class TestTraktV2 extends TraktV2 { public TestTraktV2(String apiKey) { super(apiKey); } public TestTraktV2(String apiKey, String clientSecret, String redirectUri) { super(apiKey, clientSecret, redirectUri); refreshToken(TEST_REFRESH_TOKEN); } @Override protected void setOkHttpClientDefaults(OkHttpClient.Builder builder) { super.setOkHttpClientDefaults(builder); if (DEBUG) { // add logging // standard output is easier to read HttpLoggingInterceptor logging = new HttpLoggingInterceptor(System.out::println); boolean isCI = System.getenv("CI") != null; // Reduce log size on CI server. If there is a response issue, should test on dev machine! logging.setLevel(isCI ? HttpLoggingInterceptor.Level.BASIC : HttpLoggingInterceptor.Level.BODY); // Note: currently not logging headers in CI. // if (isCI) { // logging.redactHeader(TraktV2.HEADER_TRAKT_API_KEY); // logging.redactHeader(TraktV2.HEADER_AUTHORIZATION); builder.addNetworkInterceptor(logging); } } } @BeforeClass public static void setUpOnce() { trakt.accessToken(TEST_ACCESS_TOKEN); } protected TraktV2 getTrakt() { return trakt; } /** * Execute call with non-Void response body. */ public <T> T executeCall(Call<T> call) throws IOException { Response<T> response = call.execute(); if (!response.isSuccessful()) { handleFailedResponse(response); // will throw error } T body = response.body(); if (body != null) { return body; } else { throw new IllegalStateException("Body should not be null for successful response"); } } /** * Execute call with non-Void response body, without extracting it. */ public <T> Response<T> executeCallWithoutReadingBody(Call<T> call) throws IOException { Response<T> response = call.execute(); if (!response.isSuccessful()) { handleFailedResponse(response); // will throw error } return response; } /** * Execute call with Void response body. */ public <T> void executeVoidCall(Call<T> call) throws IOException { Response<T> response = call.execute(); if (!response.isSuccessful()) { handleFailedResponse(response); // will throw error } } public <T> void assertSuccessfulResponse(Response<T> response) { if (!response.isSuccessful()) { handleFailedResponse(response); } } private <T> void handleFailedResponse(Response<T> response) { if (response.code() == 401) { fail("Authorization required, supply a valid OAuth access token: " + response.code() + " " + response.message()); } else { String message = "Request failed: " + response.code() + " " + response.message(); TraktError error = getTrakt().checkForTraktError(response); if (error != null && error.message != null) { message += " message: " + error.message; } fail(message); } } protected static <T extends BaseRatedEntity> void assertRatedEntities(List<T> ratedEntities) { for (BaseRatedEntity ratedEntity : ratedEntities) { assertThat(ratedEntity.rated_at).isNotNull(); assertThat(ratedEntity.rating).isNotNull(); } } public void assertRatings(Ratings ratings) { // rating can be null, but we use a show where we can be sure it's rated assertThat(ratings.rating).isGreaterThanOrEqualTo(0); assertThat(ratings.votes).isGreaterThanOrEqualTo(0); assertThat(ratings.distribution).hasSize(10); } public void assertStats(Stats stats) { assertThat(stats.watchers).isGreaterThanOrEqualTo(0); assertThat(stats.plays).isGreaterThanOrEqualTo(0); assertThat(stats.collectors).isGreaterThanOrEqualTo(0); assertThat(stats.comments).isGreaterThanOrEqualTo(0); assertThat(stats.lists).isGreaterThanOrEqualTo(0); assertThat(stats.votes).isGreaterThanOrEqualTo(0); } public void assertShowStats(Stats stats) { assertStats(stats); assertThat(stats.collected_episodes).isGreaterThanOrEqualTo(0); } protected static void assertSyncMovies(List<BaseMovie> movies, String type) { for (BaseMovie movie : movies) { assertThat(movie.movie).isNotNull(); switch (type) { case "collection": assertThat(movie.collected_at).isNotNull(); break; case "watched": assertThat(movie.plays).isPositive(); assertThat(movie.last_watched_at).isNotNull(); assertThat(movie.last_updated_at).isNotNull(); break; case "watchlist": assertThat(movie.listed_at).isNotNull(); break; } } } protected static void assertSyncShows(List<BaseShow> shows, String type) { for (BaseShow show : shows) { assertThat(show.show).isNotNull(); if ("collection".equals(type)) { assertThat(show.last_collected_at).isNotNull(); } else if ("watched".equals(type)) { assertThat(show.plays).isPositive(); assertThat(show.last_watched_at).isNotNull(); assertThat(show.last_updated_at).isNotNull(); } for (BaseSeason season : show.seasons) { assertThat(season.number).isGreaterThanOrEqualTo(0); for (BaseEpisode episode : season.episodes) { assertThat(episode.number).isGreaterThanOrEqualTo(0); if ("collection".equals(type)) { assertThat(episode.collected_at).isNotNull(); } else if ("watched".equals(type)) { assertThat(episode.plays).isPositive(); assertThat(episode.last_watched_at).isNotNull(); } } } } } public void assertCast(Credits credits, Type type) { for (CastMember castMember : credits.cast) { assertThat(castMember.character).isNotNull(); if (type == Type.SHOW) { assertThat(castMember.movie).isNull(); assertThat(castMember.show).isNotNull(); assertThat(castMember.person).isNull(); } else if (type == Type.MOVIE) { assertThat(castMember.movie).isNotNull(); assertThat(castMember.show).isNull(); assertThat(castMember.person).isNull(); } else if (type == Type.PERSON) { assertThat(castMember.movie).isNull(); assertThat(castMember.show).isNull(); assertThat(castMember.person).isNotNull(); } } } public void assertCrew(Credits credits, Type type) { if (credits.crew != null) { assertCrewMembers(credits.crew.production, type); assertCrewMembers(credits.crew.writing, type); assertCrewMembers(credits.crew.directing, type); assertCrewMembers(credits.crew.costumeAndMakeUp, type); assertCrewMembers(credits.crew.sound, type); assertCrewMembers(credits.crew.art, type); assertCrewMembers(credits.crew.camera, type); } } public void assertCrewMembers(@Nullable List<CrewMember> crew, Type type) { if (crew == null) { return; } for (CrewMember crewMember : crew) { assertThat(crewMember.job).isNotNull(); // may be empty, so not checking for now if (type == Type.SHOW) { assertThat(crewMember.movie).isNull(); assertThat(crewMember.show).isNotNull(); assertThat(crewMember.person).isNull(); } else if (type == Type.MOVIE) { assertThat(crewMember.movie).isNotNull(); assertThat(crewMember.show).isNull(); assertThat(crewMember.person).isNull(); } else if (type == Type.PERSON) { assertThat(crewMember.movie).isNull(); assertThat(crewMember.show).isNull(); assertThat(crewMember.person).isNotNull(); } } } protected void assertAccessTokenResponse(Response<AccessToken> response) { assertSuccessfulResponse(response); assertThat(response.body().access_token).isNotEmpty(); assertThat(response.body().refresh_token).isNotEmpty(); assertThat(response.body().created_at).isPositive(); assertThat(response.body().expires_in).isPositive(); System.out.println("Retrieved access token: " + response.body().access_token); System.out.println("Retrieved refresh token: " + response.body().refresh_token); System.out.println("Retrieved scope: " + response.body().scope); System.out.println("Retrieved expires in: " + response.body().expires_in + " seconds"); } }
package datastructures; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; /** * @author Pavel Nichita * */ public class DFJointProjectionTest { private SetUpClass setUpObject; /** * Set up. */ @Before public void setUp() { this.setUpObject = new SetUpClass(); } /** * Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}. * Projecting {AB -> C, C -> A} on {B, C}, * result: {}. */ @Test public void testProjectionOnAttributeJointDFJoint10OnBC() { FDSet dfJoint = this.setUpObject.dfJoint10(); AttributeSet attrJoint = this.setUpObject.attrJntBC(); FDSet expected = new FDSet(); assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint)); } /** * Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}. * Projecting {AB -> C, C -> A} on {A, C}, * result: {C -> A}. */ @Test public void testProjectionDFJointTenToAttributeJointAC() { FDSet dfJoint = this.setUpObject.dfJoint10(); AttributeSet attrJoint = this.setUpObject.attrJntAC(); FDSet expected = this.setUpObject.dfJoint11(); assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint)); } /** * Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}. * Projecting {A -> B, CD -> A, BD -> C, DE -> C} on {A, B}, * result: {A -> B}. */ @Test public void testProjectionDFJointTwelveToAttributeJointAB() { FDSet dfJoint = this.setUpObject.dfJoint12(); AttributeSet attrJoint = this.setUpObject.attrJntAB(); FDSet expected = this.setUpObject.dfJoint13(); assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint)); } /** * Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}. * Projecting {A -> B, CD -> A, BD -> C, DE -> C} on {A, C, D, E}, * result: {CD -> A, AD -> C, DE -> C}. */ @Test public void testProjectionDFJointTwelveToAttributeJointACDE() { FDSet dfJoint = this.setUpObject.dfJoint12(); AttributeSet attrJoint = this.setUpObject.attrJntACDE(); FDSet expected = this.setUpObject.dfJoint14(); assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint)); } /** * Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}. * Projecting {CD -> A, AD -> C, DE -> C} on {A, C, D}, * result: {CD -> A, AD -> C}. */ @Test public void testProjectionDFJointFourteenToAttributeJointACD() { FDSet dfJoint = this.setUpObject.dfJoint14(); AttributeSet attrJoint = this.setUpObject.attrJntACD(); FDSet expected = this.setUpObject.dfJoint15(); assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint)); } /** * Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}. * Projecting {CD -> A, AD -> C, DE -> C} on {C, D, E}, * result: {DE -> C}. */ @Test public void testProjectionDFJointFourteenToAttributeJointCDE() { FDSet dfJoint = this.setUpObject.dfJoint14(); AttributeSet attrJoint = this.setUpObject.attrJntCDE(); FDSet expected = this.setUpObject.dfJoint16(); assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint)); } /** * Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}. * Projecting {BCD -> E, E -> C} on {C, E}, * result: {E -> C}. */ @Test public void testProjectionDFJointSeventeenToAttributeJointCE() { FDSet dfJoint = this.setUpObject.dfJoint17(); AttributeSet attrJoint = this.setUpObject.attrJntCE(); FDSet expected = this.setUpObject.dfJoint18(); assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint)); } /** * Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}. * Projecting {BCD -> E, E -> C} on {B, D, E}, * result: {}. */ @Test public void testProjectionDFJointSeventeenToAttributeJointBDE() { FDSet dfJoint = this.setUpObject.dfJoint17(); AttributeSet attrJoint = this.setUpObject.attrJntBDE(); FDSet expected = new FDSet(); assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint)); } /** * Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}. * Projecting {AB -> C, C -> B} on {B, C}, * result: {C -> B}. */ @Test public void testProjectionDFJointNineteenToAttributeJointBC() { FDSet dfJoint = this.setUpObject.dfJoint19(); AttributeSet attrJoint = this.setUpObject.attrJntBC(); FDSet expected = this.setUpObject.dfJoint20(); assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint)); } /** * Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}. * Projecting {AB -> C, C -> B} on {A, C}, * result: {}. */ @Test public void testProjectionDFJointNineteenToAttributeJointAC() { FDSet dfJoint = this.setUpObject.dfJoint19(); AttributeSet attrJoint = this.setUpObject.attrJntAC(); FDSet expected = new FDSet(); assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint)); } /** * Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}. * Projecting {A -> BC, B -> C, A -> B, AB -> C} on {A, C}, * result: {A -> C}. */ @Test public void testProjectionDFJointFourToAttributeJointAC() { FDSet dfJoint = this.setUpObject.dfJoint04(); AttributeSet attrJoint = this.setUpObject.attrJntAC(); FDSet expected = this.setUpObject.dfJoint21(); assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint)); } /** * Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}. * Projecting {A -> BC, B -> C, A -> B, AB -> C} on {A, B}, * result: {A -> B}. */ @Test public void testProjectionDFJointFourToAttributeJointAB() { FDSet dfJoint = this.setUpObject.dfJoint04(); AttributeSet attrJoint = this.setUpObject.attrJntAB(); FDSet expected = this.setUpObject.dfJoint13(); assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint)); } /** * Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}. * Projecting {A -> BC, B -> C, A -> B, AB -> C} on {B, C}, * result: {B -> C}. */ @Test public void testProjectionDFJointFourToAttributeJointBC() { FDSet dfJoint = this.setUpObject.dfJoint04(); AttributeSet attrJoint = this.setUpObject.attrJntBC(); FDSet expected = this.setUpObject.dfJoint22(); assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint)); } /** * Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}. * Projecting {C -> A, CD -> E, A -> B} on {A, C}, * result: {C -> A}. */ @Test public void testProjectionDFJoint35AToAttributeJointAC() { FDSet dfJoint = this.setUpObject.dpJoint35A(); AttributeSet attrJoint = this.setUpObject.attrJntAC(); FDSet expected = this.setUpObject.dfJointCtoA(); assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint)); } /** * Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}. * Projecting {A -> B, B -> C, C -> D} on {A, D}, * result: {A -> D}. */ @Test public void testProjectionDFJoint07AToAttributeJointAD() { FDSet dfJoint = this.setUpObject.dfJoint07(); AttributeSet attrJoint = this.setUpObject.attrJntAD(); FDSet expected = this.setUpObject.dfJoint29(); assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint)); } /** * Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}. * Projecting {A -> B, B -> C, C -> D} on {A, B, C}, * result: {A -> B, B -> C}. */ @Test public void testProjectionDFJoint07AToAttributeJointABC() { FDSet dfJoint = this.setUpObject.dfJoint07(); AttributeSet attrJoint = this.setUpObject.attrJntABC(); FDSet expected = this.setUpObject.dfJoint05(); assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint)); } /** * Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}. * Projecting {A -> BE, B -> C, EC -> D} on {A, D}, * result: {A -> D}. */ @Test public void testProjectionDFJoint100AToAttributeJointAD() { FDSet dfJoint = this.setUpObject.dfJoint100(); AttributeSet attrJoint = this.setUpObject.attrJntAD(); FDSet expected = this.setUpObject.dfJoint29(); assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint)); } }
package cz.xtf.openshift.messaging; import cz.xtf.openshift.builder.pod.PersistentVolumeClaim; import org.apache.commons.lang3.StringUtils; import cz.xtf.docker.DockerContainer; import cz.xtf.openshift.OpenshiftUtil; import cz.xtf.openshift.builder.ApplicationBuilder; import cz.xtf.openshift.builder.DeploymentConfigBuilder; import cz.xtf.openshift.imagestream.ImageRegistry; import cz.xtf.openshift.storage.DefaultStatefulAuxiliary; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import io.fabric8.kubernetes.api.model.Pod; public class JBossAMQ extends DefaultStatefulAuxiliary implements MessageBroker { static final String SYMBOLIC_NAME = "jbamq"; private static final String USERNAME = "mqUser"; private static final String PASSWORD = "mqPassword"; private static final String ADMIN_USERNAME = "adminUser"; private static final String ADMIN_PASSWORD = "adminPassword"; private static final int OPENWIRE_PORT = 61616; private final List<String> queues = new ArrayList<>(); private final List<String> topics = new ArrayList<>(); private Boolean tracking = null; private String jndiName; private String serviceName = "amq"; public JBossAMQ() { super(SYMBOLIC_NAME, "/opt/amq/data"); } public JBossAMQ(final PersistentVolumeClaim pvc) { super(SYMBOLIC_NAME, "/opt/amq/data", pvc); } public Map<String, String> getImageVariables() { final Map<String, String> vars = new HashMap<>(); vars.put("AMQ_USER", USERNAME); vars.put("AMQ_PASSWORD", PASSWORD); vars.put("AMQ_ADMIN_USERNAME", ADMIN_USERNAME); vars.put("AMQ_ADMIN_PASSWORD", ADMIN_PASSWORD); vars.put("AMQ_PROTOCOLS", "tcp"); vars.put("AMQ_QUEUES", getQueueList()); vars.put("AMQ_TOPIC", getTopicList()); return vars; } protected String getAmqImage() { return ImageRegistry.get().amq(); } @Override public DeploymentConfigBuilder configureDeployment(ApplicationBuilder appBuilder, final boolean synchronous) { final DeploymentConfigBuilder builder = appBuilder.deploymentConfig( SYMBOLIC_NAME, SYMBOLIC_NAME, false); builder.onConfigurationChange().podTemplate().container() .fromImage(getAmqImage()) .envVars(getImageVariables()) .port(OPENWIRE_PORT, "tcp") .port(8778, "jolokia"); if (synchronous) { builder.onConfigurationChange(); builder.synchronousDeployment(); } if (isStateful) { storagePartition.configureApplicationDeployment(builder); } if(this.persistentVolClaim != null){ builder.podTemplate().addPersistenVolumeClaim( this.persistentVolClaim.getName(), this.persistentVolClaim.getClaimName()); builder.podTemplate().container().addVolumeMount(this.persistentVolClaim.getName(), dataDir, false); } appBuilder .service(SYMBOLIC_NAME + "-amq-tcp").setPort(OPENWIRE_PORT) .setContainerPort(OPENWIRE_PORT) .addContainerSelector("name", SYMBOLIC_NAME); return builder; } @Override public void configureApplicationDeployment(final DeploymentConfigBuilder dcBuilder) { String mqServiceMapping = dcBuilder.podTemplate().container().getEnvVars() .getOrDefault("MQ_SERVICE_PREFIX_MAPPING", ""); if (mqServiceMapping.length() != 0) { mqServiceMapping = mqServiceMapping.concat(","); } dcBuilder.podTemplate().container() .envVar("MQ_SERVICE_PREFIX_MAPPING", mqServiceMapping.concat(String.format("%s-%s=%S", SYMBOLIC_NAME, serviceName, SYMBOLIC_NAME))) .envVar(getEnvVarName("USERNAME"), USERNAME) .envVar(getEnvVarName("PASSWORD"), PASSWORD) .envVar(getEnvVarName("QUEUES"), getQueueList()) .envVar(getEnvVarName("TOPICS"), getTopicList()) .envVar(getEnvVarName("PROTOCOL"), "tcp"); if (tracking != null) { dcBuilder.podTemplate().container() .envVar(getEnvVarName("TRACKING"), tracking.booleanValue() ? "true" : "false"); } if (StringUtils.isNotBlank(jndiName)) { dcBuilder.podTemplate().container().envVar(getEnvVarName("JNDI"), jndiName); } } private String getTopicList() { return topics.stream().collect(Collectors.joining(",")); } private String getQueueList() { return queues.stream().collect(Collectors.joining(",")); } @Override public Pod getPod() { return OpenshiftUtil.getInstance().findNamedPod(SYMBOLIC_NAME); } @Override public DockerContainer getContainer() { return DockerContainer.createForPod(getPod(), SYMBOLIC_NAME); } @Override public JBossAMQ withQueues(final String... queues) { Collections.addAll(this.queues, queues); return this; } @Override public JBossAMQ withTopics(final String... topics) { Collections.addAll(this.topics, topics); return this; } public JBossAMQ withJndiName(final String jndiName) { this.jndiName = jndiName; return this; } public JBossAMQ withTracking(final boolean tracking) { this.tracking = tracking; return this; } public JBossAMQ withServiceName(final String serviceName) { this.serviceName = serviceName; return this; } public String getEnvVarName(final String name) { return String.format("%S_%S", SYMBOLIC_NAME, name); } }
package de.bmoth.architecture; import guru.nidi.codeassert.config.AnalyzerConfig; import guru.nidi.codeassert.dependency.DependencyRule; import guru.nidi.codeassert.dependency.DependencyRuler; import guru.nidi.codeassert.dependency.DependencyRules; import guru.nidi.codeassert.model.ModelAnalyzer; import org.junit.Before; import org.junit.Test; import java.io.File; import java.util.Arrays; import java.util.Set; import java.util.stream.Collectors; import static guru.nidi.codeassert.junit.CodeAssertMatchers.*; import static org.junit.Assert.assertThat; public class DependencyTest { private String[] packages = new String[]{"app", "backend", "checkers", "eventbus", "modelchecker", "parser"}; private AnalyzerConfig config; @Before public void setup() { // Analyze all sources in src/main/java config = new AnalyzerConfig(); config = config.withSources(new File("src/main/java/de/bmoth"), packages); config = config.withClasses(new File("build/classes/main/de/bmoth"), packages); } @Test public void noCycles() { assertThat(new ModelAnalyzer(config).analyze(), hasNoClassCycles()); // cycles in packages String[][] exceptions2DimArray = new String[][]{ new String[]{"de.bmoth.parser", "de.bmoth.parser.ast", "de.bmoth.parser.cst", "de.bmoth.parser.ast.visitors"}, new String[]{"de.bmoth.parser.ast.nodes", "de.bmoth.parser.ast.nodes.ltl"}}; @SuppressWarnings("unchecked") Set<String>[] exceptions = Arrays.stream(exceptions2DimArray) .map(a -> Arrays.stream(a).collect(Collectors.toSet())).collect(Collectors.toList()) .toArray((Set<String>[]) new Set<?>[exceptions2DimArray.length]); assertThat(new ModelAnalyzer(config).analyze(), hasNoPackgeCyclesExcept(exceptions)); } @Test public void dependency() { class ExternalPackages extends DependencyRuler { private DependencyRule comMicrosoftZ3; private DependencyRule comMicrosoftZ3Enumerations; private DependencyRule deBmothApp; private DependencyRule deBmothBackendZ3; private DependencyRule deBmothModelchecker; private DependencyRule deBmothModelchecker_; private DependencyRule deBmothCheckers_; private DependencyRule deSaxsysMvvmfx; @Override public void defineRules() { deBmothApp.mayUse(comMicrosoftZ3, comMicrosoftZ3Enumerations, deSaxsysMvvmfx); deBmothBackendZ3.mustUse(comMicrosoftZ3); deBmothBackendZ3.mayUse(comMicrosoftZ3Enumerations); deBmothModelchecker.mustUse(comMicrosoftZ3); deBmothModelchecker.mayUse(comMicrosoftZ3Enumerations); deBmothModelchecker_.mustUse(comMicrosoftZ3); deBmothCheckers_.mustUse(comMicrosoftZ3); } } class InternalPackages extends DependencyRuler { private DependencyRule deBmothParser; private DependencyRule deBmothParserAst; private DependencyRule deBmothParserAst_; private DependencyRule deBmothParserCst; private DependencyRule deBmothParserAstNodes; private DependencyRule deBmothParserAstNodesLtl; private DependencyRule deBmothParserAstTypes; private DependencyRule deBmothParserAstVisitors; @Override public void defineRules() { deBmothParserAst.mustUse(deBmothParserAst_, deBmothParserCst); deBmothParserCst.mustUse(deBmothParser); deBmothParserAstNodes.mustUse(deBmothParserAstTypes, deBmothParserAstNodesLtl); deBmothParserAstVisitors.mustUse(deBmothParserAstNodes, deBmothParserAstNodesLtl); deBmothParserAstNodesLtl.mustUse(deBmothParserAstNodes); } } class DeBmoth extends DependencyRuler { // $self is de.bmoth, added _ refers to subpackages of package private DependencyRule app; private DependencyRule antlr; private DependencyRule backend; private DependencyRule backend_; private DependencyRule checkers_; private DependencyRule eventbus; private DependencyRule modelchecker; private DependencyRule modelchecker_; private DependencyRule parser; private DependencyRule parser_; private DependencyRule preferences; @Override public void defineRules() { app.mayUse(backend_, checkers_, eventbus, modelchecker, modelchecker_, parser, parser_, preferences); backend_.mayUse(preferences, backend, backend_, parser, parser_); checkers_.mayUse(backend, backend_, parser, parser_); modelchecker.mayUse(backend, backend_, parser_); modelchecker_.mayUse(backend, backend_, modelchecker, parser_, preferences); parser.mayUse(antlr, parser_); parser_.mayUse(antlr, parser_); } } // All dependencies are forbidden, except the ones defined above // java, javafx, com and org are ignored // maybe we should include com.microsoft again and check who is // allowed to directly speak to z3 DependencyRules rules = DependencyRules.denyAll().withAbsoluteRules(new InternalPackages()) .withAbsoluteRules(new ExternalPackages()).withRelativeRules(new DeBmoth()) .withExternals("com.google.*", "java.*", "javafx.*", "org.*"); assertThat(new ModelAnalyzer(config).analyze(), packagesMatchExactly(rules)); } }
package org.safehaus.jettyjam.utils; import java.io.BufferedReader; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.lang.management.ManagementFactory; import java.net.URL; import java.util.Properties; import java.util.Timer; import java.util.TimerTask; import java.util.UUID; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** A Jetty launcher. */ public abstract class JettyRunner { private static final Logger LOG = LoggerFactory.getLogger( JettyRunner.class ); public static final String PRINT_ALL = "print_all"; public static final String SHUTDOWN = "shutdown"; public static final String SERVER_URL = "serverUrl"; public static final String SERVER_PORT = "serverPort"; public static final String APP_ID = "appId"; public static final String APP_NAME = "appName"; public static final String PID_FILE = "pidFile"; public static final String IS_SECURE = "isSecure"; public static final String PID = "pid"; private final Server server; private URL serverUrl; private int port; private boolean started; private Timer timer = new Timer(); private File pidFile; private final UUID appId; private final String appName; private String hostname; private boolean secure; protected JettyRunner( String appName ) { server = new Server(); appId = UUID.randomUUID(); this.appName = appName; LOG.info( "JettyRunner for appId {}", appId ); } protected void start() throws Exception { ServerConnector defaultConnector = ConnectorBuilder.setConnectors( getSubClass(), server ); if ( defaultConnector.getHost() == null ) { hostname = "localhost"; } HandlerBuilder handlerBuilder = new HandlerBuilder(); server.setHandler( handlerBuilder.buildForLauncher( getSubClass(), server ) ); server.start(); this.port = defaultConnector.getLocalPort(); String protocol = "http"; if ( defaultConnector.getDefaultProtocol().contains( "SSL" ) ) { protocol = "https"; secure = true; } this.serverUrl = new URL( protocol, hostname, port, "" ); setupPidFile(); Runtime.getRuntime().addShutdownHook( new Thread( new Runnable() { @Override public void run() { try { JettyRunner.this.stop(); } catch ( Exception e ) { LOG.error( "Failed to stop jetty server in JVM shutdown hook.", e ); } } } ) ); timer.scheduleAtFixedRate( new TimerTask() { @Override public void run() { if ( !pidFile.exists() ) { try { JettyRunner.this.stop(); } catch ( Exception e ) { LOG.error( "Failed to stop jetty server after pidFile removal", e ); } } } }, 200, 200 ); // @todo make these configurable command line options (archaius?) started = true; new Thread( new Runnable() { @Override public void run() { String line; BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) ); while ( started ) { try { line = in.readLine(); LOG.info( "Line gotten from CLI: {}", line ); if ( line.equalsIgnoreCase( SHUTDOWN ) ) { try { stop(); System.exit( 0 ); } catch ( Exception e ) { LOG.error( "While shutting down", e ); } } else if ( line.equalsIgnoreCase( SERVER_URL ) ) { System.err.println( serverUrl.toString() ); } else if ( line.equalsIgnoreCase( SERVER_PORT ) ) { System.err.println( port ); } else if ( line.equalsIgnoreCase( APP_ID ) ) { System.err.println( appId.toString() ); } else if ( line.equalsIgnoreCase( APP_NAME ) ) { System.err.println( appName ); } else if ( line.equalsIgnoreCase( PID_FILE ) ) { System.err.println( pidFile.getCanonicalPath() ); } else if ( line.equalsIgnoreCase( PRINT_ALL ) ) { System.err.println( SERVER_URL + ": " + serverUrl.toString() ); System.err.println( SERVER_PORT + ": " + port ); System.err.println( APP_ID + ": " + appId.toString() ); System.err.println( APP_NAME + ": " + appName ); System.err.println( PID_FILE + ": " + pidFile.getCanonicalPath() ); System.err.println( IS_SECURE + ": " + secure ); } } catch ( IOException e ) { LOG.error( "While reading from input stream", e ); } } } } ).start(); } // Also listen to standard in for a shutdown command - shutdown on pid file removal also // Removal of pid file destroys the application and exists // Remove the pid file on premature JVM shutdown - need a RT hook for that // Later on make this a real pid file with the process ID and enable the use of many apps private void setupPidFile() throws IOException { pidFile = File.createTempFile( getAppId().toString(), ".pid" ); Properties properties = new Properties(); properties.setProperty( APP_ID, getAppId().toString() ); properties.setProperty( APP_NAME, getAppName() ); properties.setProperty( SERVER_URL, getServerUrl().toString() ); properties.setProperty( SERVER_PORT, String.valueOf( port ) ); properties.setProperty( IS_SECURE, String.valueOf( secure ) ); String pid = ManagementFactory.getRuntimeMXBean().getName(); properties.setProperty( PID, pid ); FileWriter out = new FileWriter( pidFile ); properties.store( out, "Generated by launcher process: " + pid ); out.flush(); out.close(); System.out.println( "pidFile: " + pidFile.getCanonicalPath() ); } private void cleanupPidFile() throws IOException { if ( !pidFile.delete() ) { pidFile.deleteOnExit(); } } protected void stop() throws Exception { server.stop(); cleanupPidFile(); started = false; } public abstract String getSubClass(); public String getAppName() { return appName; } public UUID getAppId() { return appId; } public boolean isStarted() { return started; } public String getHostname() { return hostname; } public int getPort() { return port; } public boolean isSecure() { return secure; } public URL getServerUrl() { return serverUrl; } }
package umm3601.user; import com.google.gson.Gson; import com.mongodb.*; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.util.JSON; import org.bson.Document; import org.bson.types.ObjectId; import spark.Request; import spark.Response; import java.util.Iterator; import java.util.Map; import static com.mongodb.client.model.Filters.eq; /** * Controller that manages requests for info about users. */ public class UserController { private final Gson gson; private MongoDatabase database; private final MongoCollection<Document> userCollection; /** * Construct a controller for users. * * @param database the database containing user data */ public UserController(MongoDatabase database) { gson = new Gson(); this.database = database; userCollection = database.getCollection("users"); } /** * Method called from Server when the 'api/users/:id' endpoint is received. * * @param req the HTTP request * @param res the HTTP response * @return one user in JSON formatted string and if it fails it will return text with a different HTTP status code */ public String getUser(Request req, Response res){ res.type("application/json"); String id = req.params("id"); String user; try { user = getUser(id); } catch (IllegalArgumentException e) { // This is thrown if the ID doesn't have the appropriate // form for a Mongo Object ID. res.status(400); res.body("The requested user id " + id + " wasn't a legal Mongo Object ID.\n" + "See 'https://docs.mongodb.com/manual/reference/method/ObjectId/' for more info."); return ""; } if (user != null) { return user; } else { res.status(404); res.body("The requested user with id " + id + " was not found"); return ""; } } /** * Helper method that gets a single user specified by the `id` * parameter in the request. * * @param id the Mongo ID of the desired user * @return the desired user as a JSON object if the user with that ID is found, * and `null` if no user with that ID is found */ public String getUser(String id) { FindIterable<Document> jsonUsers = userCollection .find(eq("_id", new ObjectId(id))); Iterator<Document> iterator = jsonUsers.iterator(); if (iterator.hasNext()) { Document user = iterator.next(); return user.toJson(); } else { // We didn't find the desired user return null; } } /** Method called from Server when the 'api/users' endpoint is received. * This handles the request received and the response * that will be sent back. * @param req * @param res * @return an array of users in JSON formatted String */ public String getUsers(Request req, Response res) { res.type("application/json"); return getUsers(req.queryMap().toMap()); } /** Helper method which iterates through the collection, receiving all * documents if no query parameter is specified. If the age query parameter * is specified, then the collection is filtered so only documents of that * specified age are found. * * @param queryParams * @return an array of Users in a JSON formatted string */ public String getUsers(Map<String, String[]> queryParams) { Document filterDoc = new Document(); if (queryParams.containsKey("age")) { int targetAge = Integer.parseInt(queryParams.get("age")[0]); filterDoc = filterDoc.append("age", targetAge); } //FindIterable comes from mongo, Document comes from Gson FindIterable<Document> matchingUsers = userCollection.find(filterDoc); return JSON.serialize(matchingUsers); } /**Method called from Server when the 'api/users/new'endpoint is recieved. * Gets specified user info from request and calls addNewUser helper method * to append that info to a document * * @param req * @param res * @return */ public boolean addNewUser(Request req, Response res) { res.type("application/json"); Object o = JSON.parse(req.body()); try { if(o.getClass().equals(BasicDBObject.class)) { try { BasicDBObject dbO = (BasicDBObject) o; String name = dbO.getString("name"); //For some reason age is a string right now, caused by angular. //This is a problem and should not be this way but here ya go int age = dbO.getInt("age"); String company = dbO.getString("company"); String email = dbO.getString("email"); System.err.println("Adding new user [name=" + name + ", age=" + age + " company=" + company + " email=" + email + ']'); return addNewUser(name, age, company, email); } catch(NullPointerException e) { System.err.println("A value was malformed or omitted, new user request failed."); return false; } } else { System.err.println("Expected BasicDBObject, received " + o.getClass()); return false; } } catch(RuntimeException ree) { ree.printStackTrace(); return false; } } /**Helper method which appends received user information to the to-be added document * * @param name * @param age * @param company * @param email * @return */ public boolean addNewUser(String name, int age, String company, String email) { Document newUser = new Document(); newUser.append("name", name); newUser.append("age", age); newUser.append("company", company); newUser.append("email", email); try { userCollection.insertOne(newUser); } catch(MongoException me) { me.printStackTrace(); return false; } return true; } }
package fake_ev3dev.ev3dev.actuators; import ev3dev.actuators.LCD; import ev3dev.hardware.EV3DevPlatform; import fake_ev3dev.BaseElement; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; public class FakeLCD extends BaseElement{ public FakeLCD(final EV3DevPlatform ev3DevPlatform) throws IOException { if(ev3DevPlatform.equals(EV3DevPlatform.EV3BRICK)) { Path devicesPath = Paths.get( EV3DEV_FAKE_SYSTEM_PATH + "/" + LCD.EV3DEV_EV3_DEVICES_PATH); createDirectories(devicesPath); Path lcdPath = Paths.get( EV3DEV_FAKE_SYSTEM_PATH + "/" + LCD.EV3DEV_EV3_DEVICES_PATH + "/" + LCD.EV3DEV_EV3_LCD_NAME); createFile(lcdPath); }else { resetEV3DevInfrastructure(); } } }
package net.sf.jabb.util.stat; import static org.junit.Assert.*; import net.sf.jabb.util.stat.TimePeriod; import org.junit.Test; /** * @author James Hu * */ public class TimePeriodTest { @Test public void testIsDivisorOf() { assertIsDivisorOf("3 day", "1 year", false); assertIsDivisorOf("3 days", "3 years", true); assertIsDivisorOf("1 months", "1 year", true); assertIsDivisorOf("2 months", "1 year", true); assertIsDivisorOf("3 months", "1 year", true); assertIsDivisorOf("4 months", "1 year", true); assertIsDivisorOf("5 months", "1 year", false); assertIsDivisorOf("6 months", "1 year", true); assertIsDivisorOf("15 minutes", "1 hour", true); assertIsDivisorOf("16 minutes", "1 hour", false); assertIsDivisorOf("30 minutes", "1 week", true); assertIsDivisorOf("40 minutes", "2 hour", true); assertIsDivisorOf("40 minutes", "1 week", true); assertIsDivisorOf("1000 milliseconds", "1 second", true); assertIsDivisorOf("1000 milliseconds", "2 second", true); assertIsDivisorOf("2000 milliseconds", "1 second", false); } protected void assertIsDivisorOf(String divisor, String divident, boolean expectedResult){ assertIsDivisorOf(TimePeriod.of(divisor), TimePeriod.of(divident), expectedResult); } protected void assertIsDivisorOf(TimePeriod divisor, TimePeriod divident, boolean expectedResult){ boolean result = divisor.isDivisorOf(divident); assertEquals("" + divisor + " is" + (expectedResult? "" : " not") + " divisor of " + divident, expectedResult, result); } @Test public void testFromString(){ assertEquals(TimePeriod.from(" 1 hour"), TimePeriod.from("1h")); assertEquals(TimePeriod.from(" 1 hour"), TimePeriod.from("1 h")); assertEquals(TimePeriod.from("9 days "), TimePeriod.from(" 9d")); assertEquals(TimePeriod.from("2 days "), TimePeriod.from("2 D ")); } }
package org.neo4j.examples.socnet; import org.hamcrest.CoreMatchers; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Transaction; import org.neo4j.helpers.collection.IteratorUtil; import org.neo4j.index.IndexService; import org.neo4j.index.lucene.LuceneIndexService; import org.neo4j.kernel.EmbeddedGraphDatabase; import java.util.ArrayList; import java.util.Date; import java.util.Random; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import static org.hamcrest.collection.IsCollectionContaining.hasItems; public class SocnetTest { private static final Random r = new Random(System.currentTimeMillis()); private GraphDatabaseService graphDb; private IndexService index; private PersonRepository personRepository; private int nrOfPersons; @Before public void setup() { graphDb = new EmbeddedGraphDatabase("target/socnetdb"); index = new LuceneIndexService(graphDb); personRepository = new PersonRepository(graphDb, index); nrOfPersons = 20; createPersons(); setupFriendsBetweenPeople(10); } @After public void teardown() { try { deleteSocialGraph(graphDb, personRepository); } finally { index.shutdown(); graphDb.shutdown(); } } @Test public void addStatusAndRetrieveIt() throws Exception { Person person = getRandomPerson(); personRepository.addStatusToPerson(person, "Testing!"); StatusUpdate update = person.getStatus().iterator().next(); assertThat(update, CoreMatchers.<Object>notNullValue()); assertThat(update.getStatusText(), equalTo("Testing!")); assertThat(update.getPerson(), equalTo(person)); } @Test public void multipleStatusesComeOutInTheRightOrder() throws Exception { ArrayList<String> statuses = new ArrayList<String>(); statuses.add("Test1"); statuses.add("Test2"); statuses.add("Test3"); Person person = getRandomPerson(); for(String status : statuses) { personRepository.addStatusToPerson(person, status); } int i = statuses.size(); for(StatusUpdate update : person.getStatus()){ i assertThat(update.getStatusText(), equalTo(statuses.get(i))); } } @Test public void removingOneFriendIsHandledCleanly() { Person person1 = personRepository.getPersonByName("person Person person2 = personRepository.getPersonByName("person person1.addFriend(person2); int noOfFriends = person1.getNrOfFriends(); person1.removeFriend(person2); int noOfFriendsAfterChange = person1.getNrOfFriends(); assertThat(noOfFriends, equalTo(noOfFriendsAfterChange+1)); } @Test public void retrieveStatusUpdatesInDateOrder() throws Exception { Person person = getRandomPersonWithFriends(); int numberOfStatuses = 20; for(int i = 0; i<numberOfStatuses; i++) { Person friend = getRandomFriendOf(person); personRepository.addStatusToPerson(friend, "Dum-deli-dum..."); } ArrayList<StatusUpdate> updates = new ArrayList<StatusUpdate>(); IteratorUtil.addToCollection(person.friendStatuses(), updates); assertThat(updates.size(), equalTo(numberOfStatuses)); assertUpdatesAreSortedByDate(updates); } @Test public void friendsOfFriendsWorks() throws Exception { Person person = getRandomPerson(); Person friend = getRandomFriendOf(person); for(Person friendOfFriend : friend.getFriends()) { if(!friendOfFriend.equals(person)) { // You can't be friends with yourself. assertThat(person.getFriendsOfFriends(), hasItems(friendOfFriend)); } } } private void setupFriendsBetweenPeople(int maxNrOfFriendsEach) { Transaction tx = graphDb.beginTx(); try { for (Person person : personRepository.getAllPersons()) { int nrOfFriends = r.nextInt(maxNrOfFriendsEach) + 1; for (int j = 0; j < nrOfFriends; j++) { person.addFriend(getRandomPerson()); } } tx.success(); } finally { tx.finish(); } } private Person getRandomPerson() { return personRepository.getPersonByName("person r.nextInt(nrOfPersons)); } private static void deleteSocialGraph(GraphDatabaseService graphDb, PersonRepository personRepository) { Transaction tx = graphDb.beginTx(); try { for (Person person : personRepository.getAllPersons()) { personRepository.deletePerson(person); } tx.success(); } finally { tx.finish(); } } private Person getRandomFriendOf(Person p) { ArrayList<Person> friends = new ArrayList<Person>(); IteratorUtil.addToCollection(p.getFriends().iterator(), friends); return friends.get(r.nextInt(friends.size())); } private Person getRandomPersonWithFriends() { Person p; do { p = getRandomPerson(); } while (p.getNrOfFriends() == 0); return p; } private void createPersons() { Transaction tx = graphDb.beginTx(); try { for (int i = 0; i < nrOfPersons; i++) { personRepository.createPerson("person } tx.success(); } finally { tx.finish(); } } private void assertUpdatesAreSortedByDate(ArrayList<StatusUpdate> statusUpdates) { Date date = new Date(0); for(StatusUpdate update : statusUpdates) { org.junit.Assert.assertTrue(date.getTime() < update.getDate().getTime()); //TODO: Should be assertThat(date, lessThan(update.getDate)); } } }
package org.neo4j.talend; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Transaction; import org.neo4j.graphdb.factory.GraphDatabaseFactory; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Neo4jImportToolTest { private Neo4jImportTool importTool; private File dbPath; @Before public void before() throws IOException { this.dbPath = Files.createTempDirectory("neo4j_").toFile(); // Neo4j configuration Map<String, String> configNeo = new HashMap<>(); configNeo.put("dbms.pagecache.memory", "2G"); // Import configuration Map<String, String> configImport = new HashMap<>(); configImport.put("stacktrace", ""); // Nodes file final File actors = new File(ClassLoader.getSystemResource("importTool/actors.csv").getFile()); final File movies = new File(ClassLoader.getSystemResource("importTool/movies.csv").getFile()); List<Map<String, String>> nodes = new ArrayList<>(); nodes.add(new HashMap<String, String>() {{ put(Neo4jImportTool.FILE_KEY,actors.getAbsolutePath()); put(Neo4jImportTool.HEADERS_KEY, "personId:ID,name,:LABEL"); }}); nodes.add(new HashMap<String, String>() {{ put(Neo4jImportTool.FILE_KEY,movies.getAbsolutePath()); put(Neo4jImportTool.HEADERS_KEY, "movieId:ID,title,year:int,:LABEL"); }}); // Relationship files final File roles = new File(ClassLoader.getSystemResource("importTool/roles.csv").getFile()); List<Map<String, String>> relationships = new ArrayList<>(); relationships.add(new HashMap<String, String>() {{ put(Neo4jImportTool.FILE_KEY, roles.getAbsolutePath()); put(Neo4jImportTool.HEADERS_KEY, ":START_ID,role,:END_ID,:TYPE"); }}); importTool = new Neo4jImportTool(dbPath.getPath(), configNeo, configImport, nodes, relationships); } @Test public void create_neo4j_config_file_should_succeed() throws Exception { String path = this.importTool.createNeo4jConfigFile(); File file = new File(path); List<String> lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); Assert.assertTrue(file.exists()); Assert.assertEquals("dbms.pagecache.memory=2G",lines.get(0)); } @Test public void create_headers_file_should_succeed() throws IOException { String path = this.importTool.createHeaderFile(":START_ID,role,:END_ID,:TYPE"); File file = new File(path); List<String> lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); Assert.assertTrue(file.exists()); Assert.assertEquals(":START_ID,role,:END_ID,:TYPE",lines.get(0)); } @Test public void execute_import_should_succeed() throws IOException { this.importTool.execute(); // Testing it with real graphdb GraphDatabaseService graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(dbPath); try (Transaction tx = graphDb.beginTx()) { String result = graphDb.execute("MATCH ()-[r]->() RETURN count(r) AS count").resultAsString(); Assert.assertEquals("+ } graphDb.shutdown(); } }
package pokeraidbot.domain; import net.dv8tion.jda.core.entities.User; import org.junit.Before; import org.junit.Test; import pokeraidbot.TestServerMain; import pokeraidbot.domain.config.LocaleService; import pokeraidbot.domain.errors.GymNotFoundException; import pokeraidbot.domain.gym.Gym; import pokeraidbot.domain.gym.GymRepository; import pokeraidbot.infrastructure.CSVGymDataReader; import pokeraidbot.infrastructure.jpa.config.Config; import pokeraidbot.infrastructure.jpa.config.ServerConfigRepository; import pokeraidbot.infrastructure.jpa.config.UserConfigRepository; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Set; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.text.MatchesPattern.matchesPattern; import static org.junit.Assert.*; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class GymRepositoryTest { public static final ServerConfigRepository SERVER_CONFIG_REPOSITORY = mock(ServerConfigRepository.class); GymRepository repo; private final Gym gym = new Gym("Hästen", "3690325", "59.844542", "17.63993", "Uppsala"); private LocaleService localeService; private Map<String, Config> configMap; @Before public void setUp() throws Exception { UserConfigRepository userConfigRepository = mock(UserConfigRepository.class); when(userConfigRepository.findOne(any(String.class))).thenReturn(null); localeService = new LocaleService("sv", userConfigRepository); final Config staffordConfig = new Config("stafford uk", "stafford uk"); when(SERVER_CONFIG_REPOSITORY.getConfigForServer("stafford uk")).thenReturn(staffordConfig); final Config dalarnaConfig = new Config("dalarna", "dalarna"); when(SERVER_CONFIG_REPOSITORY.getConfigForServer("dalarna")).thenReturn(dalarnaConfig); final Config uppsalaConfig = new Config("uppsala", "uppsala"); when(SERVER_CONFIG_REPOSITORY.getConfigForServer("uppsala")).thenReturn(uppsalaConfig); final Config angelholmConfig = new Config("ängelholm", "ängelholm"); when(SERVER_CONFIG_REPOSITORY.getConfigForServer("ängelholm")).thenReturn(angelholmConfig); final Config luleConfig = new Config("luleå", "luleå"); when(SERVER_CONFIG_REPOSITORY.getConfigForServer("luleå")).thenReturn(luleConfig); final Config umeConfig = new Config("umeå", "umeå"); when(SERVER_CONFIG_REPOSITORY.getConfigForServer("umeå")).thenReturn(umeConfig); final Config vannasConfig = new Config("vännäs", "vännäs"); when(SERVER_CONFIG_REPOSITORY.getConfigForServer("vännäs")).thenReturn(vannasConfig); final Config vindelnConfig = new Config("vindeln", "vindeln"); when(SERVER_CONFIG_REPOSITORY.getConfigForServer("vindeln")).thenReturn(vindelnConfig); final Config lyckseleConfig = new Config("lycksele", "lycksele"); when(SERVER_CONFIG_REPOSITORY.getConfigForServer("lycksele")).thenReturn(lyckseleConfig); final Config norrkopingConfig = new Config("norrköping", "norrköping"); when(SERVER_CONFIG_REPOSITORY.getConfigForServer("norrköping")).thenReturn(norrkopingConfig); final Config trollhattanConfig = new Config("trollhättan", "trollhättan"); when(SERVER_CONFIG_REPOSITORY.getConfigForServer("trollhättan")).thenReturn(trollhattanConfig); final Config helsingborgConfig = new Config("helsingborg", "helsingborg"); when(SERVER_CONFIG_REPOSITORY.getConfigForServer("helsingborg")).thenReturn(helsingborgConfig); configMap = new HashMap<>(); configMap.put("stafford uk", staffordConfig); configMap.put("dalarna", dalarnaConfig); configMap.put("uppsala", uppsalaConfig); configMap.put("ängelholm", angelholmConfig); configMap.put("luleå", luleConfig); configMap.put("umeå", umeConfig); configMap.put("vännäs", vannasConfig); configMap.put("vindeln", vindelnConfig); configMap.put("norrköping", norrkopingConfig); configMap.put("trollhättan", trollhattanConfig); configMap.put("helsingborg", helsingborgConfig); configMap.put("lycksele", lyckseleConfig); when(SERVER_CONFIG_REPOSITORY.getAllConfig()).thenReturn(configMap); repo = TestServerMain.getGymRepositoryForConfig(localeService, SERVER_CONFIG_REPOSITORY); } @Test public void noDuplicatesInDataFiles() { Map<String, Set<Gym>> gymData = repo.getAllGymData(); for (String region : gymData.keySet()) { Set<Gym> gyms = gymData.get(region); for (Gym gym : gyms) { final Gym gymFromRepo = repo.findByName(gym.getName(), region); assertThat("Seems we have a duplicate for gymname: " + gym.getName() + " \n" + gymFromRepo.toStringDetails() + " != " + gym.toStringDetails(), gymFromRepo, is(gym)); } } } @Test public void allLocationsHasCorrectFormat() { Map<String, Set<Gym>> gymData = repo.getAllGymData(); for (Set<Gym> gyms : gymData.values()) { for (Gym gym : gyms) { assertThat(gym.getX(), matchesPattern("\\-?[0-9]+\\.[0-9]+")); assertThat(gym.getY(), matchesPattern("\\-?[0-9]+\\.[0-9]+")); } } } @Test public void allGymsAreReadForStafford() { assertThat(repo.getAllGymsForRegion("stafford uk").size(), is(148)); } @Test public void allGymsAreReadForDalarna() { final Set<Gym> dalarnaGyms = repo.getAllGymsForRegion("dalarna"); assertThat(dalarnaGyms.size(), is(115)); assertThat(dalarnaGyms.iterator().next().isInArea("rättvik"), is(true)); } @Test public void allGymsAreReadForLycksele() { assertThat(repo.getAllGymsForRegion("lycksele").size(), is(11)); } @Test public void allGymsAreReadForUppsala() { assertThat(repo.getAllGymsForRegion("uppsala").size(), is(345)); } @Test public void allGymsAreReadForAngelholm() { assertThat(repo.getAllGymsForRegion("ängelholm").size(), is(32)); } @Test public void allGymsAreReadForLulea() { assertThat(repo.getAllGymsForRegion("luleå").size(), is(118)); } @Test public void allGymsAreReadForUmea() { assertThat(repo.getAllGymsForRegion("umeå").size(), is(230)); } @Test public void allGymsAreReadForTrollhattan() { assertThat(repo.getAllGymsForRegion("trollhättan").size(), is(80)); } @Test public void allGymsAreReadForVindeln() { assertThat(repo.getAllGymsForRegion("vindeln").size(), is(6)); } @Test public void allGymsAreReadForVannas() { assertThat(repo.getAllGymsForRegion("vännäs").size(), is(16)); } @Test public void allGymsAreReadForNorrkoping() { assertThat(repo.getAllGymsForRegion("norrköping").size(), is(104)); } @Test public void allGymsAreReadForHelsingborg() { assertThat(repo.getAllGymsForRegion("helsingborg").size(), is(219)); } @Test public void findGymByName() throws Exception { assertThat(repo.findByName("Hästen", "uppsala"), is(gym)); } @Test public void findNonExGym() throws Exception { final Gym gym = repo.findByName("Sköldpaddorna", "norrköping"); assertThat(gym.isExGym(), is(false)); assertThat(gym.getName(), is("Sköldpaddorna")); } @Test public void feather360IsExGym() throws Exception { final Gym feather360 = repo.findByName("Feather Sculpture 360", "uppsala"); assertThat(feather360.isInArea("Uppsala"), is(true)); assertThat(feather360.isExGym(), is(true)); } @Test public void malakIsExGym() throws Exception { final Gym gym = repo.findByName("Malak", "vännäs"); assertThat(gym.isInArea("Vännäs"), is(true)); assertThat(gym.isExGym(), is(true)); } @Test public void findGymByFuzzySearch() throws Exception { User user = mock(User.class); when(user.getName()).thenReturn("Greger"); assertThat(repo.search(user,"hosten", "uppsala"), is(gym)); } @Test public void findGymById() throws Exception { assertThat(repo.findById("3690325", "uppsala"), is(gym)); } @Test public void findNewGymInUppsala() throws Exception { final Gym u969 = repo.findByName("U969", "uppsala"); assertThat(u969.getName(), is("U969")); assertThat(u969.isExGym(), is(false)); } @Test public void addTemporaryGymToUppsala() { Gym gym; try { gym = repo.findByName("Mongo", "uppsala"); fail("Gym should not exist yet."); } catch (GymNotFoundException e) { // Expected } final User userMock = mock(User.class); when(userMock.getName()).thenReturn("User"); repo.addTemporary(userMock, new Gym("Mongo", "66666666", "50.0001", "25.00001", "Uppsala", false), "uppsala"); gym = repo.findByName("Mongo", "uppsala"); assertThat(gym.getName(), is("Mongo")); assertThat(gym.isExGym(), is(false)); } @Test public void checkThatAllExGymsAreInGymRepos() { for (String region : configMap.keySet()) { assertAllExGymsInRegion(region); } } private void assertAllExGymsInRegion(String region) { Set<String> exGymNamesForRegion; final String fileName = "/gyms_" + region.toLowerCase() + ".csv.ex.txt"; final InputStream inputStreamEx = GymRepositoryTest.class.getResourceAsStream(fileName); exGymNamesForRegion = CSVGymDataReader.readExGymListIfExists(inputStreamEx, fileName); for (String gymName : exGymNamesForRegion) { final Gym gym = repo.findByName(gymName, region); assertThat(gym != null, is(true)); assertThat(gym.getName(), is(gymName)); } } }
package technology.tabula; import java.io.File; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.nio.file.Files; import java.util.*; import static org.junit.Assert.*; import com.google.gson.Gson; import com.google.gson.JsonObject; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.w3c.dom.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.pdfbox.pdmodel.PDDocument; import technology.tabula.detectors.DetectionAlgorithm; import technology.tabula.detectors.NurminenDetectionAlgorithm; import technology.tabula.detectors.SpreadsheetDetectionAlgorithm; @RunWith(Parameterized.class) public class TestTableDetection { private class TestStatistics { public int numExpectedTables; public int numDetectedTables; public TestStatistics() { this.numExpectedTables = 0; this.numDetectedTables = 0; } } private static final String STATISTICS_FILE = "src/test/resources/technology/tabula/icdar2013-dataset/test-statistics.json"; private static final boolean ASSERT = true; @Parameterized.Parameters public static Collection<Object[]> data() { String[] regionCodes = {"eu", "us"}; ArrayList<Object[]> data = new ArrayList<Object[]>(); for (String regionCode : regionCodes) { String directoryName = "src/test/resources/technology/tabula/icdar2013-dataset/competition-dataset-" + regionCode + "/"; File dir = new File(directoryName); File[] pdfs = dir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".pdf"); } }); for (File pdf : pdfs) { data.add(new Object[] {pdf}); } } return data; } @BeforeClass public static void clearStats() { try { File statsFile = new File(STATISTICS_FILE); statsFile.delete(); } catch (Exception e) { // file must not exist in the first place } } private File pdf; private DocumentBuilder builder; private TestStatistics stats; public TestTableDetection(File pdf) { this.pdf = pdf; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { this.builder = factory.newDocumentBuilder(); } catch (Exception e) { } // read in the overall test statistics Gson gson = new Gson(); String statsJson; try { statsJson = UtilsForTesting.loadJson(STATISTICS_FILE); this.stats = gson.fromJson(statsJson, TestStatistics.class); } catch (IOException ioe) { // file must not exist this.stats = new TestStatistics(); } } private void saveStats() { try { FileWriter w = new FileWriter(STATISTICS_FILE); Gson gson = new Gson(); w.write(gson.toJson(this.stats)); w.close(); } catch (Exception e) { } } private void printTables(Map<Integer, List<Rectangle>> tables) { for (Integer page : tables.keySet()) { System.out.println("Page " + page.toString()); for (Rectangle table : tables.get(page)) { System.out.println(table); } } } //@Ignore("Test is ignored until better table detection algorithms are implemented") @Test public void testDetectionOfTables() throws Exception { // xml parsing stuff for ground truth Document regionDocument = this.builder.parse(this.pdf.getAbsolutePath().replace(".pdf", "-reg.xml")); NodeList tables = regionDocument.getElementsByTagName("table"); // tabula extractors PDDocument pdfDocument = PDDocument.load(this.pdf); ObjectExtractor extractor = new ObjectExtractor(pdfDocument); // parse expected tables from the ground truth dataset Map<Integer, List<Rectangle>> expectedTables = new HashMap<Integer, List<Rectangle>>(); int numExpectedTables = 0; for (int i=0; i<tables.getLength(); i++) { Element table = (Element) tables.item(i); Element region = (Element) table.getElementsByTagName("region").item(0); Element boundingBox = (Element) region.getElementsByTagName("bounding-box").item(0); // we want to know where tables appear in the document - save the page and areas where tables appear Integer page = Integer.decode(region.getAttribute("page")); float x1 = Float.parseFloat(boundingBox.getAttribute("x1")); float y1 = Float.parseFloat(boundingBox.getAttribute("y1")); float x2 = Float.parseFloat(boundingBox.getAttribute("x2")); float y2 = Float.parseFloat(boundingBox.getAttribute("y2")); List<Rectangle> pageTables = expectedTables.get(page); if (pageTables == null) { pageTables = new ArrayList<Rectangle>(); expectedTables.put(page, pageTables); } // have to invert y co-ordinates // unfortunately the ground truth doesn't contain page dimensions // do some extra work to extract the page with tabula and get the dimensions from there Page extractedPage = extractor.extractPage(page); float top = (float)extractedPage.getHeight() - y2; float left = x1; float width = x2 - x1; float height = y2 - y1; pageTables.add(new Rectangle(top, left, width, height)); numExpectedTables++; } // save some stats this.stats.numExpectedTables += numExpectedTables; // now find tables detected by tabula-java Map<Integer, List<Rectangle>> detectedTables = new HashMap<Integer, List<Rectangle>>(); // the algorithm we're going to be testing NurminenDetectionAlgorithm detectionAlgorithm = new NurminenDetectionAlgorithm(); PageIterator pages = extractor.extract(); while (pages.hasNext()) { Page page = pages.next(); List<Rectangle> tablesOnPage = detectionAlgorithm.detect(page, this.pdf); if (tablesOnPage.size() > 0) { detectedTables.put(new Integer(page.getPageNumber()), tablesOnPage); } } // now compare System.out.println("Testing " + this.pdf.getName()); // for now for easier debugging spit out all expected/detected tables System.out.println("Expected Tables:"); this.printTables(expectedTables); System.out.println("Detected Tables:"); this.printTables(detectedTables); if (ASSERT) { assertEquals("Did not detect tables on the same number of pages", expectedTables.size(), detectedTables.size()); } else if (expectedTables.size() != detectedTables.size()) { System.out.println("Did not detect tables on the same number of pages"); } for (Integer page : expectedTables.keySet()) { List<Rectangle> expectedPageTables = expectedTables.get(page); List<Rectangle> detectedPageTables = detectedTables.get(page); if (ASSERT) { assertNotNull("Expected tables not found on page " + page.toString(), detectedPageTables); } else if (detectedPageTables == null) { System.out.println("Expected tables not found on page " + page.toString()); continue; } int maxTableNum = expectedPageTables.size(); if (ASSERT) { assertEquals("Did not find the same number of tables on page " + page.toString(), expectedPageTables.size(), detectedPageTables.size()); } else if (expectedPageTables.size() != detectedPageTables.size()) { System.out.println("Did not find the same number of tables on page " + page.toString()); maxTableNum = Math.min(expectedPageTables.size(), detectedPageTables.size()); } // contains the minimal bounding box of the ground truth without intersecting additional content. int correctlyDetected = 0; for (int i=0; i<maxTableNum; i++) { Rectangle detectedTable = detectedPageTables.get(i); Rectangle expectedTable = expectedPageTables.get(i); // make sure the detected table contains the expected table if (ASSERT) { assertTrue(detectedTable.toString() + "\ndoes not contain " + expectedTable.toString(), detectedTable.contains(expectedTable)); } else if (!detectedTable.contains(expectedTable)) { System.out.println(detectedTable.toString() + "\ndoes not contain " + expectedTable.toString()); continue; } // now make sure it doesn't intersect any other tables on the page Rectangle incorrectlyIntersectedTable = null; for (int j=0; j<expectedPageTables.size(); j++) { if (j != i) { Rectangle otherTable = expectedPageTables.get(j); if (ASSERT) { assertFalse(detectedTable.toString() + "\nintersects " + otherTable.toString(), detectedTable.intersects(otherTable)); } else if (detectedTable.intersects(otherTable)) { incorrectlyIntersectedTable = otherTable; break; } } } if (incorrectlyIntersectedTable != null) { System.out.println(detectedTable.toString() + "\nintersects " + incorrectlyIntersectedTable.toString()); continue; } // made it, this table checks out System.out.println("Table " + i + " on page " + page.toString() + " OK"); correctlyDetected++; } this.stats.numDetectedTables += correctlyDetected; this.saveStats(); } } }
package transportation.Agents; import java.awt.*; import java.util.*; import java.util.List; import market.Market; import transportation.Transportation; import transportation.TransportationPanel; import transportation.GUIs.BusGui; import transportation.GUIs.CarGui; import transportation.GUIs.TruckGui; import transportation.GUIs.WalkerGui; import transportation.Objects.*; import agent.Agent; import astar.astar.Position; import simcity.*; public class TransportationController extends Agent implements Transportation{ TransportationPanel master; enum TransportationState { REQUEST, MOVING, DESTINATION, WAITINGTOSPAWN }; class Mover { TransportationState transportationState; PersonAgent person; MobileAgent mobile; String startingLocation; String endingLocation; String method; String character; Mover(PersonAgent person, String startingLocation, String endingLocation, String method, String character) { this.person = person; this.startingLocation = startingLocation; this.endingLocation = endingLocation; this.method = method; this.character = character; transportationState = TransportationState.REQUEST; } } List<Mover> movingObjects; class Building { String name; Position walkingTile; Position vehicleTile; BusStop closestBusStop; public Building(String name) { this.name = name; walkingTile = null; vehicleTile = null; closestBusStop = null; } public Building(String name, Position walkingTile, Position vehicleTile, BusStop closestBusStop) { this.name = name; this.walkingTile = walkingTile; this.vehicleTile = vehicleTile; this.closestBusStop = closestBusStop; } public void addEnteringTiles(Position walkingTile, Position vehicleTile) { this.walkingTile = walkingTile; this.vehicleTile = vehicleTile; } public void setBusStop(BusStop busStop) { this.closestBusStop = busStop; } } Map<String, Building> directory; MovementTile[][] grid; List<BusStop> busStops; BusAgent bus; TruckAgent truck; public TransportationController(TransportationPanel panel) { master = panel; movingObjects = Collections.synchronizedList(new ArrayList<Mover>()); //++++++++++++++++++++++BEGIN CREATION OF GRID++++++++++++++++++++++ grid = new MovementTile[16][13]; for(int i = 0; i < grid.length; i++) { for(int j = 0; j< grid[0].length; j++) { grid[i][j] = new MovementTile(); } } //Walkways for(int i = 2; i <= 13; i++) { grid[i][2].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY); grid[i][3].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY); grid[i][9].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY); grid[i][10].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY); } for(int i = 4; i <= 8; i++) { grid[2][i].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY); grid[3][i].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY); grid[12][i].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY); grid[13][i].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY); } //Roads grid[5][7].setMovement(true, false, true, false, MovementTile.MovementType.ROAD); grid[11][5].setMovement(true, false, false, false, MovementTile.MovementType.ROAD); grid[11][7].setMovement(true, false, false, false, MovementTile.MovementType.ROAD); grid[11][8].setMovement(true, false, false, false, MovementTile.MovementType.ROAD); grid[4][4].setMovement(false, true, false, false, MovementTile.MovementType.ROAD); grid[4][5].setMovement(false, true, false, false, MovementTile.MovementType.ROAD); grid[4][7].setMovement(false, true, false, false, MovementTile.MovementType.ROAD); grid[10][5].setMovement(false, true, false, true, MovementTile.MovementType.ROAD); grid[5][4].setMovement(false, false, true, false, MovementTile.MovementType.ROAD); grid[10][4].setMovement(false, false, true, false, MovementTile.MovementType.ROAD); grid[11][4].setMovement(false, false, true, false, MovementTile.MovementType.ROAD); grid[10][7].setMovement(false, true, true, false, MovementTile.MovementType.ROAD); grid[5][5].setMovement(true, false, false, true, MovementTile.MovementType.ROAD); grid[4][8].setMovement(false, false, false, true, MovementTile.MovementType.ROAD); grid[5][8].setMovement(false, false, false, true, MovementTile.MovementType.ROAD); grid[10][8].setMovement(false, false, false, true, MovementTile.MovementType.ROAD); for(int i = 6; i <= 9; i++) { grid[i][4].setMovement(false, true, true, false, MovementTile.MovementType.ROAD); grid[i][7].setMovement(false, true, true, false, MovementTile.MovementType.ROAD); grid[i][5].setMovement(true, false, false, true, MovementTile.MovementType.ROAD); grid[i][8].setMovement(true, false, false, true, MovementTile.MovementType.ROAD); } grid[4][6].setMovement(false, true, false, true, MovementTile.MovementType.ROAD); grid[5][6].setMovement(true, false, true, false, MovementTile.MovementType.ROAD); grid[10][6].setMovement(false, true, false, true, MovementTile.MovementType.ROAD); grid[11][6].setMovement(true, false, true, false, MovementTile.MovementType.ROAD); grid[11][11].setMovement(true, false, false, false, MovementTile.MovementType.FLYING); //grid[7][4].setMovement(false, true, true, false, MovementTile.MovementType.CROSSWALK); //grid[11][6].setMovement(true, false, true, false, MovementTile.MovementType.CROSSWALK); //grid[5][8].setMovement(false, false, false, true, MovementTile.MovementType.CROSSWALK); //+++++++++++++++++++++++END CREATION OF GRID+++++++++++++++++++++++ //++++++++++++++++++++++BEGIN CREATION OF BUS STOPS++++++++++++++++++++++ busStops = new ArrayList<BusStop>(); BusStop tempBusStop = new BusStop("Bus Stop NW");//Top Left Bus Stop 0 tempBusStop.addNearbyBuilding("Pirate Bank"); tempBusStop.addNearbyBuilding("Rancho Del Zocalo"); tempBusStop.addNearbyBuilding("Main St Apartments tempBusStop.addNearbyBuilding("Main St Apartments tempBusStop.associateWalkTile(new Position(7, 3)); busStops.add(tempBusStop); tempBusStop = new BusStop("Bus Stop E");//Right Bus Stop 1 tempBusStop.addNearbyBuilding("Main St Apartments tempBusStop.addNearbyBuilding("Haunted Mansion"); tempBusStop.addNearbyBuilding("The Blue Bayou"); tempBusStop.addNearbyBuilding("Main St Apartments tempBusStop.addNearbyBuilding("Carnation Cafe"); tempBusStop.associateWalkTile(new Position(12, 6)); busStops.add(tempBusStop); tempBusStop = new BusStop("Bus Stop SW");//Bottom Left Bus Stop 2 tempBusStop.addNearbyBuilding("Main St Apartments tempBusStop.addNearbyBuilding("Main St Apartments tempBusStop.addNearbyBuilding("Village Haus"); tempBusStop.addNearbyBuilding("Pizza Port"); tempBusStop.addNearbyBuilding("Mickey's Market"); tempBusStop.associateWalkTile(new Position(5, 9)); busStops.add(tempBusStop); //+++++++++++++++++++++++END CREATION OF BUS STOPS+++++++++++++++++++++++ //++++++++++++++++++++++BEGIN CREATION OF DIRECTORY++++++++++++++++++++++ directory = new HashMap<String, Building>(); Building tempBuilding = new Building("Main St Apartments #1", new Position(9, 2), new Position(9, 4), busStops.get(0)); directory.put(tempBuilding.name, tempBuilding); tempBuilding = new Building("Main St Apartments #2", new Position(12, 2), new Position(12, 4), busStops.get(1)); directory.put(tempBuilding.name, tempBuilding); tempBuilding = new Building("Main St Apartments #3", new Position(2, 3), new Position(4, 5), busStops.get(2)); directory.put(tempBuilding.name, tempBuilding); tempBuilding = new Building("Main St Apartments #4", new Position(2, 6), new Position(4, 6), busStops.get(0)); directory.put(tempBuilding.name, tempBuilding); tempBuilding = new Building("Main St Apartments #5", new Position(3, 10), new Position(4, 8), busStops.get(2)); directory.put(tempBuilding.name, tempBuilding); tempBuilding = new Building("Main St Apartments #6", new Position(13, 9), new Position(11, 8), busStops.get(1)); directory.put(tempBuilding.name, tempBuilding); tempBuilding = new Building("Haunted Mansion", new Position(13, 3), new Position(11, 4), busStops.get(1)); directory.put(tempBuilding.name, tempBuilding); tempBuilding = new Building("Mickey's Market", new Position(8, 10), new Position(8, 8), busStops.get(2)); directory.put(tempBuilding.name, tempBuilding); tempBuilding = new Building("Pirate Bank", new Position(7, 2), new Position(7, 4), busStops.get(0)); directory.put(tempBuilding.name, tempBuilding); tempBuilding = new Building("Rancho Del Zocalo", new Position(2, 2), new Position(3, 2), busStops.get(0)); directory.put(tempBuilding.name, tempBuilding); tempBuilding = new Building("Carnation Cafe", new Position(12, 10), new Position(11, 8), busStops.get(1)); directory.put(tempBuilding.name, tempBuilding); tempBuilding = new Building("The Blue Bayou", new Position(13, 5), new Position(11, 5), busStops.get(1)); directory.put(tempBuilding.name, tempBuilding); tempBuilding = new Building("Pizza Port", new Position(5, 10), new Position(4, 8), busStops.get(2)); directory.put(tempBuilding.name, tempBuilding); tempBuilding = new Building("Village Haus", new Position(2, 9), new Position(4, 8), busStops.get(2)); directory.put(tempBuilding.name, tempBuilding); tempBuilding = new Building("Bus Stop NW", new Position(7, 3), new Position(7, 4), busStops.get(0)); directory.put(tempBuilding.name, tempBuilding); tempBuilding = new Building("Bus Stop E", new Position(12, 6), new Position(11, 6), busStops.get(1)); directory.put(tempBuilding.name, tempBuilding); tempBuilding = new Building("Bus Stop SW", new Position(5, 9), new Position(5, 8), busStops.get(2)); directory.put(tempBuilding.name, tempBuilding); //+++++++++++++++++++++++END CREATION OF DIRECTORY+++++++++++++++++++++++ //Connecting bus stops to tiles grid[7][4].setBusStop(busStops.get(0)); grid[11][6].setBusStop(busStops.get(1)); grid[5][8].setBusStop(busStops.get(2)); //Spawning Bus bus = new BusAgent(this); BusGui busGui = new BusGui(4, 4, bus); master.addGui(busGui); bus.setGui(busGui); bus.startThread(); //Spawning Delivery Truck truck = new TruckAgent(new Position(11, 10), this, new FlyingTraversal(grid)); TruckGui truckGui = new TruckGui(11, 10, truck); master.addGui(truckGui); truck.setGui(truckGui); truck.startThread(); super.startThread(); } //+++++++++++++++++MESSAGES+++++++++++++++++ public void msgWantToGo(String startLocation, String endLocation, PersonAgent person, String mover, String character) { for(Mover m : movingObjects) { if(m.person == person && !m.method.equals("Bus")) return; } System.out.println("RECEIVED REQUEST TO TRANSPORT"); movingObjects.add(new Mover(person, startLocation, endLocation, mover, character)); stateChanged(); } public void msgArrivedAtDestination(PersonAgent person){ for(Mover mover : movingObjects) { if(mover.person == person) { mover.transportationState = TransportationState.DESTINATION; } } stateChanged(); } public void msgSendDelivery(Restaurant restaurant, Market market, String food, int quantity, int id) { truck.msgDeliverOrder(restaurant, market, food, quantity, id); } public void msgSendDelivery(PersonAgent person, Market market, String food, int quantity, String location) { truck.msgDeliverOrder(person, market, food, quantity, location); } //+++++++++++++++++SCHEDULER+++++++++++++++++ @Override protected boolean pickAndExecuteAnAction() { synchronized(movingObjects) { for(Mover mover : movingObjects) { if(mover.transportationState == TransportationState.REQUEST) { spawnMover(mover); return true; } } } synchronized(movingObjects) { for(Mover mover : movingObjects) { if(mover.transportationState == TransportationState.DESTINATION) { despawnMover(mover);//POTENTIAL ERROR return true; } } } synchronized(movingObjects) { boolean retry = false; for(Mover mover : movingObjects) { if(mover.transportationState == TransportationState.WAITINGTOSPAWN) { retry = true; retrySpawn(mover); } } if(retry) return true; } return false; } private void spawnMover(Mover mover) { //Try to spawn mover TransportationTraversal aStar = new TransportationTraversal(grid); if(mover.method.equals("Car")){ if(grid[directory.get(mover.startingLocation).vehicleTile.getX()][directory.get(mover.startingLocation).vehicleTile.getY()].tryAcquire()) { mover.transportationState = TransportationState.MOVING; CarAgent driver = new CarAgent(mover.person, directory.get(mover.startingLocation).vehicleTile, directory.get(mover.endingLocation).vehicleTile, this, aStar); CarGui carGui = new CarGui(directory.get(mover.startingLocation).vehicleTile.getX(), directory.get(mover.startingLocation).vehicleTile.getY(), driver); master.addGui(carGui); driver.setGui(carGui); driver.startThread(); } else { mover.transportationState = TransportationState.WAITINGTOSPAWN; } } else if(mover.method.equals("Walk")){ if(grid[directory.get(mover.startingLocation).walkingTile.getX()][directory.get(mover.startingLocation).walkingTile.getY()].tryAcquire()) { mover.transportationState = TransportationState.MOVING; WalkerAgent walker = new WalkerAgent(mover.person, directory.get(mover.startingLocation).walkingTile, directory.get(mover.endingLocation).walkingTile, this, aStar); WalkerGui walkerGui = new WalkerGui(directory.get(mover.startingLocation).walkingTile.getX(), directory.get(mover.startingLocation).walkingTile.getY(), walker); master.addGui(walkerGui); walker.setGui(walkerGui); walker.startThread(); } else { mover.transportationState = TransportationState.WAITINGTOSPAWN; System.out.println("OBJECT IS WAITING"); System.exit(0); } } else if(mover.method.equals("Bus")){ //find bus stop and spawn walker to go to bus stop mover.transportationState = TransportationState.MOVING; if(directory.get(mover.startingLocation).closestBusStop == directory.get(mover.endingLocation).closestBusStop) { mover.method = "Walk"; spawnMover(mover); return; } if(grid[directory.get(mover.startingLocation).walkingTile.getX()][directory.get(mover.startingLocation).walkingTile.getY()].tryAcquire()) { WalkerAgent busWalker = new WalkerAgent(mover.person, directory.get(mover.startingLocation).walkingTile, directory.get(mover.endingLocation).walkingTile, this, aStar, directory.get(mover.startingLocation).closestBusStop, directory.get(mover.endingLocation).closestBusStop, mover.endingLocation); WalkerGui busWalkerGui = new WalkerGui(directory.get(mover.startingLocation).walkingTile.getX(), directory.get(mover.startingLocation).walkingTile.getY(), busWalker); master.addGui(busWalkerGui); busWalker.setGui(busWalkerGui); busWalker.startThread(); } else { mover.transportationState = TransportationState.WAITINGTOSPAWN; } } } private void despawnMover(Mover mover) { if(!mover.method.equals("Bus")) mover.person.msgReachedDestination(mover.endingLocation); movingObjects.remove(mover); } private void retrySpawn(Mover mover) { mover.transportationState = TransportationState.REQUEST; } public MovementTile[][] getGrid() { return grid; } public void msgPayFare(PersonAgent person, float fare) { bus.msgPayFare(person, fare); } }
package uk.org.bobulous.java.collections; import java.math.BigInteger; import java.util.ArrayList; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import uk.org.bobulous.java.intervals.GenericInterval; import uk.org.bobulous.java.intervals.Interval; public final class Combinatorics { /** * A map which holds every factorial which can be represented by a * <code>long</code> primitive. The domain contains only the integers zero * to twenty because the factorial function is not defined for negative * numbers, and the factorial of twenty-one is a number too large to be * represented by a long in Java. */ private static final Map<Byte, Long> MAP_FROM_N_TO_N_FACTORIAL; static { Map<Byte, Long> map = new HashMap<>(32); map.put((byte) 0, 1L); map.put((byte) 1, 1L); map.put((byte) 2, 2L); map.put((byte) 3, 6L); map.put((byte) 4, 24L); map.put((byte) 5, 120L); map.put((byte) 6, 720L); map.put((byte) 7, 5_040L); map.put((byte) 8, 40_320L); map.put((byte) 9, 362_880L); map.put((byte) 10, 3_628_800L); map.put((byte) 11, 39_916_800L); map.put((byte) 12, 479_001_600L); map.put((byte) 13, 6_227_020_800L); map.put((byte) 14, 87_178_291_200L); map.put((byte) 15, 1_307_674_368_000L); map.put((byte) 16, 20_922_789_888_000L); map.put((byte) 17, 355_687_428_096_000L); map.put((byte) 18, 6_402_373_705_728_000L); map.put((byte) 19, 121_645_100_408_832_000L); map.put((byte) 20, 2_432_902_008_176_640_000L); MAP_FROM_N_TO_N_FACTORIAL = Collections.unmodifiableMap(map); } /* Private constructor because this class is never intended to be instantiated. */ private Combinatorics() { } /** * Returns the factorial of the given number. * * @param n a number of at least zero and at most twenty. * @return the factorial of the given number. */ private static long factorial(int n) { if (n < 0 || n > 20) { throw new IllegalArgumentException( "n must be at least zero and not greater than twenty."); } return MAP_FROM_N_TO_N_FACTORIAL.get((byte) n); } /** * Calculates the total number of combinations of all sizes which could be * generated from a set of the given size. The number returned will count * the empty set in the total. * * @param setSize the number of elements in the source set. Cannot be less * than zero and cannot be larger than 62. * @return the number of combinations of all sizes which could be generated * from a set which has <code>setSize</code> elements. * @see #numberOfCombinations(int, int) * @see #numberOfCombinations(int, uk.org.bobulous.java.intervals.Interval) */ public static final long numberOfCombinations(int setSize) { if (setSize < 0) { throw new IllegalArgumentException( "setSize cannot be less than zero."); } if (setSize > 62) { throw new IllegalArgumentException( "setSize cannot be greater than 62."); } return 1L << setSize; } /** * Calculates the number of combinations of the specified size which could * be generated from a source set of the specified size. * * @param setSize the number of elements in the source set. Cannot be less * than zero and cannot be larger than 62. * @param chooseSize the number of elements in each combination. Cannot be * less than zero and cannot be larger than <code>setSize</code>. * @return the number of combinations of size <code>chooseSize</code> which * could be generated from a set which has <code>setSize</code> elements. */ public static final long numberOfCombinations(int setSize, int chooseSize) { if (setSize < 0) { throw new IllegalArgumentException( "setSize cannot be less than zero."); } if (setSize > 62) { throw new IllegalArgumentException( "setSize cannot be greater than 62."); } if (chooseSize < 0) { throw new IllegalArgumentException( "chooseSize cannot be less than zero."); } if (chooseSize > setSize) { throw new IllegalArgumentException( "chooseSize cannot be greater than setSize."); } return numberOfCombinationsWithoutValidation(setSize, chooseSize); } /* Use a private method without parameter validation to handle the calculations which will be called repeatedly when numerOfCombinations is called with an interval of choose sizes. */ private static long numberOfCombinationsWithoutValidation(int setSize, int chooseSize) { if (chooseSize == 0 || chooseSize == setSize) { return 1L; } if (chooseSize == 1 || chooseSize == setSize - 1) { return setSize; } /* To calculate n!/(k!(n-k)!) where n==setSize and k==chooseSize and where n! is the factorial function applied to n, take a shortcut by factoring out all common factors in the numerator and denominator. If k is larger than (n-k) then factor out all values from k! from both the numerator and the denominator. If (n-k) is larger than k then factor out all values from (n-k)! from both the numerator and the denominator. */ int sizeMinusChoose = setSize - chooseSize; int breakPoint = Math.max(chooseSize, sizeMinusChoose); int numeratorStartPoint = Math.min(chooseSize, sizeMinusChoose); // Start off by gathering all numbers which have not been factored out // of the numerator. List<Integer> numeratorFactors = new ArrayList<>(setSize - breakPoint); for (int x = setSize; x > breakPoint; --x) { numeratorFactors.add(x); } // Now gather all the numbers which have not been factored out of the // denominator. ArrayList<Integer> denominatorFactors = new ArrayList(numeratorStartPoint - 1); for (int x = numeratorStartPoint; x > 1; --x) { denominatorFactors.add(x); } // Divide the numerator by the denominator to get the final result. if (setSize > 28) { // The long primitive cannot handle a numerator which is larger than // 28! divided by 14! so if the size of the set is greater than 28 // we must switch to using BigInteger for the calculations. return bigIntegerDivision(numeratorFactors, denominatorFactors); } else { return longDivision(numeratorFactors, denominatorFactors); } } /** * Calculates the product of all specified numerator factors divided by the * product of all the specified denominator factors. A <code>long</code> * primitive is used for the calculations, so the product of the numerator * factors cannot have a value which is greater than 28!/14! (twenty-eight * factorial divided by fourteen factorial). * * @param numeratorFactors a <code>Collection&lt;Integer&gt;</code> which * contains all of the factors which make up the numerator. * @param denominatorFactors a <code>Collection&lt;Integer&gt;</code> which * contains all of the factors which make up the denominator. * @return the numerator product divided by the denominator product. */ private static long longDivision(Collection<Integer> numeratorFactors, Collection<Integer> denominatorFactors) { // Calculate the numerator and the denominator products. long numerator = 1L; for (int x : numeratorFactors) { numerator *= x; } long denominator = 1L; for (int x : denominatorFactors) { denominator *= x; } // Return the numerator divided by the denominator. return numerator / denominator; } /** * Calculates the product of all specified numerator factors divided by the * product of all the specified denominator factors. A * <code>BigDecimal</code> primitive is used for the calculations, so the * product of the numerator factors can be arbitrarily large. * * @param numeratorFactors a <code>Collection&lt;Integer&gt;</code> which * contains all of the factors which make up the numerator. * @param denominatorFactors a <code>Collection&lt;Integer&gt;</code> which * contains all of the factors which make up the denominator. * @return the numerator product divided by the denominator product. */ private static long bigIntegerDivision(Collection<Integer> numeratorFactors, Collection<Integer> denominatorFactors) { // Calculate the numerator and the denominator products. BigInteger numerator = BigInteger.ONE; for (int x : numeratorFactors) { numerator = numerator.multiply(BigInteger.valueOf(x)); } BigInteger denominator = BigInteger.ONE; for (int x : denominatorFactors) { denominator = denominator.multiply(BigInteger.valueOf(x)); } // Return the numerator divided by the denominator. return numerator.divide(denominator).longValue(); } /** * Calculates the total number of combinations of the sizes permitted by the * supplied interval which could be generated from a source set of the * specified size. * * @param setSize the number of elements in the source set. Cannot be less * than zero and cannot be larger than 62. * @param chooseInterval an <code>Interval&lt;Integer&gt;</code> which * defines the interval of combinations sizes to be included in the returned * count. The interval cannot be empty, and the lower endpoint cannot be * less than zero, and the upper endpoint cannot be greater than * <code>setSize</code>. * @return the number of combinations of the permitted sizes which could be * generated from a set which has <code>setSize</code> elements. */ public static final long numberOfCombinations(int setSize, Interval<Integer> chooseInterval) { if (setSize < 0) { throw new IllegalArgumentException( "setSize cannot be less than zero."); } if (setSize > 62) { throw new IllegalArgumentException( "setSize cannot be greater than 62."); } Objects.requireNonNull(chooseInterval); validateInterval(chooseInterval, setSize); // If the interval permits all combination sizes, or all but the zero // and/or full set sizes, then the calculation can be simplified. if (chooseInterval.includes(setSize)) { if (chooseInterval.includes(0)) { // The interval permits all possible combination sizes from zero // up to and including the full set size, so call the basic // version of this method. return numberOfCombinations(setSize); } else if (chooseInterval.includes(1)) { // The interval permits all possible combinations except the // empty set, so simply subtract one from the count of all // possible combinations. return numberOfCombinations(setSize) - 1; } } else if (chooseInterval.includes(0)) { if (chooseInterval.includes(setSize - 1)) { // The interval does not permit the full set size, but it does // permit every other size, so simply subtract one from the // count of all possible combinations (because only the // combination which holds the entire source set is being // excluded). return numberOfCombinations(setSize) - 1; } } else if (chooseInterval.includes(1) && chooseInterval.includes(setSize - 1)) { // The interval does not permit the combination of size zero (the // empty set) nor does it permit the combination which contains all // of the source elements, but it does permit every other size of // combination. So simply subtract two from the count of all // possible combinations. return numberOfCombinations(setSize) - 2; } int firstSize = chooseInterval.getLowerEndpoint(); int lastSize = chooseInterval.getUpperEndpoint(); long totalCombinationCount = 0; for (int comboSize = firstSize; comboSize <= lastSize; ++comboSize) { if (!chooseInterval.includes(comboSize)) { // This size must be excluded by an open endpoint in the // interval so skip to the next size. continue; } totalCombinationCount += numberOfCombinationsWithoutValidation( setSize, comboSize); } return totalCombinationCount; } /** * Finds every combination which can be produced using the elements from the * provided source set. * <p> * The returned <code>Set</code> will contain an empty set (which represents * the combination which uses none of the elements from the source set) and * sets of every size from one element up to and including the size of the * number of elements contained in the source set. Each element in the * source set can only be used once per combination. The total number of * combinations (and thus the total size of the returned <code>Set</code>) * will be two raised to the power of the size of the source set. (Be aware * that for a source set which contains twenty elements there are more than * one million combinations.)</p> * * @param <T> the type of the elements contained by the provided set. * @param sourceElements a <code>Set</code> which represents the source set * of elements to be used in producing combinations. Cannot be * <code>null</code> and cannot contain more than thirty elements. * @return a <code>Set</code> which contains one or more sets, one for each * possible combination of the elements found in * <code>sourceElements</code>. * @see #permutations(java.util.Set) * @see #combinationsSorted(java.util.Set) * @see #combinations(java.util.Set, int) * @see #combinations(java.util.Set, * uk.org.bobulous.java.intervals.Interval) */ public static final <T> Set<Set<T>> combinations(Set<T> sourceElements) { Objects.requireNonNull(sourceElements); if (sourceElements.size() > 30) { throw new IllegalArgumentException( "Size of sourceElements cannot be greater than thirty elements."); } return generateCombinations(sourceElements, true, null); } /** * Finds every combination of the specified size using the elements from the * provided source set. The empty set (and only the empty set) will be * returned if the specified size is zero. * <p> * The returned <code>Set</code> will contain every combination of the * specified size which can be produced using the elements contained in the * source set, where each element in the source set can only be used once * per combination.</p> * * @param <T> the type of the elements contained in the provided set. * @param sourceElements a <code>Set</code> which represents the source set * of elements to be used in producing combinations. Cannot be * <code>null</code> and cannot contain more than thirty elements. * @param choose the number of source elements to be included in each * combination returned by this method. The number must be at least zero and * must not be greater than the size of <code>sourceElements</code>. * @return a <code>Set</code> which contains one or more sets, one for each * combination of the given size produced using the elements found in * <code>sourceElements</code>. */ public static final <T> Set<Set<T>> combinations(Set<T> sourceElements, int choose) { Objects.requireNonNull(sourceElements); if (sourceElements.size() > 30) { throw new IllegalArgumentException( "Size of sourceElements cannot be greater than thirty elements."); } if (choose < 0) { throw new IllegalArgumentException( "Parameter choose must be non-negative."); } if (choose > sourceElements.size()) { throw new IllegalArgumentException( "Parameter choose cannot be greater than the size of sourceElements."); } return generateCombinations(sourceElements, false, new GenericInterval<>(choose, choose)); } /** * Finds every combination of the specified sizes using the elements from * the provided source set. The empty set will be included in the results if * the specified interval includes zero. * <p> * The returned <code>Set</code> will contain every combination of the sizes * permitted by the specified interval, each combination produced using the * elements contained in the source set, where each element in the source * set can only be used once per combination.</p> * * @param <T> the type of the elements contained in the provided set. * @param sourceElements a <code>Set</code> which represents the source set * of elements to be used to produce combinations. Cannot be * <code>null</code> and cannot contain more than thirty elements. * @param chooseInterval an <code>Interval&lt;Integer&gt;</code> which * specifies the interval of combination sizes to be included in the set of * combinations returned by this method. The lower endpoint value must be at * least zero, and the upper endpoint value must not be greater than the * size of the <code>sourceElements</code> set, and the interval must not be * an empty set (which excludes all values). * @return a <code>Set</code> which contains one or more sets, one for each * combination of the permitted sizes, produced using the elements found in * <code>sourceElements</code>. */ public static final <T> Set<Set<T>> combinations(Set<T> sourceElements, Interval<Integer> chooseInterval) { Objects.requireNonNull(sourceElements); Objects.requireNonNull(chooseInterval); if (sourceElements.size() > 30) { throw new IllegalArgumentException( "Size of sourceElements cannot be greater than thirty elements."); } validateInterval(chooseInterval, sourceElements.size()); return generateCombinations(sourceElements, false, chooseInterval); } /* Private method to contain the code used by the public overloaded methods. No need to validate parameters, as the public methods should validate them before calling this private method. */ private static <T> Set<Set<T>> generateCombinations( Set<T> sourceElements, boolean chooseAll, Interval<Integer> chooseInterval) { List<T> sourceList = new ArrayList<>(sourceElements); int elementCount = sourceList.size(); final long combinationCount; if (chooseAll) { combinationCount = numberOfCombinations(elementCount); } else { combinationCount = numberOfCombinations(elementCount, chooseInterval); } // The final set will always contain combinationCount elements, so it // makes sense to set the capacity of the HashSet so that // combinationCount is less than 75% of the capacity. This should avoid // the need for the HashSet to resize itself at any point. long idealSetCapacity = 1L + combinationCount * 4L / 3L; Set<Set<T>> allCombinations = new HashSet<>(idealSetCapacity > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) idealSetCapacity); for (int comboSize = 0; comboSize <= elementCount; ++comboSize) { if (!chooseAll && !chooseInterval.includes(comboSize)) { // We are only interested in combinations which contain a number // of elements permitted by the chooseInterval. continue; } if (comboSize == 0) { allCombinations.add(new HashSet<>(1)); continue; } // Use an array of "pegs" which each point to an element index. Each // peg must point to a unique element index, and new combinations // will be found by shifting the pegs across the element indices // from left (element index zero) to right (element index equal to // comboSize - 1) until all possible combinations have been found. int[] pegElementIndices = new int[comboSize]; // Start off with the pegs lined up tight against the left. for (int i = 0; i < comboSize; ++i) { pegElementIndices[i] = i; } do { Set<T> currentCombination = new HashSet<>(1 + comboSize * 4 / 3); for (int setIndex : pegElementIndices) { currentCombination.add(sourceList.get(setIndex)); } allCombinations.add(currentCombination); // Check whether the left-most peg is as far to the right as it // can go. When this happens all of the pegs will be lined up // tightly against the right, and this means there is no more room // to shift the pegs. if (pegElementIndices[0] == elementCount - comboSize) { // We have reached the final combination of this size, so // exit the loop. break; } // Now shift the bits in the BitSet to the find the next combination. // Find the right-most (highest index) "peg" which can shift to // the right by one position to give us a new combination. for (int peg = comboSize - 1; peg >= 0; --peg) { if (pegElementIndices[peg] < elementCount - comboSize + peg) { // This index refers to a peg which has room to move one // to the right so increase its index value by one. ++pegElementIndices[peg]; // If there are any subsequent pegs (pegs with a higher // array index than the peg we just shifted) then reset // all of their indices so that they line up tight // against the peg we just shifted. for (int subPeg = peg + 1; subPeg < comboSize; ++subPeg) { pegElementIndices[subPeg] = pegElementIndices[peg] + subPeg - peg; } break; } } } while (true); } return allCombinations; } /** * Returns an iterator of all combinations which can be produced from the * elements of the supplied set. The empty set will be amongst the * combinations returned by the iterator. * <p> * The provided set can be arbitrarily large because this method does not * return all combinations in one go, so the limitations of the * {@link #combinations(java.util.Set)} family of methods do not apply. * However, be aware that the total number of combinations of all sizes is * equal to two raised to the power of the number of elements in the * provided set. Iterating through all of the 4.2 billion combinations * generated from a set of size 32 took twenty-four minutes on the * development machine, and completion time is likely to be more than double * for a source set with a size greater by one extra element.</p> * * @param <T> the type of the elements found in the supplied set. * @param sourceElements a <code>Set</code> of elements to be used to create * combinations. Must not be <code>null</code>. * @return an <code>Iterator&lt;Set&lt;T&gt;&gt;</code> which will iterate * through every possible combination of all sizes, including the empty set. * @see #iteratorOfCombinations(java.util.Set, int) * @see #iteratorOfCombinations(java.util.Set, * uk.org.bobulous.java.intervals.Interval) */ public static final <T> Iterator<Set<T>> iteratorOfCombinations( Set<T> sourceElements) { Objects.requireNonNull(sourceElements); return new CombinationsIterator(sourceElements, null); } /** * Returns an iterator of all combinations of the specified size which can * be produced from the elements of the supplied set. The empty set (and * only the empty set) will be returned if the specified size is zero. * * @param <T> the type of the elements found in the supplied set. * @param sourceElements a <code>Set</code> of elements to be used to create * combinations. Must not be <code>null</code>. * @param chooseSize the number of elements to be included in each * combination returned by this iterator. Must be at least zero and at must * not be greater than the number of elements found in the supplied set. * @return an <code>Iterator&lt;Set&lt;T&gt;&gt;</code> which will iterate * through all combinations of the specified size. */ public static final <T> Iterator<Set<T>> iteratorOfCombinations( Set<T> sourceElements, int chooseSize) { Objects.requireNonNull(sourceElements); if (chooseSize < 0) { throw new IllegalArgumentException( "chooseSize cannot be less than zero."); } if (chooseSize > sourceElements.size()) { throw new IllegalArgumentException( "chooseSize cannot be greater than the size of sourceElements."); } return new CombinationsIterator(sourceElements, new GenericInterval<>( chooseSize, chooseSize)); } /** * Returns an iterator of combinations which can be produced from elements * of the supplied set, including only combinations with sizes permitted by * the supplied interval. The empty set will be included in the results if * the specified interval includes zero. * * @param <T> the type of the elements found in the supplied set. * @param sourceElements a <code>Set</code> of elements to be used to create * combinations. Must not be <code>null</code>. * @param chooseInterval an <code>Interval&lt;Integer&gt;</code> which * specifies which combination sizes should be returned by this iterator. * Must not be <code>null</code>, and cannot have a lower endpoint less than * zero, nor an upper endpoint greater than the number of elements found in * the supplied set. * @return an <code>Iterator&lt;Set&lt;T&gt;&gt;</code> which will iterate * through all combinations of the permitted sizes. */ public static final <T> Iterator<Set<T>> iteratorOfCombinations( Set<T> sourceElements, Interval<Integer> chooseInterval) { Objects.requireNonNull(sourceElements); Objects.requireNonNull(chooseInterval); int elementCount = sourceElements.size(); validateInterval(chooseInterval, elementCount); return new CombinationsIterator(sourceElements, chooseInterval); } /** * An iterator which returns a single combination at a time. * * @param <T> the type of the elements which will be found in the source set * supplied to this iterator, and the type of the elements which will be * found in the combination sets returned by this iterator. */ private static class CombinationsIterator<T> implements Iterator<Set<T>> { private final List<T> sourceElements; int elementCount; private final Interval<Integer> chooseInterval; private int currentComboSize; private int firstExcludedComboSize; private int[] pegElementIndices; /** * Constructs a <code>CombinationsIterator&lt;T&gt;</code> which will * return combinations using elements from the supplied set and having * sizes permitted by the supplied interval. * * @param sourceElements a <code>Set</code> of elements to be used to * create combinations. Must not be <code>null</code>. * @param chooseInterval an <code>Interval&lt;Integer&gt;</code> which * specifies which combination sizes should be returned by this * iterator. If <code>null</code> is provided then all combination sizes * from zero up to and including the number of elements in the source * set will be included in the results returned by this iterator; if an * actual interval is provided then it cannot have a lower endpoint less * than zero, nor an upper endpoint greater than the number of elements * found in the supplied set. */ CombinationsIterator(Set<T> sourceElements, Interval<Integer> chooseInterval) { Objects.requireNonNull(sourceElements); this.sourceElements = new ArrayList<>(sourceElements); elementCount = this.sourceElements.size(); this.chooseInterval = chooseInterval; if (this.chooseInterval != null) { validateInterval(this.chooseInterval, sourceElements.size()); currentComboSize = this.chooseInterval.getLowerEndpoint(); if (this.chooseInterval.getLowerEndpointMode().equals( Interval.EndpointMode.OPEN)) { ++currentComboSize; } firstExcludedComboSize = this.chooseInterval. getUpperEndpoint(); if (this.chooseInterval.getUpperEndpointMode().equals( Interval.EndpointMode.CLOSED)) { ++firstExcludedComboSize; } } else { currentComboSize = 0; firstExcludedComboSize = sourceElements.size() + 1; } if (currentComboSize > 0) { this.pegElementIndices = new int[currentComboSize]; // Start off with the pegs lined up tight against the left. for (int i = 0; i < currentComboSize; ++i) { pegElementIndices[i] = i; } } } @Override public boolean hasNext() { // If we have not exceeded the final combination size that will be // included by this iterator, then there must still be at least // one combination still to come. return currentComboSize < firstExcludedComboSize; } @Override public Set<T> next() { if(currentComboSize == firstExcludedComboSize) { throw new NoSuchElementException(); } Set<T> currentCombination = new HashSet<>(1 + currentComboSize * 4 / 3); if (currentComboSize > 0) { for (int setIndex : pegElementIndices) { currentCombination.add(sourceElements.get(setIndex)); } } if (currentComboSize == 0 || pegElementIndices[0] == elementCount - currentComboSize) { // We've found all of the combinations of the current size, so // move up to the next combination size. ++currentComboSize; if (currentComboSize < firstExcludedComboSize) { // There are still more combinations to come, so create a // new array of pegs equal in size to the new combination // size and start them off lined up tight against the left. pegElementIndices = new int[currentComboSize]; for (int i = 0; i < currentComboSize; ++i) { pegElementIndices[i] = i; } } } else { // We still have more combinations available in the current size // so shift the pegs to reach the next combination. for (int peg = currentComboSize - 1; peg >= 0; --peg) { if (pegElementIndices[peg] < elementCount - currentComboSize + peg) { // This index refers to a peg which has room to move one // to the right so increase its index value by one. ++pegElementIndices[peg]; // If there are any subsequent pegs (pegs with a higher // array index than the peg we just shifted) then reset // all of their indices so that they line up tight // against the peg we just shifted. for (int subPeg = peg + 1; subPeg < currentComboSize; ++subPeg) { pegElementIndices[subPeg] = pegElementIndices[peg] + subPeg - peg; } break; } } } return currentCombination; } } /** * Finds every combination which can be produced using the elements from the * provided source set, and returns the results in a <code>SortedSet</code>. * <p> * The returned <code>SortedSet</code> will contain an empty set (which * represents the combination which uses none of the elements from the * source set) and sets of every size from one element up to and including * the size of the number of elements contained in the source set. Each * element in the source set can only be used once per combination. The * total number of combinations (and thus the total size of the returned * <code>SortedSet</code>) will be two raised to the power of the size of * the source set.</p> * <p> * The returned <code>SortedSet</code> will be ordered firstly by the size * of each combination, so that the empty set appears first, then the sets * holding combinations of size one, then the sets holding combinations of * size two, and so on until the set whose size is that of the source set. * Where combinations have the same size, the second level of ordering takes * into consideration the element values within each combination set, so * that the natural ordering of the element type is used to determine which * combination comes first in the order. See {@link SortedSetComparator} for * the full details of the <code>Comparator</code> used in this ordering. * </p> * * @param <T> the type of the elements contained by the provided set. Must * be a type which has a natural order. * @param sourceElements a <code>Set</code> which represents the source set * of elements to be combined. Cannot be <code>null</code>, cannot contain a * <code>null</code> element, and cannot contain more than thirty elements. * @return a <code>SortedSet</code> which contains one or more sets, one for * each possible combination of the elements found in * <code>sourceElements</code>, sorted by combination sizes and by the * natural order of the elements within each combination. * @see #combinations(java.util.Set) * @see #combinationsSorted(java.util.Set, int) * @see #combinationsSorted(java.util.Set, * uk.org.bobulous.java.intervals.Interval) */ public static final <T extends Comparable<T>> SortedSet<SortedSet<T>> combinationsSorted( Set<T> sourceElements) { Objects.requireNonNull(sourceElements); if (sourceElements.size() > 30) { throw new IllegalArgumentException( "Size of sourceElements cannot be greater than thirty elements."); } if (SetUtilities.containsNull(sourceElements)) { throw new NullPointerException( "sourceElements must not contain a null element."); } return generateCombinationsSorted(sourceElements, true, null); } /** * Finds every combination of the specified size which can be produced using * the elements from the provided source set, and returns the results in a * <code>SortedSet</code>. The empty set (and only the empty set) will be * returned if the specified size is zero. * <p> * The returned <code>SortedSet</code> will contain every combination of the * specified size which can be produced using the elements contained in the * source set, where each element in the source set can only be used once * per combination.</p> * <p> * The returned <code>SortedSet</code> will be ordered by comparing the * element values within each combination set, so that the natural ordering * of the element type is used to determine which combination comes first in * the order. See {@link SortedSetComparator} for the full details of the * <code>Comparator</code> used in this ordering. * </p> * * @param <T> the type of the elements contained by the provided set. Must * be a type which has a natural order. * @param sourceElements a <code>Set</code> which represents the source set * of elements to be combined. Cannot be <code>null</code>, cannot contain a * <code>null</code> element, and cannot contain more than thirty elements. * @param choose the number of source elements to be included in the * combinations returned by this method. * @return a <code>SortedSet</code> which contains one or more sets, one for * each combination of the given size produced using the elements found in * <code>sourceElements</code>, sorted by the natural order of the elements * within each combination. */ public static final <T extends Comparable<T>> SortedSet<SortedSet<T>> combinationsSorted( Set<T> sourceElements, int choose) { Objects.requireNonNull(sourceElements); if (sourceElements.size() > 30) { throw new IllegalArgumentException( "Size of sourceElements cannot be greater than thirty elements."); } if (SetUtilities.containsNull(sourceElements)) { throw new NullPointerException( "sourceElements must not contain a null element."); } if (choose < 0) { throw new IllegalArgumentException( "Parameter choose must be non-negative."); } if (choose > sourceElements.size()) { throw new IllegalArgumentException( "Parameter choose cannot be greater than the size of sourceElements."); } return generateCombinationsSorted(sourceElements, false, new GenericInterval<>(choose, choose)); } /** * Finds every combination of the specified sizes using elements from the * provided source set, and returns the results in a <code>SortedSet</code>. * The empty set will be included in the results if the specified interval * includes zero. * <p> * The returned <code>SortedSet</code> will contain every combination of the * sizes permitted by the specified interval, each combination produced * using the elements contained in the source set, where each element in the * source set can only be used once per combination.</p> * <p> * The returned <code>SortedSet</code> will be ordered firstly by the size * of each combination, so that the smallest permitted combination size * appears first, and so on until the largest permitted combination size. * Where combinations have the same size, the second level of ordering takes * into consideration the element values within each combination set, so * that the natural ordering of the element type is used to determine which * combination comes first in the order. See {@link SortedSetComparator} for * the full details of the <code>Comparator</code> used in this ordering. * </p> * * @param <T> the type of the elements contained by the provided set. Must * be a type which has a natural order. * @param sourceElements a <code>Set</code> which represents the source set * of elements to be combined. Cannot be <code>null</code>, cannot contain a * <code>null</code> element, and cannot contain more than thirty elements. * @param chooseInterval an <code>Interval&lt;Integer&gt;</code> which * specifies the interval of combination sizes to be included in the set of * combinations returned by this method. The lower endpoint value must be at * least zero, and the upper endpoint value must not be greater than the * size of the <code>sourceElements</code> set, and the interval must not be * an empty set (which excludes all values). * @return a <code>SortedSet</code> which contains one or more sets, one for * each combination of the permitted sizes, produced using the elements * found in <code>sourceElements</code>, sorted by combination sizes and by * the natural order of the elements within each combination. */ public static final <T extends Comparable<T>> SortedSet<SortedSet<T>> combinationsSorted( Set<T> sourceElements, Interval<Integer> chooseInterval) { Objects.requireNonNull(sourceElements); if (sourceElements.size() > 30) { throw new IllegalArgumentException( "Size of sourceElements cannot be greater than thirty elements."); } if (SetUtilities.containsNull(sourceElements)) { throw new NullPointerException( "sourceElements must not contain a null element."); } Objects.requireNonNull(chooseInterval); validateInterval(chooseInterval, sourceElements.size()); return generateCombinationsSorted(sourceElements, false, chooseInterval); } /* Check that the interval permits at least one integer between zero and the specified maximum combination size, and no integer less than zero or greater than the maximum combination size. */ private static void validateInterval(Interval<Integer> interval, int maxCombinationSize) { Integer lower = interval.getLowerEndpoint(); if (lower == null || lower < 0) { throw new IllegalArgumentException( "The lower endpoint of chooseInterval must be non-negative."); } Integer upper = interval.getUpperEndpoint(); if (upper == null || upper > maxCombinationSize) { throw new IllegalArgumentException( "The upper endpoint of chooseInterval cannot be greater than the size of sourceElements."); } // Check that the interval is not an empty set (which does not permit // any integers at all). if (upper < lower || upper - lower < 2) { if (!interval.includes(lower) && !interval.includes(upper)) { throw new IllegalArgumentException( "chooseInterval cannot be an empty set."); } } } /* Private method to contain the code used by the public overloaded methods. No need to validate parameters, as the public methods should validate them before calling this private method. */ private static <T extends Comparable<T>> SortedSet<SortedSet<T>> generateCombinationsSorted( Set<T> sourceElements, boolean chooseAll, Interval<Integer> chooseInterval) { List<T> sourceList = new ArrayList<>(sourceElements); int elementCount = sourceList.size(); SortedSet<SortedSet<T>> allCombinations = new TreeSet<>( SortedSetComparator.<T>getInstance()); int maxBitMaskValue = 1 << elementCount; for (int combination = 0; combination < maxBitMaskValue; ++combination) { BitSet comboMask = BitSet.valueOf(new long[]{combination}); if (!chooseAll && !chooseInterval.includes(comboMask.cardinality())) { // We are only interested in combinations which contain a number // of elements permitted by the chooseInterval. If // this comboMask would result in number of elements which falls // outside of this interval then skip to the next comboMask. continue; } SortedSet<T> currentCombination = new TreeSet<>(); for (int elementIndex = 0; elementIndex < elementCount; ++elementIndex) { if (comboMask.get(elementIndex)) { currentCombination.add(sourceList.get(elementIndex)); } } allCombinations.add(currentCombination); } return allCombinations; } /** * Returns the number of permutations which would exist for a set of the * specified size. * * @param setSize the number of elements in a set. Cannot be less than one * and cannot be greater than twenty. * @return the number of permutations which could be generated from a set of * the given size. */ public static final long numberOfPermutations(int setSize) { if (setSize < 1) { throw new IllegalArgumentException( "setSize must be greater than zero."); } if (setSize > 20) { throw new IllegalArgumentException( "setSize cannot be greater than twenty."); } return factorial(setSize); } /** * Generates all permutations of the given <code>Set</code>. * <p> * Be warned that at a source set of size eleven will lead to heap memory * error unless at least 8GiB are allocated to the application. And a heap * memory error is almost certain with a source set of size twelve.</p> * * @param <T> the type of the elements contained in the supplied * <code>Set</code>. * @param sourceElements the source set which will be used to generate * permutations. Cannot be <code>null</code>, cannot contain a * <code>null</code> element and cannot contain more than twelve elements. * @return a <code>Set&lt;List&lt;T&gt;&gt;</code> which contains every * possible permutation of the source set. * @see #iteratorOfPermutations(java.util.Set) * @see #combinations(java.util.Set) */ public static final <T> Set<List<T>> permutations(Set<T> sourceElements) { Objects.requireNonNull(sourceElements); int elementCount = sourceElements.size(); if (elementCount < 1) { throw new IllegalArgumentException( "sourceElements must contain at least one element."); } if (elementCount > 12) { throw new IllegalArgumentException( "sourceElements cannot contain more than twelve elements."); } if (SetUtilities.containsNull(sourceElements)) { throw new NullPointerException( "sourceElements cannot contain a null element."); } List<T> elements = new ArrayList<>(sourceElements); int totalPermutationQuantity = (int) factorial(elementCount); long idealSetCapacity = 1L + (int) (totalPermutationQuantity * 4L / 3L); Set<List<T>> perms = new HashSet<>((int) idealSetCapacity); // Add the initial list as the first permutation. perms.add(new ArrayList<>(elements)); // Use Fuchs' Counting QuickPerm Algorithm to iterate through all int[] swapCount = new int[elementCount]; int elementIndex = 1; while (elementIndex < elementCount) { if (swapCount[elementIndex] < elementIndex) { int swapIndex = elementIndex % 2 == 0 ? 0 : swapCount[elementIndex]; T currentElement = elements.get(elementIndex); T swapperElement = elements.get(swapIndex); elements.set(elementIndex, swapperElement); elements.set(swapIndex, currentElement); perms.add(new ArrayList<>(elements)); ++swapCount[elementIndex]; elementIndex = 1; } else { swapCount[elementIndex] = 0; ++elementIndex; } } // Return the generated Set of all permutations. return perms; } public static final <T> Iterator<List<T>> iteratorOfPermutations( Set<T> sourceElements) { Objects.requireNonNull(sourceElements); if (sourceElements.isEmpty()) { throw new IllegalArgumentException("sourceSet cannot be empty."); } if (SetUtilities.containsNull(sourceElements)) { throw new NullPointerException( "sourceElements must not contain a null element."); } return new PermutationsIterator<>(sourceElements); } /** * An iterator which returns a single permutation at a time. * * @param <T> the type of the elements which will be found in the source set * supplied to this iterator, and the type of the elements which will be * found in the permutation lists returned by this iterator. */ private static class PermutationsIterator<T> implements Iterator<List<T>> { private final List<T> elements; private final int elementCount; private int elementIndex; private final int[] swapCount; private boolean firstPermutation; /** * Constructs a new <code>PermutationsIterator</code> which will iterate * through the permutations of the supplied set. * @param sourceElements a <code>Set&lt;T&gt;</code> which must not be * <code>null</code>, must not be empty, and must not contain a * <code>null</code> element. */ private PermutationsIterator(Set<T> sourceElements) { elements = new ArrayList<>(sourceElements); elementCount = elements.size(); swapCount = new int[elementCount]; elementIndex = 1; firstPermutation = true; } /** * Reports on whether this iterator has any further permutations to * offer. * * @return <code>true</code> if calling the <code>next()</code> method * of this iterator will return a new permutation; <code>false</code> if * there are no further permutations available. */ @Override public boolean hasNext() { if (elementIndex == elementCount) { return false; } for (int i = elementIndex; i < elementCount; ++i) { if (swapCount[i] < i) { return true; } } return false; } /** * Returns a new permutation of the elements found in the source set * which was used to create this iterator. * <p> * Permutations will not be returned in any guaranteed order, but each * call to <code>next()</code> will return a permutation which has not * already been returned by this iterator, or throw a * <code>NoSuchElementException</code> if this iterator has no more * unique permutations to return.</p> * * @return a <code>List&lt;T&gt;</code> which represents a uniquely * ordered permutation of the elements found in the source set which was * used to construct this iterator. * @throws NoSuchElementException if all permutations have already been * returned by this iterator and there is no new permutation which can * be provided. */ @Override public List<T> next() { List<T> perm = null; if (firstPermutation) { perm = new ArrayList<>(elements); firstPermutation = false; } // Use Fuchs' Counting QuickPerm Algorithm to swap elements in the while (perm == null && elementIndex < elementCount) { if (swapCount[elementIndex] < elementIndex) { int swapIndex = elementIndex % 2 == 0 ? 0 : swapCount[elementIndex]; T currentElement = elements.get(elementIndex); T swapperElement = elements.get(swapIndex); elements.set(elementIndex, swapperElement); elements.set(swapIndex, currentElement); perm = new ArrayList<>(elements); ++swapCount[elementIndex]; elementIndex = 1; } else { swapCount[elementIndex] = 0; ++elementIndex; } } if (perm == null) { throw new NoSuchElementException(); } return perm; } } }
package us.kbase.jgiintegration.perftest; import static us.kbase.jgiintegration.common.JGIUtils.wipeRemoteServer; import java.io.File; import java.net.URL; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import us.kbase.jgiintegration.common.JGIFileLocation; import us.kbase.jgiintegration.common.JGIOrganismPage; import com.gargoylesoftware.htmlunit.WebClient; public class MassPushFiles { private static final boolean SKIP_WIPE = true; private static final String JGI_PUSHABLE_FILES = "/home/crusherofheads/localgit/jgi_kbase_integration_tests/test_data/putative_pushable_files"; private static final int WORKERS = 1; private static final int MAX_PUSH_PER_WORKER = 2; private static final String WIPE_URL = "http://dev03.berkeley.kbase.us:9000"; private static String JGI_USER; private static String JGI_PWD; private static String KB_USER; private static String KB_PWD; public static void main(String[] args) throws Exception { Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF); JGI_USER = System.getProperty("test.jgi.user"); JGI_PWD = System.getProperty("test.jgi.pwd"); KB_USER = System.getProperty("test.kbase.user1"); KB_PWD = System.getProperty("test.kbase.pwd1"); String wipeUser = System.getProperty("test.kbase.wipe_user"); String wipePwd = System.getProperty("test.kbase.wipe_pwd"); if (!SKIP_WIPE) { wipeRemoteServer(new URL(WIPE_URL), wipeUser, wipePwd); } List<String> lines = Files.readAllLines( new File(JGI_PUSHABLE_FILES).toPath(), Charset.forName("UTF-8")); List<List<PushableFile>> filesets = new LinkedList<List<PushableFile>>(); for (int i = 0; i < WORKERS; i++) { filesets.add(new LinkedList<PushableFile>()); } int index = 0; for (String line: lines) { String[] temp = line.split("\t"); PushableFile pf = new PushableFile( temp[1], temp[0], temp[2], temp[3]); if (index >= filesets.size()) { index = 0; } filesets.get(index).add(pf); index++; } List<PushFilesToKBaseRunner> theruns = new LinkedList<PushFilesToKBaseRunner>(); for (List<PushableFile> list: filesets) { theruns.add(new PushFilesToKBaseRunner(list)); } List<Thread> threads = new LinkedList<Thread>(); for (PushFilesToKBaseRunner r: theruns) { Thread t = new Thread(r); t.start(); threads.add(t); } for (Thread t: threads) { t.join(); } index = 1; for (PushFilesToKBaseRunner r: theruns) { System.out.println(String.format( "Worker %s exceptions, count is %s:", index, r.getExceptions().size())); for (Throwable t: r.getExceptions()) { t.printStackTrace(); } index++; } } private static class PushFilesToKBaseRunner implements Runnable { private final List<PushableFile> files; private final List<Throwable> exceptions = new LinkedList<Throwable>(); public PushFilesToKBaseRunner(List<PushableFile> files) { this.files = files; } @Override public void run() { WebClient wc = new WebClient(); try { //perform known good login new JGIOrganismPage( wc, "BlaspURHD0036", JGI_USER, JGI_PWD); } catch (Exception e) { exceptions.add(e); } int count = 1; for (PushableFile f: files) { if (count > MAX_PUSH_PER_WORKER) { break; } try { JGIOrganismPage p = new JGIOrganismPage( wc, f.getOrganism(), null, null); p.selectFile(new JGIFileLocation( f.getFileGroup(), f.getFile())); p.pushToKBase(KB_USER, KB_PWD); } catch (Exception e) { exceptions.add(e); } count++; } } public List<Throwable> getExceptions() { return exceptions; } } }
package org.mozartoz.truffle.nodes.builtins; import static org.mozartoz.truffle.nodes.builtins.Builtin.ALL; import java.util.HashMap; import java.util.Map; import org.mozartoz.truffle.nodes.OzNode; import org.mozartoz.truffle.runtime.OzCons; import org.mozartoz.truffle.runtime.OzVar; import org.mozartoz.truffle.translator.Loader; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.NodeChild; import com.oracle.truffle.api.dsl.NodeChildren; import com.oracle.truffle.api.dsl.Specialization; public abstract class PropertyBuiltins { private static final Map<String, Object> PROPERTIES = new HashMap<>(); static { PROPERTIES.put("platform.os", System.getProperty("os.name")); PROPERTIES.put("platform.name", System.getProperty("os.name")); PROPERTIES.put("oz.home", Loader.PROJECT_ROOT); PROPERTIES.put("oz.version", "3.0.0-alpha"); PROPERTIES.put("oz.search.path", "."); PROPERTIES.put("oz.search.load", "."); PROPERTIES.put("limits.bytecode.xregisters", 65536L); PROPERTIES.put("limits.int.max", Long.MAX_VALUE); PROPERTIES.put("limits.int.min", Long.MIN_VALUE); PROPERTIES.put("application.gui", false); } public static void setApplicationURL(String appURL) { PROPERTIES.put("application.url", appURL); } public static void setApplicationArgs(String[] args) { Object list = "nil"; for (int i = args.length - 1; i >= 0; i list = new OzCons(args[i].intern(), list); } PROPERTIES.put("application.args", list); } @Builtin(proc = true, deref = ALL) @GenerateNodeFactory @NodeChildren({ @NodeChild("property"), @NodeChild("value") }) public static abstract class RegisterValueNode extends OzNode { @Specialization Object registerValue(String property, Object value) { assert !PROPERTIES.containsKey(property); PROPERTIES.put(property, value); return unit; } } @Builtin(proc = true, deref = ALL) @GenerateNodeFactory @NodeChildren({ @NodeChild("property"), @NodeChild("value") }) public static abstract class RegisterConstantNode extends OzNode { @Specialization Object registerConstant(Object property, Object value) { return unimplemented(); } } @Builtin(deref = 1) @GenerateNodeFactory @NodeChildren({ @NodeChild("property"), @NodeChild("result") }) public static abstract class GetNode extends OzNode { @Specialization boolean get(String property, OzVar result) { if (PROPERTIES.containsKey(property)) { result.bind(PROPERTIES.get(property)); return true; } else { result.bind(unit); return false; } } } @Builtin(deref = ALL) @GenerateNodeFactory @NodeChildren({ @NodeChild("property"), @NodeChild("value") }) public static abstract class PutNode extends OzNode { @Specialization boolean put(String property, Object value) { if (PROPERTIES.containsKey(property)) { PROPERTIES.put(property, value); return true; } else { return false; } } } }
package alphagram; import alphagram.model.Alphagram; import alphagram.model.Anagram; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * @author Fanaen <contact@fanaen.fr> */ public class AlphagramCLI { /** * @param args the command line arguments */ public static void main(String[] args) { AlphagramCLI process = new AlphagramCLI(); process.run(); } // -- Attributes -- private Map<String, Alphagram> variableMap = new HashMap<>(); // -- Methods -- private void run() { Scanner in = new Scanner(System.in, "UTF-8"); String line = ""; boolean pursue = true; // Display welcome message -- System.out.println("-- Alphagram --"); System.out.println("Type \"quit\" to exit."); while(pursue) { System.out.print("> "); line = in.nextLine(); // Quit condition -- if(line.toLowerCase().equals("quit")) { pursue = false; System.out.println("ahknsT for ginsu Aaaghlmpr. Bey!"); } // Standard line -- else { processOperation(line); } } } private void processOperation(String line) { Pattern p = Pattern.compile("^([a-zA-Z0-9]+) *= *(.+)$"); Matcher m = p.matcher(line.trim()); if(m.matches()) { String key = m.group(1); Alphagram alphagram = processLine(m.group(2)); variableMap.put(key, alphagram); System.out.println("# " + key + " set."); } else { processLine(line); } } private String insertVariables(String line) { Pattern p = Pattern.compile("\\$([a-zA-Z0-9]+)"); Matcher m = p.matcher(line); while(m.find()) { String key = m.group(1); Alphagram alpha = variableMap.get(key); if(alpha != null) { line = line.replaceAll("\\$"+ key, alpha.getRaw()); } } return line; } private Alphagram processLine(String line) { line = insertVariables(line); String[] words = line.split(" "); System.out.print(" boolean add = true; // Multiple words -- if(words.length > 1) { int i = 0; Alphagram alphagram = new Alphagram(""); for (String word : words) { i++; // Handle operators -- if(word.trim().equals("+") || word.trim().equals("-")) { add = word.equals("+"); continue; } if(add) { // Add the word to the result -- if(i>1) System.out.print(" + "); alphagram.apply(processWord(word), +1); } else { // Withdraw the word to the result -- if(i>1) System.out.print(" - "); alphagram.apply(processWord(word), -1); } } System.out.print(" = "); display(alphagram); System.out.println(); return alphagram; } // Single words -- else { Alphagram alphagram = processWord(line); System.out.println(); return alphagram; } } private static Alphagram processWord(String word) { Anagram anagram = new Anagram(word); Alphagram alphagram = anagram.alphagram(); display(alphagram); return alphagram; } private static void display(Alphagram alphagram) { System.out.print(alphagram.getRaw() + " (" + alphagram.getShort() + ")"); } }
package com.newrelic.cordova; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaActivity; import org.apache.cordova.CordovaWebView; import org.json.JSONArray; import com.newrelic.agent.android.NewRelic; import android.util.Log; public class NewRelicPlugin extends CordovaPlugin { /** Common tag used for logging statements. */ private static final String LOGTAG = "NewRelicPlugin"; /** * @param cordova The context of the main Activity. * @param webView The associated CordovaWebView. */ @Override public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova,webView); this.cordova = cordova; this.webView = webView; NewRelic.withApplicationToken( this.getAppToken() ).start(this.cordova.getActivity().getApplication()); } private String getAppToken(){ String token = ""; token = this.cordova.getActivity().getStringProperty("NewRelicApplicationToken"); Log.d(LOGTAG, "NewRelic Token: " + token); return token; } }
package forestry.api.mail; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTUtil; import net.minecraft.server.MinecraftServer; import org.apache.commons.lang3.StringUtils; import com.mojang.authlib.GameProfile; import forestry.api.core.INBTTagable; public class MailAddress implements INBTTagable { private String type; private Object identifier; // identifier is a GameProfile if this.type is "player" and String for traders private MailAddress() { } public MailAddress(GameProfile identifier) { this(identifier, "player"); } public MailAddress(String identifier) { this(identifier, "trader"); } private MailAddress(Object identifier, String type) { this.identifier = identifier; this.type = type; } public static MailAddress makeMailAddress(String identifier, String type) { if (StringUtils.isBlank(identifier)) return null; if (StringUtils.isBlank(type)) return null; MailAddress mailAddress = new MailAddress(); mailAddress.type = type; if (mailAddress.isPlayer()) mailAddress.identifier = MinecraftServer.getServer().func_152358_ax().func_152655_a(identifier); else mailAddress.identifier = identifier; if (mailAddress.identifier == null) return null; return mailAddress; } public String getType() { return type; } public Object getIdentifier() { return this.identifier; } public String getIdentifierName() { if (isPlayer()) return ((GameProfile)this.identifier).getName(); else return (String)this.identifier; } @Override public String toString() { if (isPlayer()) { GameProfile profile = (GameProfile)this.identifier; return profile.getName() + ":" + profile.getId().toString(); } else { return (String) this.identifier; } } @Override public boolean equals(Object o) { if (!(o instanceof MailAddress)) return false; MailAddress address = (MailAddress)o; return (address.getIdentifier().equals(this.getIdentifier())); } @Override public int hashCode() { return this.identifier.hashCode(); } public boolean isPlayer() { return "player".equals(type); } @Override public void readFromNBT(NBTTagCompound nbttagcompound) { if(nbttagcompound.hasKey("TP")) type = nbttagcompound.getString("TP"); else type = nbttagcompound.getShort("TYP") == 0 ? "player" : "trader"; if (isPlayer()) { if (nbttagcompound.hasKey("identifier")) { identifier = NBTUtil.func_152459_a(nbttagcompound.getCompoundTag("identifier")); } } else { identifier = nbttagcompound.getString("identifier"); } } @Override public void writeToNBT(NBTTagCompound nbttagcompound) { nbttagcompound.setString("TP", type); if (isPlayer()) { if (identifier != null) { NBTTagCompound profileNbt = new NBTTagCompound(); NBTUtil.func_152460_a(profileNbt, (GameProfile)identifier); nbttagcompound.setTag("identifier", profileNbt); } } else { nbttagcompound.setString("identifier", (String)identifier); } } public static MailAddress loadFromNBT(NBTTagCompound nbttagcompound) { MailAddress address = new MailAddress(); address.readFromNBT(nbttagcompound); return address; } }
package me.brendanweinstein; public enum CardType { VISA(1, "Visa", false, 3), MASTERCARD(2, "Mastercard", false, 3), AMERICAN_EXPRESS(3, "American Express", false, 4), DISCOVER(4,"Discover", false, 3), JCB(5, "JCB", false, 3), DINERS_CLUB(6, "Diners Club", false, 3), UNKNOWN_CARD(7, "Unknown", true, 3), TOO_MANY_DIGITS(8, "Too Many Digits", true, 3), NOT_ENOUGH_DIGITS(9, "Not Enough Digits", true, 3), PAYPAL(10, "", false, 0); private int mVal; private String mName; private boolean mIsError; private int mMaxCVVLength; CardType(int val, String name, boolean isError, int maxCVVLength) { this.mVal = val; this.mName = name; this.mIsError = isError; mMaxCVVLength = maxCVVLength; } public int getValue() { return mVal; } public String getName() { return mName; } public boolean isError() { return mIsError; } public int getMaxCVVLength() { return mMaxCVVLength; } public static CardType fromString(String text) { if (text != null) { int num = Integer.parseInt(text); for (CardType c : CardType.values()) { if (c.mVal == num) { return c; } } } return CardType.UNKNOWN_CARD; } }
import com.scalien.scaliendb.*; import java.io.*; import java.util.ArrayList; import java.util.Random; public class ConcurrentWords { public static void main(String[] args) { try { final String wordsFile = "/usr/share/dict/words"; String[] controllers = {"127.0.0.1:7080"}; boolean createSchema = false; if (args.length > 0) { controllers[0] = args[0]; if (args.length > 1) { if (args[1].equals("createSchema")) createSchema = true; } } System.out.println("Reading words file..."); FileInputStream fstream = new FileInputStream(wordsFile); DataInputStream in = new DataInputStream(fstream); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); ArrayList<String> words = new ArrayList<String>(); String line; while ((line = reader.readLine()) != null) words.add(line.trim()); in.close(); System.out.println("Randomizing words..."); Random random = new Random(System.nanoTime()); ArrayList<String> randomWords = new ArrayList<String>(); for (int i = 0; i < 10000; i++) { int toRemove = random.nextInt(words.size()); randomWords.add(words.remove(toRemove)); } System.out.println("Writing words to database..."); Client client = new Client(controllers); //client.setTrace(true); if (createSchema) { long[] nodes = {100}; long quorumID = client.createQuorum(nodes); long databaseID = client.createDatabase("test"); long tableID = client.createTable(databaseID, quorumID, "words"); } client.useDatabase("test"); client.useTable("words"); client.begin(); for (String word : randomWords) client.setIfNotExists(word, word); System.out.println("Submitting to database..."); long startTime = System.currentTimeMillis(); client.submit(); long endTime = System.currentTimeMillis(); long wps = (long)(randomWords.size() / (float)(endTime - startTime) * 1000.0 + 0.5); System.out.println(randomWords.size() + " words written at " + wps + " word/s"); } catch (Exception e) { System.err.println(e.getMessage()); } } }
package com.example.wrench; import android.content.ContentResolver; import android.content.Context; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Handler; import android.support.annotation.Nullable; public class BoltLiveData extends LiveData<Bolt> { private final String key; private final String type; private final String defValue; private final Context context; private BoltContentObserver boltContentObserver; BoltLiveData(Context context, String key, String defValue, String type) { this.context = context; this.key = key; this.type = type; this.defValue = defValue; boltContentObserver = new BoltContentObserver(new Handler()); } public static BoltLiveData string(Context context, String key, String def) { return new BoltLiveData(context, key, def, String.class.getName()); } public static BoltLiveData bool(Context context, String key, boolean def) { return new BoltLiveData(context, key, String.valueOf(def), Boolean.class.getName()); } public static BoltLiveData integer(Context context, String key, int def) { return new BoltLiveData(context, key, String.valueOf(def), Integer.class.getName()); } @Nullable private static Bolt getBolt(ContentResolver contentResolver, String key) { Cursor cursor = null; try { cursor = contentResolver.query(WrenchProviderContract.boltUri(key), null, null, null, null); if (cursor == null) { return null; } if (cursor.moveToFirst()) { return Bolt.fromCursor(cursor); } } finally { if (cursor != null && !cursor.isClosed()) { cursor.close(); } } return new Bolt(); } private static Uri insertBolt(ContentResolver contentResolver, Bolt bolt) { return contentResolver.insert(WrenchProviderContract.boltUri(), bolt.toContentValues()); } @Override protected void onActive() { context.getContentResolver() .registerContentObserver(WrenchProviderContract.boltUri(), true, boltContentObserver); boltChanged(); } @Override protected void onInactive() { context.getContentResolver().unregisterContentObserver(boltContentObserver); } private void boltChanged() { Bolt bolt = getBolt(context.getContentResolver(), key); if (bolt == null) { setValue(null); return; } if (bolt.id == 0) { bolt.key = key; bolt.type = type; bolt.value = defValue; Uri uri = insertBolt(context.getContentResolver(), bolt); bolt.id = Long.parseLong(uri.getLastPathSegment()); } setValue(bolt); } class BoltContentObserver extends ContentObserver { BoltContentObserver(Handler handler) { super(handler); } @Override public void onChange(boolean selfChange) { this.onChange(selfChange, null); } @Override public void onChange(boolean selfChange, Uri uri) { BoltLiveData.this.boltChanged(); } } }
package perf.backend; import io.netty.handler.codec.http.HttpResponseStatus; import io.reactivex.netty.RxNetty; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import java.util.List; import rx.Observable; public class StartMockService { public static void main(String[] args) { int port = 8989; if (args.length > 0) { port = Integer.parseInt(args[0]); } System.out.println("Starting mock service on port " + port + "..."); RxNetty.createHttpServer(port, (request, response) -> { try { return handleRequest(request, response); } catch (Throwable e) { e.printStackTrace(); System.err.println("Server => Error [" + request.getPath() + "] => " + e); response.setStatus(HttpResponseStatus.BAD_REQUEST); return response.writeStringAndFlush("Error 500: Bad Request\n" + e.getMessage() + "\n"); } }).startAndWait(); } protected static Observable<Void> writeError(HttpServerRequest<?> request, HttpServerResponse<?> response, String message) { System.err.println("Server => Error [" + request.getPath() + "] => " + message); response.setStatus(HttpResponseStatus.BAD_REQUEST); return response.writeStringAndFlush("Error 500: " + message + "\n"); } protected static int getParameter(HttpServerRequest<?> request, String key, int defaultValue) { List<String> v = request.getQueryParameters().get(key); if (v == null || v.size() != 1) { return defaultValue; } else { return Integer.parseInt(String.valueOf(v.get(0))); } } private static Observable<Void> handleRequest(HttpServerRequest<?> request, HttpServerResponse<?> response) { List<String> _id = request.getQueryParameters().get("id"); if (_id == null || _id.size() != 1) { return writeError(request, response, "Please provide a numerical 'id' value. It can be a random number (uuid). Received => " + _id); } long id = Long.parseLong(String.valueOf(_id.get(0))); int delay = getParameter(request, "delay", 50); // default to 50ms server-side delay int itemSize = getParameter(request, "itemSize", 128); // default to 128 bytes item size (assuming ascii text) int numItems = getParameter(request, "numItems", 10); // default to 10 items in a list // no more than 100 items if (numItems < 1 || numItems > 100) { return writeError(request, response, "Please choose a 'numItems' value from 1 to 100."); } // no larger than 50KB per item if (itemSize < 1 || itemSize > 1024 * 50) { return writeError(request, response, "Please choose an 'itemSize' value from 1 to 1024*50 (50KB)."); } // no larger than 60 second delay if (delay < 0 || delay > 60000) { return writeError(request, response, "Please choose a 'delay' value from 0 to 60000 (60 seconds)."); } response.setStatus(HttpResponseStatus.OK); return MockResponse.generateJson(id, delay, itemSize, numItems).flatMap(json -> response.writeStringAndFlush(json)); } }
package org.yamcs.tctm.ccsds; import java.util.function.Consumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yamcs.tctm.PacketTooLongException; import org.yamcs.tctm.TcTmException; import org.yamcs.utils.ByteArrayUtils; /** * Receives data chunk by chunk and assembles it into packets. Two types of packets are supported: * <p> * <strong>Space Packet Protocol CCSDS 133.0-B-1 September 2003.</strong> * <p> * The first 3 bits of these packets are 000. * <p> * The header is 6 bytes and the last two bytes of the header represent the * size of the packet (including the header) - 7. * <p> * The minimum packet length is 7 bytes. * * <p> * <strong>Encapsulation Service. CCSDS 133.1-B-2. October 2009.</strong> * <p> * The first 3 bits of these packets are 111. * <p> * The minimum packet length is 1 byte. * <p> * Depending on the last 2 bits of the first byte, the size of the header can be 1,2,4 or 8 bytes with the length of the * packet read from the last 0,1,2 or 4 header bytes respectively * * <p> * The two types can be both present on the same stream. * * <p> * The objects of this class can processes one "stream" at a time and they are not thread safe! * * @author nm * */ public class PacketDecoder { private final int maxPacketLength; // length of the encapsulated packet header based on the last 2 bits of the first byte static final byte[] ENCAPSULATION_HEADER_LENGTH = { 1, 2, 4, 8 }; static final int PACKET_VERSION_CCSDS = 0; static final int PACKET_VERSION_ENCAPSULATION = 7; // the actual header length (valid when the headerOffset>0) private int headerLength; // max header length for the encapsulation packets is 8 bytes final byte[] header = new byte[8]; private int headerOffset; // the packetOffset and packet will be valid when the header is completely read (i.e. // headerOffset==header.length==lengthFieldEndOffset) private int packetOffset; private byte[] packet; final Consumer<byte[]> consumer; private boolean skipIdlePackets = true; private boolean stripEncapsulationHeader = false; final static byte[] ZERO_BYTES = new byte[0]; static Logger log = LoggerFactory.getLogger(PacketDecoder.class.getName()); public PacketDecoder(int maxPacketLength, Consumer<byte[]> consumer) { this.maxPacketLength = maxPacketLength; this.consumer = consumer; } public void process(byte[] data, int offset, int length) throws TcTmException { while (length > 0) { if (headerOffset == 0) { // read the first byte of the header to know what kind of packet it is as well as byte d0 = data[offset]; offset++; length headerLength = getHeaderLength(d0); header[0] = d0; if (headerLength == 1) { // special case, encapsulation packet of size 1, send the packet and reset the header if (stripEncapsulationHeader) { packet = ZERO_BYTES; } else { packet = new byte[] { d0 }; } sendToConsumer(); headerOffset = 0; } else { headerOffset++; } } else if (headerOffset < headerLength) { // reading the header int n = Math.min(length, headerLength - headerOffset); System.arraycopy(data, offset, header, headerOffset, n); offset += n; headerOffset += n; length -= n; if (headerOffset == headerLength) { allocatePacket(); } } else {// reading the packet int n = Math.min(packet.length - packetOffset, length); System.arraycopy(data, offset, packet, packetOffset, n); offset += n; packetOffset += n; length -= n; if (packetOffset == packet.length) { sendToConsumer(); packet = null; headerOffset = 0; } } } } private static boolean isIdle(byte[] header) { int b0 = header[0] & 0xFF; int pv = b0 >>> 5; if (pv == PACKET_VERSION_CCSDS) { return ((ByteArrayUtils.decodeShort(header, 0) & 0x7FF) == 0x7FF); } else { return ((b0 & 0x1C) == 0); } } private void sendToConsumer() { if (!skipIdlePackets || !isIdle(header)) { consumer.accept(packet); } else { log.trace("skiping idle packet of size {}", packet.length); } } // get headerLength based on the first byte of the packet private static int getHeaderLength(byte b0) throws UnsupportedPacketVersionException { int pv = (b0 & 0xFF) >>> 5; if (pv == PACKET_VERSION_CCSDS) { return 6; } else if (pv == PACKET_VERSION_ENCAPSULATION) { return ENCAPSULATION_HEADER_LENGTH[b0 & 3]; } else { throw new UnsupportedPacketVersionException(pv); } } private void allocatePacket() throws TcTmException { int packetLength = getPacketLength(header); if (packetLength > maxPacketLength) { throw new PacketTooLongException(maxPacketLength, packetLength); } else if (packetLength < headerLength) { throw new TcTmException( "Invalid packet length " + packetLength + " (it is smaller than the header length)"); } if (stripEncapsulationHeader && isEncapsulation(header)) { if (packetLength == headerLength) { packet = ZERO_BYTES; sendToConsumer(); headerOffset = 0; } else { packet = new byte[packetLength - headerLength]; packetOffset = 0; } } else { packet = new byte[packetLength]; System.arraycopy(header, 0, packet, 0, headerLength); if (packetLength == headerLength) { sendToConsumer(); headerOffset = 0; } else { packetOffset = headerLength; } } } private static boolean isEncapsulation(byte[] header) { int pv = (header[0] & 0xFF) >>> 5; return (pv == PACKET_VERSION_ENCAPSULATION); } // decodes the packet length from the header private static int getPacketLength(byte[] header) throws UnsupportedPacketVersionException { int h0 = header[0] & 0xFF; int pv = h0 >>> 5; if (pv == PACKET_VERSION_CCSDS) { return 7 + ByteArrayUtils.decodeShort(header, 4); } else if (pv == PACKET_VERSION_ENCAPSULATION) { int l = h0 & 3; if (l == 0) { return 1; } else if (l == 1) { return header[1] & 0xFF; } else if (l == 2) { return ByteArrayUtils.decodeShort(header, 2); } else { return ByteArrayUtils.decodeInt(header, 4); } } else { throw new UnsupportedPacketVersionException(pv); } } /** * Removes a partial packet if any */ public void reset() { headerOffset = 0; packet = null; } /** * * @return true of the decoder is in the middle of a packet decoding */ public boolean hasIncompletePacket() { return (headerOffset > 0) && ((headerOffset < headerLength) || (packetOffset < packet.length)); } /** * * @return true of the idle packets are skipped (i.e. not sent to the consumer) */ public boolean skipIdlePackets() { return skipIdlePackets; } /** * Skip or not the idle packets. If true (default), the idle packets are not sent to the consumer. * * @param skipIdlePackets */ public void skipIdlePackets(boolean skipIdlePackets) { this.skipIdlePackets = skipIdlePackets; } /** * * @return true if the header of the encapsulated packets will be stripped out. */ public boolean stripEncapsulationHeader() { return stripEncapsulationHeader; } /** * If set to true, the encapsulation header will be stripped out. This means: * <ul> * <li>the Protocol ID information will be lost.</li> * <li>an empty array buffer will be delivered for the one byte packets (or any other packet of size 0)</li> * </ul> * * @param stripEncapsulationHeader */ public void stripEncapsulationHeader(boolean stripEncapsulationHeader) { this.stripEncapsulationHeader = stripEncapsulationHeader; } }
package simizer.laws; import java.lang.reflect.Field; import org.junit.*; /** * Basic tests that should be run on all Law subclasses. */ @Ignore public class LawTest { protected Law law; /** * Outputs values from the law to evaluate their distribution. */ @Test public void testOutput() { for (int i = 0; i < 10000; i++) { System.out.println(law.nextValue()); } } /** * Tests whether or not the theoretically maximum value can be achieved. * * @throws Exception if there is a problem with the reflection */ @Test public void testMaximum() throws Exception { Field upperBound = Law.class.getDeclaredField("upperBound"); upperBound.setAccessible(true); int bound = (Integer) upperBound.get(law); long target = System.currentTimeMillis() + 4*1000; boolean found = false; while (System.currentTimeMillis() < target) { int value = law.nextValue(); Assert.assertTrue("generated a value that was too large", value < bound); Assert.assertTrue("generated a value that was too small", value >= 0); if (value == (bound - 1)) { found = true; break; } } Assert.assertTrue("could not generate the maximum value", found); } /** * Tests whether or not the theoretically minimum value can be achieved. */ @Test public void testMinimum() { long target = System.currentTimeMillis() + 4*1000; boolean found = false; while (System.currentTimeMillis() < target) { int value = law.nextValue(); Assert.assertTrue("generated a value that was too small", value >= 0); if (value == 0) { found = true; break; } } Assert.assertTrue("could not generate the minimum value", found); } }
package git4idea.history; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.FileStatus; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.changes.Change; import com.intellij.openapi.vcs.diff.ItemLatestState; import com.intellij.openapi.vcs.history.VcsRevisionDescription; import com.intellij.openapi.vcs.history.VcsRevisionDescriptionImpl; import com.intellij.openapi.vcs.history.VcsRevisionNumber; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.ArrayUtil; import com.intellij.util.Consumer; import com.intellij.util.containers.ContainerUtil; import com.intellij.vcs.log.TimedVcsCommit; import com.intellij.vcs.log.VcsCommitMetadata; import com.intellij.vcs.log.VcsLogObjectsFactory; import com.intellij.vcsUtil.VcsUtil; import git4idea.*; import git4idea.branch.GitBranchUtil; import git4idea.commands.Git; import git4idea.commands.GitCommand; import git4idea.commands.GitLineHandler; import git4idea.history.browser.SHAHash; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import static git4idea.history.GitLogParser.GitLogOption.*; /** * A collection of methods for retrieving history information from native Git. */ public class GitHistoryUtils { private GitHistoryUtils() { } /** * Load commit information in a form of {@link GitCommit} (containing commit details and changes to commit parents) * in the repository using `git log` command. * * @param project context project * @param root git repository root * @param commitConsumer consumer for commits * @param parameters additional parameters for `git log` command * @throws VcsException if there is a problem with running git */ @SuppressWarnings("unused") // used externally public static void loadDetails(@NotNull Project project, @NotNull VirtualFile root, @NotNull Consumer<? super GitCommit> commitConsumer, @NotNull String... parameters) throws VcsException { GitLogUtil.readFullDetails(project, root, commitConsumer, true, true, false, parameters); } /** * Load commit information in a form of {@link TimedVcsCommit} (containing hash, parents and commit time) * in the repository using `git log` command. * * @param project context project * @param root git repository root * @param commitConsumer consumer for commits * @param parameters additional parameters for `git log` command * @throws VcsException if there is a problem with running git */ public static void loadTimedCommits(@NotNull Project project, @NotNull VirtualFile root, @NotNull Consumer<? super TimedVcsCommit> commitConsumer, @NotNull String... parameters) throws VcsException { GitLogUtil.readTimedCommits(project, root, Arrays.asList(parameters), null, null, commitConsumer); } /** * Collect commit information in a form of {@link TimedVcsCommit} (containing hash, parents and commit time) * in the repository using `git log` command. * * @param project context project * @param root git repository root * @param parameters additional parameters for `git log` command * @throws VcsException if there is a problem with running git */ @SuppressWarnings("unused") public static List<? extends TimedVcsCommit> collectTimedCommits(@NotNull Project project, @NotNull VirtualFile root, @NotNull String... parameters) throws VcsException { List<TimedVcsCommit> commits = ContainerUtil.newArrayList(); loadTimedCommits(project, root, commits::add, parameters); return commits; } /** * Collect commit information in a form of {@link VcsCommitMetadata} (containing commit details, but no changes) * for the specified hashes or references. * * @param project context project * @param root git repository root * @param hashes hashes or references * @return a list of {@link VcsCommitMetadata} (one for each specified hash or reference) or null if something went wrong * @throws VcsException if there is a problem with running git */ @Nullable public static List<? extends VcsCommitMetadata> collectCommitsMetadata(@NotNull Project project, @NotNull VirtualFile root, @NotNull String... hashes) throws VcsException { List<? extends VcsCommitMetadata> result = GitLogUtil.collectShortDetails(project, GitVcs.getInstance(project), root, Arrays.asList(hashes)); if (result.size() != hashes.length) return null; return result; } /** * Collect commit information in a form of {@link GitCommit} (containing commit details and changes to commit parents) * in the repository using `git log` command. * <br/> * Warning: this is method is efficient by speed, but don't query too much, because the whole log output is retrieved at once, * and it can occupy too much memory. The estimate is ~600Kb for 1000 commits. * * @param project context project * @param root git repository root * @param parameters additional parameters for `git log` command * @return a list of {@link GitCommit} * @throws VcsException if there is a problem with running git */ @NotNull public static List<GitCommit> history(@NotNull Project project, @NotNull VirtualFile root, String... parameters) throws VcsException { VcsLogObjectsFactory factory = GitLogUtil.getObjectsFactoryWithDisposeCheck(project); if (factory == null) { return Collections.emptyList(); } return GitLogUtil.collectFullDetails(project, root, parameters); } /** * Create a proper list of parameters for `git log` command from a list of hashes. * * @param vcs an instance of {@link GitVcs} class for the repository, could be obtained from the * corresponding {@link git4idea.repo.GitRepository} or from a project by calling {@code GitVcs.getInstance(project)} * @param hashes a list of hashes to call `git log` for * @return a list of parameters that could be fed to a `git log` command * @throws VcsException if there is a problem with running git */ @NotNull public static String[] formHashParameters(@NotNull GitVcs vcs, @NotNull Collection<String> hashes) { List<String> parameters = ContainerUtil.newArrayList(); parameters.add(GitLogUtil.getNoWalkParameter(vcs)); parameters.addAll(hashes); return ArrayUtil.toStringArray(parameters); } /** * Get current revision for the file under git in the current or specified branch. * * @param project context project * @param filePath file path to the file which revision is to be retrieved * @param branch name of branch or null if current branch wanted * @return revision number or null if the file is unversioned or new * @throws VcsException if there is a problem with running git */ @Nullable public static VcsRevisionNumber getCurrentRevision(@NotNull Project project, @NotNull FilePath filePath, @Nullable String branch) throws VcsException { filePath = VcsUtil.getLastCommitPath(project, filePath); GitLineHandler h = new GitLineHandler(project, GitUtil.getRepositoryForFile(project, filePath).getRoot(), GitCommand.LOG); GitLogParser parser = new GitLogParser(project, HASH, COMMIT_TIME); h.setSilent(true); h.addParameters("-n1", parser.getPretty()); h.addParameters(!StringUtil.isEmpty(branch) ? branch : "--all"); h.endOptions(); h.addRelativePaths(filePath); String result = Git.getInstance().runCommand(h).getOutputOrThrow(); if (result.length() == 0) { return null; } final GitLogRecord record = parser.parseOneRecord(result); if (record == null) { return null; } record.setUsedHandler(h); return new GitRevisionNumber(record.getHash(), record.getDate()); } @Nullable public static VcsRevisionDescription getCurrentRevisionDescription(@NotNull Project project, @NotNull FilePath filePath) throws VcsException { filePath = VcsUtil.getLastCommitPath(project, filePath); GitLineHandler h = new GitLineHandler(project, GitUtil.getRepositoryForFile(project, filePath).getRoot(), GitCommand.LOG); GitLogParser parser = new GitLogParser(project, HASH, COMMIT_TIME, AUTHOR_NAME, COMMITTER_NAME, SUBJECT, BODY, RAW_BODY); h.setSilent(true); h.addParameters("-n1", parser.getPretty()); h.addParameters("--encoding=UTF-8"); h.addParameters("--all"); h.endOptions(); h.addRelativePaths(filePath); String result = Git.getInstance().runCommand(h).getOutputOrThrow(); if (result.length() == 0) { return null; } final GitLogRecord record = parser.parseOneRecord(result); if (record == null) { return null; } record.setUsedHandler(h); final String author = Comparing.equal(record.getAuthorName(), record.getCommitterName()) ? record.getAuthorName() : record.getAuthorName() + " (" + record.getCommitterName() + ")"; return new VcsRevisionDescriptionImpl(new GitRevisionNumber(record.getHash(), record.getDate()), record.getDate(), author, record.getFullMessage()); } /** * Get current revision for the file under git. * * @param project context project * @param filePath file path to the file which revision is to be retrieved * @return a revision number or null if the file is unversioned or new * @throws VcsException if there is problem with running git */ @Nullable public static ItemLatestState getLastRevision(@NotNull Project project, @NotNull FilePath filePath) throws VcsException { VirtualFile root = GitUtil.getRepositoryForFile(project, filePath).getRoot(); GitBranch c = GitBranchUtil.getCurrentBranch(project, root); GitBranch t = c == null ? null : GitBranchUtil.tracked(project, root, c.getName()); if (t == null) { return new ItemLatestState(getCurrentRevision(project, filePath, null), true, false); } filePath = VcsUtil.getLastCommitPath(project, filePath); GitLineHandler h = new GitLineHandler(project, root, GitCommand.LOG); GitLogParser parser = new GitLogParser(project, GitLogParser.NameStatus.STATUS, HASH, COMMIT_TIME, PARENTS); h.setSilent(true); h.addParameters("-n1", parser.getPretty(), "--name-status", t.getFullName()); h.endOptions(); h.addRelativePaths(filePath); String result = Git.getInstance().runCommand(h).getOutputOrThrow(); if (result.length() == 0) { return null; } GitLogRecord record = parser.parseOneRecord(result); if (record == null) { return null; } final List<Change> changes = record.parseChanges(project, root); boolean exists = changes.isEmpty() || !FileStatus.DELETED.equals(changes.get(0).getFileStatus()); record.setUsedHandler(h); return new ItemLatestState(new GitRevisionNumber(record.getHash(), record.getDate()), exists, false); } @Nullable public static GitRevisionNumber getMergeBase(@NotNull Project project, @NotNull VirtualFile root, @NotNull String first, @NotNull String second) throws VcsException { GitLineHandler h = new GitLineHandler(project, root, GitCommand.MERGE_BASE); h.setSilent(true); h.addParameters(first, second); String output = Git.getInstance().runCommand(h).getOutputOrThrow().trim(); if (output.length() == 0) { return null; } else { return GitRevisionNumber.resolve(project, root, output); } } public static long getAuthorTime(@NotNull Project project, @NotNull VirtualFile root, @NotNull String commitsId) throws VcsException { GitLineHandler h = new GitLineHandler(project, root, GitCommand.SHOW); GitLogParser parser = new GitLogParser(project, GitLogParser.NameStatus.NONE, AUTHOR_TIME); h.setSilent(true); h.addParameters("-s", parser.getPretty(), "--encoding=UTF-8"); h.addParameters(commitsId); String output = Git.getInstance().runCommand(h).getOutputOrThrow(); GitLogRecord logRecord = parser.parseOneRecord(output); if (logRecord == null) throw new VcsException("Can not parse log output \"" + output + "\""); return logRecord.getAuthorTimeStamp(); } /** * Get name of the file in the last commit. If file was renamed, returns the previous name. * * @param project the context project * @param path the path to check * @return the name of file in the last commit or argument * @deprecated use {@link VcsUtil#getLastCommitPath(Project, FilePath)} */ @NotNull @Deprecated public static FilePath getLastCommitName(@NotNull Project project, @NotNull FilePath path) { return VcsUtil.getLastCommitPath(project, path); } /** * @deprecated use {@link GitHistoryUtils#collectTimedCommits(Project, VirtualFile, String...)} */ @Deprecated @SuppressWarnings("unused") @NotNull public static List<Pair<SHAHash, Date>> onlyHashesHistory(@NotNull Project project, @NotNull FilePath path, String... parameters) throws VcsException { final VirtualFile root = GitUtil.getRepositoryForFile(project, path).getRoot(); return onlyHashesHistory(project, path, root, parameters); } /** * @deprecated use {@link GitHistoryUtils#collectTimedCommits(Project, VirtualFile, String...)} */ @Deprecated @NotNull public static List<Pair<SHAHash, Date>> onlyHashesHistory(@NotNull Project project, @NotNull FilePath path, @NotNull VirtualFile root, String... parameters) throws VcsException { // adjust path using change manager path = VcsUtil.getLastCommitPath(project, path); GitLineHandler h = new GitLineHandler(project, root, GitCommand.LOG); GitLogParser parser = new GitLogParser(project, HASH, COMMIT_TIME); h.setStdoutSuppressed(true); h.addParameters(parameters); h.addParameters(parser.getPretty(), "--encoding=UTF-8"); h.endOptions(); h.addRelativePaths(path); String output = Git.getInstance().runCommand(h).getOutputOrThrow(); final List<Pair<SHAHash, Date>> rc = new ArrayList<>(); for (GitLogRecord record : parser.parse(output)) { record.setUsedHandler(h); rc.add(Pair.create(new SHAHash(record.getHash()), record.getDate())); } return rc; } /** * @deprecated use {@link GitHistoryUtils#collectCommitsMetadata(Project, VirtualFile, String...)} instead. */ @Deprecated public static List<? extends VcsCommitMetadata> readLastCommits(@NotNull Project project, @NotNull VirtualFile root, @NotNull String... hashes) throws VcsException { return collectCommitsMetadata(project, root, hashes); } }
package build.pluto.builder; import java.io.Serializable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import build.pluto.BuildUnit; import build.pluto.BuildUnit.State; import build.pluto.dependency.BuildRequirement; import build.pluto.output.Output; public class BuildAtOnceCycleHandler < In extends Serializable, Out extends Output, B extends BuildCycleAtOnceBuilder<In, Out>, F extends BuilderFactory<ArrayList<In>, Out, B> > //@formatter:on extends CycleHandler { private final F builderFactory; protected BuildAtOnceCycleHandler(BuildCycle cycle, F builderFactory) { super(cycle); this.builderFactory = builderFactory; } @Override public boolean canBuildCycle(BuildCycle cycle) { return cycle.getCycleComponents().stream().allMatch((BuildRequest<?, ?, ?, ?> req) -> req.factory == builderFactory && (req.input instanceof ArrayList<?>)); } @SuppressWarnings("unchecked") @Override public Set<BuildUnit<?>> buildCycle(BuildCycle cycle, BuildUnitProvider manager) throws Throwable { ArrayList<BuildUnit<Out>> cyclicResults = new ArrayList<>(); ArrayList<In> inputs = new ArrayList<>(); ArrayList<BuildRequest<?, Out, ?, ?>> requests = new ArrayList<>(); for (BuildRequest<?, ?, ?, ?> req : cycle.getCycleComponents()) { Builder<?, ?> tmpBuilder = req.createBuilder(); // Casts are safe, otherwise the cycle support would had rejected to // compile the cycle cyclicResults.add(BuildUnit.<Out> create(tmpBuilder.persistentPath(), (BuildRequest<?, Out, ?, ?>) req)); inputs.addAll((ArrayList<In>) req.input); requests.add((BuildRequest<?, Out, ?, ?>) req); } B newBuilder = builderFactory.makeBuilder(inputs); newBuilder.manager = manager; newBuilder.cyclicResults = cyclicResults; List<Out> outputs = newBuilder.buildAll(inputs); if (outputs.size() != inputs.size()) { throw new AssertionError("buildAll needs to return one output for one input"); } for (int i = 0; i < outputs.size(); i++) { BuildUnit<Out> unit = cyclicResults.get(i); unit.setBuildResult(outputs.get(i)); unit.setState(State.finished(true)); } /* * for (BuildUnit<Out> out1 : cyclicResults) { for (BuildUnit<Out> out2 : * cyclicResults) { if (out1 != out2) out1.requires(new * BuildRequirement<>(out2, out2.getGeneratedBy())); } } */ for (int i = 0; i < cyclicResults.size(); i++) { BuildUnit<Out> unit1 = cyclicResults.get(i); BuildUnit<Out> unit2 = cyclicResults.get((i + 1 == cyclicResults.size()) ? 0 : i); unit1.requires(new BuildRequirement<>(unit2, unit2.getGeneratedBy())); } return new HashSet<>(cyclicResults); } @SuppressWarnings("unchecked") @Override public String cycleDescription(BuildCycle cycle) { ArrayList<In> inputs = new ArrayList<>(cycle.getCycleComponents().size()); for (BuildRequest<?, ?, ?, ?> request : cycle.getCycleComponents()) { // Cast is safe, otherwise cycle handler rejected to compile the cycle inputs.addAll((ArrayList<In>) request.input); } return builderFactory.makeBuilder(inputs).description(); } }
package org.mskcc.cgds.test.servlet; import java.io.IOException; import java.io.File; import java.util.ArrayList; import java.util.HashSet; import junit.framework.TestCase; import org.mskcc.cgds.dao.DaoCancerStudy; import org.mskcc.cgds.dao.DaoCase; import org.mskcc.cgds.dao.DaoCaseList; import org.mskcc.cgds.dao.DaoException; import org.mskcc.cgds.dao.DaoGeneticProfile; import org.mskcc.cgds.dao.DaoUser; import org.mskcc.cgds.dao.DaoUserAccessRight; import org.mskcc.cgds.model.CancerStudy; import org.mskcc.cgds.model.CaseList; import org.mskcc.cgds.model.GeneticAlterationType; import org.mskcc.cgds.model.GeneticProfile; import org.mskcc.cgds.model.User; import org.mskcc.cgds.model.UserAccessRight; import org.mskcc.cgds.scripts.ImportTypesOfCancers; import org.mskcc.cgds.scripts.ResetDatabase; import org.mskcc.cgds.servlet.WebService; import org.mskcc.cgds.test.util.NullHttpServletRequest; import org.mskcc.cgds.util.AccessControl; import org.mskcc.cgds.util.internal.AccessControlImpl; import org.mskcc.cgds.util.ProgressMonitor; public class TestWebService extends TestCase { CancerStudy publicCancerStudy; CancerStudy privateCancerStudy1; CancerStudy privateCancerStudy2; User user1; User user2; String cleartextPwd; GeneticProfile privateGeneticProfile; GeneticProfile publicGeneticProfile; AccessControl accessControl = new AccessControlImpl(); public void testWebService() throws Exception { setUpDBMS(); WebService webService = new WebService(); // null request NullHttpServletRequest aNullHttpServletRequest = new NullHttpServletRequest(); NullHttpServletResponse aNullHttpServletResponse = new NullHttpServletResponse(); webService.processClient( aNullHttpServletRequest, aNullHttpServletResponse ); assertTrue( aNullHttpServletResponse.getOutput().contains("# CGDS Kernel: Data served up fresh at") ); checkRequest( mkStringArray( WebService.CMD, "getTypesOfCancer" ), mkStringArray( "type_of_cancer_id\tname", "LUAD\tLung adenocarcinoma" ) ); // bad command checkRequest( mkStringArray( WebService.CMD, "badCommand" ), "Error: 'badCommand' not a valid command." ); // public studies String[] publicStudies = mkStringArray( "cancer_study_id\tname\tdescription", studyLine( publicCancerStudy ) ); checkRequest( mkStringArray( WebService.CMD, "getCancerStudies" ), publicStudies ); checkRequest( mkStringArray( WebService.CMD, "getCancerStudies", WebService.EMAIL_ADDRESS, "no such email" ), publicStudies ); checkRequest( mkStringArray( WebService.CMD, "getCancerStudies", WebService.SECRET_KEY, "no such key" ), publicStudies ); // public and private studies String[] publicAndPrivateStudiesFor1 = mkStringArray( "cancer_study_id\tname\tdescription", studyLine( privateCancerStudy1 ), studyLine( publicCancerStudy ) ); checkRequest( mkStringArray( WebService.CMD, "getCancerStudies", WebService.EMAIL_ADDRESS, user1.getEmail(), WebService.SECRET_KEY, cleartextPwd ), publicAndPrivateStudiesFor1 ); // no cancer_study_id for "getGeneticProfiles" checkRequest( mkStringArray( WebService.CMD, "getGeneticProfiles" ), mkStringArray( "Error: " + "No cancer study (cancer_study_id), or genetic profile (genetic_profile_id) " + "or case list or (case_list) case set (case_set_id) provided by request. " + "Please reformulate request." ) ); checkRequest( mkStringArray( WebService.CMD, "getGeneticProfiles", WebService.CANCER_STUDY_ID, CancerStudy.NO_SUCH_STUDY +"" ), mkStringArray( "Error: " + "Problem when identifying a cancer study for the request." ) ); // getGeneticProfiles for public study String[] publicGenePro = mkStringArray( "genetic_profile_id\tgenetic_profile_name\tgenetic_profile_description\tcancer_study_id\tgenetic_alteration_type\tshow_profile_in_analysis_tab", "stableIdpublic\tprofileName\tprofileDescription\t3\tCOPY_NUMBER_ALTERATION\ttrue"); checkRequest( mkStringArray( WebService.CMD, "getGeneticProfiles", WebService.CANCER_STUDY_ID, publicCancerStudy.getCancerStudyIdentifier()), publicGenePro ); // with bad key checkRequest( mkStringArray( WebService.CMD, "getGeneticProfiles", WebService.SECRET_KEY, "not_good_key", WebService.CANCER_STUDY_ID, publicCancerStudy.getCancerStudyIdentifier()), publicGenePro ); // missing email address for private study String deniedError = "Error: User cannot access the cancer study called 'name'. Please provide credentials to access private data."; checkRequest( mkStringArray( WebService.CMD, "getGeneticProfiles", WebService.CANCER_STUDY_ID, "study1" ), mkStringArray( deniedError ) ); // denied for "getGeneticProfiles"; no key checkRequest( mkStringArray( WebService.CMD, "getGeneticProfiles", WebService.CANCER_STUDY_ID, "study1", WebService.EMAIL_ADDRESS, user1.getEmail() ), mkStringArray( deniedError ) ); // denied for "getGeneticProfiles"; bad key checkRequest( mkStringArray( WebService.CMD, "getGeneticProfiles", WebService.SECRET_KEY, "not_good_key", WebService.CANCER_STUDY_ID, "study1", WebService.EMAIL_ADDRESS, user1.getEmail() ), mkStringArray( deniedError ) ); // getGeneticProfiles works for private study String[] privateGenePro1 = mkStringArray( "genetic_profile_id\tgenetic_profile_name\tgenetic_profile_description\tcancer_study_id\tgenetic_alteration_type\tshow_profile_in_analysis_tab", "stableIdPrivate\tprofileName\tprofileDescription\t1\tCOPY_NUMBER_ALTERATION\ttrue"); checkRequest( mkStringArray( WebService.CMD, "getGeneticProfiles", WebService.SECRET_KEY, cleartextPwd, WebService.CANCER_STUDY_ID, "study1", WebService.EMAIL_ADDRESS, user1.getEmail() ), mkStringArray( privateGenePro1 ) ); } private void checkRequest( String[] requestFields, String... responseLines ) throws IOException{ checkRequest( false, requestFields, responseLines ); } /** * check a request * @param debug if true, print servlet's output * @param requestFields array embedded with name, value pairs for the httpRequest * @param responseLines array of expected responses * @throws IOException */ private void checkRequest( boolean debug, String[] requestFields, String... responseLines ) throws IOException{ WebService webService = new WebService(); NullHttpServletRequest aNullHttpServletRequest = new NullHttpServletRequest(); NullHttpServletResponse aNullHttpServletResponse = new NullHttpServletResponse(); for( int i=0; i<requestFields.length; i += 2 ){ aNullHttpServletRequest.setParameter( requestFields[i], requestFields[i+1] ); } webService.processClient( aNullHttpServletRequest, aNullHttpServletResponse ); assertTrue( aNullHttpServletResponse.getOutput().contains("# CGDS Kernel: Data served up fresh at") ); if( debug ){ System.out.println( "\nResponse says:\n" + aNullHttpServletResponse.getOutput() ); } String[] lines = aNullHttpServletResponse.getOutput().split("\n"); for( int i=0; i<responseLines.length; i++ ){ assertEquals( responseLines[i], lines[i+1]); } } private String[] mkStringArray( String... requestFields ){ return requestFields; } private String studyLine( CancerStudy cancerStudy ){ return cancerStudy.getCancerStudyIdentifier() + "\t" + cancerStudy.getName() + "\t" + cancerStudy.getDescription(); } public void testGetCancerStudyIDs() throws Exception { setUpDBMS(); HashSet<String> studies; NullHttpServletRequest aNullHttpServletRequest = new NullHttpServletRequest(); studies = WebService.getCancerStudyIDs(aNullHttpServletRequest); assertEquals( 0, studies.size() ); // example getGeneticProfiles request aNullHttpServletRequest.setParameter(WebService.CANCER_STUDY_ID, "HI"); studies = WebService.getCancerStudyIDs(aNullHttpServletRequest); assertEquals( null, studies ); aNullHttpServletRequest.setParameter(WebService.CANCER_STUDY_ID, "33"); studies = WebService.getCancerStudyIDs(aNullHttpServletRequest); assertEquals( null, studies ); aNullHttpServletRequest.setParameter(WebService.CANCER_STUDY_ID, "study1"); studies = WebService.getCancerStudyIDs(aNullHttpServletRequest); assertEquals( 1, studies.size() ); assertTrue( studies.contains("study1")); // example getProfileData, getMutationData, ... request with existing CASE_SET_ID aNullHttpServletRequest = new NullHttpServletRequest(); aNullHttpServletRequest.setParameter(WebService.CASE_SET_ID, "HI"); studies = WebService.getCancerStudyIDs(aNullHttpServletRequest); assertEquals( null, studies ); DaoCaseList aDaoCaseList = new DaoCaseList(); String exampleCaseSetId = "exampleID"; int thisIsNotACancerStudyId = 5; CaseList caseList = new CaseList( exampleCaseSetId, 0, thisIsNotACancerStudyId, "" ); ArrayList<String> t = new ArrayList<String>(); caseList.setCaseList( t ); aDaoCaseList.addCaseList(caseList); aNullHttpServletRequest.setParameter(WebService.CASE_SET_ID, exampleCaseSetId ); studies = WebService.getCancerStudyIDs(aNullHttpServletRequest); assertEquals( null, studies ); aDaoCaseList.deleteAllRecords(); caseList.setCancerStudyId( 1 ); // CancerStudyId inserted by setUpDBMS() aDaoCaseList.addCaseList(caseList); studies = WebService.getCancerStudyIDs(aNullHttpServletRequest); assertEquals( 1, studies.size() ); assertTrue( studies.contains("study1")); // test situations when case_set_id not provided, but profile_id is, as by getProfileData aNullHttpServletRequest = new NullHttpServletRequest(); aNullHttpServletRequest.setParameter(WebService.GENETIC_PROFILE_ID, privateGeneticProfile.getStableId() ); studies = WebService.getCancerStudyIDs(aNullHttpServletRequest); assertEquals( 1, studies.size() ); assertTrue( studies.contains (DaoCancerStudy.getCancerStudyByInternalId(privateGeneticProfile.getCancerStudyId()).getCancerStudyIdentifier())); // test situation when multiple profile_ids provided, as by getProfileData aNullHttpServletRequest = new NullHttpServletRequest(); aNullHttpServletRequest.setParameter( WebService.GENETIC_PROFILE_ID, privateGeneticProfile.getStableId() + "," + publicGeneticProfile.getStableId() ); studies = WebService.getCancerStudyIDs(aNullHttpServletRequest); assertTrue( studies.contains(DaoCancerStudy.getCancerStudyByInternalId (privateGeneticProfile.getCancerStudyId()).getCancerStudyIdentifier())); assertTrue( studies.contains(DaoCancerStudy.getCancerStudyByInternalId (privateGeneticProfile.getCancerStudyId()).getCancerStudyIdentifier())); // test situation when a case_list is explicitly provided, as in getClinicalData, etc. DaoCase daoCase = new DaoCase(); String c1 = "TCGA-12345"; daoCase.addCase( c1, publicGeneticProfile.getGeneticProfileId()); aNullHttpServletRequest = new NullHttpServletRequest(); aNullHttpServletRequest.setParameter( WebService.CASE_LIST, c1 ); studies = WebService.getCancerStudyIDs(aNullHttpServletRequest); assertTrue( studies.contains(DaoCancerStudy.getCancerStudyByInternalId (publicGeneticProfile.getCancerStudyId()).getCancerStudyIdentifier())); String c2 = "TCGA-54321"; daoCase.addCase( c2, privateGeneticProfile.getGeneticProfileId() ); aNullHttpServletRequest = new NullHttpServletRequest(); aNullHttpServletRequest.setParameter( WebService.CASE_LIST, c1 + "," + c2 ); studies = WebService.getCancerStudyIDs(aNullHttpServletRequest); assertTrue( studies.contains(DaoCancerStudy.getCancerStudyByInternalId (privateGeneticProfile.getCancerStudyId()).getCancerStudyIdentifier())); assertTrue( studies.contains(DaoCancerStudy.getCancerStudyByInternalId (publicGeneticProfile.getCancerStudyId()).getCancerStudyIdentifier())); } private void setUpDBMS() throws DaoException, IOException{ ResetDatabase.resetDatabase(); user1 = new User("artg@gmail.com", "Arthur", true); DaoUser.addUser(user1); user2 = new User("joe@gmail.com", "J", true); DaoUser.addUser(user2); // load cancers ImportTypesOfCancers.load(new ProgressMonitor(), new File("test_data/cancers.txt")); // make a couple of private studies (1 and 2) privateCancerStudy1 = new CancerStudy( "name", "description", "study1", "brca", false ); DaoCancerStudy.addCancerStudy(privateCancerStudy1); privateCancerStudy2 = new CancerStudy( "other name", "other description", "study2", "brca", false ); DaoCancerStudy.addCancerStudy(privateCancerStudy2); publicCancerStudy = new CancerStudy( "public name", "description", "study3", "brca", true ); DaoCancerStudy.addCancerStudy(publicCancerStudy); UserAccessRight userAccessRight = new UserAccessRight( user1.getEmail(), privateCancerStudy1.getStudyId() ); DaoUserAccessRight.addUserAccessRight(userAccessRight); DaoGeneticProfile aDaoGeneticProfile = new DaoGeneticProfile(); String publicSid = "stableIdpublic"; publicGeneticProfile = new GeneticProfile( publicSid, publicCancerStudy.getStudyId(), GeneticAlterationType.COPY_NUMBER_ALTERATION, "profileName", "profileDescription", true); aDaoGeneticProfile.addGeneticProfile( publicGeneticProfile ); // have to refetch from the dbms to get the profile_id; sigh! publicGeneticProfile = aDaoGeneticProfile.getGeneticProfileByStableId( publicSid ); String privateSid = "stableIdPrivate"; privateGeneticProfile = new GeneticProfile( privateSid, privateCancerStudy1.getStudyId(), GeneticAlterationType.COPY_NUMBER_ALTERATION, "profileName", "profileDescription", true); aDaoGeneticProfile.addGeneticProfile( privateGeneticProfile ); privateGeneticProfile = aDaoGeneticProfile.getGeneticProfileByStableId(privateSid); cleartextPwd = "SillyKey"; accessControl.createSecretKey(cleartextPwd); } }
package org.batfish.client; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.output.WriterOutputStream; import org.batfish.common.BfConsts; import org.batfish.common.BatfishLogger; import org.batfish.common.Util; import org.batfish.common.WorkItem; import org.batfish.common.CoordConsts.WorkStatusCode; import org.batfish.common.ZipUtility; import jline.console.ConsoleReader; import jline.console.completer.Completer; import jline.console.completer.StringsCompleter; public class Client { private static final String COMMAND_ANSWER = "answer"; private static final String COMMAND_ANSWER_BYTYPE = "answer-bytype"; private static final String COMMAND_ANSWER_DIFF = "answer-diff"; private static final String COMMAND_ANSWER_DIFF_BYTYPE = "answer-diff-bytype"; private static final String COMMAND_CAT = "cat"; private static final String COMMAND_CLEAR_SCREEN = "cls"; private static final String COMMAND_DEL_CONTAINER = "del-container"; private static final String COMMAND_DEL_ENVIRONMENT = "del-environment"; private static final String COMMAND_DEL_QUESTION = "del-question"; private static final String COMMAND_DEL_TESTRIG = "del-testrig"; private static final String COMMAND_DIR = "dir"; private static final String COMMAND_ECHO = "echo"; private static final String COMMAND_EXIT = "exit"; private static final String COMMAND_GEN_DIFF_DP = "generate-diff-dataplane"; private static final String COMMAND_GEN_DP = "generate-dataplane"; private static final String COMMAND_HELP = "help"; private static final String COMMAND_CHECK_API_KEY = "checkapikey"; private static final String COMMAND_INIT_CONTAINER = "init-container"; private static final String COMMAND_INIT_DIFF_ENV = "init-diff-environment"; private static final String COMMAND_INIT_TESTRIG = "init-testrig"; private static final String COMMAND_LIST_CONTAINERS = "list-containers"; private static final String COMMAND_LIST_ENVIRONMENTS = "list-environments"; private static final String COMMAND_LIST_QUESTIONS = "list-questions"; private static final String COMMAND_LIST_TESTRIGS = "list-testrigs"; private static final String COMMAND_PROMPT = "prompt"; private static final String COMMAND_PWD = "pwd"; private static final String COMMAND_QUIT = "quit"; private static final String COMMAND_SET_CONTAINER = "set-container"; private static final String COMMAND_SET_DIFF_ENV = "set-diff-environment"; private static final String COMMAND_SET_LOGLEVEL = "set-loglevel"; private static final String COMMAND_SET_TESTRIG = "set-testrig"; private static final String COMMAND_SHOW_API_KEY = "show-api-key"; private static final String COMMAND_SHOW_CONTAINER = "show-container"; private static final String COMMAND_SHOW_COORDINATOR_HOST = "show-coordinator-host"; private static final String COMMAND_SHOW_TESTRIG = "show-testrig"; private static final String COMMAND_UPLOAD_CUSTOM_OBJECT = "upload-custom"; private static final String DEFAULT_CONTAINER_PREFIX = "cp"; private static final String DEFAULT_DIFF_ENV_PREFIX = "delta"; private static final String DEFAULT_ENV_NAME = "default"; private static final String DEFAULT_QUESTION_PREFIX = "q"; private static final String DEFAULT_TESTRIG_PREFIX = "tr"; private static final Map<String, String> MAP_COMMANDS = initCommands(); private static Map<String, String> initCommands() { Map<String, String> descs = new TreeMap<String, String>(); descs.put(COMMAND_ANSWER, COMMAND_ANSWER + " <question-file> [param1=value1 [param2=value2] ...]\n" + "\t Answer the question in the file for the default environment"); descs.put(COMMAND_ANSWER_BYTYPE, COMMAND_ANSWER_BYTYPE + " <question-type> [param1=value1 [param2=value2] ...]\n" + "\t Answer the question by type for the differential environment"); descs.put(COMMAND_ANSWER_DIFF, COMMAND_ANSWER_DIFF + " <question-file> [param1=value1 [param2=value2] ...]\n" + "\t Answer the question in the file for the differential environment"); descs.put(COMMAND_ANSWER_DIFF_BYTYPE, COMMAND_ANSWER_DIFF_BYTYPE + " <question-file> [param1=value1 [param2=value2] ...]\n" + "\t Answer the question by type for the differential environment"); descs.put(COMMAND_CAT, COMMAND_CAT + " <filename>\n" + "\t Print the contents of the file"); // descs.put(COMMAND_CHANGE_DIR, COMMAND_CHANGE_DIR // + " <dirname>\n" // + "\t Change the working directory"); descs.put(COMMAND_CLEAR_SCREEN, COMMAND_CLEAR_SCREEN + "\n" + "\t Clear screen"); descs.put(COMMAND_DEL_CONTAINER, COMMAND_DEL_CONTAINER + "<container-name>" + "\t Delete the specified container"); descs.put(COMMAND_DEL_ENVIRONMENT, COMMAND_DEL_ENVIRONMENT + "<environment-name>" + "\t Delete the specified environment"); descs.put(COMMAND_DEL_QUESTION, COMMAND_DEL_QUESTION + "<question-name>" + "\t Delete the specified question"); descs.put(COMMAND_DEL_TESTRIG, COMMAND_DEL_TESTRIG + "<testrig-name>" + "\t Delete the specified testrig"); descs.put(COMMAND_DIR, COMMAND_DIR + "<dir>" + "\t List directory contents"); descs.put(COMMAND_ECHO, COMMAND_ECHO + "<message>" + "\t Echo the message"); descs.put(COMMAND_EXIT, COMMAND_EXIT + "\n" + "\t Terminate interactive client session"); descs.put(COMMAND_GEN_DIFF_DP, COMMAND_GEN_DIFF_DP + "\n" + "\t Generate dataplane for the differential environment"); descs.put(COMMAND_GEN_DP, COMMAND_GEN_DP + "\n" + "\t Generate dataplane for the default environment"); descs.put(COMMAND_HELP, COMMAND_HELP + "\n" + "\t Print the list of supported commands"); descs.put(COMMAND_CHECK_API_KEY, COMMAND_CHECK_API_KEY + "\t Check if API Key is valid"); descs.put(COMMAND_INIT_CONTAINER, COMMAND_INIT_CONTAINER + " [<container-name-prefix>]\n" + "\t Initialize a new container"); descs.put(COMMAND_INIT_DIFF_ENV, COMMAND_INIT_DIFF_ENV + " [-nodataplane] <environment zipfile or directory> [<environment-name>]\n" + "\t Initialize the differential environment"); descs.put(COMMAND_INIT_TESTRIG, COMMAND_INIT_TESTRIG + " [-nodataplane] <testrig zipfile or directory> [<environment name>]\n" + "\t Initialize the testrig with default environment"); descs.put(COMMAND_LIST_CONTAINERS, COMMAND_LIST_CONTAINERS + "\n" + "\t List the containers to which you have access"); descs.put(COMMAND_LIST_ENVIRONMENTS, COMMAND_LIST_ENVIRONMENTS + "\n" + "\t List the environments under current container and testrig"); descs.put(COMMAND_LIST_QUESTIONS, COMMAND_LIST_QUESTIONS + "\n" + "\t List the questions under current container and testrig"); descs.put(COMMAND_LIST_TESTRIGS, COMMAND_LIST_TESTRIGS + "\n" + "\t List the testrigs within the current container"); descs.put(COMMAND_PROMPT, COMMAND_PROMPT + "\n" + "\t Prompts for user to press enter"); descs.put(COMMAND_PWD, COMMAND_PWD + "\n" + "\t Prints the working directory"); descs.put(COMMAND_QUIT, COMMAND_QUIT + "\n" + "\t Terminate interactive client session"); descs.put(COMMAND_SET_CONTAINER, COMMAND_SET_CONTAINER + " <container-name>\n" + "\t Set the current container"); descs.put(COMMAND_SET_DIFF_ENV, COMMAND_SET_DIFF_ENV + " <environment-name>\n" + "\t Set the current differential environment"); descs.put(COMMAND_SET_LOGLEVEL, COMMAND_SET_LOGLEVEL + " <debug|info|output|warn|error>\n" + "\t Set the loglevel. Default is output"); descs.put(COMMAND_SET_TESTRIG, COMMAND_SET_TESTRIG + " <testrig-name>\n" + "\t Set the current testrig"); descs.put(COMMAND_SHOW_API_KEY, COMMAND_SHOW_API_KEY + "\n" + "\t Show API Key"); descs.put(COMMAND_SHOW_CONTAINER, COMMAND_SHOW_CONTAINER + "\n" + "\t Show active container"); descs.put(COMMAND_SHOW_COORDINATOR_HOST, COMMAND_SHOW_COORDINATOR_HOST + "\n" + "\t Show coordinator host"); descs.put(COMMAND_SHOW_TESTRIG, COMMAND_SHOW_TESTRIG + "\n" + "\t Show active testrig"); descs.put(COMMAND_UPLOAD_CUSTOM_OBJECT, COMMAND_UPLOAD_CUSTOM_OBJECT + " <object-name> <object-file>\n" + "\t Uploads a custom object"); return descs; } private String _currContainerName = null; private String _currDiffEnv = null; private String _currEnv = null; private String _currTestrigName = null; private BatfishLogger _logger; private BfCoordPoolHelper _poolHelper; private ConsoleReader _reader; private Settings _settings; private BfCoordWorkHelper _workHelper; public Client(String[] args) throws Exception { this(new Settings(args)); } public Client(Settings settings) { _settings = settings; switch (_settings.getRunMode()) { case "batch": _logger = new BatfishLogger(_settings.getLogLevel(), false, _settings.getLogFile(), false, false); break; case "interactive": try { _reader = new ConsoleReader(); _reader.setPrompt("batfish> "); List<Completer> completors = new LinkedList<Completer>(); completors.add(new StringsCompleter(MAP_COMMANDS.keySet())); for (Completer c : completors) { _reader.addCompleter(c); } PrintWriter pWriter = new PrintWriter(_reader.getOutput(), true); OutputStream os = new WriterOutputStream(pWriter); PrintStream ps = new PrintStream(os, true); _logger = new BatfishLogger(_settings.getLogLevel(), false, ps); } catch (Exception e) { System.err.printf("Could not initialize client: %s\n", e.getMessage()); System.exit(1); } break; default: System.err.println("org.batfish.client: Unknown run mode. Expect {batch, interactive}"); System.exit(1); } } private boolean answerType(String questionType, String paramsLine, boolean isDiff) throws Exception { Map<String, String> parameters = parseParams(paramsLine); String questionString = QuestionHelper.getQuestionString(questionType); _logger.debugf("Question Json:\n%s\n", questionString); String parametersString = QuestionHelper.getParametersString(parameters); _logger.debugf("Parameters Json:\n%s\n", parametersString); File questionFile = createTempFile("question", questionString); boolean result = answerFile(questionFile.getAbsolutePath(), parametersString, isDiff); if (questionFile != null) { questionFile.delete(); } return result; } private Map<String, String> parseParams(String paramsLine) { Map<String,String> parameters = new HashMap<String, String>(); Pattern pattern = Pattern.compile("([\\w_]+)\\s*=\\s*(.+)"); String[] params = paramsLine.split("\\|"); _logger.debugf("Found %d parameters\n", params.length); for (String param : params) { Matcher matcher = pattern.matcher(param); while (matcher.find()) { String key = matcher.group(1).trim(); String value = matcher.group(2).trim(); _logger.debugf("key=%s value=%s\n", key, value); parameters.put(key, value); } } return parameters; } private boolean answerFile(String questionFile, String paramsLine, boolean isDiff) throws Exception { if (! new File(questionFile).exists()) throw new FileNotFoundException("Question file not found: " + questionFile); String questionName = DEFAULT_QUESTION_PREFIX + "_" + UUID.randomUUID().toString(); File paramsFile = createTempFile("parameters", paramsLine); // upload the question boolean resultUpload = _workHelper.uploadQuestion( _currContainerName, _currTestrigName, questionName, questionFile, paramsFile.getAbsolutePath()); if (!resultUpload) return false; _logger.debug("Uploaded question. Answering now.\n"); // delete the temporary params file if (paramsFile != null) { paramsFile.delete(); } // answer the question WorkItem wItemAs = (isDiff) ? _workHelper.getWorkItemAnswerDiffQuestion( questionName, _currContainerName, _currTestrigName, _currEnv, _currDiffEnv) : _workHelper.getWorkItemAnswerQuestion( questionName, _currContainerName, _currTestrigName, _currEnv, _currDiffEnv); return execute(wItemAs); } private File createTempFile(String filePrefix, String content) throws IOException { File tempFile = Files.createTempFile(filePrefix, null).toFile(); _logger.debugf("Creating temporary %s file: %s\n", filePrefix, tempFile.getAbsolutePath()); BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile)); writer.write(content + "\n"); writer.close(); return tempFile; } private boolean execute(WorkItem wItem) throws Exception { wItem.addRequestParam(BfConsts.ARG_LOG_LEVEL, _logger.getLogLevelStr()); _logger.info("work-id is " + wItem.getId() + "\n"); boolean queueWorkResult = _workHelper.queueWork(wItem); _logger.info("Queuing result: " + queueWorkResult + "\n"); if (!queueWorkResult) { return queueWorkResult; } WorkStatusCode status = _workHelper.getWorkStatus(wItem.getId()); while (status != WorkStatusCode.TERMINATEDABNORMALLY && status != WorkStatusCode.TERMINATEDNORMALLY && status != WorkStatusCode.ASSIGNMENTERROR) { _logger.output(". "); _logger.infof("status: %s\n", status); Thread.sleep(1 * 1000); status = _workHelper.getWorkStatus(wItem.getId()); } _logger.output("\n"); _logger.infof("final status: %s\n", status); // get the results String logFileName = wItem.getId() + ".log"; String downloadedFile = _workHelper.getObject(wItem.getContainerName(), wItem.getTestrigName(), logFileName); if (downloadedFile == null) { _logger.errorf("Failed to get output file %s\n", logFileName); return false; } else { try (BufferedReader br = new BufferedReader(new FileReader( downloadedFile))) { String line = null; while ((line = br.readLine()) != null) { _logger.output(line + "\n"); } } } // TODO: remove the log file? if (status == WorkStatusCode.TERMINATEDNORMALLY) { return true; } else { // _logger.errorf("WorkItem failed: %s", wItem); return false; } } private boolean generateDataplane() throws Exception { if (!isSetTestrig() || !isSetContainer(true)) return false; // generate the data plane WorkItem wItemGenDp = _workHelper.getWorkItemGenerateDataPlane( _currContainerName, _currTestrigName, _currEnv); return execute(wItemGenDp); } private boolean generateDiffDataplane() throws Exception { if (!isSetDiffEnvironment() || !isSetTestrig() || !isSetContainer(true)) return false; WorkItem wItemGenDdp = _workHelper .getWorkItemGenerateDiffDataPlane(_currContainerName, _currTestrigName, _currEnv, _currDiffEnv); return execute(wItemGenDdp); } private List<String> getCommandParameters(String[] words, int numOptions) { List<String> parameters = new LinkedList<String>(); for (int index=numOptions+1; index < words.length; index++) parameters.add(words[index]); return parameters; } private List<String> getCommandOptions(String[] words) { List<String> options = new LinkedList<String>(); int currIndex = 1; while (currIndex < words.length && words[currIndex].startsWith("-")) { options.add(words[currIndex]); currIndex++; } return options; } public BatfishLogger getLogger() { return _logger; } private void initHelpers() { String workMgr = _settings.getCoordinatorHost() + ":" + _settings.getCoordinatorWorkPort(); String poolMgr = _settings.getCoordinatorHost() + ":" + _settings.getCoordinatorPoolPort(); _workHelper = new BfCoordWorkHelper(workMgr, _logger, _settings); _poolHelper = new BfCoordPoolHelper(poolMgr); int numTries = 0; while (true) { try { numTries++; if (_workHelper.isReachable()) { //print this message only we might have printed unable to connect message earlier if (numTries > 1) _logger.outputf("Connected to coordinator after %d tries\n", numTries); break; } Thread.sleep(1 * 1000); // 1 second } catch (Exception e) { _logger.errorf("Exeption while checking reachability to coordinator: ", e.getMessage()); System.exit(1); } } } private boolean isSetContainer(boolean printError) { if (!_settings.getSanityCheck()) return true; if (_currContainerName == null) { if (printError) _logger.errorf("Active container is not set\n"); return false; } return true; } private boolean isSetDiffEnvironment() { if (!_settings.getSanityCheck()) return true; if (_currDiffEnv == null) { _logger.errorf("Active diff environment is not set\n"); return false; } return true; } private boolean isSetTestrig() { if (!_settings.getSanityCheck()) return true; if (_currTestrigName == null) { _logger.errorf("Active testrig is not set\n"); return false; } return true; } private void printUsage() { for (Map.Entry<String, String> entry : MAP_COMMANDS.entrySet()) { _logger.output(entry.getValue() + "\n\n"); } } private boolean processCommand(String[] words) { try { List<String> options = getCommandOptions(words); List<String> parameters = getCommandParameters(words, options.size()); switch (words[0]) { // this is a hidden command for testing case "add-worker": { boolean result = _poolHelper.addBatfishWorker(words[1]); _logger.output("Result: " + result + "\n"); return true; } case COMMAND_ANSWER: { if (!isSetTestrig() || !isSetContainer(true)) { return false; } String questionFile = parameters.get(0); String paramsLine = Util.joinStrings(" ", Arrays.copyOfRange(words, 2 + options.size(), words.length)); return answerFile(questionFile, paramsLine, false); } case COMMAND_ANSWER_BYTYPE: { if (!isSetTestrig() || !isSetContainer(true)) { return false; } String questionType = parameters.get(0); String paramsLine = Util.joinStrings(" ", Arrays.copyOfRange(words, 2 + options.size(), words.length)); return answerType(questionType, paramsLine, false); } case COMMAND_ANSWER_DIFF: { if (!isSetDiffEnvironment() || !isSetTestrig() || !isSetContainer(true)) { return false; } String questionFile = parameters.get(0); String paramsLine = Util.joinStrings(" ", Arrays.copyOfRange(words, 2 + options.size(), words.length)); return answerFile(questionFile, paramsLine, true); } case COMMAND_ANSWER_DIFF_BYTYPE: { if (!isSetDiffEnvironment() || !isSetTestrig() || !isSetContainer(true)) { return false; } String questionType = parameters.get(0); String paramsLine = Util.joinStrings(" ", Arrays.copyOfRange(words, 2 + options.size(), words.length)); return answerType(questionType, paramsLine, true); } case COMMAND_CAT: { String filename = words[1]; try (BufferedReader br = new BufferedReader( new FileReader(filename))) { String line = null; while ((line = br.readLine()) != null) { _logger.output(line + "\n"); } } return true; } case COMMAND_DEL_CONTAINER: { String containerName = parameters.get(0); boolean result = _workHelper.delContainer(containerName); _logger.outputf("Result of deleting container: %s\n", result); return true; } case COMMAND_DEL_ENVIRONMENT: { if (!isSetTestrig() || !isSetContainer(true)) { return false; } String envName = parameters.get(0); boolean result = _workHelper.delEnvironment(_currContainerName, _currTestrigName, envName); _logger.outputf("Result of deleting environment: %s\n", result); return true; } case COMMAND_DEL_QUESTION: { if (!isSetTestrig() || !isSetContainer(true)) { return false; } String qName = parameters.get(0); boolean result = _workHelper.delQuestion(_currContainerName, _currTestrigName, qName); _logger.outputf("Result of deleting question: %s\n", result); return true; } case COMMAND_DEL_TESTRIG: { if (!isSetContainer(true)) { return false; } String testrigName = parameters.get(0); boolean result = _workHelper.delTestrig(_currContainerName, testrigName); _logger.outputf("Result of deleting testrig: %s\n", result); return true; } case COMMAND_DIR: { String dirname = (parameters.size() == 1) ? parameters.get(0) : "."; File currDirectory = new File(dirname); for (File file : currDirectory.listFiles()) { _logger.output(file.getName() + "\n"); } return true; } case COMMAND_ECHO: { _logger.outputf("%s\n", Util.joinStrings(" ", Arrays.copyOfRange(words, 1, words.length))); return true; } case COMMAND_EXIT: case COMMAND_QUIT: { System.exit(0); return true; } case COMMAND_GEN_DP: { return generateDataplane(); } case COMMAND_GEN_DIFF_DP: { return generateDiffDataplane(); } case COMMAND_HELP: { printUsage(); return true; } case COMMAND_CHECK_API_KEY: { String isValid = _workHelper.checkApiKey(); _logger.outputf("Api key validitiy: %s\n", isValid); return true; } case COMMAND_INIT_CONTAINER: { String containerPrefix = (words.length > 1) ? words[1] : DEFAULT_CONTAINER_PREFIX; _currContainerName = _workHelper.initContainer(containerPrefix); _logger.outputf("Active container set to %s\n", _currContainerName); return true; } case COMMAND_INIT_DIFF_ENV: { if (!isSetTestrig() || !isSetContainer(true)) { return false; } //check if we are being asked to not generate the dataplane boolean generateDiffDataplane = true; if (options.size() == 1) { if (options.get(0).equals("-nodataplane")) generateDiffDataplane = false; else { _logger.outputf("Unknown option %s\n", options.get(0)); return false; } } String diffEnvLocation = parameters.get(0); String diffEnvName = (parameters.size() > 1) ? parameters.get(1) : DEFAULT_DIFF_ENV_PREFIX + UUID.randomUUID().toString(); if (!uploadTestrigOrEnv(diffEnvLocation, diffEnvName, false)) return false; _currDiffEnv = diffEnvName; _logger.outputf( "Active delta environment is now %s\n", _currDiffEnv); if (generateDiffDataplane) { _logger.output("Generating delta dataplane\n"); if (!generateDiffDataplane()) return false; _logger.output("Generated delta dataplane\n"); } return true; } case COMMAND_INIT_TESTRIG: { boolean generateDataplane = true; if (options.size() == 1) { if (options.get(0).equals("-nodataplane")) generateDataplane = false; else { _logger.outputf("Unknown option %s\n", options.get(0)); return false; } } String testrigLocation = parameters.get(0); String testrigName = (parameters.size() > 1) ? parameters.get(1) : DEFAULT_TESTRIG_PREFIX + "_" + UUID.randomUUID().toString(); //initialize the container if it hasn't been init'd before if (!isSetContainer(false)) { _currContainerName = _workHelper.initContainer(DEFAULT_CONTAINER_PREFIX); _logger.outputf("Init'ed and set active container to %s\n", _currContainerName); } if (!uploadTestrigOrEnv(testrigLocation, testrigName, true)) return false; _logger.output("Uploaded testrig. Parsing now.\n"); WorkItem wItemParse = _workHelper.getWorkItemParse( _currContainerName, testrigName); if (!execute(wItemParse)) return false; // set the name of the current testrig _currTestrigName = testrigName; _currEnv = DEFAULT_ENV_NAME; _logger.outputf( "Active testrig is now %s\n", _currTestrigName); if (generateDataplane) { _logger.output("Generating dataplane now\n"); if (!generateDataplane()) return false; _logger.output("Generated dataplane\n"); } return true; } case COMMAND_LIST_CONTAINERS: { String[] containerList = _workHelper.listContainers(); _logger.outputf("Containers: %s\n", Arrays.toString(containerList)); return true; } case COMMAND_LIST_ENVIRONMENTS: { if (!isSetTestrig() || !isSetContainer(true)) { return false; } String[] environmentList = _workHelper.listEnvironments( _currContainerName, _currTestrigName); _logger.outputf("Environments: %s\n", Arrays.toString(environmentList)); return true; } case COMMAND_LIST_QUESTIONS: { if (!isSetTestrig() || !isSetContainer(true)) { return false; } String[] questionList = _workHelper.listQuestions( _currContainerName, _currTestrigName); _logger.outputf("Questions: %s\n", Arrays.toString(questionList)); return true; } case COMMAND_LIST_TESTRIGS: { Map<String,String> testrigs = _workHelper.listTestrigs(_currContainerName); if (testrigs != null) for (String testrigName : testrigs.keySet()) _logger.outputf("Testrig: %s\n%s\n", testrigName, testrigs.get(testrigName)); return true; } case COMMAND_PROMPT: { if (_settings.getRunMode() == "interactive") { _logger.output("\n\n[Press enter to proceed]\n\n"); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); in.readLine(); } return true; } case COMMAND_PWD: { final String dir = System.getProperty("user.dir"); _logger.output("working directory = " + dir + "\n"); return true; } case COMMAND_SET_CONTAINER: { _currContainerName = parameters.get(0); _logger.outputf("Active container is now set to %s\n", _currContainerName); return true; } case COMMAND_SET_TESTRIG: { _currTestrigName = parameters.get(0); _currEnv = DEFAULT_ENV_NAME; _logger.outputf( "Active testrig is now %s\n", _currTestrigName); return true; } case COMMAND_SET_DIFF_ENV: { _currDiffEnv = parameters.get(0); _logger.outputf( "Active differential environment is now set to %s\n", _currDiffEnv); return true; } case COMMAND_SET_LOGLEVEL: { String logLevelStr = parameters.get(0); try { _logger.setLogLevel(logLevelStr); _logger.output("Changed loglevel to " + logLevelStr + "\n"); } catch (Exception e) { _logger.errorf("Undefined loglevel value: %s\n", logLevelStr); return false; } return true; } case COMMAND_SHOW_API_KEY: { _logger.outputf("Current API Key is %s\n", _settings.getApiKey()); return true; } case COMMAND_SHOW_CONTAINER: { _logger.outputf("Current container is %s\n", _currContainerName); return true; } case COMMAND_SHOW_COORDINATOR_HOST: { _logger.outputf("Current coordinator host is %s\n", _settings.getCoordinatorHost()); return true; } case COMMAND_SHOW_TESTRIG: { _logger.outputf("Current testrig is %s\n", _currTestrigName); return true; } case COMMAND_UPLOAD_CUSTOM_OBJECT: { if (!isSetTestrig() || !isSetContainer(true)) { return false; } String objectName = parameters.get(0); String objectFile = parameters.get(1); // upload the object return _workHelper.uploadCustomObject( _currContainerName, _currTestrigName, objectName, objectFile); } default: _logger.error("Unsupported command " + words[0] + "\n"); _logger.error("Type 'help' to see the list of valid commands\n"); return false; } } catch (Exception e) { e.printStackTrace(); return false; } } private boolean processCommands(List<String> commands) { for (String rawLine : commands) { String line = rawLine.trim(); if (line.length() == 0 || line.startsWith(" continue; } _logger.debug("Doing command: " + line + "\n"); String[] words = line.split("\\s+"); if (words.length > 0) { if (validCommandUsage(words)) { if (!processCommand(words)) return false; } } } return true; } public void run(List<String> initialCommands) { initHelpers(); _logger.debugf("Will use coordinator at %s: (_settings.getUseSsl())? "https" : "http", _settings.getCoordinatorHost()); if (!processCommands(initialCommands)) return; switch (_settings.getRunMode()) { case "batch": if (_settings.getBatchCommandFile() == null) { System.err.println("org.batfish.client: Command file not specified while running in batch mode. Did you mean to run in interactive mode (-runmode interactive)?"); System.exit(1); } List<String> commands = null; try { commands = Files.readAllLines( Paths.get(_settings.getBatchCommandFile()), StandardCharsets.US_ASCII); } catch (Exception e) { System.err.printf("Exception in reading command file %s: %s", _settings.getBatchCommandFile(), e.getMessage()); System.exit(1); } processCommands(commands); break; case "interactive": runInteractive(); break; default: System.err.println("org.batfish.client: Unknown run mode. Expect {batch, interactive}"); System.exit(1); } } private void runInteractive() { try { String rawLine; while ((rawLine = _reader.readLine()) != null) { String line = rawLine.trim(); if (line.length() == 0) continue; if (line.equals(COMMAND_CLEAR_SCREEN)) { _reader.clearScreen(); continue; } String[] words = line.split("\\s+"); if (words.length > 0) { if (validCommandUsage(words)) { processCommand(words); } } } } catch (Throwable t) { t.printStackTrace(); } } private boolean uploadTestrigOrEnv(String fileOrDir, String testrigOrEnvName, boolean isTestrig) throws Exception { File filePointer = new File(fileOrDir); String uploadFilename = fileOrDir; if (filePointer.isDirectory()) { uploadFilename = File.createTempFile("testrigOrEnv", "zip") .getAbsolutePath(); ZipUtility.zipFiles(filePointer.getAbsolutePath(), uploadFilename); } boolean result = (isTestrig)? _workHelper.uploadTestrig( _currContainerName, testrigOrEnvName, uploadFilename): _workHelper.uploadEnvironment( _currContainerName, _currTestrigName, testrigOrEnvName, uploadFilename); // unequal means we must have created a temporary file if (uploadFilename != fileOrDir) new File(uploadFilename).delete(); return result; } private boolean validCommandUsage(String[] words) { return true; } }
package frs.amantonrun; import android.content.pm.ActivityInfo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.DisplayMetrics; import android.util.Log; import android.view.MotionEvent; import android.widget.ImageView; public class GamePlayActivity extends AppCompatActivity { public static ImageView i; private float x; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); setContentView(R.layout.activity_game); i = (ImageView) findViewById(R.id.imageView); DisplayMetrics ecran = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(ecran); int largeur = ecran.widthPixels; Log.i("TAG",largeur+""); this.x = largeur/2; } public boolean onTouchEvent(MotionEvent event) { Log.i("TAG",this.x+" "+event.getX()+" "+Math.abs(this.x-event.getX())); if(Math.abs(this.x-event.getX()) < 50) { i.setX(event.getX()); this.x= event.getX(); Log.i("TAG","OK"); } else { Log.i("TAG","!OK"); } return true; } }
package frs.amantonrun; import android.content.pm.ActivityInfo; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.DisplayMetrics; import android.util.Log; import android.view.animation.Animation; import android.widget.ImageView; public class GamePlayActivity extends AppCompatActivity implements SensorEventListener { private ImageView i; Animation anim; private int largeur; private SensorManager sensorManager; private Sensor accelerometer; private int move; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); setContentView(R.layout.activity_game); i = (ImageView) findViewById(R.id.imageView); DisplayMetrics ecran = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(ecran); largeur = ecran.widthPixels; sensorManager= (SensorManager) getSystemService(SENSOR_SERVICE); accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_UI); move=0; } @Override protected void onPause() { sensorManager.unregisterListener(this, accelerometer); super.onPause(); } @Override protected void onResume() { sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_UI); super.onResume(); } public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) if(Math.abs(event.values[0]) > 1 && i.getX() - (event.values[0]*5)>0 && i.getX() - (event.values[0]*5)+(i.getWidth())<largeur) { if(event.values[0]<0) if(move<4) { i.setImageResource(R.mipmap.right); i.invalidate(); } else { i.setImageResource(R.mipmap.right2); i.invalidate(); } else if(move<=4) { i.setImageResource(R.mipmap.left); i.invalidate(); } else { i.setImageResource(R.mipmap.left2); i.invalidate(); } Log.i("PERSO",move+""); move = (move+1)%8;//0 1 2 3 i.setX(i.getX() - event.values[0]*5); } else { i.setImageResource(R.mipmap.center); i.invalidate(); } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }
// $Id: PlaylistPanel.java,v 1.4 2001/07/26 01:18:49 mdb Exp $ package robodj.chooser; import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.SQLException; import java.util.ArrayList; import javax.swing.*; import com.samskivert.swing.*; import com.samskivert.swing.util.*; import com.samskivert.util.StringUtil; import robodj.Log; import robodj.repository.*; public class PlaylistPanel extends JPanel implements TaskObserver, ActionListener { public PlaylistPanel () { GroupLayout gl = new VGroupLayout(GroupLayout.STRETCH); gl.setOffAxisPolicy(GroupLayout.STRETCH); setLayout(gl); // create the pane that will hold the buttons gl = new VGroupLayout(GroupLayout.NONE); gl.setJustification(GroupLayout.TOP); _bpanel = new SmartPanel(); _bpanel.setLayout(gl); // give ourselves a wee bit of a border _bpanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); // put it into a scrolling pane JScrollPane bscroll = new JScrollPane(_bpanel); add(bscroll); GroupLayout bgl = new HGroupLayout(GroupLayout.NONE); bgl.setJustification(GroupLayout.RIGHT); JPanel cbar = new JPanel(bgl); // add our control buttons cbar.add(_clearbut = createControlButton("Clear", "clear")); cbar.add(createControlButton("Skip", "skip")); cbar.add(createControlButton("Refresh", "refresh")); add(cbar, GroupLayout.FIXED); // use a special font for our name buttons _nameFont = new Font("Helvetica", Font.PLAIN, 10); // load up the playlist refreshPlaylist(); } protected JButton createControlButton (String label, String action) { JButton cbut = new JButton(label); cbut.setActionCommand(action); cbut.addActionListener(this); return cbut; } public void actionPerformed (ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.equals("clear")) { Chooser.scontrol.clear(); refreshPlaylist(); } else if (cmd.equals("skip")) { Chooser.scontrol.skip(); refreshPlaying(); } else if (cmd.equals("refresh")) { refreshPlaylist(); } else if (cmd.equals("skipto")) { JButton src = (JButton)e.getSource(); PlaylistEntry entry = (PlaylistEntry)src.getClientProperty("entry"); Chooser.scontrol.skipto(entry.song.songid); refreshPlaying(); } else if (cmd.equals("remove")) { JButton src = (JButton)e.getSource(); PlaylistEntry entry = (PlaylistEntry)src.getClientProperty("entry"); Chooser.scontrol.remove(entry.song.songid); // remove the entry UI elements JPanel epanel = (JPanel)entry.label.getParent(); epanel.getParent().remove(epanel); // update the playing indicator because we may have removed // the playing entry refreshPlaying(); } } protected void refreshPlaylist () { // stick a "loading" label in the list to let the user know // what's up _bpanel.removeAll(); _bpanel.add(new JLabel("Loading...")); // we've removed and added components and swing won't properly // repaint automatically _bpanel.repaint(); // start up the task that reads the CD info from the database TaskMaster.invokeMethodTask("readPlaylist", this, this); } protected void refreshPlaying () { // unhighlight whoever is playing now PlaylistEntry pentry = getPlayingEntry(); if (pentry != null) { pentry.label.setForeground(Color.black); } // figure out who's playing TaskMaster.invokeMethodTask("readPlaying", this, this); } public void readPlaylist () throws SQLException { // clear out any previous playlist _plist.clear(); // find out what's currently playing readPlaying(); // get the playlist from the music daemon String[] plist = Chooser.scontrol.getPlaylist(); // parse it into playlist entries for (int i = 0; i < plist.length; i++) { String[] toks = StringUtil.split(plist[i], "\t"); int eid, sid; try { eid = Integer.parseInt(toks[0]); sid = Integer.parseInt(toks[1]); } catch (NumberFormatException nfe) { Log.warning("Bogus playlist record: '" + plist[i] + "'."); continue; } Entry entry = Chooser.model.getEntry(eid); Song song = entry.getSong(sid); _plist.add(new PlaylistEntry(entry, song)); } } public void readPlaying () { String playing = Chooser.scontrol.getPlaying(); playing = StringUtil.split(playing, ":")[1].trim(); _playid = -1; if (!playing.equals("<none>")) { try { _playid = Integer.parseInt(playing); } catch (NumberFormatException nfe) { Log.warning("Unable to parse currently playing id '" + playing + "'."); } } } public void taskCompleted (String name, Object result) { if (name.equals("readPlaylist")) { populatePlaylist(); } else if (name.equals("readPlaying")) { highlightPlaying(); } } public void taskFailed (String name, Throwable exception) { String msg; if (Exception.class.equals(exception.getClass())) { msg = exception.getMessage(); } else { msg = exception.toString(); } JOptionPane.showMessageDialog(this, msg, "Error", JOptionPane.ERROR_MESSAGE); Log.logStackTrace(exception); } protected void populatePlaylist () { // clear out any existing children _bpanel.removeAll(); // adjust our layout policy GroupLayout gl = (GroupLayout)_bpanel.getLayout(); gl.setOffAxisPolicy(GroupLayout.EQUALIZE); gl.setOffAxisJustification(GroupLayout.LEFT); // add buttons for every entry String title = null; for (int i = 0; i < _plist.size(); i++) { PlaylistEntry entry = (PlaylistEntry)_plist.get(i); // add record/artist indicators when the record and artist // changes if (!entry.entry.title.equals(title)) { title = entry.entry.title; JLabel label = new JLabel(entry.entry.title + " - " + entry.entry.artist); _bpanel.add(label); } // create a browse and a play button JPanel hpanel = new JPanel(); gl = new HGroupLayout(GroupLayout.NONE); gl.setOffAxisPolicy(GroupLayout.STRETCH); gl.setJustification(GroupLayout.LEFT); hpanel.setLayout(gl); entry.label = new JLabel(entry.song.title); entry.label.setForeground((entry.song.songid == _playid) ? Color.red : Color.black); entry.label.setFont(_nameFont); hpanel.add(entry.label); JButton button; button = new JButton("Skip to"); button.setFont(_nameFont); button.setActionCommand("skipto"); button.addActionListener(this); button.putClientProperty("entry", entry); hpanel.add(button); button = new JButton("Remove"); button.setActionCommand("remove"); button.setFont(_nameFont); button.addActionListener(this); button.putClientProperty("entry", entry); hpanel.add(button); // let the bpanel know that we want to scroll the active track // label into place once we're all laid out if (entry.song.songid == _playid) { _bpanel.setScrollTarget(hpanel); } _bpanel.add(hpanel); } // if there were no entries, stick a label in to that effect if (_plist.size() == 0) { _bpanel.add(new JLabel("Nothing playing.")); } // we've removed and added components and swing won't properly // repaint automatically _bpanel.repaint(); } protected void highlightPlaying () { for (int i = 0; i < _plist.size(); i++) { PlaylistEntry entry = (PlaylistEntry)_plist.get(i); if (entry.song.songid == _playid) { entry.label.setForeground(Color.red); } } } protected PlaylistEntry getPlayingEntry () { for (int i = 0; i < _plist.size(); i++) { PlaylistEntry entry = (PlaylistEntry)_plist.get(i); if (entry.song.songid == _playid) { return entry; } } return null; } protected static class PlaylistEntry { public Entry entry; public Song song; public JLabel label; public PlaylistEntry (Entry entry, Song song) { this.entry = entry; this.song = song; } } /** * A panel that can be made to scroll a particular child into view * when it becomes visible. */ protected static class SmartPanel extends JPanel { public void setScrollTarget (JComponent comp) { _target = comp; } public void doLayout () { super.doLayout(); if (_target != null) { scrollRectToVisible(_target.getBounds()); _target = null; } } protected JComponent _target; } protected SmartPanel _bpanel; protected JButton _clearbut; protected ArrayList _plist = new ArrayList(); protected int _playid; protected int _oldid = -1; protected Font _nameFont; }
// $Id: PlaylistPanel.java,v 1.10 2002/02/22 08:37:17 mdb Exp $ package robodj.chooser; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; import java.util.ArrayList; import java.util.Iterator; import com.samskivert.io.PersistenceException; import com.samskivert.swing.*; import com.samskivert.swing.util.*; import com.samskivert.util.StringUtil; import robodj.Log; import robodj.repository.*; public class PlaylistPanel extends JPanel implements TaskObserver, ActionListener { public PlaylistPanel () { GroupLayout gl = new VGroupLayout(GroupLayout.STRETCH); gl.setOffAxisPolicy(GroupLayout.STRETCH); setLayout(gl); // create the pane that will hold the buttons gl = new VGroupLayout(GroupLayout.NONE); gl.setJustification(GroupLayout.TOP); _bpanel = new SmartPanel(); _bpanel.setLayout(gl); // give ourselves a wee bit of a border _bpanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); // put it into a scrolling pane JScrollPane bscroll = new JScrollPane(_bpanel); add(bscroll); GroupLayout bgl = new HGroupLayout(GroupLayout.NONE); bgl.setJustification(GroupLayout.RIGHT); JPanel cbar = new JPanel(bgl); // add our control buttons cbar.add(_clearbut = createControlButton("Clear", "clear")); cbar.add(createControlButton("Skip", "skip")); cbar.add(createControlButton("Refresh", "refresh")); add(cbar, GroupLayout.FIXED); // use a special font for our name buttons _nameFont = new Font("Helvetica", Font.PLAIN, 10); // load up the playlist refreshPlaylist(); } protected JButton createControlButton (String label, String action) { JButton cbut = new JButton(label); cbut.setActionCommand(action); cbut.addActionListener(this); return cbut; } public void actionPerformed (ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.equals("clear")) { Chooser.scontrol.clear(); refreshPlaylist(); } else if (cmd.equals("skip")) { Chooser.scontrol.skip(); refreshPlaying(); } else if (cmd.equals("refresh")) { refreshPlaylist(); } else if (cmd.equals("skipto")) { JButton src = (JButton)e.getSource(); PlaylistEntry entry = (PlaylistEntry)src.getClientProperty("entry"); Chooser.scontrol.skipto(entry.song.songid); refreshPlaying(); } else if (cmd.equals("remove")) { JButton src = (JButton)e.getSource(); PlaylistEntry entry = (PlaylistEntry)src.getClientProperty("entry"); Chooser.scontrol.remove(entry.song.songid); // remove the entry UI elements JPanel epanel = (JPanel)entry.label.getParent(); epanel.getParent().remove(epanel); revalidate(); // relayout // remove the entry from the playlist _plist.remove(entry); // update the playing indicator because we may have removed // the playing entry refreshPlaying(); } else if (cmd.equals("remove_all")) { JButton src = (JButton)e.getSource(); PlaylistEntry entry = (PlaylistEntry)src.getClientProperty("entry"); // remove all entries starting with this one until we get to // one that has a different entryid int count = 0; Iterator iter = _plist.iterator(); while (iter.hasNext()) { PlaylistEntry pe = (PlaylistEntry)iter.next(); if (entry == pe) { count++; // remove the entry UI elements JPanel epanel = (JPanel)pe.label.getParent(); epanel.getParent().remove(epanel); // remove the entry iter.remove(); } else if (count > 0) { if (pe.entry.entryid == entry.entry.entryid) { count++; // remove the entry UI elements JPanel epanel = (JPanel)pe.label.getParent(); epanel.getParent().remove(epanel); // remove the entry iter.remove(); } else { // we hit an entry that doesn't match, bail break; } } } // remove the title and stuff JPanel tpanel = (JPanel)src.getParent(); tpanel.getParent().remove(tpanel); revalidate(); // relayout // now tell the music daemon to remove these entries Chooser.scontrol.removeGroup(entry.song.songid, count); // update the playing indicator because we may have removed // the playing entry refreshPlaying(); } } protected void refreshPlaylist () { // stick a "loading" label in the list to let the user know // what's up _bpanel.removeAll(); _bpanel.add(new JLabel("Loading...")); // swing doesn't automatically validate after adding/removing // children _bpanel.revalidate(); // start up the task that reads the CD info from the database TaskMaster.invokeMethodTask("readPlaylist", this, this); } protected void refreshPlaying () { // unhighlight whoever is playing now PlaylistEntry pentry = getPlayingEntry(); if (pentry != null) { pentry.label.setForeground(Color.black); } // figure out who's playing TaskMaster.invokeMethodTask("readPlaying", this, this); } public void readPlaylist () throws PersistenceException { // clear out any previous playlist _plist.clear(); // find out what's currently playing readPlaying(); // get the playlist from the music daemon String[] plist = Chooser.scontrol.getPlaylist(); // parse it into playlist entries for (int i = 0; i < plist.length; i++) { String[] toks = StringUtil.split(plist[i], "\t"); int eid, sid; try { eid = Integer.parseInt(toks[0]); sid = Integer.parseInt(toks[1]); } catch (NumberFormatException nfe) { Log.warning("Bogus playlist record: '" + plist[i] + "'."); continue; } Entry entry = Chooser.model.getEntry(eid); if (entry != null) { Song song = entry.getSong(sid); _plist.add(new PlaylistEntry(entry, song)); } else { Log.warning("Unable to load entry [eid=" + eid + "]."); } } } public void readPlaying () { String playing = Chooser.scontrol.getPlaying(); playing = StringUtil.split(playing, ":")[1].trim(); _playid = -1; if (!playing.equals("<none>")) { try { _playid = Integer.parseInt(playing); } catch (NumberFormatException nfe) { Log.warning("Unable to parse currently playing id '" + playing + "'."); } } } public void taskCompleted (String name, Object result) { if (name.equals("readPlaylist")) { populatePlaylist(); } else if (name.equals("readPlaying")) { highlightPlaying(); } } public void taskFailed (String name, Throwable exception) { String msg; if (Exception.class.equals(exception.getClass())) { msg = exception.getMessage(); } else { msg = exception.toString(); } JOptionPane.showMessageDialog(this, msg, "Error", JOptionPane.ERROR_MESSAGE); Log.logStackTrace(exception); } protected void populatePlaylist () { // clear out any existing children _bpanel.removeAll(); // adjust our layout policy GroupLayout gl = (GroupLayout)_bpanel.getLayout(); gl.setOffAxisPolicy(GroupLayout.EQUALIZE); gl.setOffAxisJustification(GroupLayout.LEFT); // add buttons for every entry String title = null; for (int i = 0; i < _plist.size(); i++) { PlaylistEntry entry = (PlaylistEntry)_plist.get(i); JButton button; // add record/artist indicators when the record and artist // changes if (!entry.entry.title.equals(title)) { JPanel tpanel = new JPanel(); gl = new HGroupLayout(GroupLayout.NONE); gl.setOffAxisPolicy(GroupLayout.STRETCH); gl.setJustification(GroupLayout.LEFT); tpanel.setLayout(gl); title = entry.entry.title; JLabel label = new JLabel(entry.entry.title + " - " + entry.entry.artist); tpanel.add(label); tpanel.add(newButton("Remove", "remove_all", entry)); _bpanel.add(tpanel); } // create a browse and a play button JPanel hpanel = new JPanel(); gl = new HGroupLayout(GroupLayout.NONE); gl.setOffAxisPolicy(GroupLayout.STRETCH); gl.setJustification(GroupLayout.LEFT); hpanel.setLayout(gl); entry.label = new JLabel(entry.song.title); entry.label.setForeground((entry.song.songid == _playid) ? Color.red : Color.black); entry.label.setFont(_nameFont); hpanel.add(entry.label); hpanel.add(newButton("Skip to", "skipto", entry)); hpanel.add(newButton("Remove", "remove", entry)); // let the bpanel know that we want to scroll the active track // label into place once we're all laid out if (entry.song.songid == _playid) { _bpanel.setScrollTarget(hpanel); } _bpanel.add(hpanel); } // if there were no entries, stick a label in to that effect if (_plist.size() == 0) { _bpanel.add(new JLabel("Nothing playing.")); } // swing doesn't automatically validate after adding/removing // children _bpanel.revalidate(); } protected JButton newButton (String label, String command, Object clientProperty) { JButton button = new JButton(label); button.setFont(_nameFont); button.setActionCommand(command); button.addActionListener(this); button.putClientProperty("entry", clientProperty); return button; } protected void highlightPlaying () { for (int i = 0; i < _plist.size(); i++) { PlaylistEntry entry = (PlaylistEntry)_plist.get(i); if (entry.song.songid == _playid) { entry.label.setForeground(Color.red); } } repaint(); } protected PlaylistEntry getPlayingEntry () { for (int i = 0; i < _plist.size(); i++) { PlaylistEntry entry = (PlaylistEntry)_plist.get(i); if (entry.song.songid == _playid) { return entry; } } return null; } protected static class PlaylistEntry { public Entry entry; public Song song; public JLabel label; public PlaylistEntry (Entry entry, Song song) { this.entry = entry; this.song = song; } } /** * A panel that can be made to scroll a particular child into view * when it becomes visible. */ protected static class SmartPanel extends JPanel { public void setScrollTarget (JComponent comp) { _target = comp; } public void doLayout () { super.doLayout(); if (_target != null) { Rectangle bounds = _target.getBounds(); _target = null; // this seems to sometimes call layout(), so we need to // prevent recursion scrollRectToVisible(bounds); } } protected JComponent _target; } protected SmartPanel _bpanel; protected JButton _clearbut; protected ArrayList _plist = new ArrayList(); protected int _playid; protected int _oldid = -1; protected Font _nameFont; }
package com.jetbrains.python.debugger; import com.intellij.icons.AllIcons; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.ColoredTextContainer; import com.intellij.ui.SimpleTextAttributes; import com.intellij.xdebugger.XSourcePosition; import com.intellij.xdebugger.evaluation.XDebuggerEvaluator; import com.intellij.xdebugger.frame.XCompositeNode; import com.intellij.xdebugger.frame.XStackFrame; import com.intellij.xdebugger.frame.XValueChildrenList; import org.jetbrains.annotations.NotNull; public class PyStackFrame extends XStackFrame { private static final Logger LOG = Logger.getInstance("#com.jetbrains.python.pydev.PyStackFrame"); private static final Object STACK_FRAME_EQUALITY_OBJECT = new Object(); private final PyDebugProcess myDebugProcess; private final PyStackFrameInfo myFrameInfo; private final XSourcePosition myPosition; public PyStackFrame(@NotNull final PyDebugProcess debugProcess, @NotNull final PyStackFrameInfo frameInfo) { myDebugProcess = debugProcess; myFrameInfo = frameInfo; myPosition = myDebugProcess.getPositionConverter().convertFromPython(frameInfo.getPosition()); } @Override public Object getEqualityObject() { return STACK_FRAME_EQUALITY_OBJECT; } @Override public XSourcePosition getSourcePosition() { return myPosition; } @Override public XDebuggerEvaluator getEvaluator() { return new PyDebuggerEvaluator(myDebugProcess); } @Override public void customizePresentation(ColoredTextContainer component) { component.setIcon(AllIcons.Debugger.StackFrame); if (myPosition == null) { component.append("<frame not available>", SimpleTextAttributes.GRAY_ATTRIBUTES); return; } boolean isExternal = true; final VirtualFile file = myPosition.getFile(); final Document document = FileDocumentManager.getInstance().getDocument(file); if (document != null) { final Project project = myDebugProcess.getSession().getProject(); isExternal = !ProjectRootManager.getInstance(project).getFileIndex().isInContent(file); } component.append(myFrameInfo.getName(), gray(SimpleTextAttributes.REGULAR_ATTRIBUTES, isExternal)); component.append(", ", gray(SimpleTextAttributes.REGULAR_ATTRIBUTES, isExternal)); component.append(myPosition.getFile().getName(), gray(SimpleTextAttributes.REGULAR_ATTRIBUTES, isExternal)); component.append(":", gray(SimpleTextAttributes.REGULAR_ATTRIBUTES, isExternal)); component.append(Integer.toString(myPosition.getLine() + 1), gray(SimpleTextAttributes.REGULAR_ATTRIBUTES, isExternal)); } private static SimpleTextAttributes gray(SimpleTextAttributes attributes, boolean gray) { if (!gray) { return attributes; } else { return (attributes.getStyle() & SimpleTextAttributes.STYLE_ITALIC) != 0 ? SimpleTextAttributes.GRAY_ITALIC_ATTRIBUTES : SimpleTextAttributes.GRAYED_ATTRIBUTES; } } @Override public void computeChildren(@NotNull final XCompositeNode node) { if (node.isObsolete()) return; ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { @Override public void run() { try { final XValueChildrenList values = myDebugProcess.loadFrame(); if (!node.isObsolete()) { node.addChildren(values != null ? values : XValueChildrenList.EMPTY, true); } } catch (PyDebuggerException e) { if (!node.isObsolete()) { node.setErrorMessage("Unable to display frame variables"); } LOG.warn(e); } } }); } public String getThreadId() { return myFrameInfo.getThreadId(); } public String getFrameId() { return myFrameInfo.getId(); } public String getThreadFrameId() { return myFrameInfo.getThreadId() + ":" + myFrameInfo.getId(); } protected XSourcePosition getPosition() { return myPosition; } }