answer
stringlengths
17
10.2M
package com.bls.core.poi; import com.bls.core.IdentifiableEntity; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import org.hibernate.validator.constraints.NotEmpty; public class Person<K> extends IdentifiableEntity<K> { @NotEmpty private final String name; @NotEmpty private final String surname; @NotEmpty private final Location location; @JsonCreator public Person(@JsonProperty(value = "id", required = false) final K id, @JsonProperty("name") final String name, @JsonProperty("surname") final String surname, @JsonProperty("location") final Location location) { super(id); this.name = name; this.surname = surname; this.location = location; } public String getName() { return name; } public String getSurname() { return surname; } public Location getLocation() { return location; } }
package org.grails.ignite; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; /** * This class manages instances of scheduled feeds in the Ignite grid. Instances of this class are managed in a schedule * set which is distributed across the grid so that if the singleton scheduler node goes down, whichever nodes takes * over can retrieve the current schedule from the grid and pick up the scheduling. */ public class ScheduledRunnable implements Callable, NamedRunnable, Serializable { private String name; private Runnable underlyingRunnable; private long initialDelay = -1; private long period = -1; private long delay = -1; private long timeout = 60000; private TimeUnit timeUnit; private String cronString; public ScheduledRunnable() { this.name = UUID.randomUUID().toString(); } public ScheduledRunnable(String name) { this.name = name; } public ScheduledRunnable(Runnable runnable) { if (runnable instanceof NamedRunnable) { this.name = ((NamedRunnable) runnable).getName(); } this.underlyingRunnable = runnable; this.name = UUID.randomUUID().toString(); } public ScheduledRunnable(String name, Runnable runnable) { if (runnable instanceof NamedRunnable) { this.name = ((NamedRunnable) runnable).getName(); } this.underlyingRunnable = runnable; this.name = name; } public TimeUnit getTimeUnit() { return timeUnit; } public void setTimeUnit(TimeUnit timeUnit) { this.timeUnit = timeUnit; } public Runnable getUnderlyingRunnable() { return underlyingRunnable; } // public void setRunnable(Runnable underlyingRunnable) { // this.underlyingRunnable = underlyingRunnable; public long getInitialDelay() { return initialDelay; } public void setInitialDelay(long initialDelay) { this.initialDelay = initialDelay; } public long getPeriod() { return period; } public void setPeriod(long period) { this.period = period; } public long getDelay() { return delay; } public void setDelay(long delay) { this.delay = delay; } public String toString() { return this.getClass().getSimpleName() + "[name=\"" + name + "\", period=" + period + ", delay=" + delay + ", initialDelay=" + initialDelay + ", timeUnit=" + timeUnit + ", cronString=\"" + cronString + "\"]"; } public String getName() { return name; } public void run() { underlyingRunnable.run(); } public String getCronString() { return this.cronString; } public void setCronString(String cronString) { this.cronString = cronString; } public long getTimeout() { return this.timeout; } public void setTimeout(long timeout) { this.timeout = timeout; } @Override public boolean equals(Object obj) { if (!(obj instanceof ScheduledRunnable)) return false; return ((ScheduledRunnable) obj).getName().equals(this.getName()); } @Override public int hashCode() { return name.hashCode(); } @Override public Object call() throws Exception { underlyingRunnable.run(); return null; } public Map toDataMap() { Map result = new HashMap(); result.put("name", this.name); result.put("initialDelay", this.initialDelay); result.put("delay", this.delay); result.put("timeout", this.timeout); result.put("timeUnit", this.timeUnit); result.put("cronString", this.cronString); return result; } }
package org.jdesktop.swingx.painter; import java.awt.Graphics2D; /** * <p>A painting delegate. The Painter interface defines exactly one method, * <code>paint</code>. It is used in situations where the developer can change * the painting routine of a component without having to resort to subclassing * the component.</p> * * <p><code>Painter</code>s are simply encapsulations of Java2D code and make * it fairly trivial to reuse existing <code>Painter</code>s or to combine * them together. Implementations of this interface are also trivial to write, * such that if you can't find a <code>Painter</code> that does what you need, * you can write one with minimal effort. Writing a <code>Painter</code> requires * knowledge of Java2D.</p> * * <p>A <code>Painter</code> may be created with a type parameter. This type will be * expected in the <code>paint</code> method. For example, you may wish to write a * <code>Painter</code> that only works with subclasses of {@link java.awt.Component}. * In that case, when the <code>Painter</code> is declared, you may declare that * it requires a <code>Component</code>, allowing the paint method to be type safe. Ex: * <pre><code> * Painter<Component> p = new Painter<Component>() { * public void paint(Graphics2D g, Component c, int width, int height) { * g.setColor(c.getBackground()); * //and so forth * } * } * </code></pre></p> * * @author rbair * @see AbstractPainter * @see CompoundPainter * @see org.jdesktop.swingx.JXPanel * @see org.jdesktop.swingx.JXLabel * @see org.jdesktop.swingx.JXButton */ public interface Painter<T> { /** * <p>Renders to the given {@link java.awt.Graphics2D} object. Implementations * of this method may modify state on the <code>Graphics2D</code>, and are not * required to restore that state upon completion. In most cases, it is recommended * that the caller pass in a scratch graphics object. The <code>Graphics2D</code> * must never be null.</p> * * <p>The supplied object parameter acts as an optional configuration argument. * For example, it could be of type <code>Component</code>. A <code>Painter</code> * that expected it could then read state from that <code>Component</code> and * use the state for painting. For example, an implementation may read the * backgroundColor and use that.</p> * * <p>Generally, to enhance reusability, most standard <code>Painter</code>s ignore * this parameter. They can thus be reused in any context. The <code>object</code> * may be null. Implementations must not throw a NullPointerException if the object * parameter is null.</p> * * <p>Finally, the <code>width</code> and <code>height</code> arguments specify the * width and height that the <code>Painter</code> should paint into. More * specifically, the specified width and height instruct the painter that it should * paint fully within this width and height. Any specified clip on the * <code>g</code> param will further constrain the region.</p> * * <p>For example, suppose I have a <code>Painter</code> implementation that draws * a gradient. The gradient goes from white to black. It "stretches" to fill the * painted region. Thus, if I use this <code>Painter</code> to paint a 500 x 500 * region, the far left would be black, the far right would be white, and a smooth * gradient would be painted between. I could then, without modification, reuse the * <code>Painter</code> to paint a region that is 20x20 in size. This region would * also be black on the left, white on the right, and a smooth gradient painted * between.</p> * * @param g The Graphics2D to render to. This must not be null. * @param object an optional configuration parameter. This may be null. * @param width width of the area to paint. * @param height height of the area to paint. */ public void paint(Graphics2D g, T object, int width, int height); }
package com.yahoo.vespa.config.server.maintenance; import com.google.inject.Inject; import com.yahoo.cloud.config.ConfigserverConfig; import com.yahoo.component.AbstractComponent; import com.yahoo.jdisc.Metric; import com.yahoo.vespa.config.server.ApplicationRepository; import com.yahoo.vespa.curator.Curator; import com.yahoo.vespa.flags.FlagSource; import java.time.Clock; import java.time.Duration; /** * Maintenance jobs of the config server. * Each maintenance job is a singleton instance of its implementing class, created and owned by this, * and running its own dedicated thread. * * @author hmusum */ public class ConfigServerMaintenance extends AbstractComponent { private final TenantsMaintainer tenantsMaintainer; private final FileDistributionMaintainer fileDistributionMaintainer; private final SessionsMaintainer sessionsMaintainer; private final ApplicationPackageMaintainer applicationPackageMaintainer; @Inject public ConfigServerMaintenance(ConfigserverConfig configserverConfig, ApplicationRepository applicationRepository, Curator curator, FlagSource flagSource, Metric metric) { DefaultTimes defaults = new DefaultTimes(configserverConfig); tenantsMaintainer = new TenantsMaintainer(applicationRepository, curator, flagSource, defaults.defaultInterval, Clock.systemUTC()); fileDistributionMaintainer = new FileDistributionMaintainer(applicationRepository, curator, defaults.defaultInterval, flagSource); sessionsMaintainer = new SessionsMaintainer(applicationRepository, curator, Duration.ofMinutes(1), flagSource); applicationPackageMaintainer = new ApplicationPackageMaintainer(applicationRepository, curator, Duration.ofMinutes(1), flagSource); } @Override public void deconstruct() { fileDistributionMaintainer.close(); sessionsMaintainer.close(); applicationPackageMaintainer.close(); tenantsMaintainer.close(); } /* * Default values from config. If one of the values needs to be changed, add the value to * configserver-config.xml in the config server application directory and restart the config server */ private static class DefaultTimes { private final Duration defaultInterval; DefaultTimes(ConfigserverConfig configserverConfig) { this.defaultInterval = Duration.ofMinutes(configserverConfig.maintainerIntervalMinutes()); } } public void runBeforeBootstrap() { fileDistributionMaintainer.lockAndMaintain(); sessionsMaintainer.lockAndMaintain(); } }
package hudson.maven; import hudson.FilePath; import hudson.Util; import hudson.maven.agent.Main; import hudson.maven.reporters.SurefireArchiver; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.model.DependencyGraph; import hudson.model.Hudson; import hudson.model.Result; import hudson.model.Run; import hudson.model.Slave; import hudson.remoting.Callable; import hudson.remoting.Channel; import hudson.remoting.Launcher; import hudson.remoting.Which; import hudson.scm.ChangeLogSet; import hudson.scm.ChangeLogSet.Entry; import hudson.tasks.Maven.MavenInstallation; import hudson.util.ArgumentListBuilder; import hudson.util.IOException2; import org.apache.maven.lifecycle.LifecycleExecutorInterceptor; import org.codehaus.classworlds.NoSuchRealmException; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.io.OutputStream; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.List; import java.util.Set; /** * {@link Run} for {@link MavenModule}. * * @author Kohsuke Kawaguchi */ public class MavenBuild extends AbstractBuild<MavenModule,MavenBuild> { /** * {@link MavenReporter}s that will contribute project actions. * Can be null if there's none. */ /*package*/ List<MavenReporter> projectActionReporters; /** * {@link ExecutedMojo}s that record what was run. * Null until some time before the build completes, * or if this build is performed in earlier versions of Hudson. * @since 1.98. */ private List<ExecutedMojo> executedMojos; public MavenBuild(MavenModule job) throws IOException { super(job); } public MavenBuild(MavenModule job, Calendar timestamp) { super(job, timestamp); } public MavenBuild(MavenModule project, File buildDir) throws IOException { super(project, buildDir); } /** * Gets the {@link MavenModuleSetBuild} that has the same build number. * * @return * null if no such build exists, which happens when the module build * is manually triggered. * @see #getModuleSetBuild() */ public MavenModuleSetBuild getParentBuild() { return getParent().getParent().getBuildByNumber(getNumber()); } /** * Gets the "governing" {@link MavenModuleSet} that has set * the workspace for this build. * * @return * null if no such build exists, which happens if the build * is manually removed. * @see #getParentBuild() */ public MavenModuleSetBuild getModuleSetBuild() { return getParent().getParent().getNearestOldBuild(getNumber()); } @Override public ChangeLogSet<? extends Entry> getChangeSet() { return new FilteredChangeLogSet(this); } /** * We always get the changeset from {@link MavenModuleSetBuild}. */ @Override public boolean hasChangeSetComputed() { return true; } public void registerAsProjectAction(MavenReporter reporter) { if(projectActionReporters==null) projectActionReporters = new ArrayList<MavenReporter>(); projectActionReporters.add(reporter); } public List<ExecutedMojo> getExecutedMojos() { if(executedMojos==null) return Collections.emptyList(); else return Collections.unmodifiableList(executedMojos); } @Override public void run() { run(new RunnerImpl()); getProject().updateTransientActions(); MavenModuleSetBuild parentBuild = getModuleSetBuild(); if(parentBuild!=null) parentBuild.notifyModuleBuild(this); } /** * Runs Maven and builds the project. */ private static final class Builder implements Callable<Result,IOException> { private final BuildListener listener; private final MavenBuildProxy buildProxy; private final MavenReporter[] reporters; private final List<String> goals; public Builder(BuildListener listener,MavenBuildProxy buildProxy,MavenReporter[] reporters, List<String> goals) { this.listener = listener; this.buildProxy = buildProxy; this.reporters = reporters; this.goals = goals; } /** * This code is executed inside the maven jail process. */ public Result call() throws IOException { try { PluginManagerInterceptor pmi = new PluginManagerInterceptor(buildProxy, reporters, listener); hudson.maven.agent.PluginManagerInterceptor.setListener(pmi); LifecycleExecutorInterceptor.setListener(pmi); markAsSuccess = false; int r = Main.launch(goals.toArray(new String[goals.size()])); if(r==0) return Result.SUCCESS; if(markAsSuccess) { listener.getLogger().println("Maven failed with error."); return Result.SUCCESS; } return Result.FAILURE; } catch (NoSuchMethodException e) { throw new IOException2(e); } catch (IllegalAccessException e) { throw new IOException2(e); } catch (NoSuchRealmException e) { throw new IOException2(e); } catch (InvocationTargetException e) { throw new IOException2(e); } catch (ClassNotFoundException e) { throw new IOException2(e); } } } /** * {@link MavenBuildProxy} implementation. */ private class ProxyImpl implements MavenBuildProxy, Serializable { public <V, T extends Throwable> V execute(BuildCallable<V, T> program) throws T, IOException, InterruptedException { return program.call(MavenBuild.this); } public FilePath getRootDir() { return new FilePath(MavenBuild.this.getRootDir()); } public FilePath getProjectRootDir() { return new FilePath(MavenBuild.this.getParent().getRootDir()); } public FilePath getArtifactsDir() { return new FilePath(MavenBuild.this.getArtifactsDir()); } public void setResult(Result result) { MavenBuild.this.setResult(result); } public void registerAsProjectAction(MavenReporter reporter) { MavenBuild.this.registerAsProjectAction(reporter); } public void setExecutedMojos(List<ExecutedMojo> executedMojos) { MavenBuild.this.executedMojos = executedMojos; } private Object writeReplace() { return Channel.current().export(MavenBuildProxy.class, new ProxyImpl()); } } private static final class GetJavaExe implements Callable<String,IOException> { public String call() throws IOException { return new File(new File(System.getProperty("java.home")),"bin/java").getPath(); } } private static final class GetRemotingJar implements Callable<String,IOException> { public String call() throws IOException { return Which.jarFile(Launcher.class).getPath(); } } private class RunnerImpl extends AbstractRunner implements ProcessCache.Factory { private List<MavenReporter> reporters = new ArrayList<MavenReporter>(); protected Result doRun(BuildListener listener) throws Exception { // pick up a list of reporters to run getProject().getReporters().addAllTo(reporters); getProject().getParent().getReporters().addAllTo(reporters); for (MavenReporterDescriptor d : MavenReporters.LIST) { if(getProject().getReporters().contains(d)) continue; // already configured MavenReporter auto = d.newAutoInstance(getProject()); if(auto!=null) reporters.add(auto); } if(debug) listener.getLogger().println("Reporters="+reporters); ProcessCache.MavenProcess process = mavenProcessCache.get(launcher.getChannel(), listener, this); ArgumentListBuilder margs = new ArgumentListBuilder(); margs.add("-N"); margs.add("-f",getParent().getModuleRoot().child("pom.xml").getRemote()); margs.addTokenized(getProject().getGoals()); boolean normalExit = false; try { Result r = process.channel.call(new Builder( listener,new ProxyImpl(), reporters.toArray(new MavenReporter[0]), margs.toList())); normalExit = true; return r; } finally { if(normalExit) process.recycle(); else process.discard(); } } /** * Starts maven process. */ public Channel newProcess(BuildListener listener, OutputStream out) throws IOException, InterruptedException { return launcher.launchChannel(buildMavenCmdLine(listener).toCommandArray(), out, getProject().getParent().getModuleRoot()); } /** * Builds the command line argument list to launch the maven process. * * UGLY. */ private ArgumentListBuilder buildMavenCmdLine(BuildListener listener) throws IOException, InterruptedException { MavenInstallation mvn = getMavenInstallation(); if(mvn==null) { listener.error("Maven version is not configured for this project. Can't determine which Maven to run"); throw new RunnerAbortedException(); } // find classworlds.jar File bootDir = new File(mvn.getHomeDir(), "core/boot"); File[] classworlds = bootDir.listFiles(CLASSWORLDS_FILTER); if(classworlds==null || classworlds.length==0) { // Maven 2.0.6 puts it to a different place bootDir = new File(mvn.getHomeDir(), "boot"); classworlds = bootDir.listFiles(CLASSWORLDS_FILTER); if(classworlds==null || classworlds.length==0) { listener.error("No classworlds*.jar found in "+mvn.getHomeDir()+" -- Is this a valid maven2 directory?"); throw new RunnerAbortedException(); } } boolean isMaster = getCurrentNode()==Hudson.getInstance(); FilePath slaveRoot=null; if(!isMaster) slaveRoot = ((Slave)getCurrentNode()).getFilePath(); ArgumentListBuilder args = new ArgumentListBuilder(); args.add(launcher.getChannel().call(new GetJavaExe())); if(debugPort!=0) args.add("-Xrunjdwp:transport=dt_socket,server=y,address="+debugPort); args.addTokenized(getMavenOpts()); args.add("-cp"); args.add( (isMaster?Which.jarFile(Main.class).getAbsolutePath():slaveRoot.child("maven-agent.jar").getRemote())+ (launcher.isUnix()?":":";")+ classworlds[0].getAbsolutePath()); args.add(Main.class.getName()); // M2_HOME args.add(mvn.getMavenHome()); // remoting.jar args.add(launcher.getChannel().call(new GetRemotingJar())); // interceptor.jar args.add(isMaster? Which.jarFile(hudson.maven.agent.PluginManagerInterceptor.class).getAbsolutePath(): slaveRoot.child("maven-interceptor.jar").getRemote()); return args; } public String getMavenOpts() { return getParent().getParent().getMavenOpts(); } public MavenInstallation getMavenInstallation() { return getParent().getParent().getMaven(); } public void post(BuildListener listener) { try { for (MavenReporter reporter : reporters) reporter.end(MavenBuild.this,launcher,listener); } catch (InterruptedException e) { e.printStackTrace(listener.fatalError("aborted")); setResult(Result.FAILURE); } catch (IOException e) { e.printStackTrace(listener.fatalError("failed")); setResult(Result.FAILURE); } if(!getResult().isWorseThan(Result.UNSTABLE)) { // trigger dependency builds DependencyGraph graph = Hudson.getInstance().getDependencyGraph(); for( AbstractProject<?,?> down : getParent().getDownstreamProjects()) { if(debug) listener.getLogger().println("Considering whether to trigger "+down+" or not"); if(graph.hasIndirectDependencies(getParent(),down)) { // if there's a longer dependency path to this project, // then scheduling the build now is going to be a waste, // so don't do that. // let the longer path eventually trigger this build if(debug) listener.getLogger().println(" -> No, because there's a longer dependency path"); continue; } // if the downstream module depends on multiple modules, // only trigger them when all the upstream dependencies are updated. boolean trigger = true; AbstractBuild<?,?> dlb = down.getLastBuild(); // can be null. for (MavenModule up : Util.filter(down.getUpstreamProjects(),MavenModule.class)) { MavenBuild ulb; if(up==getProject()) { // the current build itself is not registered as lastSuccessfulBuild // at this point, so we have to take that into account. ugly. if(getResult()==null || !getResult().isWorseThan(Result.UNSTABLE)) ulb = MavenBuild.this; else ulb = up.getLastSuccessfulBuild(); } else ulb = up.getLastSuccessfulBuild(); if(ulb==null) { // if no usable build is available from the upstream, // then we have to wait at least until this build is ready if(debug) listener.getLogger().println(" -> No, because another upstream "+up+" for "+down+" has no successful build"); trigger = false; break; } // if no record of the relationship in the last build // is available, we'll just have to assume that the condition // for the new build is met, or else no build will be fired forever. if(dlb==null) continue; int n = dlb.getUpstreamRelationship(up); if(n==-1) continue; assert ulb.getNumber()>=n; if(ulb.getNumber()==n) { // there's no new build of this upstream since the last build // of the downstream, and the upstream build is in progress. // The new downstream build should wait until this build is started AbstractProject bup = getBuildingUpstream(graph, up); if(bup!=null) { if(debug) listener.getLogger().println(" -> No, because another upstream "+bup+" for "+down+" is building"); trigger = false; break; } } } if(trigger) { listener.getLogger().println("Triggering a new build of "+down.getName()); down.scheduleBuild(); } } } } /** * Returns the project if any of the upstream project (or itself) is either * building or is in the queue. * <p> * This means eventually there will be an automatic triggering of * the given project (provided that all builds went smoothly.) */ private AbstractProject getBuildingUpstream(DependencyGraph graph, AbstractProject project) { Set<AbstractProject> tups = graph.getTransitiveUpstream(project); tups.add(project); for (AbstractProject tup : tups) { if(tup!=getProject() && (tup.isBuilding() || tup.isInQueue())) return tup; } return null; } } /** * If not 0, launch Maven with a debugger port. */ public static int debugPort; private static final int MAX_PROCESS_CACHE = 5; static { String port = System.getProperty(MavenBuild.class.getName() + ".debugPort"); if(port!=null) debugPort = Integer.parseInt(port); } private static final ProcessCache mavenProcessCache = new ProcessCache(MAX_PROCESS_CACHE); /** * Used by selected {@link MavenReporter}s to notify the maven build agent * that even though Maven is going to fail, we should report the build as * success. * * <p> * This rather ugly hook is necessary to mark builds as unstable, since * maven considers a test failure to be a build failure, which will otherwise * mark the build as FAILED. * * <p> * It's OK for this field to be static, because the JVM where this is actually * used is in the Maven JVM, so only one build is going on for the whole JVM. * * <p> * Even though this field is public, please consider this field reserved * for {@link SurefireArchiver}. Subject to change without notice. */ public static boolean markAsSuccess; private static final FilenameFilter CLASSWORLDS_FILTER = new FilenameFilter() { public boolean accept(File dir, String name) { return name.startsWith("classworlds") && name.endsWith(".jar"); } }; /** * Set true to produce debug output. */ public static boolean debug = false; }
package com.yahoo.vespa.hosted.controller.deployment; import ai.vespa.validation.Validation; import com.yahoo.vespa.hosted.controller.api.integration.deployment.ApplicationVersion; import com.yahoo.vespa.hosted.controller.api.integration.deployment.JobId; import com.yahoo.vespa.hosted.controller.api.integration.deployment.RevisionId; import java.util.ArrayDeque; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Deque; import java.util.List; import java.util.Map; import java.util.NavigableMap; import java.util.Optional; import java.util.OptionalLong; import java.util.TreeMap; import static ai.vespa.validation.Validation.require; import static java.util.Collections.emptyNavigableMap; import static java.util.stream.Collectors.toList; /** * History of application revisions for an {@link com.yahoo.vespa.hosted.controller.Application}. * * @author jonmv */ public class RevisionHistory { private static final Comparator<JobId> comparator = Comparator.comparing(JobId::application).thenComparing(JobId::type); private final NavigableMap<RevisionId, ApplicationVersion> production; private final NavigableMap<JobId, NavigableMap<RevisionId, ApplicationVersion>> development; private RevisionHistory(NavigableMap<RevisionId, ApplicationVersion> production, NavigableMap<JobId, NavigableMap<RevisionId, ApplicationVersion>> development) { this.production = production; this.development = development; } public static RevisionHistory empty() { return ofRevisions(List.of(), Map.of()); } public static RevisionHistory ofRevisions(Collection<ApplicationVersion> productionRevisions, Map<JobId, ? extends Collection<ApplicationVersion>> developmentRevisions) { NavigableMap<RevisionId, ApplicationVersion> production = new TreeMap<>(); for (ApplicationVersion revision : productionRevisions) production.put(revision.id(), revision); NavigableMap<JobId, NavigableMap<RevisionId, ApplicationVersion>> development = new TreeMap<>(comparator); developmentRevisions.forEach((job, jobRevisions) -> { NavigableMap<RevisionId, ApplicationVersion> revisions = development.computeIfAbsent(job, __ -> new TreeMap<>()); for (ApplicationVersion revision : jobRevisions) revisions.put(revision.id(), revision); }); return new RevisionHistory(production, development); } /** Returns a copy of this without any production revisions older than the given. */ public RevisionHistory withoutOlderThan(RevisionId id) { if (production.headMap(id).isEmpty()) return this; return new RevisionHistory(production.tailMap(id, true), development); } /** Returns a copy of this without any development revisions older than the given. */ public RevisionHistory withoutOlderThan(RevisionId id, JobId job) { if ( ! development.containsKey(job) || development.get(job).headMap(id).isEmpty()) return this; NavigableMap<JobId, NavigableMap<RevisionId, ApplicationVersion>> development = new TreeMap<>(this.development); development.compute(job, (__, revisions) -> revisions.tailMap(id, true)); return new RevisionHistory(production, development); } /** Returns a copy of this with the revision added or updated. */ public RevisionHistory with(ApplicationVersion revision) { if (revision.id().isProduction()) { if ( ! production.isEmpty() && revision.bundleHash().flatMap(hash -> production.lastEntry().getValue().bundleHash().map(hash::equals)).orElse(false)) revision = revision.skipped(); NavigableMap<RevisionId, ApplicationVersion> production = new TreeMap<>(this.production); production.put(revision.id(), revision); return new RevisionHistory(production, development); } else { NavigableMap<JobId, NavigableMap<RevisionId, ApplicationVersion>> development = new TreeMap<>(this.development); NavigableMap<RevisionId, ApplicationVersion> revisions = development.compute(revision.id().job(), (__, old) -> new TreeMap<>(old != null ? old : emptyNavigableMap())); if ( ! revisions.isEmpty()) revisions.compute(revisions.lastKey(), (__, last) -> last.withoutPackage()); revisions.put(revision.id(), revision); return new RevisionHistory(production, development); } } // Fallback for when an application version isn't known for the given key. private static ApplicationVersion revisionOf(RevisionId id) { return new ApplicationVersion(id, Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), false, false, Optional.empty(), 0); } /** Returns the production {@link ApplicationVersion} with this revision ID. */ public ApplicationVersion get(RevisionId id) { return id.isProduction() ? production.getOrDefault(id, revisionOf(id)) : development.getOrDefault(id.job(), emptyNavigableMap()) .getOrDefault(id, revisionOf(id)); } /** Returns the last submitted production build. */ public Optional<ApplicationVersion> last() { return Optional.ofNullable(production.lastEntry()).map(Map.Entry::getValue); } /** Returns all known production revisions we still have the package for, from oldest to newest. */ public List<ApplicationVersion> withPackage() { return production.values().stream() .filter(ApplicationVersion::hasPackage) .collect(toList()); } /** Returns the currently deployable revisions of the application. */ public Deque<ApplicationVersion> deployable(boolean ascending) { Deque<ApplicationVersion> versions = new ArrayDeque<>(); for (ApplicationVersion version : withPackage()) { if (version.isDeployable()) { if (ascending) versions.addLast(version); else versions.addFirst(version); } } return versions; } /** All known production revisions, in ascending order. */ public List<ApplicationVersion> production() { return List.copyOf(production.values()); } /* All known development revisions, in ascending order, per job. */ public NavigableMap<JobId, List<ApplicationVersion>> development() { NavigableMap<JobId, List<ApplicationVersion>> copy = new TreeMap<>(comparator); development.forEach((job, revisions) -> copy.put(job, List.copyOf(revisions.values()))); return Collections.unmodifiableNavigableMap(copy); } }
// This source code is available under agreement available at // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France package org.talend.components.api.component.runtime; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; import java.net.URLStreamHandlerFactory; import java.util.List; import java.util.Objects; import org.ops4j.pax.url.mvn.MavenResolver; import org.ops4j.pax.url.mvn.MavenResolvers; import org.ops4j.pax.url.mvn.ServiceConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.talend.daikon.runtime.RuntimeInfo; import org.talend.daikon.sandbox.SandboxControl; import sun.misc.Unsafe; /** * create a {@link RuntimeInfo} that will look for a given jar and will look for a dependency.txt file inside this jar * given the maven groupId and artifactID to find the right path to the file. */ public class JarRuntimeInfo implements RuntimeInfo, SandboxControl { private static final Logger LOG = LoggerFactory.getLogger(JarRuntimeInfo.class); private final String runtimeClassName; private final URL jarUrl; private final String depTxtPath; private final boolean reusable; static { try { new URL("mvn:foo/bar"); } catch (MalformedURLException e) { // handles mvn local repository String mvnLocalRepo = System.getProperty("maven.repo.local"); if (mvnLocalRepo != null && !mvnLocalRepo.isEmpty()) { System.setProperty("org.ops4j.pax.url.mvn.localRepository", mvnLocalRepo); } try { Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe"); theUnsafe.setAccessible(true); Unsafe unsafe = (Unsafe) theUnsafe.get(null); Class clazz = Class.forName("jdk.internal.module.IllegalAccessLogger"); Field logger = clazz.getDeclaredField("logger"); unsafe.putObjectVolatile(clazz, unsafe.staticFieldOffset(logger), null); } catch (Exception ue) { // ignore } // If the URL above failed, the mvn protocol needs to be installed. // not advice create a wrap URLStreamHandlerFactory class now try { final Field factoryField = URL.class.getDeclaredField("factory"); factoryField.setAccessible(true); final Field lockField = URL.class.getDeclaredField("streamHandlerLock"); lockField.setAccessible(true); synchronized (lockField.get(null)) { final URLStreamHandlerFactory factory = (URLStreamHandlerFactory) factoryField.get(null); // avoid the factory already defined error if (factory == null) { URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() { @Override public URLStreamHandler createURLStreamHandler(String protocol) { if (!ServiceConstants.PROTOCOL.equals(protocol)) { return null; } return new URLStreamHandler() { @Override public URLConnection openConnection(URL url) throws IOException { MavenResolver resolver = MavenResolvers.createMavenResolver(null, ServiceConstants.PID); // java11 adds #runtime spec for (classloader) resource loading and breaks pax Connection conn = new Connection(new URL(url.toExternalForm().replace("#runtime", "")), resolver); conn.setUseCaches(false); return conn; } @Override protected void parseURL(URL u, String spec, int start, int limit) { if (!"mvn:".equals(u.toString())) {// remove the spec to only return the url. LOG.debug("ignoring specs for parseUrl with url[" + u + "] and spec[" + spec + "]"); super.parseURL(u, "", 0, 0); } else {// simple url being "mvn:" and the rest is specs. super.parseURL(u, spec, start, limit); } } }; } }); } } } catch (Exception exception) { LOG.warn(exception.getMessage()); } } if (System.getProperty("sun.boot.class.path") == null) { // j11 workaround due to daikon System.setProperty("sun.boot.class.path", System.getProperty("java.class.path")); } } private static class Connection extends URLConnection { // forked cause not exposed through OSGi meta private static final Logger LOG = LoggerFactory.getLogger(Connection.class); private final MavenResolver resolver; private Connection(final URL url, final MavenResolver resolver) { super( url ); this.resolver = resolver; } @Override public void connect() { // do nothing } @Override public InputStream getInputStream() throws IOException { connect(); LOG.debug( "Resolving [" + url.toExternalForm() + "]" ); return new FileInputStream(resolver.resolve(url.toExternalForm())); } } /** * uses the <code>mavenGroupId</code> <code>mavenArtifactId</code> to locate the *dependency.txt* file using the * rule defined in {@link DependenciesReader#computeDependenciesFilePath} * * @param jarUrl url of the jar to read the dependency.txt from * @param depTxtPath, path used to locate the dependency.txt file * @param runtimeClassName class to be instantiated */ public JarRuntimeInfo(URL jarUrl, String depTxtPath, String runtimeClassName) { this(jarUrl, depTxtPath, runtimeClassName, SandboxControl.CLASSLOADER_REUSABLE); } /** * uses the <code>mavenGroupId</code> <code>mavenArtifactId</code> to locate the *dependency.txt* file using the * rule defined in {@link DependenciesReader#computeDependenciesFilePath} * * @param jarUrl url of the jar to read the dependency.txt from * @param depTxtPath, path used to locate the dependency.txt file * @param runtimeClassName class to be instantiated * @param reusable whether the ClassLoader for the runtime instance is cacheable and reusable across calls. */ public JarRuntimeInfo(URL jarUrl, String depTxtPath, String runtimeClassName, boolean reusable) { this.jarUrl = jarUrl; this.depTxtPath = depTxtPath; this.runtimeClassName = runtimeClassName; this.reusable = reusable; } /** * uses the <code>mavenGroupId</code> <code>mavenArtifactId</code> to locate the *dependency.txt* file using the * rule defined in {@link DependenciesReader#computeDependenciesFilePath} * * @param jarUrlString url of the jar to read the dependency.txt from * @param depTxtPath, path used to locate the dependency.txt file * @param runtimeClassName class to be instantiated * @throws {@link TalendRuntimeException} if the jarUrlString is malformed */ public JarRuntimeInfo(String jarUrlString, String depTxtPath, String runtimeClassName) { this(createJarUrl(jarUrlString), depTxtPath, runtimeClassName, SandboxControl.CLASSLOADER_REUSABLE); } public JarRuntimeInfo(String jarUrlString, String depTxtPath, String runtimeClassName, URLStreamHandler handler) { this(createJarUrl(jarUrlString, handler), depTxtPath, runtimeClassName, SandboxControl.CLASSLOADER_REUSABLE); } /** * Constructor * * @param jarUrlString URL of the jar to read the dependency.txt from * @param depTxtPath path used to locate the dependency.txt file * @param runtimeClassName class to be instantiated * @param reusable defines whether {@link ClassLoader} should be cached or not * @throws {@link TalendRuntimeException} if the jarUrlString is malformed */ public JarRuntimeInfo(String jarUrlString, String depTxtPath, String runtimeClassName, boolean reusable) { this(createJarUrl(jarUrlString), depTxtPath, runtimeClassName, reusable); } private static URL createJarUrl(String jarUrlString) { try { return new URL(jarUrlString); } catch (MalformedURLException e) { LOG.debug(e.getMessage()); } return null; } private static URL createJarUrl(String jarUrlString, URLStreamHandler handler) { try { return new URL(null, jarUrlString, handler); } catch (MalformedURLException e) { LOG.debug(e.getMessage()); } return null; } public JarRuntimeInfo cloneWithNewJarUrlString(String newJarUrlString) { return new JarRuntimeInfo(newJarUrlString, this.getDepTxtPath(), this.getRuntimeClassName()); } public JarRuntimeInfo cloneWithNewJarUrlString(String newJarUrlString, URLStreamHandler handler) { return new JarRuntimeInfo(newJarUrlString, this.getDepTxtPath(), this.getRuntimeClassName(), handler); } public URL getJarUrl() { return jarUrl; } public String getDepTxtPath() { return depTxtPath; } @Override public List<URL> getMavenUrlDependencies() { return DependenciesReader.extractDepenencies(jarUrl, depTxtPath); } @Override public String getRuntimeClassName() { return runtimeClassName; } @Override public boolean isClassLoaderReusable() { return reusable; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!JarRuntimeInfo.class.isAssignableFrom(obj.getClass())) { return false; } JarRuntimeInfo other = (JarRuntimeInfo) obj; // we assume that 2 list of dependencies are equals if they have the same elements in the same order cause we // are using them // as a classpath in a classloader so the order matters. return this.runtimeClassName.equals(other.runtimeClassName) && getMavenUrlDependencies().equals(other.getMavenUrlDependencies()); } @Override public int hashCode() { return Objects.hash(runtimeClassName, getMavenUrlDependencies()); } @Override public String toString() { return "JarRunTimeInfo: {" + "runtimeClassName:" + runtimeClassName + ", " + "jarUrl: " + jarUrl + ", " + "depTxtPath: " + depTxtPath + "}"; } }
package com.siberia.plugin; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CallbackContext; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.os.Handler; import android.os.Message; import android.util.Log; import android.net.nsd.NsdServiceInfo; import com.siberia.plugin.NsdHelper; public class Discovery extends CordovaPlugin { NsdHelper mNsdHelper; private Handler mHandler; // ChatConnection mConnection; // CallbackContextHandler ccHandler; @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if (action.equals("initChat")) { Log.d(TAG, "initChat"); // this.initChat(callbackContext); } else if (action.equals("advertizeChat")) { Log.d(TAG, "advertizeChat"); // this.advertizeChat(callbackContext); } else if (action.equals("identify")) { Log.d(TAG, "identify"); this.discoverServices(callbackContext); } else if (action.equals("connectChat")) { Log.d(TAG, "connectChat"); // this.connectChat(callbackContext); } else if (action.equals("sendChatMessage")) { Log.d(TAG, "sendChatMessage"); // String messageString = args.getString(0); // this.sendChatMessage(callbackContext, messageString); } else { callbackContext.error(String.format("Discovery - invalid action:", action)); return false; } // PluginResult.Status status = PluginResult.Status.NO_RESULT; // PluginResult pluginResult = new PluginResult(status); // pluginResult.setKeepCallback(true); // callbackContext.sendPluginResult(pluginResult); return true; } // private void initChat(CallbackContext callbackContext) { // final CallbackContext cbc = callbackContext; // try { // mHandler = new Handler() { // @Override // public void handleMessage(Message msg) { // String type = msg.getData().getString("type"); // String message = msg.getData().getString("msg"); // JSONObject data = new JSONObject(); // try { // data.put("type", new String(type)); // data.put("data", new String(message)); // } catch(JSONException e) { // PluginResult result = new PluginResult(PluginResult.Status.OK, data); // result.setKeepCallback(true); // cbc.sendPluginResult(result); // // mConnection = new ChatConnection(ccHandler); // mConnection = new ChatConnection(mHandler); // // mNsdHelper = new NsdHelper(cordova.getActivity(), ccHandler); // mNsdHelper = new NsdHelper(cordova.getActivity(), mHandler); // mNsdHelper.initializeNsd(); // } catch(Exception e) { // callbackContext.error("Error " + e); // private void advertizeChat(CallbackContext callbackContext) { // final CallbackContext cbc = callbackContext; // if(mConnection.getLocalPort() > -1) { // mNsdHelper.registerService(mConnection.getLocalPort()); // } else { // cbc.error("ServerSocket isn't bound."); private void identify(CallbackContext callbackContext) { final CallbackContext cbc = callbackContext; mNsdHelper.discoverServices(); } // private void connectChat(CallbackContext callbackContext) { // final CallbackContext cbc = callbackContext; // NsdServiceInfo service = mNsdHelper.getChosenServiceInfo(); // if (service != null) { // mConnection.connectToServer(service.getHost(), // service.getPort()); // } else { // cbc.error("No service to connect to!"); // private void sendChatMessage(CallbackContext callbackContext, String messageString) { // mConnection.sendMessage(messageString); }
package org.csstudio.platform.model; import org.eclipse.core.runtime.PlatformObject; /** * An abstract superclass for CSS specific model items. The preferred way to * introduce new model items to the platform is to inherit from this class. * * Central control system items (e.g. ProcessVariables) are already defined and * can be created using {@link CentralItemFactory}. * * @author Sven Wende * */ public abstract class AbstractControlSystemItem extends PlatformObject implements IControlSystemItem { /** * The name of the control system item. */ private String _name; /** * Constructor. * * @param name * The name of the control system item. */ public AbstractControlSystemItem(final String name) { assert name != null; _name = name; } /** * {@inheritDoc} */ public final String getName() { return _name; } /** * {@inheritDoc} */ @Override public String toString() { return _name; } }
package net.becvert.cordova; import android.content.Context; import android.net.wifi.WifiManager; import android.os.Build; import android.provider.Settings; import android.text.TextUtils; import android.util.Log; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.apache.cordova.PluginResult; import org.apache.cordova.PluginResult.Status; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import javax.jmdns.JmDNS; import javax.jmdns.ServiceEvent; import javax.jmdns.ServiceInfo; import javax.jmdns.ServiceListener; import static android.content.Context.WIFI_SERVICE; public class ZeroConf extends CordovaPlugin { private static final String TAG = "ZeroConf"; WifiManager.MulticastLock lock; private RegistrationManager registrationManager; private BrowserManager browserManager; private List<InetAddress> addresses; private List<InetAddress> ipv6Addresses; private List<InetAddress> ipv4Addresses; private String hostname; public static final String ACTION_GET_HOSTNAME = "getHostname"; // publisher public static final String ACTION_REGISTER = "register"; public static final String ACTION_UNREGISTER = "unregister"; public static final String ACTION_STOP = "stop"; // browser public static final String ACTION_WATCH = "watch"; public static final String ACTION_UNWATCH = "unwatch"; public static final String ACTION_CLOSE = "close"; // Re-initialize public static final String ACTION_REINIT = "reInit"; @Override public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); Context context = this.cordova.getActivity().getApplicationContext(); WifiManager wifi = (WifiManager) context.getSystemService(WIFI_SERVICE); lock = wifi.createMulticastLock("ZeroConfPluginLock"); lock.setReferenceCounted(false); try { addresses = new CopyOnWriteArrayList<InetAddress>(); ipv6Addresses = new CopyOnWriteArrayList<InetAddress>(); ipv4Addresses = new CopyOnWriteArrayList<InetAddress>(); List<NetworkInterface> intfs = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface intf : intfs) { if (intf.supportsMulticast()) { List<InetAddress> addrs = Collections.list(intf.getInetAddresses()); for (InetAddress addr : addrs) { if (!addr.isLoopbackAddress()) { if (addr instanceof Inet6Address) { addresses.add(addr); ipv6Addresses.add(addr); } else if (addr instanceof Inet4Address) { addresses.add(addr); ipv4Addresses.add(addr); } } } } } } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } Log.d(TAG, "Addresses " + addresses); try { hostname = getHostName(cordova); } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } Log.d(TAG, "Hostname " + hostname); Log.v(TAG, "Initialized"); } @Override public void onDestroy() { super.onDestroy(); if (registrationManager != null) { try { registrationManager.stop(); } catch (IOException e) { Log.e(TAG, e.getMessage(), e); } finally { registrationManager = null; } } if (browserManager != null) { try { browserManager.close(); } catch (IOException e) { Log.e(TAG, e.getMessage(), e); } finally { browserManager = null; } } if (lock != null) { lock.release(); lock = null; } Log.v(TAG, "Destroyed"); } @Override public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) { if (ACTION_GET_HOSTNAME.equals(action)) { if (hostname != null) { Log.d(TAG, "Hostname: " + hostname); callbackContext.success(hostname); } else { callbackContext.error("Error: undefined hostname"); return false; } } else if (ACTION_REGISTER.equals(action)) { final String type = args.optString(0); final String domain = args.optString(1); final String name = args.optString(2); final int port = args.optInt(3); final JSONObject props = args.optJSONObject(4); final String addressFamily = args.optString(5); Log.d(TAG, "Register " + type + domain); cordova.getThreadPool().execute(new Runnable() { @Override public void run() { try { if (registrationManager == null) { List<InetAddress> selectedAddresses = addresses; if ("ipv6".equalsIgnoreCase(addressFamily)) { selectedAddresses = ipv6Addresses; } else if ("ipv4".equalsIgnoreCase(addressFamily)) { selectedAddresses = ipv4Addresses; } registrationManager = new RegistrationManager(selectedAddresses, hostname); } ServiceInfo service = registrationManager.register(type, domain, name, port, props); if (service == null) { callbackContext.error("Failed to register"); return; } JSONObject status = new JSONObject(); status.put("action", "registered"); status.put("service", jsonifyService(service)); Log.d(TAG, "Sending result: " + status.toString()); PluginResult result = new PluginResult(PluginResult.Status.OK, status); callbackContext.sendPluginResult(result); } catch (JSONException e) { Log.e(TAG, e.getMessage(), e); callbackContext.error("Error: " + e.getMessage()); } catch (IOException e) { Log.e(TAG, e.getMessage(), e); callbackContext.error("Error: " + e.getMessage()); } catch (RuntimeException e) { Log.e(TAG, e.getMessage(), e); callbackContext.error("Error: " + e.getMessage()); } } }); } else if (ACTION_UNREGISTER.equals(action)) { final String type = args.optString(0); final String domain = args.optString(1); final String name = args.optString(2); Log.d(TAG, "Unregister " + type + domain); if (registrationManager != null) { final RegistrationManager rm = registrationManager; cordova.getThreadPool().execute(new Runnable() { @Override public void run() { rm.unregister(type, domain, name); callbackContext.success(); } }); } else { callbackContext.success(); } } else if (ACTION_STOP.equals(action)) { Log.d(TAG, "Stop"); if (registrationManager != null) { final RegistrationManager rm = registrationManager; registrationManager = null; cordova.getThreadPool().execute(new Runnable() { @Override public void run() { try { rm.stop(); callbackContext.success(); } catch (IOException e) { Log.e(TAG, e.getMessage(), e); callbackContext.error("Error: " + e.getMessage()); } } }); } else { callbackContext.success(); } } else if (ACTION_WATCH.equals(action)) { final String type = args.optString(0); final String domain = args.optString(1); final String addressFamily = args.optString(2); Log.d(TAG, "Watch " + type + domain); cordova.getThreadPool().execute(new Runnable() { @Override public void run() { try { if (browserManager == null) { List<InetAddress> selectedAddresses = addresses; if ("ipv6".equalsIgnoreCase(addressFamily)) { selectedAddresses = ipv6Addresses; } else if ("ipv4".equalsIgnoreCase(addressFamily)) { selectedAddresses = ipv4Addresses; } browserManager = new BrowserManager(selectedAddresses, hostname); } browserManager.watch(type, domain, callbackContext); } catch (IOException e) { Log.e(TAG, e.getMessage(), e); callbackContext.error("Error: " + e.getMessage()); } catch (RuntimeException e) { Log.e(TAG, e.getMessage(), e); callbackContext.error("Error: " + e.getMessage()); } } }); PluginResult result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); callbackContext.sendPluginResult(result); } else if (ACTION_UNWATCH.equals(action)) { final String type = args.optString(0); final String domain = args.optString(1); Log.d(TAG, "Unwatch " + type + domain); if (browserManager != null) { final BrowserManager bm = browserManager; cordova.getThreadPool().execute(new Runnable() { @Override public void run() { bm.unwatch(type, domain); callbackContext.success(); } }); } else { callbackContext.success(); } } else if (ACTION_CLOSE.equals(action)) { Log.d(TAG, "Close"); if (browserManager != null) { final BrowserManager bm = browserManager; browserManager = null; cordova.getThreadPool().execute(new Runnable() { @Override public void run() { try { bm.close(); callbackContext.success(); } catch (IOException e) { Log.e(TAG, e.getMessage(), e); callbackContext.error("Error: " + e.getMessage()); } } }); } else { callbackContext.success(); } } else if (ACTION_REINIT.equals(action)) { Log.e(TAG, "Re-Initializing"); cordova.getThreadPool().execute(new Runnable() { @Override public void run() { onDestroy(); initialize(cordova, webView); callbackContext.success(); Log.e(TAG, "Re-Initialization complete"); } }); } else { Log.e(TAG, "Invalid action: " + action); callbackContext.error("Invalid action: " + action); return false; } return true; } private class RegistrationManager { private List<JmDNS> publishers = new ArrayList<JmDNS>(); public RegistrationManager(List<InetAddress> addresses, String hostname) throws IOException { if (addresses == null || addresses.size() == 0) { publishers.add(JmDNS.create(null, hostname)); } else { for (InetAddress addr : addresses) { publishers.add(JmDNS.create(addr, hostname)); } } } public ServiceInfo register(String type, String domain, String name, int port, JSONObject props) throws JSONException, IOException { HashMap<String, String> txtRecord = new HashMap<String, String>(); if (props != null) { Iterator<String> iter = props.keys(); while (iter.hasNext()) { String key = iter.next(); txtRecord.put(key, props.getString(key)); } } ServiceInfo aService = null; for (JmDNS publisher : publishers) { ServiceInfo service = ServiceInfo.create(type + domain, name, port, 0, 0, txtRecord); try { publisher.registerService(service); aService = service; } catch (IOException e) { Log.e(TAG, e.getMessage(), e); } } // returns only one of the ServiceInfo instances! return aService; } public void unregister(String type, String domain, String name) { for (JmDNS publisher : publishers) { ServiceInfo serviceInfo = publisher.getServiceInfo(type + domain, name, 5000); if (serviceInfo != null) { publisher.unregisterService(serviceInfo); } } } public void stop() throws IOException { for (JmDNS publisher : publishers) { publisher.close(); } } } private class BrowserManager implements ServiceListener { private List<JmDNS> browsers = new ArrayList<JmDNS>(); private Map<String, CallbackContext> callbacks = new HashMap<String, CallbackContext>(); public BrowserManager(List<InetAddress> addresses, String hostname) throws IOException { lock.acquire(); if (addresses == null || addresses.size() == 0) { browsers.add(JmDNS.create(null, hostname)); } else { for (InetAddress addr : addresses) { browsers.add(JmDNS.create(addr, hostname)); } } } private void watch(String type, String domain, CallbackContext callbackContext) { callbacks.put(type + domain, callbackContext); for (JmDNS browser : browsers) { browser.addServiceListener(type + domain, this); } } private void unwatch(String type, String domain) { callbacks.remove(type + domain); for (JmDNS browser : browsers) { browser.removeServiceListener(type + domain, this); } } private void close() throws IOException { lock.release(); callbacks.clear(); for (JmDNS browser : browsers) { browser.close(); } } @Override public void serviceResolved(ServiceEvent ev) { Log.d(TAG, "Resolved"); sendCallback("resolved", ev.getInfo()); } @Override public void serviceRemoved(ServiceEvent ev) { Log.d(TAG, "Removed"); sendCallback("removed", ev.getInfo()); } @Override public void serviceAdded(ServiceEvent ev) { Log.d(TAG, "Added"); sendCallback("added", ev.getInfo()); } public void sendCallback(String action, ServiceInfo service) { CallbackContext callbackContext = callbacks.get(service.getType()); if (callbackContext == null) { return; } JSONObject status = new JSONObject(); try { status.put("action", action); status.put("service", jsonifyService(service)); Log.d(TAG, "Sending result: " + status.toString()); PluginResult result = new PluginResult(PluginResult.Status.OK, status); result.setKeepCallback(true); callbackContext.sendPluginResult(result); } catch (JSONException e) { Log.e(TAG, e.getMessage(), e); callbackContext.error("Error: " + e.getMessage()); } } } private static JSONObject jsonifyService(ServiceInfo service) throws JSONException { JSONObject obj = new JSONObject(); String domain = service.getDomain() + "."; obj.put("domain", domain); obj.put("type", service.getType().replace(domain, "")); obj.put("name", service.getName()); obj.put("port", service.getPort()); obj.put("hostname", service.getServer()); JSONArray ipv4Addresses = new JSONArray(); InetAddress[] inet4Addresses = service.getInet4Addresses(); for (int i = 0; i < inet4Addresses.length; i++) { if (inet4Addresses[i] != null) { ipv4Addresses.put(inet4Addresses[i].getHostAddress()); } } obj.put("ipv4Addresses", ipv4Addresses); JSONArray ipv6Addresses = new JSONArray(); InetAddress[] inet6Addresses = service.getInet6Addresses(); for (int i = 0; i < inet6Addresses.length; i++) { if (inet6Addresses[i] != null) { ipv6Addresses.put(inet6Addresses[i].getHostAddress()); } } obj.put("ipv6Addresses", ipv6Addresses); JSONObject props = new JSONObject(); Enumeration<String> names = service.getPropertyNames(); while (names.hasMoreElements()) { String name = names.nextElement(); props.put(name, service.getPropertyString(name)); } obj.put("txtRecord", props); return obj; } public static String getHostName(CordovaInterface cordova) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Method getString = Build.class.getDeclaredMethod("getString", String.class); getString.setAccessible(true); String hostName = getString.invoke(null, "net.hostname").toString(); if (TextUtils.isEmpty(hostName) || hostName == "unknown") { // API 26+ : // Querying the net.hostname system property produces a null result String id = Settings.Secure.getString(cordova.getActivity().getContentResolver(), Settings.Secure.ANDROID_ID); hostName = "android-" + id; } return hostName; } }
// Triple Play - utilities for use in PlayN-based games package tripleplay.util; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Random; import java.util.RandomAccess; /** * Provides utility routines to simplify obtaining randomized values. */ public class Randoms { /** * A factory to create a new Randoms object. */ public static Randoms with (Random rand) { return new Randoms(rand); } public int getInt (int high) { return _r.nextInt(high); } public int getInRange (int low, int high) { return low + _r.nextInt(high - low); } /** * Returns a pseudorandom, uniformly distributed <code>float</code> value between * <code>0.0</code> (inclusive) and the <code>high</code> (exclusive). * * @param high the high value limiting the random number sought. */ public float getFloat (float high) { return _r.nextFloat() * high; } /** * Returns a pseudorandom, uniformly distributed <code>float</code> value between * <code>low</code> (inclusive) and <code>high</code> (exclusive). */ public float getInRange (float low, float high) { return low + (_r.nextFloat() * (high - low)); } public boolean getChance (int n) { return (0 == _r.nextInt(n)); } /** * Has a probability <code>p</code> of returning true. */ public boolean getProbability (float p) { return _r.nextFloat() < p; } /** * Returns <code>true</code> or <code>false</code> with approximately even probability. */ public boolean getBoolean () { return _r.nextBoolean(); } /** * Returns a pseudorandom, normally distributed <code>float</code> value around the * <code>mean</code> with the standard deviation <code>dev</code>. */ public float getNormal (float mean, float dev) { return (float)_r.nextGaussian() * dev + mean; } /** * Shuffle the specified list using our Random. */ public <T> void shuffle (List<T> list) { // we can't use Collections.shuffle here because GWT doesn't implement it int size = list.size(); if (list instanceof RandomAccess) { for (int ii = size; ii > 1; ii swap(list, ii-1, _r.nextInt(ii)); } } else { Object[] array = list.toArray(); for (int ii = size; ii > 1; ii swap(array, ii-1, _r.nextInt(ii)); } ListIterator<T> it = list.listIterator(); for (int ii = 0; ii < size; ii++) { it.next(); @SuppressWarnings("unchecked") T elem = (T)array[ii]; it.set(elem); } } } /** * Pick a random element from the specified Iterator, or return <code>ifEmpty</code> * if it is empty. * * <p><b>Implementation note:</b> because the total size of the Iterator is not known, * the random number generator is queried after the second element and every element * thereafter. * * @throws NullPointerException if the iterator is null. */ public <T> T pick (Iterator<? extends T> iterator, T ifEmpty) { if (!iterator.hasNext()) { return ifEmpty; } T pick = iterator.next(); for (int count = 2; iterator.hasNext(); count++) { T next = iterator.next(); if (0 == _r.nextInt(count)) { pick = next; } } return pick; } /** * Pick a random element from the specified Iterable, or return <code>ifEmpty</code> * if it is empty. * * <p><b>Implementation note:</b> optimized implementations are used if the Iterable * is a List or Collection. Otherwise, it behaves as if calling {@link #pick(Iterator, Object)} * with the Iterable's Iterator. * * @throws NullPointerException if the iterable is null. */ public <T> T pick (Iterable<? extends T> iterable, T ifEmpty) { return pickPluck(iterable, ifEmpty, false); } public <T> T pick (Map<? extends T, ? extends Number> weightMap, T ifEmpty) { T pick = ifEmpty; double total = 0.0; for (Map.Entry<? extends T, ? extends Number> entry : weightMap.entrySet()) { double weight = entry.getValue().doubleValue(); if (weight > 0.0) { total += weight; if ((total == weight) || ((_r.nextDouble() * total) < weight)) { pick = entry.getKey(); } } else if (weight < 0.0) { throw new IllegalArgumentException("Weight less than 0: " + entry); } // else: weight == 0.0 is OK } return pick; } /** * Pluck (remove) a random element from the specified Iterable, or return <code>ifEmpty</code> * if it is empty. * * <p><b>Implementation note:</b> optimized implementations are used if the Iterable * is a List or Collection. Otherwise, two Iterators are created from the Iterable * and a random number is generated after the second element and all beyond. * * @throws NullPointerException if the iterable is null. * @throws UnsupportedOperationException if the iterable is unmodifiable or its Iterator * does not support {@link Iterator#remove()}. */ public <T> T pluck (Iterable<? extends T> iterable, T ifEmpty) { return pickPluck(iterable, ifEmpty, true); } /** * Construct a Randoms. */ protected Randoms (Random rand) { _r = rand; } /** * Shared code for pick and pluck. */ protected <T> T pickPluck (Iterable<? extends T> iterable, T ifEmpty, boolean remove) { if (iterable instanceof Collection) { // optimized path for Collection @SuppressWarnings("unchecked") Collection<? extends T> coll = (Collection<? extends T>)iterable; int size = coll.size(); if (size == 0) { return ifEmpty; } if (coll instanceof List) { // extra-special optimized path for Lists @SuppressWarnings("unchecked") List<? extends T> list = (List<? extends T>)coll; int idx = _r.nextInt(size); if (remove) { // ternary conditional causes warning here with javac 1.6, :( return list.remove(idx); } return list.get(idx); } // for other Collections, we must iterate Iterator<? extends T> it = coll.iterator(); for (int idx = _r.nextInt(size); idx > 0; idx it.next(); } try { return it.next(); } finally { if (remove) { it.remove(); } } } if (!remove) { return pick(iterable.iterator(), ifEmpty); } // from here on out, we're doing a pluck with a complicated two-iterator solution Iterator<? extends T> it = iterable.iterator(); if (!it.hasNext()) { return ifEmpty; } Iterator<? extends T> lagIt = iterable.iterator(); T pick = it.next(); lagIt.next(); for (int count = 2, lag = 1; it.hasNext(); count++, lag++) { T next = it.next(); if (0 == _r.nextInt(count)) { pick = next; // catch up lagIt so that it has just returned 'pick' as well for ( ; lag > 0; lag lagIt.next(); } } } lagIt.remove(); // remove 'pick' from the lagging iterator return pick; } /** Helper for {@link #shuffle}. */ protected static <T> void swap (List<T> list, int ii, int jj) { list.set(ii, list.set(jj, list.get(ii))); } /** Helper for {@link #shuffle}. */ protected static void swap (Object[] array, int ii, int jj) { Object tmp = array[ii]; array[ii] = array[jj]; array[jj] = tmp; } /** The random number generator. */ protected final Random _r; }
package som.interpreter.objectstorage; import java.lang.reflect.Field; import som.compiler.MixinDefinition.SlotDefinition; import som.interpreter.TruffleCompiler; import som.interpreter.objectstorage.FieldAccess.AbstractFieldRead; import som.interpreter.objectstorage.FieldAccess.ReadObjectFieldNode; import som.interpreter.objectstorage.FieldAccess.ReadSetDoubleFieldNode; import som.interpreter.objectstorage.FieldAccess.ReadSetLongFieldNode; import som.interpreter.objectstorage.FieldAccess.ReadSetOrUnsetDoubleFieldNode; import som.interpreter.objectstorage.FieldAccess.ReadSetOrUnsetLongFieldNode; import som.interpreter.objectstorage.FieldAccess.ReadUnwrittenFieldNode; import som.vm.constants.Nil; import som.vmobjects.SObject; import sun.misc.Unsafe; import com.oracle.truffle.api.CompilerAsserts; import com.oracle.truffle.api.profiles.IntValueProfile; public abstract class StorageLocation { private static Unsafe loadUnsafe() { try { return Unsafe.getUnsafe(); } catch (SecurityException e) { // can fail, is ok, just to the fallback below } try { Field theUnsafeInstance = Unsafe.class.getDeclaredField("theUnsafe"); theUnsafeInstance.setAccessible(true); return (Unsafe) theUnsafeInstance.get(Unsafe.class); } catch (Exception e) { throw new RuntimeException("exception while trying to get Unsafe.theUnsafe via reflection:", e); } } private static final Unsafe unsafe = loadUnsafe(); public static long getFieldOffset(final Field field) { return unsafe.objectFieldOffset(field); } public interface LongStorageLocation { boolean isSet(SObject obj, IntValueProfile primMarkProfile); void markAsSet(SObject obj); long readLongSet(final SObject obj); void writeLongSet(final SObject obj, final long value); } public interface DoubleStorageLocation { boolean isSet(SObject obj, IntValueProfile primMarkProfile); void markAsSet(SObject obj); double readDoubleSet(final SObject obj); void writeDoubleSet(final SObject obj, final double value); } public static StorageLocation createForLong(final ObjectLayout layout, final SlotDefinition slot, final int primFieldIndex) { if (primFieldIndex < SObject.NUM_PRIMITIVE_FIELDS) { return new LongDirectStoreLocation(layout, slot, primFieldIndex); } else { return new LongArrayStoreLocation(layout, slot, primFieldIndex); } } public static StorageLocation createForDouble(final ObjectLayout layout, final SlotDefinition slot, final int primFieldIndex) { if (primFieldIndex < SObject.NUM_PRIMITIVE_FIELDS) { return new DoubleDirectStoreLocation(layout, slot, primFieldIndex); } else { return new DoubleArrayStoreLocation(layout, slot, primFieldIndex); } } public static StorageLocation createForObject(final ObjectLayout layout, final SlotDefinition slot, final int objFieldIndex) { if (objFieldIndex < SObject.NUM_PRIMITIVE_FIELDS) { return new ObjectDirectStorageLocation(layout, slot, objFieldIndex); } else { return new ObjectArrayStorageLocation(layout, slot, objFieldIndex); } } protected final ObjectLayout layout; protected final SlotDefinition slot; protected StorageLocation(final ObjectLayout layout, final SlotDefinition slot) { this.layout = layout; this.slot = slot; } public abstract boolean isSet(SObject obj, IntValueProfile primMarkProfile); /** * @return true, if it is an object location, false otherwise. */ public abstract boolean isObjectLocation(); public abstract Object read(SObject obj); public abstract void write(SObject obj, Object value); public abstract AbstractFieldRead getReadNode(boolean isSet); public static final class UnwrittenStorageLocation extends StorageLocation { public UnwrittenStorageLocation(final ObjectLayout layout, final SlotDefinition slot) { super(layout, slot); } @Override public boolean isSet(final SObject obj, final IntValueProfile primMarkProfile) { return false; } @Override public boolean isObjectLocation() { return false; } @Override public Object read(final SObject obj) { CompilerAsserts.neverPartOfCompilation("StorageLocation"); return Nil.nilObject; } @Override public void write(final SObject obj, final Object value) { CompilerAsserts.neverPartOfCompilation("StorageLocation"); obj.writeUninitializedSlot(slot, value); } @Override public AbstractFieldRead getReadNode(final boolean isSet) { return new ReadUnwrittenFieldNode(slot); } } public abstract static class AbstractObjectStorageLocation extends StorageLocation { public AbstractObjectStorageLocation(final ObjectLayout layout, final SlotDefinition slot) { super(layout, slot); } @Override public final boolean isObjectLocation() { return true; } @Override public final AbstractFieldRead getReadNode(final boolean isSet) { return new ReadObjectFieldNode(slot, layout); } } public static final class ObjectDirectStorageLocation extends AbstractObjectStorageLocation { private final long fieldOffset; public ObjectDirectStorageLocation(final ObjectLayout layout, final SlotDefinition slot, final int objFieldIdx) { super(layout, slot); fieldOffset = SObject.getObjectFieldOffset(objFieldIdx); } @Override public boolean isSet(final SObject obj, final IntValueProfile primMarkProfile) { assert read(obj) != null; return true; } @Override public Object read(final SObject obj) { return unsafe.getObject(obj, fieldOffset); } @Override public void write(final SObject obj, final Object value) { assert value != null; unsafe.putObject(obj, fieldOffset, value); } } public static final class ObjectArrayStorageLocation extends AbstractObjectStorageLocation { private final int extensionIndex; public ObjectArrayStorageLocation(final ObjectLayout layout, final SlotDefinition slot, final int objFieldIdx) { super(layout, slot); extensionIndex = objFieldIdx - SObject.NUM_OBJECT_FIELDS; } @Override public boolean isSet(final SObject obj, final IntValueProfile primMarkProfile) { assert read(obj) != null; return true; } @Override public Object read(final SObject obj) { Object[] arr = obj.getExtensionObjFields(); return arr[extensionIndex]; } @Override public void write(final SObject obj, final Object value) { assert value != null; Object[] arr = obj.getExtensionObjFields(); arr[extensionIndex] = value; } } public abstract static class PrimitiveStorageLocation extends StorageLocation { protected final int mask; protected PrimitiveStorageLocation(final ObjectLayout layout, final SlotDefinition slot, final int primField) { super(layout, slot); mask = SObject.getPrimitiveFieldMask(primField); } @Override public final boolean isSet(final SObject obj, final IntValueProfile primMarkProfile) { return obj.isPrimitiveSet(mask, primMarkProfile); } @Override public final boolean isObjectLocation() { return false; } public final void markAsSet(final SObject obj) { obj.markPrimAsSet(mask); } } public abstract static class PrimitiveDirectStoreLocation extends PrimitiveStorageLocation { protected final long offset; public PrimitiveDirectStoreLocation(final ObjectLayout layout, final SlotDefinition slot, final int primField) { super(layout, slot, primField); offset = SObject.getPrimitiveFieldOffset(primField); } } public static final class DoubleDirectStoreLocation extends PrimitiveDirectStoreLocation implements DoubleStorageLocation { private final IntValueProfile primMarkProfile = IntValueProfile.createIdentityProfile(); public DoubleDirectStoreLocation(final ObjectLayout layout, final SlotDefinition slot, final int primField) { super(layout, slot, primField); } @Override public Object read(final SObject obj) { if (isSet(obj, primMarkProfile)) { return readDoubleSet(obj); } else { return Nil.nilObject; } } @Override public double readDoubleSet(final SObject obj) { return unsafe.getDouble(obj, offset); } @Override public void write(final SObject obj, final Object value) { assert layout.isValid(); assert layout == obj.getObjectLayout(); assert value != null; if (value instanceof Double) { writeDoubleSet(obj, (double) value); markAsSet(obj); } else { TruffleCompiler.transferToInterpreterAndInvalidate("unstabelized read node"); assert value != Nil.nilObject; obj.writeAndGeneralizeSlot(slot, value); } } @Override public void writeDoubleSet(final SObject obj, final double value) { unsafe.putDouble(obj, offset, value); } @Override public AbstractFieldRead getReadNode(final boolean isSet) { if (isSet) { return new ReadSetDoubleFieldNode(slot, layout); } else { return new ReadSetOrUnsetDoubleFieldNode(slot, layout); } } } public static final class LongDirectStoreLocation extends PrimitiveDirectStoreLocation implements LongStorageLocation { private final IntValueProfile primMarkProfile = IntValueProfile.createIdentityProfile(); public LongDirectStoreLocation(final ObjectLayout layout, final SlotDefinition slot, final int primField) { super(layout, slot, primField); } @Override public Object read(final SObject obj) { if (isSet(obj, primMarkProfile)) { return readLongSet(obj); } else { return Nil.nilObject; } } @Override public long readLongSet(final SObject obj) { return unsafe.getLong(obj, offset); } @Override public void write(final SObject obj, final Object value) { assert value != null; if (value instanceof Long) { writeLongSet(obj, (long) value); markAsSet(obj); } else { TruffleCompiler.transferToInterpreterAndInvalidate("unstabelized write node"); obj.writeAndGeneralizeSlot(slot, value); } } @Override public void writeLongSet(final SObject obj, final long value) { unsafe.putLong(obj, offset, value); } @Override public AbstractFieldRead getReadNode(final boolean isSet) { if (isSet) { return new ReadSetLongFieldNode(slot, layout); } else { return new ReadSetOrUnsetLongFieldNode(slot, layout); } } } public abstract static class PrimitiveArrayStoreLocation extends PrimitiveStorageLocation { protected final int extensionIndex; public PrimitiveArrayStoreLocation(final ObjectLayout layout, final SlotDefinition slot, final int primField) { super(layout, slot, primField); extensionIndex = primField - SObject.NUM_PRIMITIVE_FIELDS; assert extensionIndex >= 0; } } public static final class LongArrayStoreLocation extends PrimitiveArrayStoreLocation implements LongStorageLocation { private final IntValueProfile primMarkProfile = IntValueProfile.createIdentityProfile(); public LongArrayStoreLocation(final ObjectLayout layout, final SlotDefinition slot, final int primField) { super(layout, slot, primField); } @Override public Object read(final SObject obj) { if (isSet(obj, primMarkProfile)) { return readLongSet(obj); } else { return Nil.nilObject; } } @Override public long readLongSet(final SObject obj) { return obj.getExtendedPrimFields()[extensionIndex]; } @Override public void write(final SObject obj, final Object value) { assert value != null; if (value instanceof Long) { writeLongSet(obj, (long) value); markAsSet(obj); } else { TruffleCompiler.transferToInterpreterAndInvalidate("unstabelized write node"); assert value != Nil.nilObject; obj.writeAndGeneralizeSlot(slot, value); } } @Override public void writeLongSet(final SObject obj, final long value) { obj.getExtendedPrimFields()[extensionIndex] = value; } @Override public AbstractFieldRead getReadNode(final boolean isSet) { if (isSet) { return new ReadSetLongFieldNode(slot, layout); } else { return new ReadSetOrUnsetLongFieldNode(slot, layout); } } } public static final class DoubleArrayStoreLocation extends PrimitiveArrayStoreLocation implements DoubleStorageLocation { public DoubleArrayStoreLocation(final ObjectLayout layout, final SlotDefinition slot, final int primField) { super(layout, slot, primField); } private final IntValueProfile primMarkProfile = IntValueProfile.createIdentityProfile(); @Override public Object read(final SObject obj) { if (isSet(obj, primMarkProfile)) { return readDoubleSet(obj); } else { return Nil.nilObject; } } @Override public double readDoubleSet(final SObject obj) { long[] arr = obj.getExtendedPrimFields(); return unsafe.getDouble(arr, (long) Unsafe.ARRAY_DOUBLE_BASE_OFFSET + Unsafe.ARRAY_DOUBLE_INDEX_SCALE * extensionIndex); } @Override public void write(final SObject obj, final Object value) { assert value != null; if (value instanceof Double) { writeDoubleSet(obj, (double) value); markAsSet(obj); } else { TruffleCompiler.transferToInterpreterAndInvalidate("unstabelized write node"); assert value != Nil.nilObject; obj.writeAndGeneralizeSlot(slot, value); } } @Override public void writeDoubleSet(final SObject obj, final double value) { final long[] arr = obj.getExtendedPrimFields(); unsafe.putDouble(arr, (long) Unsafe.ARRAY_DOUBLE_BASE_OFFSET + Unsafe.ARRAY_DOUBLE_INDEX_SCALE * this.extensionIndex, value); } @Override public AbstractFieldRead getReadNode(final boolean isSet) { if (isSet) { return new ReadSetDoubleFieldNode(slot, layout); } else { return new ReadSetOrUnsetDoubleFieldNode(slot, layout); } } } }
package com.javadude.observer; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.WindowConstants; public class ButtonExample { public static void main(String[] args) { JFrame frame = new JFrame(); JButton button = new JButton("Press Me"); frame.add(button); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("Button was pressed!"); }}); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } }
package net.plastboks.gameworld; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.math.Intersector; import com.badlogic.gdx.math.Rectangle; import net.plastboks.gameobjects.Bird; import net.plastboks.gameobjects.Mouse; import net.plastboks.gameobjects.Snake; import net.plastboks.screens.GameScreen; import net.plastboks.sneikhelpers.AssetLoader; public class GameWorld { private Snake snake; private Bird bird; private Mouse mouse; private Rectangle ground; private int score = 0; private int midPointY; public enum GameState { READY, RUNNING, GAMEOVER, HIGHSCORE } private GameState currentState; public GameWorld(int midPointY) { this.midPointY = midPointY; currentState = GameState.READY; snake = new Snake(33, midPointY - 5, 15, 15, midPointY * 2); bird = new Bird(15, 15); mouse = new Mouse(15, 15); ground = new Rectangle(0, midPointY + 66, GameScreen.GAME_WIDTH, 11); } public void update(float delta) { switch (currentState) { case READY: updateReady(delta); break; case RUNNING: updateRunning(delta); break; default: break; } } public void updateReady(float delta) { } public void updateRunning(float delta) { if (delta > .15f) { delta = .15f; } snake.update(delta); bird.update(delta); mouse.update(delta); if (snake.collides(bird)) { Gdx.app.log("bird: ", "nom nom"); bird.respawn(); } if (snake.collides(mouse)) { Gdx.app.log("mouse: ", "nom nom"); mouse.respawn(); } //sh.update(delta); //if (snake.isAlive()) { // snake.die(); // AssetLoader.dead.play(); /* if (Intersector.overlaps(snake.getBoundingCircle(), ground)) { snake.die(); currentState = GameState.GAMEOVER; if (score > AssetLoader.getHighScore()) { AssetLoader.setHighScore(score); currentState = GameState.HIGHSCORE; } } */ } public void restart() { currentState = GameState.READY; score = 0; snake.onRestart(midPointY - 5); currentState = GameState.READY; } public void addScore(int inc) { score += inc; } public void start() { currentState = GameState.RUNNING; } public Snake getSnake() { return snake; } public Bird getBird() { return bird; } public Mouse getMouse() { return mouse; } public int getScore() { return score; } public boolean isReady() { return currentState == GameState.READY; } public boolean isGameOver() { return currentState == GameState.GAMEOVER; } public boolean isHighScore() { return currentState == GameState.HIGHSCORE; } }
package kodkod.engine.fol2sat; import static kodkod.engine.bool.Operator.AND; import kodkod.engine.bool.BooleanFormula; import kodkod.engine.bool.BooleanVariable; import kodkod.engine.bool.BooleanVisitor; import kodkod.engine.bool.ITEGate; import kodkod.engine.bool.MultiGate; import kodkod.engine.bool.NotGate; import kodkod.engine.satlab.SATFactory; import kodkod.engine.satlab.SATSolver; import kodkod.util.ints.IntSet; import kodkod.util.ints.Ints; /** * Transforms a boolean circuit into a formula in conjunctive * normal form. * * @author Emina Torlak */ final class Bool2CNFTranslator implements BooleanVisitor<int[], Object> { /** * Creates a new instance of SATSolver using the provided factory * and uses it to translate the given circuit into conjunctive normal form * using the <i>definitional translation algorithm</i>. * The third parameter is required to contain the number of primary variables * allocated during translation from FOL to booelan. * @return a SATSolver instance returned by the given factory and initialized * to contain the CNF translation of the given circuit. */ static SATSolver translate(BooleanFormula circuit, SATFactory factory, int numPrimaryVariables) { final SATSolver solver = factory.instance(); final Bool2CNFTranslator translator = new Bool2CNFTranslator(solver, numPrimaryVariables, circuit); solver.addClause(circuit.accept(translator,null)); return solver; } /** * Helper visitor that performs <i> definitional translation to cnf </i>. * @specfield root: BooleanFormula // the translated circuit */ private final SATSolver solver; private final IntSet visited; private final PolarityDetector pdetector; private final int[] unaryClause = new int[1]; private final int[] binaryClause = new int[2]; private final int[] ternaryClause = new int[3]; /** * Constructs a translator for the given circuit. * @effects this.root' = circuit */ private Bool2CNFTranslator(SATSolver solver, int numPrimaryVars, BooleanFormula circuit) { final int maxLiteral = StrictMath.abs(circuit.label()); this.solver = solver; this.solver.addVariables(StrictMath.max(numPrimaryVars, maxLiteral)); this.pdetector = (new PolarityDetector(numPrimaryVars, maxLiteral)).apply(circuit); this.visited = Ints.bestSet(pdetector.offset, StrictMath.max(pdetector.offset, maxLiteral)); } public int[] visit(MultiGate multigate, Object arg) { final int oLit = multigate.label(); if (visited.add(oLit)) { final int sgn; final boolean p, n; if (multigate.op()==AND) { sgn = 1; p = pdetector.positive(oLit); n = pdetector.negative(oLit); } else { // multigate.op()==OR sgn = -1; n = pdetector.positive(oLit); p = pdetector.negative(oLit); } final int[] lastClause = n ? new int[multigate.size()+1] : null; final int output = oLit * -sgn; int i = 0; for(BooleanFormula input : multigate) { int iLit = input.accept(this, arg)[0]; if (p) { binaryClause[0] = iLit * sgn; binaryClause[1] = output; solver.addClause(binaryClause); } if (n) { lastClause[i++] = iLit * -sgn; } } if (n) { lastClause[i] = oLit * sgn; solver.addClause(lastClause); } } unaryClause[0] = oLit; return unaryClause; } public int[] visit(ITEGate itegate, Object arg) { final int oLit = itegate.label(); if (visited.add(oLit)) { final int i = itegate.input(0).accept(this, arg)[0]; final int t = itegate.input(1).accept(this, arg)[0]; final int e = itegate.input(2).accept(this, arg)[0]; final boolean p = pdetector.positive(oLit), n = pdetector.negative(oLit); if (p) { ternaryClause[0] = -i; ternaryClause[1] = t; ternaryClause[2] = -oLit; solver.addClause(ternaryClause); ternaryClause[0] = i; ternaryClause[1] = e; ternaryClause[2] = -oLit; solver.addClause(ternaryClause); // redundant clause that strengthens unit propagation ternaryClause[0] = t; ternaryClause[1] = e; ternaryClause[2] = -oLit; solver.addClause(ternaryClause); } if (n) { ternaryClause[0] = -i; ternaryClause[1] = -t; ternaryClause[2] = oLit; solver.addClause(ternaryClause); ternaryClause[0] = i; ternaryClause[1] = -e; ternaryClause[2] = oLit; solver.addClause(ternaryClause); // redundant clause that strengthens unit propagation ternaryClause[0] = -t; ternaryClause[1] = -e; ternaryClause[2] = oLit; solver.addClause(ternaryClause); } } unaryClause[0] = oLit; return unaryClause; } /** * Returns the negation of the result of visiting negation.input, wrapped in * an array. * @return o: int[] | o.length = 1 && o[0] = - translate(negation.inputs)[0] * */ public int[] visit(NotGate negation, Object arg) { final int[] o = negation.input(0).accept(this, arg); assert o.length == 1; o[0] = -o[0]; return o; } /** * Returns the variable's literal wrapped in a an array. * @return o: int[] | o.length = 1 && o[0] = variable.literal */ public int[] visit(BooleanVariable variable, Object arg) { unaryClause[0] = variable.label(); return unaryClause; } /** * Helper visitor that detects pdetector of subformulas. * @specfield root: BooleanFormula // the root of the DAG for whose components we are storing pdetector information */ private static final class PolarityDetector implements BooleanVisitor<Object, Integer> { final int offset; /** * @invariant all i : [0..polarity.length) | * pdetector[i] = 0 <=> formula with label offset + i has not been visited, * pdetector[i] = 1 <=> formula with label offset + i has been visited with positive pdetector only, * pdetector[i] = 2 <=> formula with label offset + i has been visited with negative pdetector only, * pdetector[i] = 3 <=> formula with label offset + i has been visited with both polarities */ private final int[] polarity; private final Integer[] ints = { Integer.valueOf(3), Integer.valueOf(1), Integer.valueOf(2) }; /** * Creates a new pdetector detector and applies it to the given circuit. * @requires maxLiteral = |root.label()| */ PolarityDetector(int numPrimaryVars, int maxLiteral) { this.offset = numPrimaryVars+1; this.polarity = new int[StrictMath.max(0, maxLiteral-numPrimaryVars)]; } /** * Applies this detector to the given formula, and returns this. * @requires this.root = root * @effects this.visit(root) * @return this */ PolarityDetector apply(BooleanFormula root) { root.accept(this, ints[1]); return this; } /** * Returns true if the formula with the given label occurs positively in this.root. * @requires this visitor has been applied to this.root * @requires label in (MultiGate + ITEGate).label * @return true if the formula with the given label occurs positively in this.root. */ boolean positive(int label) { return (polarity[label-offset] & 1) > 0; } /** * Returns true if the formula with the given label occurs negatively in this.root. * @requires this visitor has been applied to this.root * @requires label in (MultiGate + ITEGate).label * @return true if the formula with the given label occurs negatively in this.root. */ boolean negative(int label) { return (polarity[label-offset] & 2) > 0; } /** * Returns true if the given formula has been visited with the specified * pdetector (1 = positive, 2 = negative, 3 = both). Otherwise records the visit and returns false. * @requires formula in (MultiGate + ITEGate) * @requires pdetector in this.ints * @return true if the given formula has been visited with the specified * pdetector. Otherwise records the visit and returns false. */ private boolean visited(BooleanFormula formula, Integer polarity) { final int index = formula.label() - offset; final int value = this.polarity[index]; return (this.polarity[index] = value | polarity) == value; } public Object visit(MultiGate multigate, Integer arg) { if (!visited(multigate, arg)) { for(BooleanFormula input : multigate) { input.accept(this, arg); } } return null; } public Object visit(ITEGate ite, Integer arg) { if (!visited(ite, arg)) { // the condition occurs both positively and negative in an ITE gate ite.input(0).accept(this, ints[0]); ite.input(1).accept(this, arg); ite.input(2).accept(this, arg); } return null; } public Object visit(NotGate negation, Integer arg) { return negation.input(0).accept(this, ints[3-arg]); } public Object visit(BooleanVariable variable, Integer arg) { return null; // nothing to do } } }
package br.com.cronapi.logic; import cronapi.Var; import cronapi.logic.Operations; import java.util.ArrayList; import java.util.List; import org.testng.Assert; import org.testng.annotations.Test; public class OperationsTest { @Test public void checkMethodIsNull() { Assert.assertFalse(Operations.isNull(Var.VAR_EMPTY).getObjectAsBoolean()); Assert.assertTrue(Operations.isNull(null).getObjectAsBoolean()); } @Test public void checkMethodIsNullOrEmpty() { List<Object> list = new ArrayList<>(); list.add(new Object()); Var listVar = Var.valueOf(list); Assert.assertFalse(Operations.isNullOrEmpty(listVar).getObjectAsBoolean()); Assert.assertTrue(Operations.isNullOrEmpty(Var.VAR_EMPTY).getObjectAsBoolean()); Assert.assertTrue(Operations.isNullOrEmpty(null).getObjectAsBoolean()); Assert.assertFalse(Operations.isNullOrEmpty(Var.VAR_ZERO).getObjectAsBoolean()); } @Test public void checkMethodIsEmpty() { List<Object> list = new ArrayList<>(); list.add(new Object()); Var listVar = Var.valueOf(list); Assert.assertFalse(Operations.isEmpty(listVar).getObjectAsBoolean()); Assert.assertTrue(Operations.isEmpty(Var.VAR_EMPTY).getObjectAsBoolean()); Assert.assertFalse(Operations.isEmpty(null).getObjectAsBoolean()); Assert.assertFalse(Operations.isEmpty(Var.VAR_ZERO).getObjectAsBoolean()); } }
package com.levelup.java.guava; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.lang.reflect.Field; import java.util.List; import org.hamcrest.collection.IsIterableContainingInOrder; import org.hamcrest.collection.IsIterableWithSize; import org.junit.Test; import com.google.common.base.Enums; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; public class EnumsExample { enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } @Test public void enums_getfield () { Field field = Enums.getField(Day.FRIDAY); assertTrue(field.isEnumConstant()); } @Test public void enums_getIfPresent () { Optional<Day> friday = Enums.getIfPresent(Day.class, "FRIDAY"); assertEquals(friday.get(), Day.FRIDAY); } @Test public void enums_valueOfFunction () { Function<String, Day> valueOfFunction = Enums.valueOfFunction(Day.class); Day friday = valueOfFunction.apply("FRIDAY"); assertEquals(friday, Day.FRIDAY); } @Test public void transform_string_to_enum () { List<String> days = Lists.newArrayList( "WEDNESDAY", "SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY"); Function<String, Day> valueOfFunction = Enums.valueOfFunction(Day.class); Iterable<Day> daysAsEnums = Iterables.transform(days, valueOfFunction); assertThat(daysAsEnums, IsIterableWithSize.<Day>iterableWithSize(5)); assertThat(daysAsEnums, IsIterableContainingInOrder. <Day>contains( Day.WEDNESDAY, Day.SUNDAY, Day.MONDAY, Day.TUESDAY, Day.WEDNESDAY)); } @Test public void transform_string_to_enum_string_converter () { List<String> days = Lists.newArrayList( "WEDNESDAY", "SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY"); Function<String, Day> valueOfFunction = Enums.stringConverter(Day.class); Iterable<Day> daysAsEnums = Iterables.transform(days, valueOfFunction); assertThat(daysAsEnums, IsIterableWithSize.<Day>iterableWithSize(5)); assertThat(daysAsEnums, IsIterableContainingInOrder. <Day>contains( Day.WEDNESDAY, Day.SUNDAY, Day.MONDAY, Day.TUESDAY, Day.WEDNESDAY)); } }
package com.openfin.desktop; import static org.junit.Assert.assertEquals; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.json.JSONObject; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ApplicationTest { private static Logger logger = LoggerFactory.getLogger(ApplicationTest.class.getName()); private static final String DESKTOP_UUID = ApplicationTest.class.getName(); private static DesktopConnection desktopConnection; @BeforeClass public static void setup() throws Exception { logger.debug("starting"); desktopConnection = TestUtils.setupConnection(DESKTOP_UUID); } @AfterClass public static void teardown() throws Exception { TestUtils.teardownDesktopConnection(desktopConnection); } @Test public void runAndClose() throws Exception { logger.debug("runAndClose"); ApplicationOptions options = TestUtils.getAppOptions(null); Application application = TestUtils.runApplication(options, desktopConnection); // duplicate UUID is not allowed ApplicationOptions options2 = TestUtils.getAppOptions(options.getUUID(), null); CountDownLatch dupLatch = new CountDownLatch(1); Application application2 = new Application(options2, desktopConnection, new AckListener() { @Override public void onSuccess(Ack ack) { } @Override public void onError(Ack ack) { if (ack.getReason().contains("Application with specified UUID already exists")) { dupLatch.countDown(); } } }); dupLatch.await(5, TimeUnit.SECONDS); assertEquals("Duplicate app UUID validation timeout " + options.getUUID(), dupLatch.getCount(), 0); TestUtils.closeApplication(application); } @Test public void runAndTerminate() throws Exception { logger.debug("runAndTerminate"); ApplicationOptions options = TestUtils.getAppOptions(null); Application application = TestUtils.createApplication(options, desktopConnection); CountDownLatch stoppedLatch = new CountDownLatch(1); EventListener listener = new EventListener() { @Override public void eventReceived(ActionEvent actionEvent) { if (actionEvent.getType().equals("closed")) { stoppedLatch.countDown(); } } }; TestUtils.addEventListener(application, "closed", listener); TestUtils.runApplication(application, true); application.terminate(); stoppedLatch.await(5, TimeUnit.SECONDS); assertEquals("Terminate application timeout " + options.getUUID(), stoppedLatch.getCount(), 0); } @Test public void getApplicationManifest() throws Exception { logger.debug("getApplicationManifest"); ApplicationOptions options = TestUtils.getAppOptions(null); Application application = TestUtils.runApplication(options, desktopConnection); CountDownLatch latch = new CountDownLatch(1); application.getManifest(new AckListener() { @Override public void onSuccess(Ack ack) { } @Override public void onError(Ack ack) { logger.debug(ack.getJsonObject().toString()); logger.debug(String.format("Reason reason: %s", ack.getReason())); if (ack.getReason().contains("App not started from manifest")) { latch.countDown(); } } }); latch.await(5, TimeUnit.SECONDS); assertEquals("getApplicationManifest timeout " + options.getUUID(), latch.getCount(), 0); TestUtils.closeApplication(application); } @Test public void restartApplication() throws Exception { ApplicationOptions options = TestUtils.getAppOptions(null); Application application = TestUtils.runApplication(options, desktopConnection); CountDownLatch latch = new CountDownLatch(1); TestUtils.addEventListener(application.getWindow(), "shown", actionEvent -> { if (actionEvent.getType().equals("shown")) { latch.countDown(); } }); application.restart(); latch.await(5, TimeUnit.SECONDS); assertEquals("restartApplication timeout " + options.getUUID(), latch.getCount(), 0); TestUtils.closeApplication(application); } @Test public void runReqestedEventListeners() throws Exception { ApplicationOptions options = TestUtils.getAppOptions(null); Application application = TestUtils.createApplication(options, desktopConnection); CountDownLatch latch = new CountDownLatch(1); TestUtils.addEventListener(application, "run-requested", actionEvent -> { if (actionEvent.getType().equals("run-requested")) { logger.debug(String.format("%s", actionEvent.getEventObject().toString())); latch.countDown(); } }); TestUtils.runApplication(application, true); // run-requested is generated when Application.run is called on an active application application.run(); latch.await(5, TimeUnit.SECONDS); assertEquals("run-requested timeout " + options.getUUID(), latch.getCount(), 0); TestUtils.closeApplication(application); } @Test public void createChildWindow() throws Exception { Application application = TestUtils.runApplication(TestUtils.getAppOptions(null), desktopConnection); WindowOptions childOptions = TestUtils.getWindowOptions("child1", TestUtils.openfin_app_url); // use same URL as main app Window childWindow = TestUtils.createChildWindow(application, childOptions, desktopConnection); TestUtils.closeApplication(application); } @Test public void crossAppDockAndUndock() throws Exception { Application application1 = TestUtils.runApplication(TestUtils.getAppOptions(null), desktopConnection); Application application2 = TestUtils.runApplication(TestUtils.getAppOptions(null), desktopConnection); WindowBounds beforeMoveBounds = TestUtils.getBounds(application2.getWindow()); CountDownLatch joinLatch = new CountDownLatch(1); application2.getWindow().joinGroup(application1.getWindow(), new AckListener() { @Override public void onSuccess(Ack ack) { if (ack.isSuccessful()) { joinLatch.countDown(); } } @Override public void onError(Ack ack) { logger.error(String.format("onError %s", ack.getReason())); } }); joinLatch.await(3, TimeUnit.SECONDS); assertEquals(joinLatch.getCount(), 0); // get group info for a window CountDownLatch groupInfoLatch = new CountDownLatch(2); application1.getWindow().getGroup(result -> { for (Window window : result) { if (window.getUuid().equals(application1.getWindow().getUuid()) && window.getName().equals(application1.getWindow().getName())) { groupInfoLatch.countDown(); } else if (window.getUuid().equals(application2.getWindow().getUuid()) && window.getName().equals(application2.getWindow().getName())) { groupInfoLatch.countDown(); } } }, new AckListener() { @Override public void onSuccess(Ack ack) { } @Override public void onError(Ack ack) { logger.error(String.format("onError %s", ack.getReason())); } }); groupInfoLatch.await(3, TimeUnit.SECONDS); assertEquals(groupInfoLatch.getCount(), 0); // get group info for an application CountDownLatch appGroupInfoLatch = new CountDownLatch(2); application1.getGroups(result -> { for (List<Window> list: result) { for (Window window : list) { if (window.getUuid().equals(application1.getWindow().getUuid()) && window.getName().equals(application1.getWindow().getName())) { appGroupInfoLatch.countDown(); } else if (window.getUuid().equals(application2.getWindow().getUuid()) && window.getName().equals(application2.getWindow().getName())) { appGroupInfoLatch.countDown(); } } } }, new AckListener() { @Override public void onSuccess(Ack ack) { } @Override public void onError(Ack ack) { logger.error(String.format("onError %s", ack.getReason())); } } ); appGroupInfoLatch.await(3, TimeUnit.SECONDS); assertEquals(appGroupInfoLatch.getCount(), 0); int leftBy = 20, topBy = 30; TestUtils.moveWindowBy(application1.getWindow(), leftBy, topBy); // child window sohuld move with main window since they are docked WindowBounds afterMoveBounds = TestUtils.getBounds(application2.getWindow()); int topAfterDockMove = afterMoveBounds.getTop(), leftAfterDockMove = afterMoveBounds.getLeft(); assertEquals(afterMoveBounds.getTop() - beforeMoveBounds.getTop(), topBy); assertEquals(afterMoveBounds.getLeft() - beforeMoveBounds.getLeft(), leftBy); // undock by leaving the group CountDownLatch undockLatch = new CountDownLatch(1); application2.getWindow().leaveGroup(new AckListener() { @Override public void onSuccess(Ack ack) { if (ack.isSuccessful()) { undockLatch.countDown(); } } @Override public void onError(Ack ack) { logger.error(String.format("onError %s", ack.getReason())); } }); undockLatch.await(5, TimeUnit.SECONDS); assertEquals(undockLatch.getCount(), 0); TestUtils.moveWindowBy(application1.getWindow(), leftBy, topBy); // child window should not move afer leaving group afterMoveBounds = TestUtils.getBounds(application2.getWindow()); assertEquals(afterMoveBounds.getLeft().intValue(), leftAfterDockMove); assertEquals(afterMoveBounds.getTop().intValue(), topAfterDockMove); TestUtils.closeApplication(application1); TestUtils.closeApplication(application2); } @Test public void addEventListener() throws Exception { ApplicationOptions options = TestUtils.getAppOptions(null); Application application = TestUtils.createApplication(options, desktopConnection); CountDownLatch latch = new CountDownLatch(1); application.addEventListener("started", event -> { latch.countDown(); }, new AckListener() { @Override public void onSuccess(Ack ack) { } @Override public void onError(Ack ack) { } }); application.run(new AckListener() { @Override public void onSuccess(Ack ack) { } @Override public void onError(Ack ack) { } }); latch.await(5, TimeUnit.SECONDS); assertEquals("eventListener test timeout", 0, latch.getCount()); TestUtils.closeApplication(application); } @Test public void getWindow() throws Exception { ApplicationOptions options = TestUtils.getAppOptions(null); String mainWindowName = options.getName(); Application application = TestUtils.createApplication(options, desktopConnection); TestUtils.runApplication(application, true); Window window = application.getWindow(); assertEquals(window.getName(), mainWindowName); TestUtils.closeApplication(application); } @Test public void removeEventListener() throws Exception { ApplicationOptions options = TestUtils.getAppOptions(null); Application application = TestUtils.createApplication(options, desktopConnection); int cnt = 10; CountDownLatch latch = new CountDownLatch(cnt); AtomicInteger invokeCnt = new AtomicInteger(0); EventListener[] listeners = new EventListener[cnt]; for (int i=0; i<cnt; i++) { listeners[i] = new EventListener(){ @Override public void eventReceived(ActionEvent actionEvent) { invokeCnt.incrementAndGet(); latch.countDown(); } }; } for (int i=0; i<cnt; i++) { TestUtils.addEventListener(application, "window-closed", listeners[i]); } TestUtils.runApplication(application, true); for (int i=0; i<cnt/2; i++) { application.removeEventListener("window-closed", listeners[i*2], null); } Window window = application.getWindow(); window.close(); latch.await(5, TimeUnit.SECONDS); assertEquals(cnt/2, latch.getCount()); assertEquals(cnt/2, invokeCnt.get()); } @Test public void createFromManifest() throws Exception { final CountDownLatch latch = new CountDownLatch(1); Application.createFromManifest( "https://demoappdirectory.openf.in/desktop/config/apps/OpenFin/HelloOpenFin/app.json", new AsyncCallback<Application>() { @Override public void onSuccess(Application app) { latch.countDown(); } }, new AckListener() { @Override public void onSuccess(Ack ack) { } @Override public void onError(Ack ack) { logger.info("error creating app: {}", ack.getReason()); } }, desktopConnection); latch.await(10, TimeUnit.SECONDS); assertEquals(0, latch.getCount()); } @Test public void getChildWindows() throws Exception { final int cnt = 5; Application application = TestUtils.runApplication(TestUtils.getAppOptions(null), desktopConnection); for (int i=0; i<cnt; i++) { WindowOptions childOptions = TestUtils.getWindowOptions("childWindow_" + i, TestUtils.openfin_app_url); TestUtils.createChildWindow(application, childOptions, desktopConnection); } final CountDownLatch latch = new CountDownLatch(1); final AtomicInteger winCnt = new AtomicInteger(0); application.getChildWindows( new AsyncCallback<List<Window>>() { @Override public void onSuccess(List<Window> windows) { for (Window w : windows) { try { w.close(); winCnt.incrementAndGet(); } catch (DesktopException e) { e.printStackTrace(); } } latch.countDown(); } }, new AckListener() { @Override public void onSuccess(Ack ack) { } @Override public void onError(Ack ack) { logger.info("error getting child windows: {}", ack.getReason()); } }); latch.await(10, TimeUnit.SECONDS); assertEquals(0, latch.getCount()); assertEquals(cnt, winCnt.get()); } @Test public void getInfo() throws Exception { Application application = TestUtils.runApplication(TestUtils.getAppOptions(null), desktopConnection); final CountDownLatch latch = new CountDownLatch(1); application.getInfo( new AsyncCallback<JSONObject>() { @Override public void onSuccess(JSONObject obj) { logger.info("getInfo: {}", obj.toString()); latch.countDown(); } }, new AckListener() { @Override public void onSuccess(Ack ack) { } @Override public void onError(Ack ack) { logger.info("error getting application info: {}", ack.getReason()); } }); latch.await(5, TimeUnit.SECONDS); assertEquals(0, latch.getCount()); } @Test public void getParentUuid() throws Exception { Application application = TestUtils.runApplication(TestUtils.getAppOptions(null), desktopConnection); final CountDownLatch latch = new CountDownLatch(1); application.getParentUuid( new AsyncCallback<String>() { @Override public void onSuccess(String uuid) { logger.info("getParentUuid: {}", uuid); latch.countDown(); } }, new AckListener() { @Override public void onSuccess(Ack ack) { } @Override public void onError(Ack ack) { logger.info("error getting uuid of parent application: {}", ack.getReason()); } }); latch.await(5, TimeUnit.SECONDS); assertEquals(0, latch.getCount()); } @Test public void getTrayIconInfo() throws Exception { Application application = TestUtils.runApplication(TestUtils.getAppOptions(null), desktopConnection); final CountDownLatch latch = new CountDownLatch(1); application.setTrayIcon( "http://icons.iconarchive.com/icons/marcus-roberto/google-play/512/Google-Search-icon.png", null, new AckListener() { @Override public void onSuccess(Ack ack) { application.getTrayIconInfo( new AsyncCallback<JSONObject>() { @Override public void onSuccess(JSONObject obj) { logger.info("getTrayIconInfo: {}", obj.toString()); latch.countDown(); } }, new AckListener() { @Override public void onSuccess(Ack ack) { } @Override public void onError(Ack ack) { logger.info("error getting tray icon info: {}", ack.getReason()); } }); } @Override public void onError(Ack ack) { } }); latch.await(5, TimeUnit.SECONDS); assertEquals(0, latch.getCount()); } @Test public void isRunning() throws Exception { Application application = TestUtils.runApplication(TestUtils.getAppOptions(null), desktopConnection); final CountDownLatch latch = new CountDownLatch(1); application.isRunning( new AsyncCallback<Boolean>() { @Override public void onSuccess(Boolean running) { logger.info("isRunning: {}", running); latch.countDown(); } }, new AckListener() { @Override public void onSuccess(Ack ack) { } @Override public void onError(Ack ack) { logger.info("error getting application running status: {}", ack.getReason()); } }); latch.await(5, TimeUnit.SECONDS); assertEquals(0, latch.getCount()); } @Test public void registerUser() throws Exception { Application application = TestUtils.runApplication(TestUtils.getAppOptions(null), desktopConnection); final CountDownLatch latch = new CountDownLatch(1); application.registerUser("MyUser", "MyApp", new AckListener() { @Override public void onSuccess(Ack ack) { logger.info("registered custom data"); latch.countDown(); } @Override public void onError(Ack ack) { logger.info("error registering user: {}", ack.getReason()); } }); latch.await(5, TimeUnit.SECONDS); assertEquals(0, latch.getCount()); } @Test public void errorStack() throws Exception { Application application = TestUtils.runApplication(TestUtils.getAppOptions(null), desktopConnection); final CountDownLatch latch = new CountDownLatch(1); application.close(true, new AckListener() { @Override public void onSuccess(Ack ack) { application.getChildWindows(new AsyncCallback<List<Window>>() { @Override public void onSuccess(List<Window> result) { } }, new AckListener() { @Override public void onSuccess(Ack ack) { } @Override public void onError(Ack ack) { if (ack.getErrorStack() != null) { latch.countDown(); } } }); } @Override public void onError(Ack ack) { } }); latch.await(5, TimeUnit.SECONDS); assertEquals(0, latch.getCount()); } }
package com.suse.salt.netapi.examples; import com.suse.salt.netapi.AuthModule; import com.suse.salt.netapi.calls.modules.Grains; import com.suse.salt.netapi.calls.modules.Test; import com.suse.salt.netapi.client.SaltClient; import com.suse.salt.netapi.datatypes.target.Glob; import com.suse.salt.netapi.datatypes.target.MinionList; import com.suse.salt.netapi.datatypes.target.Target; import com.suse.salt.netapi.exception.SaltException; import com.suse.salt.netapi.results.Result; import java.net.URI; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * Example code calling salt modules using the generic interface. */ public class Calls { private static final String SALT_API_URL = "http://localhost:8000"; private static final String USER = "saltdev"; private static final String PASSWORD = "saltdev"; public static void main(String[] args) throws SaltException { // Init the client SaltClient client = new SaltClient(URI.create(SALT_API_URL)); // Ping all minions using a glob matcher Target<String> globTarget = new Glob("*"); Map<String, Result<Boolean>> results = Test.ping().callSync( client, globTarget, USER, PASSWORD, AuthModule.AUTO); System.out.println("--> Ping results:\n"); results.forEach((minion, result) -> System.out.println(minion + " -> " + result)); // Get the grains from a list of minions Target<List<String>> minionList = new MinionList("minion1", "minion2"); // An empty result is returned for targeted minions that are down or minionList // entries that do not match actual targets. Map<String, Result<Map<String, Object>>> grainResults = Grains.items(false) .callSync(client, minionList, USER, PASSWORD, AuthModule.AUTO); grainResults.forEach((minion, grains) -> { System.out.println("\n--> Listing grains for '" + minion + "':\n"); String grainsOutput = grains.fold( error -> "Error: " + error.toString(), grainsMap -> grainsMap.entrySet().stream() .map(e -> e.getKey() + ": " + e.getValue()) .collect(Collectors.joining("\n")) ); System.out.println(grainsOutput); }); } }
package com.wizzardo.http.filter; import com.wizzardo.http.Filter; import com.wizzardo.http.ServerTest; import com.wizzardo.http.request.Request; import com.wizzardo.http.response.Response; import org.junit.Assert; import org.junit.Test; import java.io.IOException; public class FilterTest extends ServerTest { @Test public void testBasicAuth() throws IOException { handler = (request, response) -> response.setBody("ok"); String user = "user"; String password = "password";
package gov.adlnet.xapi; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Files; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Properties; import java.util.TimeZone; import java.util.UUID; import javax.mail.MessagingException; import org.bouncycastle.util.encoders.Hex; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.google.gson.JsonSyntaxException; import gov.adlnet.xapi.AppTest.ISO8601; import gov.adlnet.xapi.client.StatementClient; import gov.adlnet.xapi.model.Activity; import gov.adlnet.xapi.model.ActivityDefinition; import gov.adlnet.xapi.model.Actor; import gov.adlnet.xapi.model.Agent; import gov.adlnet.xapi.model.Attachment; import gov.adlnet.xapi.model.Context; import gov.adlnet.xapi.model.ContextActivities; import gov.adlnet.xapi.model.InteractionComponent; import gov.adlnet.xapi.model.Statement; import gov.adlnet.xapi.model.StatementReference; import gov.adlnet.xapi.model.StatementResult; import gov.adlnet.xapi.model.Verb; import gov.adlnet.xapi.model.Verbs; import gov.adlnet.xapi.util.AttachmentResult; import gov.adlnet.xapi.util.Base64; import junit.framework.TestCase; public class StatementClientTest extends TestCase { private String STMNT_ID = null; private static final String LRS_URI = "https://lrs.adlnet.gov/xAPI"; private static final String USERNAME = "jXAPI"; private static final String PASSWORD = "password"; private static final String MBOX = "mailto:test@example.com"; private String lrs_uri = null; private String username = null; private String password = null; private String mbox = null; private String activity_id = null; private Agent a = null; private Verb v = null; private StatementClient sc = null; private Statement st = null; @Before public void setUp() throws IOException { Properties p = new Properties(); p.load(new FileReader(new File("../jxapi/src/test/java/config/config.properties"))); lrs_uri = p.getProperty("lrs_uri"); username = p.getProperty("username"); password = p.getProperty("password"); mbox = p.getProperty("mbox"); if (lrs_uri == null || lrs_uri.length() == 0) { lrs_uri = LRS_URI; } if (username == null || username.length() == 0) { username = USERNAME; } if (password == null || password.length() == 0) { password = PASSWORD; } if (mbox == null || mbox.length() == 0) { mbox = MBOX; } sc = new StatementClient(lrs_uri, username, password); a = new Agent(); a.setMbox(mbox); v = new Verb("http://example.com/tested"); activity_id = "http://example.com/" + UUID.randomUUID().toString(); Activity act = new Activity(activity_id); st = new Statement(a, v, act); STMNT_ID = st.getId(); assertTrue(STMNT_ID.length() > 0); assertTrue(sc.putStatement(st, STMNT_ID)); } @After public void tearDown() throws Exception { a = null; v = null; sc = null; st = null; } @Test public void testStatementClientStringStringString() throws IOException { // Happy path StatementClient validArgs = new StatementClient(lrs_uri, username, password); activity_id = "http://example.com/" + UUID.randomUUID().toString(); Activity act = new Activity(activity_id); st = new Statement(a, v, act); String publishedId = validArgs.postStatement(st); assertTrue(publishedId.length() > 0); // With a trailing slash validArgs = new StatementClient(lrs_uri + "/", username, password); activity_id = "http://example.com/" + UUID.randomUUID().toString(); act = new Activity(activity_id); st = new Statement(a, v, act); publishedId = validArgs.postStatement(st); assertTrue(publishedId.length() > 0); // Incorrect username StatementClient incorrectUser = new StatementClient(lrs_uri, "username", password); try { activity_id = "http://example.com/" + UUID.randomUUID().toString(); act = new Activity(activity_id); st = new Statement(a, v, act); incorrectUser.postStatement(st); } catch (Exception e) { assertTrue(true); } // Incorrect password StatementClient incorrectPassword = new StatementClient(lrs_uri, username, "passw0rd"); try { activity_id = "http://example.com/" + UUID.randomUUID().toString(); act = new Activity(activity_id); st = new Statement(a, v, act); incorrectPassword.postStatement(st); } catch (Exception e) { assertTrue(true); } // Non URL parameter try { StatementClient incorrectURL = new StatementClient("fail", username, password); } catch (Exception e) { assertTrue(true); } } @Test public void testStatementClientURLStringString() throws IOException { URL lrs_url = new URL(lrs_uri); // Happy path StatementClient validArgs = new StatementClient(lrs_url, username, password); activity_id = "http://example.com/" + UUID.randomUUID().toString(); Activity act = new Activity(activity_id); st = new Statement(a, v, act); String publishedId = validArgs.postStatement(st); assertTrue(publishedId.length() > 0); // Incorrect username StatementClient incorrectUser = new StatementClient(lrs_url, "username", password); try { activity_id = "http://example.com/" + UUID.randomUUID().toString(); act = new Activity(activity_id); st = new Statement(a, v, act); incorrectUser.postStatement(st); } catch (Exception e) { assertTrue(true); } // Incorrect password StatementClient incorrectPassword = new StatementClient(lrs_url, username, "passw0rd"); try { activity_id = "http://example.com/" + UUID.randomUUID().toString(); act = new Activity(activity_id); st = new Statement(a, v, act); incorrectPassword.postStatement(st); } catch (Exception e) { assertTrue(true); } } @Test public void testStatementClientStringString() throws IOException { String encodedCreds = Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP); // Happy path StatementClient validArgs = new StatementClient(lrs_uri, encodedCreds); activity_id = "http://example.com/" + UUID.randomUUID().toString(); Activity act = new Activity(activity_id); st = new Statement(a, v, act); String publishedId = validArgs.postStatement(st); assertTrue(publishedId.length() > 0); // With a trailing slash validArgs = new StatementClient(lrs_uri+"/", encodedCreds); activity_id = "http://example.com/" + UUID.randomUUID().toString(); act = new Activity(activity_id); st = new Statement(a, v, act); publishedId = validArgs.postStatement(st); assertTrue(publishedId.length() > 0); // Incorrect username encodedCreds = Base64.encodeToString(("username" + ":" + password).getBytes(), Base64.NO_WRAP); StatementClient incorrectUser = new StatementClient(lrs_uri, "username", password); try { activity_id = "http://example.com/" + UUID.randomUUID().toString(); act = new Activity(activity_id); st = new Statement(a, v, act); incorrectUser.postStatement(st); } catch (Exception e) { assertTrue(true); } // Incorrect password encodedCreds = Base64.encodeToString((username + ":" + "passw0rd").getBytes(), Base64.NO_WRAP); StatementClient incorrectPassword = new StatementClient(lrs_uri, encodedCreds); try { activity_id = "http://example.com/" + UUID.randomUUID().toString(); act = new Activity(activity_id); st = new Statement(a, v, act); incorrectPassword.postStatement(st); } catch (Exception e) { assertTrue(true); } encodedCreds = Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP); // Non URL parameter try { sc = new StatementClient("fail", encodedCreds); } catch (Exception e) { assertTrue(true); } } @Test public void testStatementClientURLString() throws IOException { URL lrs_url = new URL(lrs_uri); String encodedCreds = Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP); // Happy path StatementClient validArgs = new StatementClient(lrs_url, encodedCreds); activity_id = "http://example.com/" + UUID.randomUUID().toString(); Activity act = new Activity(activity_id); st = new Statement(a, v, act); validArgs.postStatement(st); // Incorrect username encodedCreds = Base64.encodeToString(("username" + ":" + password).getBytes(), Base64.NO_WRAP); StatementClient incorrectUser = new StatementClient(lrs_url, "username", password); try { activity_id = "http://example.com/" + UUID.randomUUID().toString(); act = new Activity(activity_id); st = new Statement(a, v, act); incorrectUser.postStatement(st); } catch (Exception e) { assertTrue(true); } // Incorrect password encodedCreds = Base64.encodeToString((username + ":" + "passw0rd").getBytes(), Base64.NO_WRAP); StatementClient incorrectPassword = new StatementClient(lrs_url, encodedCreds); try { activity_id = "http://example.com/" + UUID.randomUUID().toString(); act = new Activity(activity_id); st = new Statement(a, v, act); incorrectPassword.postStatement(st); } catch (Exception e) { assertTrue(true); } } @Test public void testPostStatement() throws IOException { activity_id = "http://example.com/" + UUID.randomUUID().toString(); Activity act = new Activity(activity_id); st = new Statement(a, v, act); String publishedId = sc.postStatement(st); assertTrue(publishedId.length() > 0); } @Test public void testPutStatement() throws IOException { activity_id = "http://example.com/" + UUID.randomUUID().toString(); Activity act = new Activity(activity_id); st = new Statement(a, v, act); String stmntID = st.getId(); assertTrue(stmntID.length() > 0); assertTrue(sc.putStatement(st, stmntID)); } @Rule public TemporaryFolder testFolder = new TemporaryFolder(); private String generateSha2(byte[] bytes) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(bytes); return new String(Hex.encode(md.digest())); } @Test public void testPostStatementWithAttachment() throws IOException, URISyntaxException, NoSuchAlgorithmException { Agent a = new Agent(); a.setMbox(MBOX); Verb v = new Verb("http://example.com/tested"); Activity act = new Activity(activity_id); Statement statement = new Statement(a, v, act); ActivityDefinition ad = new ActivityDefinition(); ad.setChoices(new ArrayList<InteractionComponent>()); InteractionComponent ic = new InteractionComponent(); ic.setId("http://example.com"); ic.setDescription(new HashMap<String, String>()); ic.getDescription().put("en-US", "test"); ad.getChoices().add(ic); ad.setInteractionType("choice"); ArrayList<String> crp = new ArrayList<String>(); crp.add("http://example.com"); ad.setCorrectResponsesPattern(crp); ad.setMoreInfo("http://example.com"); act.setDefinition(ad); Attachment att = new Attachment(); HashMap<String, String> display = new HashMap<String, String>(); display.put("en-US", "Test Display."); att.setDisplay(display); HashMap<String, String> description = new HashMap<String, String>(); description.put("en-US", "Test Description."); att.setDescription(description); URI usageType = new URI("http://example.com/test/usage"); att.setUsageType(usageType); byte[] arr = "This is a text/plain test.".getBytes("UTF-8"); String contentType = "text/plain"; att.setContentType(contentType); att.setLength(arr.length); att.setSha2(generateSha2(arr)); ArrayList<Attachment> attList = new ArrayList<Attachment>(); attList.add(att); statement.setAttachments(attList); ArrayList<byte[]> attachedData = new ArrayList<byte[]>(); attachedData.add(arr); String publishedId = sc.postStatementWithAttachment(statement, contentType, attachedData); assertTrue(publishedId.length() > 0); } @Test public void testGetStatementsString() throws IOException { StatementResult collection = sc.getStatements(); assertFalse(collection.getStatements().isEmpty()); String more = collection.getMore(); if (!more.isEmpty()) { StatementResult moreCollection = sc.getStatements(more); assertFalse(moreCollection.getStatements().isEmpty()); } } @Test public void testGetStatements() throws IOException { StatementResult returned = sc.getStatements(); assertNotNull(returned); } @Test public void testGetStatementsWithAttachments() throws NoSuchAlgorithmException, IOException, URISyntaxException, JsonSyntaxException, NumberFormatException, MessagingException { Agent a = new Agent(); a.setMbox(MBOX); Verb v = new Verb("http://example.com/tested"); activity_id = "http://example.com/" + UUID.randomUUID().toString(); Activity act = new Activity(activity_id); Statement statement = new Statement(a, v, act); ActivityDefinition ad = new ActivityDefinition(); ad.setChoices(new ArrayList<InteractionComponent>()); InteractionComponent ic = new InteractionComponent(); ic.setId("http://example.com"); ic.setDescription(new HashMap<String, String>()); ic.getDescription().put("en-US", "test"); ad.getChoices().add(ic); ad.setInteractionType("choice"); ArrayList<String> crp = new ArrayList<String>(); crp.add("http://example.com"); ad.setCorrectResponsesPattern(crp); ad.setMoreInfo("http://example.com"); act.setDefinition(ad); Attachment att = new Attachment(); HashMap<String, String> attDis = new HashMap<String, String>(); attDis.put("en-US", "jxapi Test Attachment From File"); att.setDisplay(attDis); URI usageType = new URI("http://example.com/test/usage"); att.setUsageType(usageType); // Test plain text byte[] expectedArray = "This is a text/plain test.".getBytes("UTF-8"); String contentType = "text/plain"; att.setContentType(contentType); att.setLength((int) expectedArray.length); att.setSha2(generateSha2(expectedArray)); String expectedHash = att.getSha2(); // File file1 = new File("/home/randy/Downloads/bueno.bin"); // FileUtils.writeByteArrayToFile(file1, arr); // BufferedImage bf = ImageIO.read( new ByteArrayInputStream(arr)); // ImageIO.write(bf, "jpeg", file1); // bf.flush(); ArrayList<Attachment> attList = new ArrayList<Attachment>(); attList.add(att); statement.setAttachments(attList); ArrayList<byte[]> realAtts = new ArrayList<byte[]>(); realAtts.add(expectedArray); String publishedId = sc.postStatementWithAttachment(statement, contentType, realAtts); assertTrue(publishedId.length() > 0); AttachmentResult attachmntResult = sc.getStatementsWithAttachments(); Statement s = attachmntResult.getXapiStatements().getStatements().get(0); assertTrue(s.getAttachments().get(0).getSha2().contains(att.getSha2())); byte[] actualArray = attachmntResult.getAttachment().get(expectedHash).getAttachment().get(0); assertEquals(new String(expectedArray), new String(actualArray)); activity_id = "http://example.com/" + UUID.randomUUID().toString(); act = new Activity(activity_id); statement = new Statement(a, v, act); // Test image/binary File testFile = new File("/home/randy/Downloads/example.png"); contentType = "image/png"; att.setContentType(contentType); att.setLength((int) testFile.length()); expectedArray = Files.readAllBytes(testFile.toPath()); att.setSha2(generateSha2(expectedArray)); expectedHash = att.getSha2(); attList = null; attList = new ArrayList<Attachment>(); attList.add(att); statement.setAttachments(attList); realAtts = null; realAtts = new ArrayList<byte[]>(); realAtts.add(expectedArray); publishedId = sc.postStatementWithAttachment(statement, contentType, realAtts); assertTrue(publishedId.length() > 0); attachmntResult = sc.getStatementsWithAttachments(); s = attachmntResult.getXapiStatements().getStatements().get(0); assertTrue(s.getAttachments().get(0).getSha2().contains(att.getSha2())); attachmntResult = sc.addFilter("statementId", publishedId).getStatementsWithAttachments(); actualArray = attachmntResult.getAttachment().get(expectedHash).getAttachment().get(0); assertEquals(attachmntResult.getXapiStatement().getAttachments().get(0).getSha2(), expectedHash); assertEquals(new String(expectedArray), new String(actualArray)); } @Test public void testGetStatementsWithAttachmentsString() throws NoSuchAlgorithmException, IOException, URISyntaxException, JsonSyntaxException, NumberFormatException, MessagingException { Agent a = new Agent(); a.setMbox(MBOX); Verb v = new Verb("http://example.com/tested"); Activity act = new Activity(activity_id); Statement statement = new Statement(a, v, act); ActivityDefinition ad = new ActivityDefinition(); ad.setChoices(new ArrayList<InteractionComponent>()); InteractionComponent ic = new InteractionComponent(); ic.setId("http://example.com"); ic.setDescription(new HashMap<String, String>()); ic.getDescription().put("en-US", "test"); ad.getChoices().add(ic); ad.setInteractionType("choice"); ArrayList<String> crp = new ArrayList<String>(); crp.add("http://example.com"); ad.setCorrectResponsesPattern(crp); ad.setMoreInfo("http://example.com"); act.setDefinition(ad); Attachment att = new Attachment(); HashMap<String, String> attDis = new HashMap<String, String>(); attDis.put("en-US", "jxapi Test Attachment From File"); att.setDisplay(attDis); URI usageType = new URI("http://example.com/test/usage"); att.setUsageType(usageType); // Test plain text byte[] expectedArray = "This is a text/plain test.".getBytes("UTF-8"); String contentType = "text/plain"; att.setContentType(contentType); att.setLength((int) expectedArray.length); att.setSha2(generateSha2(expectedArray)); String expectedHash = att.getSha2(); ArrayList<Attachment> attList = new ArrayList<Attachment>(); attList.add(att); statement.setAttachments(attList); ArrayList<byte[]> realAtts = new ArrayList<byte[]>(); realAtts.add(expectedArray); String publishedId = sc.postStatementWithAttachment(statement, contentType, realAtts); assertTrue(publishedId.length() > 0); AttachmentResult attachmntResult = sc.getStatementWithAttachments(publishedId); String id = attachmntResult.getXapiStatement().getId(); assertTrue(id.contains((publishedId))); byte[] actualArray = attachmntResult.getAttachment().get(expectedHash).getAttachment().get(0); assertEquals(attachmntResult.getXapiStatement().getAttachments().get(0).getSha2(), expectedHash); assertEquals(new String(expectedArray), new String(actualArray)); } @Test public void testGetStatement() throws IOException { Statement result = sc.getStatement(STMNT_ID); assertNotNull(result); } @Test public void testGetVoided() throws IOException { String voidedId = UUID.randomUUID().toString(); Agent a = new Agent(); a.setMbox(MBOX); Verb v = new Verb("http://example.com/tested"); Activity act = new Activity(activity_id); Statement st = new Statement(a, v, act); st.setId(voidedId); Boolean put = sc.putStatement(st, voidedId); assertTrue(put); Statement stmt2 = new Statement(a, Verbs.voided(), new StatementReference(voidedId)); String postedId = sc.postStatement(stmt2); assertTrue(postedId.length() > 0); Statement collection = sc.getVoided(voidedId); assertTrue(collection.getId().equals(voidedId)); } @Test public void testAddFilter() throws IOException { String verbId = "http://example.com/tested"; StatementResult result = sc.addFilter("verb", verbId).limitResults(10).getStatements(); assertFalse(result.getStatements().isEmpty()); } @Test public void testFilterByVerbVerb() throws IOException { Verb v = new Verb("http://example.com/tested"); StatementResult result = sc.filterByVerb(v).limitResults(10).getStatements(); assertFalse(result.getStatements().isEmpty()); for (Statement s : result.getStatements()) { assertNotNull(s.getVerb()); assertTrue(s.getVerb().getId().equals(v.getId()) || s.getVerb().getId().equals(Verbs.voided().getId())); } } @Test public void testFilterByVerbString() throws IOException { String v = "http://example.com/tested"; StatementResult result = sc.filterByVerb("http://example.com/tested").limitResults(10).getStatements(); assertFalse(result.getStatements().isEmpty()); for (Statement s : result.getStatements()) { assertNotNull(s.getVerb()); assertTrue(s.getVerb().getId().equals(v) || s.getVerb().getId().equals(Verbs.voided().getId())); } } @Test public void testFilterByActor() throws IOException { Actor a = new Agent(); a.setMbox(MBOX); StatementResult result = sc.filterByActor(a).limitResults(10).getStatements(); assertFalse(result.getStatements().isEmpty()); for (Statement s : result.getStatements()) { assertNotNull(s.getActor()); assertEquals(a.getMbox(), s.getActor().getMbox()); } } @Test public void testFilterByActivity() throws IOException { StatementResult result = sc.filterByActivity(activity_id).getStatements(); assertFalse(result.getStatements().isEmpty()); for (Statement s : result.getStatements()) { assertNotNull(s.getObject()); assertEquals(activity_id, ((Activity) s.getObject()).getId()); } } @Test public void testFilterByRegistration() throws IOException { String reg = UUID.randomUUID().toString(); Agent a = new Agent(); a.setMbox(MBOX); Verb v = new Verb("http://example.com/tested"); Activity act = new Activity(activity_id); Statement statement = new Statement(a, v, act); Context c = new Context(); c.setRegistration(reg); statement.setContext(c); String publishedId = sc.postStatement(statement); assertTrue(publishedId.length() > 0); StatementResult result = sc.filterByRegistration(reg).limitResults(10).getStatements(); assertFalse(result.getStatements().isEmpty()); } @Test public void testIncludeRelatedActivities() throws IOException { Agent a = new Agent(); a.setMbox(MBOX); ArrayList<Activity> arr = new ArrayList<Activity>(); arr.add(new Activity("http://caexample.com")); Context c = new Context(); ContextActivities ca = new ContextActivities(); ca.setCategory(arr); c.setContextActivities(ca); Statement stmt = new Statement(a, Verbs.asked(), new Activity("http://example.com")); stmt.setContext(c); String publishedId = sc.postStatement(stmt); assertTrue(publishedId.length() > 0); StatementResult result = sc.filterByActivity("http://caexample.com").includeRelatedActivities(true) .limitResults(10).exact().getStatements(); assertFalse(result.getStatements().isEmpty()); result = sc.filterByActivity("http://caexample.com").includeRelatedActivities(false).limitResults(10).exact() .getStatements(); assertTrue(result.getStatements().isEmpty()); } @Test public void testIncludeRelatedAgents() throws IOException { Agent a = new Agent(); a.setMbox(MBOX); Agent oa = new Agent(); oa.setMbox("mailto:tester2@example.com"); Statement stmt = new Statement(a, Verbs.asked(), oa); String publishedId = sc.postStatement(stmt); assert publishedId.length() > 0; StatementResult result = sc.filterByActor(oa).includeRelatedAgents(true).limitResults(10).canonical() .getStatements(); assertFalse(result.getStatements().isEmpty()); result = sc.filterByActor(oa).includeRelatedAgents(false).limitResults(10).canonical().getStatements(); assertFalse(result.getStatements().isEmpty()); } @Test public void testFilterBySince() throws IOException { String dateQuery = "2014-05-02T00:00:00Z"; Calendar date = javax.xml.bind.DatatypeConverter.parseDateTime(dateQuery); StatementResult result = sc.filterBySince(dateQuery).limitResults(10).getStatements(); assertFalse(result.getStatements().isEmpty()); for (Statement s : result.getStatements()) { Calendar statementTimestamp = javax.xml.bind.DatatypeConverter.parseDateTime(s.getTimestamp()); // the since date should be less than (denoted by a compareTo value // being less than 0 assertTrue(date.compareTo(statementTimestamp) < 0); } } @Test public void testLimitResults() throws IOException { StatementResult result = sc.limitResults(1).getStatements(); assertFalse(result.getStatements().isEmpty()); assertEquals(result.getStatements().size(), 1); } @Test public void testFilterByUntil() throws IOException { TimeZone tz = TimeZone.getTimeZone("UTC"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); df.setTimeZone(tz); String dateQuery = df.format(new Date()); Calendar date = javax.xml.bind.DatatypeConverter.parseDateTime(dateQuery); StatementResult result = sc.filterByUntil(dateQuery).limitResults(10).getStatements(); assertFalse(result.getStatements().isEmpty()); for (Statement s : result.getStatements()) { Calendar statementTimestamp = javax.xml.bind.DatatypeConverter.parseDateTime(s.getTimestamp()); // the until date should be greater than (denoted by a compareTo // value // being greater than 0 assertTrue(date.compareTo(statementTimestamp) >= 0); } } @Test public void testExact() throws IOException { StatementResult result = sc.exact().getStatements(); assertFalse(result.getStatements().isEmpty()); } @Test public void testIds() throws IOException { StatementResult result = sc.limitResults(10).ids().getStatements(); assertFalse(result.getStatements().isEmpty()); } @Test public void testCanonical() throws IOException { Agent a = new Agent(); a.setMbox("mailto:tester2@example.com"); StatementResult result = sc.filterByActor(a).canonical().getStatements(); assertFalse(result.getStatements().isEmpty()); } @Test public void testAscending() throws IOException, ParseException { // Test ascending StatementResult result = sc.limitResults(10).ascending(true).getStatements(); assertFalse(result.getStatements().isEmpty()); for (int i = 0; i < result.getStatements().size() - 1; i++) { Calendar firstTimestamp = ISO8601.toCalendar(result.getStatements().get(i).getStored()); Calendar secondTimestamp = ISO8601.toCalendar(result.getStatements().get(i + 1).getStored()); assertTrue(firstTimestamp.compareTo(secondTimestamp) < 0 || firstTimestamp.compareTo(secondTimestamp) == 0); } // Test descending result = sc.limitResults(10).ascending(false).getStatements(); assertFalse(result.getStatements().isEmpty()); for (int i = 0; i < result.getStatements().size() - 1; i++) { Calendar firstTimestamp = ISO8601.toCalendar(result.getStatements().get(i).getStored()); Calendar secondTimestamp = ISO8601.toCalendar(result.getStatements().get(i + 1).getStored()); assertTrue(firstTimestamp.compareTo(secondTimestamp) > 0 || firstTimestamp.compareTo(secondTimestamp) == 0); } } }
package liquibase.ext.spatial; import java.sql.SQLException; import org.h2.tools.DeleteDbFiles; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; /** * <code>LiquibaseH2IT</code> is an integration test of Liquibase with H2. */ public class LiquibaseH2IT extends LiquibaseIT { @Override protected String getUrl() { return "jdbc:h2:./target/" + getDatabaseName(); } @BeforeMethod public void beforeMethod() throws SQLException { DeleteDbFiles.execute("./target", getDatabaseName(), true); getConnection().close(); } @AfterMethod public void afterMethod() throws SQLException { DeleteDbFiles.execute("./target", getDatabaseName(), true); } }
package mho.qbar.objects; import mho.qbar.iterableProviders.QBarExhaustiveProvider; import mho.qbar.iterableProviders.QBarIterableProvider; import mho.qbar.iterableProviders.QBarRandomProvider; import mho.qbar.testing.QBarTestProperties; import mho.wheels.iterables.ExhaustiveProvider; import mho.wheels.numberUtils.BigDecimalUtils; import mho.wheels.numberUtils.FloatingPointUtils; import mho.wheels.ordering.Ordering; import mho.wheels.structures.Pair; import mho.wheels.structures.Triple; import org.jetbrains.annotations.NotNull; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import static mho.qbar.objects.Interval.*; import static mho.qbar.objects.Interval.greaterThanOrEqualTo; import static mho.qbar.objects.Interval.lessThanOrEqualTo; import static mho.qbar.objects.Interval.sum; import static mho.qbar.testing.QBarTesting.*; import static mho.qbar.testing.QBarTesting.propertiesCompareToHelper; import static mho.qbar.testing.QBarTesting.propertiesEqualsHelper; import static mho.qbar.testing.QBarTesting.propertiesHashCodeHelper; import static mho.wheels.iterables.IterableUtils.*; import static mho.wheels.ordering.Ordering.*; import static mho.wheels.testing.Testing.*; public class IntervalProperties extends QBarTestProperties { private static final @NotNull String INTERVAL_CHARS = " (),-/0123456789I[]finty"; public IntervalProperties() { super("Interval"); } @Override protected void testBothModes() { propertiesGetLower(); propertiesGetUpper(); propertiesOf_Rational_Rational(); propertiesLessThanOrEqualTo(); propertiesGreaterThanOrEqualTo(); propertiesOf_Rational(); propertiesIsFinitelyBounded(); propertiesContains_Rational(); propertiesContains_Interval(); propertiesDiameter(); propertiesConvexHull_Interval(); propertiesConvexHull_List_Interval(); compareImplementationsConvexHull_List_Interval(); propertiesIntersection(); propertiesDisjoint(); propertiesMakeDisjoint(); // propertiesComplement(); propertiesMidpoint(); propertiesSplit(); propertiesBisect(); propertiesRoundingPreimage_float(); propertiesRoundingPreimage_double(); propertiesRoundingPreimage_BigDecimal(); propertiesFloatRange(); propertiesDoubleRange(); propertiesAdd(); propertiesNegate(); propertiesAbs(); propertiesSignum(); propertiesSubtract(); propertiesMultiply_Interval(); propertiesMultiply_Rational(); propertiesMultiply_BigInteger(); propertiesMultiply_int(); propertiesInvert(); propertiesInvertHull(); propertiesDivide_Interval(); propertiesDivideHull(); propertiesDivide_Rational(); propertiesDivide_BigInteger(); propertiesDivide_int(); propertiesShiftLeft(); compareImplementationsShiftLeft(); propertiesShiftRight(); compareImplementationsShiftRight(); propertiesSum(); propertiesProduct(); propertiesDelta(); propertiesPow(); propertiesPowHull(); propertiesElementCompare(); propertiesEquals(); propertiesHashCode(); propertiesCompareTo(); propertiesRead(); propertiesFindIn(); propertiesToString(); } private void propertiesGetLower() { initialize("getLower()"); for (Interval a : take(LIMIT, P.intervals())) { a.getLower(); } } private void propertiesGetUpper() { initialize("getUpper()"); for (Interval a : take(LIMIT, P.intervals())) { a.getUpper(); } } private void propertiesOf_Rational_Rational() { initialize(""); System.out.println("\t\ttesting of(Rational, Rational) properties..."); Iterable<Pair<Rational, Rational>> ps = filter(q -> le(q.a, q.b), P.pairs(P.rationals())); for (Pair<Rational, Rational> p : take(LIMIT, ps)) { Interval a = of(p.a, p.b); a.validate(); assertTrue(a, a.isFinitelyBounded()); } for (Interval a : take(LIMIT, P.finitelyBoundedIntervals())) { assertEquals(a, of(a.getLower().get(), a.getUpper().get()), a); } } private void propertiesLessThanOrEqualTo() { initialize(""); System.out.println("\t\ttesting lessThanOrEqualTo(Rational) properties..."); for (Rational r : take(LIMIT, P.rationals())) { Interval a = lessThanOrEqualTo(r); a.validate(); assertFalse(a, a.getLower().isPresent()); assertTrue(a, a.getUpper().isPresent()); for (Rational s : take(TINY_LIMIT, P.rationalsIn(a))) { assertTrue(r, le(s, r)); } } } private void propertiesGreaterThanOrEqualTo() { initialize(""); System.out.println("\t\ttesting greaterThanOrEqualTo(Rational) properties..."); for (Rational r : take(LIMIT, P.rationals())) { Interval a = greaterThanOrEqualTo(r); a.validate(); assertTrue(a, a.getLower().isPresent()); assertFalse(a, a.getUpper().isPresent()); for (Rational s : take(TINY_LIMIT, P.rationalsIn(a))) { assertTrue(r, ge(s, r)); } } } private void propertiesOf_Rational() { initialize(""); System.out.println("\t\ttesting of(Rational) properties..."); for (Rational r : take(LIMIT, P.rationals())) { Interval a = of(r); a.validate(); assertTrue(a, a.isFinitelyBounded()); assertEquals(a, a.diameter().get(), Rational.ZERO); } } private void propertiesIsFinitelyBounded() { initialize(""); System.out.println("\t\ttesting isFinitelyBounded() properties..."); for (Interval a : take(LIMIT, P.intervals())) { a.isFinitelyBounded(); } for (Interval a : take(LIMIT, P.finitelyBoundedIntervals())) { assertTrue(a, a.isFinitelyBounded()); } for (Rational r : take(LIMIT, P.rationals())) { assertFalse(r, lessThanOrEqualTo(r).isFinitelyBounded()); assertFalse(r, greaterThanOrEqualTo(r).isFinitelyBounded()); } } private void propertiesContains_Rational() { initialize(""); System.out.println("\t\ttesting contains(Rational) properties..."); for (Pair<Interval, Rational> p : take(LIMIT, P.pairs(P.intervals(), P.rationals()))) { p.a.contains(p.b); } for (Rational r : take(LIMIT, P.rationals())) { assertTrue(r, ALL.contains(r)); assertTrue(r, of(r).contains(r)); } for (Pair<Rational, Rational> p : take(LIMIT, filter(q -> !q.a.equals(q.b), P.pairs(P.rationals())))) { assertFalse(p, of(p.a).contains(p.b)); } } private void propertiesContains_Interval() { initialize(""); System.out.println("\t\ttesting contains(Interval) properties..."); for (Pair<Interval, Interval> p : take(LIMIT, P.pairs(P.intervals()))) { p.a.contains(p.b); } for (Interval a : take(LIMIT, P.intervals())) { assertTrue(a, ALL.contains(a)); assertTrue(a, a.contains(a)); } for (Pair<Interval, Interval> p : take(LIMIT, filter(q -> q.a.contains(q.b), P.pairs(P.intervals())))) { Optional<Rational> ad = p.a.diameter(); Optional<Rational> bd = p.b.diameter(); assertTrue(p, !ad.isPresent() || le(bd.get(), ad.get())); assertTrue(p, p.a.convexHull(p.b).equals(p.a)); } Iterable<Pair<Rational, Interval>> ps = filter( q -> !q.b.equals(of(q.a)), P.pairs(P.rationals(), P.intervals()) ); for (Pair<Rational, Interval> p : take(LIMIT, ps)) { assertFalse(p, of(p.a).contains(p.b)); } } private void propertiesDiameter() { initialize(""); System.out.println("\t\ttesting diameter() properties..."); for (Interval a : take(LIMIT, P.intervals())) { a.diameter(); } for (Interval a : take(LIMIT, P.finitelyBoundedIntervals())) { assertTrue(a, a.diameter().get().signum() != -1); } for (Rational r : take(LIMIT, P.rationals())) { assertFalse(r, lessThanOrEqualTo(r).diameter().isPresent()); assertFalse(r, greaterThanOrEqualTo(r).diameter().isPresent()); } } private void propertiesConvexHull_Interval() { initialize(""); System.out.println("\t\ttesting convexHull(Interval) properties..."); for (Pair<Interval, Interval> p : take(LIMIT, P.pairs(P.intervals()))) { Interval c = p.a.convexHull(p.b); c.validate(); assertEquals(p, c, p.b.convexHull(p.a)); //Given an interval c whose endpoints are in each of two intervals a and b, any Rational in c lies in the //convex hull of a and b for (Pair<Rational, Rational> q : take(TINY_LIMIT, P.pairs(P.rationalsIn(p.a), P.rationalsIn(p.b)))) { for (Rational r : take(TINY_LIMIT, P.rationalsIn(of(min(q.a, q.b), max(q.a, q.b))))) { assertTrue(p, c.contains(r)); } } } for (Pair<Interval, Interval> p : take(LIMIT, P.pairs(P.finitelyBoundedIntervals()))) { Interval c = p.a.convexHull(p.b); assertTrue(p, ge(c.diameter().get(), p.a.diameter().get())); assertTrue(p, ge(c.diameter().get(), p.b.diameter().get())); } for (Interval a : take(LIMIT, P.intervals())) { assertTrue(a, a.convexHull(a).equals(a)); assertTrue(a, ALL.convexHull(a).equals(ALL)); } } private static @NotNull Pair<Rational, Rational> convexHull_List_Interval_alt(@NotNull List<Interval> as) { if (isEmpty(as)) throw new IllegalArgumentException("cannot take convex hull of empty set"); Rational lower = minimum( (x, y) -> { if (x == null) return -1; if (y == null) return 1; return x.compareTo(y); }, map(a -> a.getLower().isPresent() ? a.getLower().get() : null, as) ); Rational upper = maximum( (x, y) -> { if (x == null) return 1; if (y == null) return -1; return x.compareTo(y); }, map(a -> a.getUpper().isPresent() ? a.getUpper().get() : null, as) ); return new Pair<>(lower, upper); } private void propertiesConvexHull_List_Interval() { initialize(""); System.out.println("\t\ttesting convexHull(List<Interval>) properties..."); for (List<Interval> as : take(LIMIT, P.listsAtLeast(1, P.intervals()))) { Interval c = convexHull(as); Pair<Rational, Rational> altC = convexHull_List_Interval_alt(as); Interval alt; if (altC.a == null && altC.b == null) { alt = ALL; } else if (altC.a == null) { alt = lessThanOrEqualTo(altC.b); } else if (altC.b == null) { alt = greaterThanOrEqualTo(altC.a); } else { alt = of(altC.a, altC.b); } assertEquals(as, alt, c); c.validate(); } for (List<Interval> as : take(LIMIT, P.listsAtLeast(1, P.finitelyBoundedIntervals()))) { Interval c = convexHull(as); Rational cd = c.diameter().get(); assertTrue(as, all(a -> ge(cd, a.diameter().get()), as)); } Iterable<Pair<List<Interval>, List<Interval>>> ps = P.dependentPairs( P.listsAtLeast(1, P.intervals()), P::permutationsFinite ); for (Pair<List<Interval>, List<Interval>> p : take(LIMIT, ps)) { assertEquals(p, convexHull(p.a), convexHull(p.b)); } for (Interval a : take(LIMIT, P.intervals())) { assertEquals(a, convexHull(Collections.singletonList(a)), a); } for (Pair<Interval, Interval> p : take(LIMIT, P.pairs(P.intervals()))) { assertEquals(p, convexHull(Arrays.asList(p.a, p.b)), p.a.convexHull(p.b)); } Iterable<Pair<Interval, Integer>> ps2; if (P instanceof QBarExhaustiveProvider) { ps2 = ((QBarExhaustiveProvider) P).pairsLogarithmicOrder(P.intervals(), P.positiveIntegers()); } else { ps2 = P.pairs(P.intervals(), P.withScale(20).positiveIntegersGeometric()); } for (Pair<Interval, Integer> p : take(LIMIT, ps2)) { assertEquals(p, convexHull(toList(replicate(p.b, p.a))), p.a); } for (List<Interval> as : take(LIMIT, P.listsWithElement(ALL, P.intervals()))) { assertEquals(as, convexHull(as), ALL); } for (List<Interval> as : take(LIMIT, P.listsWithElement(null, P.intervals()))) { try { convexHull(as); fail(as); } catch (NullPointerException ignored) {} } } private void compareImplementationsConvexHull_List_Interval() { initialize(""); System.out.println("\t\tcomparing convexHull(List<Interval>) implementations..."); long totalTime = 0; for (List<Interval> as : take(LIMIT, P.listsAtLeast(1, P.intervals()))) { long time = System.nanoTime(); convexHull_List_Interval_alt(as); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\talt: " + ((double) totalTime) / 1e9 + " s"); totalTime = 0; for (List<Interval> as : take(LIMIT, P.listsAtLeast(1, P.intervals()))) { long time = System.nanoTime(); convexHull(as); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s"); } private void propertiesIntersection() { initialize(""); System.out.println("\t\ttesting intersection(Interval) properties..."); for (Pair<Interval, Interval> p : take(LIMIT, P.pairs(P.intervals()))) { Optional<Interval> oi = p.a.intersection(p.b); if (oi.isPresent()) { oi.get().validate(); } assertEquals(p, oi, p.b.intersection(p.a)); assertEquals(p, oi.isPresent(), !p.a.disjoint(p.b)); } for (Pair<Interval, Interval> p : take(LIMIT, P.pairs(P.finitelyBoundedIntervals()))) { Optional<Interval> oi = p.a.intersection(p.b); if (oi.isPresent()) { assertTrue(p, le(oi.get().diameter().get(), p.a.diameter().get())); assertTrue(p, le(oi.get().diameter().get(), p.b.diameter().get())); } } for (Interval a : take(LIMIT, P.intervals())) { assertEquals(a, ALL.intersection(a).get(), a); assertEquals(a, a.intersection(a).get(), a); } for (Pair<Interval, Interval> p : take(LIMIT, filter(q -> !q.a.disjoint(q.b), P.pairs(P.intervals())))) { Interval intersection = p.a.intersection(p.b).get(); for (Rational r : take(TINY_LIMIT, P.rationalsIn(intersection))) { assertTrue(p, p.a.contains(r)); assertTrue(p, p.b.contains(r)); } } } private void propertiesDisjoint() { initialize(""); System.out.println("\t\ttesting disjoint(Interval) properties..."); for (Pair<Interval, Interval> p : take(LIMIT, P.pairs(P.intervals()))) { boolean disjoint = p.a.disjoint(p.b); assertEquals(p, p.b.disjoint(p.a), disjoint); } for (Interval a : take(LIMIT, P.intervals())) { assertFalse(a, ALL.disjoint(a)); assertFalse(a, a.disjoint(a)); } for (Pair<Interval, Interval> p : take(LIMIT, filter(q -> q.a.disjoint(q.b), P.pairs(P.intervals())))) { for (Rational r : take(TINY_LIMIT, P.rationalsIn(p.a))) { assertFalse(p, p.b.contains(r)); } } } private void propertiesMakeDisjoint() { initialize(""); System.out.println("\t\ttesting makeDisjoint(List<Interval>) properties..."); for (List<Interval> as : take(LIMIT, P.lists(P.intervals()))) { List<Interval> disjoint = makeDisjoint(as); disjoint.forEach(Interval::validate); assertTrue(as, weaklyIncreasing(disjoint)); assertTrue( as.toString(), and(map(p -> p.a.disjoint(p.b), ExhaustiveProvider.INSTANCE.distinctPairs(disjoint))) ); for (Rational r : take(TINY_LIMIT, mux(toList(map(P::rationalsIn, as))))) { assertTrue(as, or(map(a -> a.contains(r), disjoint))); } } Iterable<Pair<List<Interval>, List<Interval>>> ps = P.dependentPairs( P.lists(P.intervals()), P::permutationsFinite ); for (Pair<List<Interval>, List<Interval>> p : take(LIMIT, ps)) { assertEquals(p, makeDisjoint(p.a), makeDisjoint(p.b)); } for (Interval a : take(LIMIT, P.intervals())) { assertEquals(a, makeDisjoint(Collections.singletonList(a)), Collections.singletonList(a)); } for (Pair<Interval, Interval> p : take(LIMIT, filter(q -> q.a.disjoint(q.b), P.pairs(P.intervals())))) { assertEquals(p, makeDisjoint(Pair.toList(p)), sort(Pair.toList(p))); } for (Pair<Interval, Interval> p : take(LIMIT, filter(q -> !q.a.disjoint(q.b), P.pairs(P.intervals())))) { assertEquals(p, makeDisjoint(Pair.toList(p)), Collections.singletonList(convexHull(Pair.toList(p)))); } for (List<Interval> as : take(LIMIT, P.listsWithElement(ALL, P.intervals()))) { assertEquals(as, makeDisjoint(as), Collections.singletonList(ALL)); } for (List<Interval> as : take(LIMIT, P.listsWithElement(null, P.intervals()))) { try { convexHull(as); fail(as); } catch (NullPointerException ignored) {} } } private void propertiesComplement() { initialize(""); System.out.println("\t\ttesting complement() properties..."); for (Interval a : take(LIMIT, P.intervals())) { List<Interval> complement = a.complement(); complement.forEach(Interval::validate); assertEquals(a, makeDisjoint(complement), complement); List<Rational> endpoints = new ArrayList<>(); if (a.getLower().isPresent()) endpoints.add(a.getLower().get()); if (a.getUpper().isPresent()) endpoints.add(a.getUpper().get()); for (Rational endpoint : endpoints) { any(b -> b.contains(endpoint), complement); } //todo: fix hanging // for (Rational r : take(TINY_LIMIT, filter(s -> !endpoints.contains(s), P.rationals(a)))) { // assertFalse(a, any(b -> b.contains(r), complement)); for (Rational r : take(TINY_LIMIT, P.rationalsNotIn(a))) { assertTrue(a, any(b -> b.contains(r), complement)); } } for (Interval a : take(LIMIT, map(Interval::lessThanOrEqualTo, P.rationals()))) { List<Interval> complement = a.complement(); assertEquals(a, complement.size(), 1); Interval x = complement.get(0); assertTrue(a, x.getLower().isPresent()); assertFalse(a, x.getUpper().isPresent()); } for (Interval a : take(LIMIT, map(Interval::greaterThanOrEqualTo, P.rationals()))) { List<Interval> complement = a.complement(); assertEquals(a, complement.size(), 1); Interval x = complement.get(0); assertFalse(a, x.getLower().isPresent()); assertTrue(a, x.getUpper().isPresent()); } for (Interval a : take(LIMIT, map(Interval::of, P.rationals()))) { assertEquals(a, a.complement(), Collections.singletonList(ALL)); } Iterable<Interval> as = filter(b -> b.diameter().get() != Rational.ZERO, P.finitelyBoundedIntervals()); for (Interval a : take(LIMIT, as)) { List<Interval> complement = a.complement(); assertEquals(a, complement.size(), 2); Interval x = complement.get(0); Interval y = complement.get(1); assertFalse(a, x.getLower().isPresent()); assertTrue(a, x.getUpper().isPresent()); assertTrue(a, y.getLower().isPresent()); assertFalse(a, y.getUpper().isPresent()); } } private void propertiesMidpoint() { initialize(""); System.out.println("\t\ttesting midpoint() properties..."); for (Interval a : take(LIMIT, P.finitelyBoundedIntervals())) { Rational midpoint = a.midpoint(); assertEquals(a, midpoint.subtract(a.getLower().get()), a.getUpper().get().subtract(midpoint)); } for (Rational r : take(LIMIT, P.rationals())) { assertEquals(r, of(r).midpoint(), r); } for (Rational r : take(LIMIT, P.rationals())) { try { lessThanOrEqualTo(r).midpoint(); fail(r); } catch (ArithmeticException ignored) {} try { greaterThanOrEqualTo(r).midpoint(); fail(r); } catch (ArithmeticException ignored) {} } } private void propertiesSplit() { initialize(""); System.out.println("\t\ttesting split(Rational) properties..."); Iterable<Pair<Interval, Rational>> ps = filter(q -> q.a.contains(q.b), P.pairs(P.intervals(), P.rationals())); for (Pair<Interval, Rational> p : take(LIMIT, ps)) { Pair<Interval, Interval> split = p.a.split(p.b); split.a.validate(); split.b.validate(); assertEquals(p, split.a.getUpper().get(), p.b); assertEquals(p, split.b.getLower().get(), p.b); for (Rational r : take(TINY_LIMIT, P.rationalsIn(p.a))) { assertTrue(p, split.a.contains(r) || split.b.contains(r)); } } for (Rational r : take(LIMIT, P.rationals())) { Interval a = of(r); assertEquals(r, a.split(r), new Pair<>(a, a)); Pair<Interval, Interval> p = ALL.split(r); assertFalse(r, p.a.getLower().isPresent()); assertTrue(r, p.a.getUpper().isPresent()); assertTrue(r, p.b.getLower().isPresent()); assertFalse(r, p.b.getUpper().isPresent()); } for (Pair<Rational, Rational> p : take(LIMIT, filter(q -> le(q.a, q.b), P.pairs(P.rationals())))) { Interval a = lessThanOrEqualTo(p.b); Pair<Interval, Interval> q = a.split(p.a); assertFalse(p, q.a.getLower().isPresent()); assertTrue(p, q.a.getUpper().isPresent()); assertTrue(p, q.b.isFinitelyBounded()); } for (Pair<Rational, Rational> p : take(LIMIT, filter(q -> le(q.a, q.b), P.pairs(P.rationals())))) { Interval a = greaterThanOrEqualTo(p.a); Pair<Interval, Interval> q = a.split(p.b); assertTrue(p, q.a.isFinitelyBounded()); assertTrue(p, q.b.getLower().isPresent()); assertFalse(p, q.b.getUpper().isPresent()); } Iterable<Pair<Interval, Rational>> psFail = filter( q -> !q.a.contains(q.b), P.pairs(P.intervals(), P.rationals()) ); for (Pair<Interval, Rational> p : take(LIMIT, psFail)) { try { p.a.split(p.b); fail(p); } catch (ArithmeticException ignored) {} } } private void propertiesBisect() { initialize(""); System.out.println("\t\ttesting bisect() properties..."); for (Interval a : take(LIMIT, P.finitelyBoundedIntervals())) { Pair<Interval, Interval> bisection = a.bisect(); bisection.a.validate(); bisection.b.validate(); assertTrue(a, bisection.a.isFinitelyBounded()); assertTrue(a, bisection.b.isFinitelyBounded()); assertEquals(a, bisection.a.diameter().get(), bisection.b.diameter().get()); assertEquals(a, bisection.a.getUpper().get(), bisection.b.getLower().get()); for (Rational r : take(TINY_LIMIT, P.rationalsIn(a))) { assertTrue(a, bisection.a.contains(r) || bisection.b.contains(r)); } } for (Rational r : take(LIMIT, P.rationals())) { Interval a = of(r); assertEquals(r, a.bisect(), new Pair<>(a, a)); } for (Rational r : take(LIMIT, P.rationals())) { try { lessThanOrEqualTo(r).bisect(); fail(r); } catch (ArithmeticException ignored) {} try { greaterThanOrEqualTo(r).bisect(); fail(r); } catch (ArithmeticException ignored) {} } } private void propertiesRoundingPreimage_float() { initialize(""); System.out.println("\t\ttesting roundingPreimage(float) properties..."); for (float f : take(LIMIT, filter(g -> !Float.isNaN(g), P.floats()))) { Interval a = roundingPreimage(f); a.validate(); assertEquals(f, roundingPreimage(-f), a.negate()); } for (float f : take(LIMIT, filter(g -> !Float.isNaN(g) && Math.abs(g) < Float.MAX_VALUE, P.floats()))) { Interval a = roundingPreimage(f); Rational central = Rational.ofExact(f).get(); Rational pred = Rational.ofExact(FloatingPointUtils.predecessor(f)).get(); Rational succ = Rational.ofExact(FloatingPointUtils.successor(f)).get(); for (Rational r : take(TINY_LIMIT, P.rationalsIn(a))) { Rational centralDistance = central.subtract(r).abs(); Rational predDistance = pred.subtract(r).abs(); Rational succDistance = succ.subtract(r).abs(); assertTrue(f, le(centralDistance, predDistance)); assertTrue(f, le(centralDistance, succDistance)); } for (Rational r : take(TINY_LIMIT, P.rationalsNotIn(a))) { Rational centralDistance = central.subtract(r).abs(); Rational predDistance = pred.subtract(r).abs(); Rational succDistance = succ.subtract(r).abs(); assertTrue(f, gt(centralDistance, predDistance) || gt(centralDistance, succDistance)); } Rational x = a.getLower().get(); Rational y = a.getUpper().get(); for (Rational r : take(TINY_LIMIT, filter(s -> !s.equals(x) && !s.equals(y), P.rationalsIn(a)))) { float g = r.floatValue(); float h = f; //get rid of negative zero if (g == 0.0f) g = Math.abs(g); if (h == 0.0f) h = Math.abs(h); assertEquals(f, g, h); } for (Rational r : take(TINY_LIMIT, filter(s -> !s.equals(x) && !s.equals(y), P.rationalsNotIn(a)))) { assertNotEquals(f, r.floatValue(), f); } } } private void propertiesRoundingPreimage_double() { initialize(""); System.out.println("\t\ttesting roundingPreimage(double) properties..."); for (double d : take(LIMIT, filter(e -> !Double.isNaN(e), P.doubles()))) { Interval a = roundingPreimage(d); a.validate(); assertEquals(d, roundingPreimage(-d), a.negate()); } for (double d : take(LIMIT, filter(e -> !Double.isNaN(e) && Math.abs(e) < Double.MAX_VALUE, P.doubles()))) { Interval a = roundingPreimage(d); Rational central = Rational.ofExact(d).get(); Rational pred = Rational.ofExact(FloatingPointUtils.predecessor(d)).get(); Rational succ = Rational.ofExact(FloatingPointUtils.successor(d)).get(); for (Rational r : take(TINY_LIMIT, P.rationalsIn(a))) { Rational centralDistance = central.subtract(r).abs(); Rational predDistance = pred.subtract(r).abs(); Rational succDistance = succ.subtract(r).abs(); assertTrue(d, le(centralDistance, predDistance)); assertTrue(d, le(centralDistance, succDistance)); } for (Rational r : take(TINY_LIMIT, P.rationalsNotIn(a))) { Rational centralDistance = central.subtract(r).abs(); Rational predDistance = pred.subtract(r).abs(); Rational succDistance = succ.subtract(r).abs(); assertTrue(d, gt(centralDistance, predDistance) || gt(centralDistance, succDistance)); } Rational x = a.getLower().get(); Rational y = a.getUpper().get(); for (Rational r : take(TINY_LIMIT, filter(s -> !s.equals(x) && !s.equals(y), P.rationalsIn(a)))) { double g = r.doubleValue(); double h = d; //get rid of negative zero if (g == 0.0) g = Math.abs(g); if (h == 0.0) h = Math.abs(h); assertEquals(d, g, h); } for (Rational r : take(TINY_LIMIT, filter(s -> !s.equals(x) && !s.equals(y), P.rationalsNotIn(a)))) { assertNotEquals(d, r.doubleValue(), d); } } } private void propertiesRoundingPreimage_BigDecimal() { initialize(""); System.out.println("\t\ttesting roundingPreimage(BigDecimal) properties..."); for (BigDecimal bd : take(LIMIT, P.bigDecimals())) { Interval a = roundingPreimage(bd); a.validate(); assertEquals(bd, roundingPreimage(bd.negate()), a.negate()); Rational central = Rational.of(bd); Rational pred = Rational.of(BigDecimalUtils.predecessor(bd)); Rational succ = Rational.of(BigDecimalUtils.successor(bd)); for (Rational r : take(TINY_LIMIT, P.rationalsIn(a))) { Rational centralDistance = central.subtract(r).abs(); Rational predDistance = pred.subtract(r).abs(); Rational succDistance = succ.subtract(r).abs(); assertTrue(bd, le(centralDistance, predDistance)); assertTrue(bd, le(centralDistance, succDistance)); } for (Rational r : take(TINY_LIMIT, P.rationalsNotIn(a))) { Rational centralDistance = central.subtract(r).abs(); Rational predDistance = pred.subtract(r).abs(); Rational succDistance = succ.subtract(r).abs(); assertTrue(bd, gt(centralDistance, predDistance) || gt(centralDistance, succDistance)); } } } private void propertiesFloatRange() { initialize(""); System.out.println("\t\ttesting floatRange() properties..."); for (Interval a : take(LIMIT, P.intervals())) { Pair<Float, Float> range = a.floatRange(); assertTrue(a, range.a != null); assertTrue(a, range.b != null); assertFalse(a, range.a.isNaN()); assertFalse(a, range.b.isNaN()); assertTrue(a, range.b >= range.a); assertFalse(a, range.a > 0 && range.a.isInfinite()); assertFalse(a, FloatingPointUtils.isNegativeZero(range.a)); assertFalse(a, range.b < 0 && range.b.isInfinite()); assertFalse(a, FloatingPointUtils.isNegativeZero(range.b) && FloatingPointUtils.isPositiveZero(range.a)); Pair<Float, Float> negRange = a.negate().floatRange(); negRange = new Pair<>(-negRange.b, -negRange.a); float x = FloatingPointUtils.absNegativeZeros(range.a); float y = FloatingPointUtils.absNegativeZeros(range.b); float xn = FloatingPointUtils.absNegativeZeros(negRange.a); float yn = FloatingPointUtils.absNegativeZeros(negRange.b); assertEquals(a, x, xn); assertEquals(a, y, yn); Interval b; if (range.a.isInfinite() && range.b.isInfinite()) { b = ALL; } else if (range.a.isInfinite()) { b = lessThanOrEqualTo(Rational.ofExact(range.b).get()); } else if (range.b.isInfinite()) { b = greaterThanOrEqualTo(Rational.ofExact(range.a).get()); } else { b = of(Rational.ofExact(range.a).get(), Rational.ofExact(range.b).get()); } assertTrue(a, b.contains(a)); } for (Interval a : take(LIMIT, P.finitelyBoundedIntervals())) { Pair<Float, Float> range = a.floatRange(); assertTrue(a, le(a.getLower().get(), Rational.ofExact(FloatingPointUtils.successor(range.a)).get())); assertTrue(a, ge(a.getUpper().get(), Rational.ofExact(FloatingPointUtils.predecessor(range.b)).get())); } } private void propertiesDoubleRange() { initialize(""); System.out.println("\t\ttesting doubleRange() properties..."); for (Interval a : take(LIMIT, P.intervals())) { Pair<Double, Double> range = a.doubleRange(); assertTrue(a, range.a != null); assertTrue(a, range.b != null); assertFalse(a, range.a.isNaN()); assertFalse(a, range.b.isNaN()); assertTrue(a, range.b >= range.a); assertFalse(a, range.a > 0 && range.a.isInfinite()); assertFalse(a, FloatingPointUtils.isNegativeZero(range.a)); assertFalse(a, range.b < 0 && range.b.isInfinite()); assertFalse(a, FloatingPointUtils.isNegativeZero(range.b) && FloatingPointUtils.isPositiveZero(range.a)); Pair<Double, Double> negRange = a.negate().doubleRange(); negRange = new Pair<>(-negRange.b, -negRange.a); double x = FloatingPointUtils.absNegativeZeros(range.a); double y = FloatingPointUtils.absNegativeZeros(range.b); double xn = FloatingPointUtils.absNegativeZeros(negRange.a); double yn = FloatingPointUtils.absNegativeZeros(negRange.b); assertEquals(a, x, xn); assertEquals(a, y, yn); Interval b; if (range.a.isInfinite() && range.b.isInfinite()) { b = ALL; } else if (range.a.isInfinite()) { b = lessThanOrEqualTo(Rational.ofExact(range.b).get()); } else if (range.b.isInfinite()) { b = greaterThanOrEqualTo(Rational.ofExact(range.a).get()); } else { b = of(Rational.ofExact(range.a).get(), Rational.ofExact(range.b).get()); } assertTrue(a, b.contains(a)); } for (Interval a : take(LIMIT, P.finitelyBoundedIntervals())) { Pair<Float, Float> range = a.floatRange(); assertTrue(a, le(a.getLower().get(), Rational.ofExact(FloatingPointUtils.successor(range.a)).get())); assertTrue(a, ge(a.getUpper().get(), Rational.ofExact(FloatingPointUtils.predecessor(range.b)).get())); } } private void propertiesAdd() { initialize(""); System.out.println("\t\ttesting add(Interval) properties..."); for (Pair<Interval, Interval> p : take(LIMIT, P.pairs(P.intervals()))) { Interval sum = p.a.add(p.b); sum.validate(); assertEquals(p, sum, p.b.add(p.a)); assertTrue(p, sum.subtract(p.b).contains(p.a)); for (Pair<Rational, Rational> q : take(TINY_LIMIT, P.pairs(P.rationalsIn(p.a), P.rationalsIn(p.b)))) { assertTrue(p, sum.contains(q.a.add(q.b))); } } for (Pair<Interval, Interval> p : take(LIMIT, P.pairs(P.finitelyBoundedIntervals()))) { Interval sum = p.a.add(p.b); Rational diameter = sum.diameter().get(); assertTrue(p, ge(diameter, p.a.diameter().get())); assertTrue(p, ge(diameter, p.b.diameter().get())); } for (Interval a : take(LIMIT, P.intervals())) { assertEquals(a, ZERO.add(a), a); assertEquals(a, a.add(ZERO), a); assertTrue(a, a.subtract(a).contains(ZERO)); assertEquals(a, ALL.add(a), ALL); assertEquals(a, a.add(ALL), ALL); } for (Triple<Interval, Interval, Interval> t : take(LIMIT, P.triples(P.intervals()))) { Interval sum1 = t.a.add(t.b).add(t.c); Interval sum2 = t.a.add(t.b.add(t.c)); assertEquals(t, sum1, sum2); } for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) { assertEquals(p, of(p.a).add(of(p.b)), of(p.a.add(p.b))); } } private void propertiesNegate() { initialize(""); System.out.println("\t\ttesting negate() properties..."); for (Interval a : take(LIMIT, P.intervals())) { Interval negative = a.negate(); negative.validate(); assertEquals(a, a, negative.negate()); assertTrue(a, a.add(negative).contains(ZERO)); assertEquals(a, a.diameter(), negative.diameter()); for (Rational r : take(TINY_LIMIT, P.rationalsIn(a))) { assertTrue(a, negative.contains(r.negate())); } } for (Rational r : take(LIMIT, P.rationals())) { assertEquals(r, of(r).negate(), of(r.negate())); } } private void propertiesAbs() { initialize(""); System.out.println("\t\ttesting abs() properties..."); for (Interval a : take(LIMIT, P.intervals())) { Interval abs = a.abs(); abs.validate(); assertEquals(a, abs, abs.abs()); Optional<Interval> negativeIntersection = abs.intersection(lessThanOrEqualTo(Rational.ZERO)); assertTrue(a, !negativeIntersection.isPresent() || negativeIntersection.get().equals(ZERO)); for (Rational r : take(TINY_LIMIT, P.rationalsIn(a))) { assertTrue(a, abs.contains(r.abs())); } } for (Interval a : take(LIMIT, P.finitelyBoundedIntervals())) { Rational diameter = a.diameter().get(); Rational absDiameter = a.abs().diameter().get(); assertTrue(a, le(absDiameter, diameter)); } for (Rational r : take(LIMIT, P.rationals())) { assertEquals(r, of(r).abs(), of(r.abs())); } } private void propertiesSignum() { initialize(""); System.out.println("\t\ttesting signum() properties..."); for (Interval a : take(LIMIT, P.intervals())) { Optional<Integer> signumA = a.signum(); assertEquals(a, signumA, a.elementCompare(ZERO).map(Ordering::toInt)); if (signumA.isPresent()) { Integer s = signumA.get(); assertTrue(a, s == -1 || s == 0 || s == 1); for (Rational r : take(TINY_LIMIT, P.rationalsIn(a))) { assertTrue(a, r.signum() == s); } } else { assertTrue(a, !a.equals(ZERO)); assertTrue(a, a.contains(ZERO)); } } } private void propertiesSubtract() { initialize(""); System.out.println("\t\ttesting subtract(Interval) properties..."); for (Pair<Interval, Interval> p : take(LIMIT, P.pairs(P.intervals()))) { Interval difference = p.a.subtract(p.b); difference.validate(); assertEquals(p, difference, p.b.subtract(p.a).negate()); assertTrue(p, difference.add(p.b).contains(p.a)); for (Pair<Rational, Rational> q : take(TINY_LIMIT, P.pairs(P.rationalsIn(p.a), P.rationalsIn(p.b)))) { assertTrue(p, difference.contains(q.a.subtract(q.b))); } } for (Pair<Interval, Interval> p : take(LIMIT, P.pairs(P.finitelyBoundedIntervals()))) { Interval difference = p.a.subtract(p.b); Rational diameter = difference.diameter().get(); assertTrue(p, ge(diameter, p.a.diameter().get())); assertTrue(p, ge(diameter, p.b.diameter().get())); } for (Interval a : take(LIMIT, P.intervals())) { assertEquals(a, ZERO.subtract(a), a.negate()); assertEquals(a, a.subtract(ZERO), a); assertTrue(a, a.subtract(a).contains(ZERO)); assertEquals(a, ALL.subtract(a), ALL); assertEquals(a, a.subtract(ALL), ALL); } for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) { assertEquals(p, of(p.a).subtract(of(p.b)), of(p.a.subtract(p.b))); } } private void propertiesMultiply_Interval() { initialize(""); System.out.println("\t\ttesting multiply(Interval) properties..."); for (Pair<Interval, Interval> p : take(LIMIT, P.pairs(P.intervals()))) { Interval product = p.a.multiply(p.b); product.validate(); assertEquals(p, product, p.b.multiply(p.a)); for (Pair<Rational, Rational> q : take(TINY_LIMIT, P.pairs(P.rationalsIn(p.a), P.rationalsIn(p.b)))) { assertTrue(p, product.contains(q.a.multiply(q.b))); } } Iterable<Pair<Interval, Interval>> ps = P.pairs(P.intervals(), filter(a -> !a.equals(ZERO), P.intervals())); for (Pair<Interval, Interval> p : take(LIMIT, ps)) { Interval product = p.a.multiply(p.b); List<Interval> quotient = product.divide(p.b); assertTrue(p, any(a -> a.contains(p.a), quotient)); quotient = makeDisjoint(toList(concatMap(p.a::divide, p.b.invert()))); assertTrue(p, quotient.contains(product)); } for (Interval a : take(LIMIT, P.intervals())) { assertEquals(a, ONE.multiply(a), a); assertEquals(a, a.multiply(ONE), a); assertTrue(a, ZERO.multiply(a).equals(ZERO)); assertTrue(a, a.multiply(ZERO).equals(ZERO)); } for (Interval a : take(LIMIT, filter(b -> !b.equals(ZERO), P.intervals()))) { assertEquals(a, ALL.multiply(a), ALL); assertEquals(a, a.multiply(ALL), ALL); List<Interval> inverse = a.invert(); List<Interval> back = makeDisjoint(toList(map(a::multiply, inverse))); assertTrue(a, any(b -> b.contains(ONE), back)); } for (Triple<Interval, Interval, Interval> t : take(LIMIT, P.triples(P.intervals()))) { Interval product1 = t.a.multiply(t.b).multiply(t.c); Interval product2 = t.a.multiply(t.b.multiply(t.c)); assertEquals(t, product1, product2); Interval expression1 = t.a.add(t.b).multiply(t.c); Interval expression2 = t.a.multiply(t.c).add(t.b.multiply(t.c)); assertTrue(t, expression2.contains(expression1)); } for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) { assertEquals(p, of(p.a).multiply(of(p.b)), of(p.a.multiply(p.b))); } } private void propertiesMultiply_Rational() { initialize(""); System.out.println("\t\ttesting multiply(Rational) properties..."); for (Pair<Interval, Rational> p : take(LIMIT, P.pairs(P.intervals(), P.rationals()))) { Interval a = p.a.multiply(p.b); a.validate(); assertEquals(p, a, p.a.multiply(of(p.b))); for (Rational r : take(TINY_LIMIT, P.rationalsIn(p.a))) { assertTrue(p, a.contains(r.multiply(p.b))); } } Iterable<Pair<Interval, Rational>> ps = P.pairs(P.intervals(), filter(r -> r != Rational.ZERO, P.rationals())); for (Pair<Interval, Rational> p : take(LIMIT, ps)) { assertEquals(p, p.a.multiply(p.b).divide(p.b), p.a); assertEquals(p, p.a.multiply(p.b), p.a.divide(p.b.invert())); } for (Interval a : take(LIMIT, P.intervals())) { assertEquals(a, a, a.multiply(Rational.ONE)); assertEquals(a, a.multiply(Rational.ZERO), ZERO); } for (Rational r : take(LIMIT, P.rationals())) { assertEquals(r, ZERO.multiply(r), ZERO); assertEquals(r, ONE.multiply(r), of(r)); } for (Rational r : take(LIMIT, filter(s -> s != Rational.ZERO, P.rationals()))) { assertEquals(r, ALL.multiply(r), ALL); } } private void propertiesMultiply_BigInteger() { initialize(""); System.out.println("\t\ttesting multiply(BigInteger) properties..."); for (Pair<Interval, BigInteger> p : take(LIMIT, P.pairs(P.intervals(), P.bigIntegers()))) { Interval a = p.a.multiply(p.b); a.validate(); assertEquals(p, a, p.a.multiply(Rational.of(p.b))); for (Rational r : take(TINY_LIMIT, P.rationalsIn(p.a))) { assertTrue(p, a.contains(r.multiply(p.b))); } } Iterable<Pair<Interval, BigInteger>> ps = P.pairs( P.intervals(), filter(i -> !i.equals(BigInteger.ZERO), P.bigIntegers()) ); for (Pair<Interval, BigInteger> p : take(LIMIT, ps)) { assertEquals(p, p.a.multiply(p.b).divide(p.b), p.a); } for (Interval a : take(LIMIT, P.intervals())) { assertEquals(a, a, a.multiply(BigInteger.ONE)); assertEquals(a, a.multiply(BigInteger.ZERO), ZERO); } for (BigInteger i : take(LIMIT, P.bigIntegers())) { assertEquals(i.toString(), ZERO.multiply(i), ZERO); assertEquals(i.toString(), ONE.multiply(i), of(Rational.of(i))); } for (BigInteger i : take(LIMIT, filter(j -> !j.equals(BigInteger.ZERO), P.bigIntegers()))) { assertEquals(i.toString(), ALL.multiply(i), ALL); } } private void propertiesMultiply_int() { initialize(""); System.out.println("\t\ttesting multiply(int) properties..."); for (Pair<Interval, Integer> p : take(LIMIT, P.pairs(P.intervals(), P.integers()))) { Interval a = p.a.multiply(p.b); a.validate(); assertEquals(p, a, p.a.multiply(Rational.of(p.b))); for (Rational r : take(TINY_LIMIT, P.rationalsIn(p.a))) { assertTrue(p, a.contains(r.multiply(p.b))); } } Iterable<Pair<Interval, Integer>> ps = P.pairs(P.intervals(), filter(i -> i != 0, P.integers())); for (Pair<Interval, Integer> p : take(LIMIT, ps)) { assertEquals(p, p.a.multiply(p.b).divide(p.b), p.a); } for (Interval a : take(LIMIT, P.intervals())) { assertEquals(a, a, a.multiply(1)); assertEquals(a, a.multiply(0), ZERO); } for (int i : take(LIMIT, P.integers())) { assertEquals(i, ZERO.multiply(i), ZERO); assertEquals(i, ONE.multiply(i), of(Rational.of(i))); } for (int i : take(LIMIT, filter(j -> j != 0, P.integers()))) { assertEquals(i, ALL.multiply(i), ALL); } } private void propertiesInvert() { initialize(""); System.out.println("\t\ttesting invert() properties..."); for (Interval a : take(LIMIT, P.intervals())) { List<Interval> inverse = a.invert(); inverse.forEach(Interval::validate); //todo fix hanging // for (Rational r : take(TINY_LIMIT, filter(s -> s != Rational.ZERO, P.rationals(a)))) { // assertTrue(a, any(b -> b.contains(r.invert()), inverse)); int size = inverse.size(); assertTrue(a, size == 0 || size == 1 || size == 2); if (size == 1) { Interval i1 = inverse.get(0); Rational p = i1.getLower().isPresent() ? i1.getLower().get() : null; Rational q = i1.getUpper().isPresent() ? i1.getUpper().get() : null; if (p == null && q != null) { assertTrue(a, le(q, Rational.ZERO)); } else if (p != null && q == null) { assertTrue(a, ge(p, Rational.ZERO)); } else if (i1.isFinitelyBounded()) { if (p.equals(q)) { assertNotEquals(a, p, Rational.ZERO); } else { int ps = p.signum(); int qs = q.signum(); if (qs == 1) { assertTrue(a, ps != -1); } if (ps == -1) { assertTrue(a, qs != 1); } } } } else if (size == 2) { Interval i1 = inverse.get(0); Interval i2 = inverse.get(1); Rational p1 = i1.getLower().isPresent() ? i1.getLower().get() : null; Rational q1 = i1.getUpper().isPresent() ? i1.getUpper().get() : null; Rational p2 = i2.getLower().isPresent() ? i2.getLower().get() : null; Rational q2 = i2.getUpper().isPresent() ? i2.getUpper().get() : null; assertTrue(a, p1 == null); assertTrue(a, q2 == null); if (p2 == Rational.ZERO) { assertTrue(a, q1.signum() == -1); } else if (q1 == Rational.ZERO) { assertTrue(a, p2.signum() == 1); } else { assertTrue(a, q1.signum() == -1); assertTrue(a, p2.signum() == 1); } } } for (Interval a : take(LIMIT, filter(b -> !b.equals(ZERO), P.intervals()))) { List<Interval> inverse = a.invert(); List<Interval> back = makeDisjoint(toList(concatMap(Interval::invert, inverse))); assertTrue(a, convexHull(back).contains(a)); assertTrue(a, convexHull(toList(map(a::multiply, inverse))).contains(ONE)); } } private void propertiesInvertHull() { initialize(""); System.out.println("\t\ttesting invertHull() properties..."); for (Interval a : take(LIMIT, filter(b -> !b.equals(ZERO), P.intervals()))) { Interval inverse = a.invertHull(); inverse.validate(); for (Rational r : take(TINY_LIMIT, filter(s -> s != Rational.ZERO, P.rationalsIn(a)))) { assertTrue(a, inverse.contains(r.invert())); } Rational p = inverse.getLower().isPresent() ? inverse.getLower().get() : null; Rational q = inverse.getUpper().isPresent() ? inverse.getUpper().get() : null; if (p == null && q != null) { assertTrue(a, le(q, Rational.ZERO)); } else if (p != null && q == null) { assertTrue(a, ge(p, Rational.ZERO)); } else if (inverse.isFinitelyBounded()) { if (p.equals(q)) { assertNotEquals(a, p, ZERO); } else { int ps = p.signum(); int qs = q.signum(); if (qs == 1) { assertTrue(a, ps != -1); } if (ps == -1) { assertTrue(a, qs != 1); } } } assertTrue(a, all(inverse::contains, a.invert())); Interval back = inverse.invertHull(); assertTrue(a, back.contains(a)); assertTrue(a, a.multiply(inverse).contains(ONE)); } } private void propertiesDivide_Interval() { initialize(""); System.out.println("\t\ttesting divide(Interval) properties..."); for (Pair<Interval, Interval> p : take(LIMIT, P.pairs(P.intervals()))) { List<Interval> quotient = p.a.divide(p.b); quotient.forEach(Interval::validate); //todo fix hanging // Iterable<Pair<Rational, Rational>> qs = P.pairs( // P.rationals(p.a), // filter(r -> r != Rational.ZERO, P.rationals(p.b)) // for (Pair<Rational, Rational> q : take(TINY_LIMIT, qs)) { // assertTrue(p, any(b -> b.contains(q.a.divide(q.b)), quotient)); int size = quotient.size(); assertTrue(p, size == 0 || size == 1 || size == 2); if (size == 2) { Interval i1 = quotient.get(0); Interval i2 = quotient.get(1); Rational p1 = i1.getLower().isPresent() ? i1.getLower().get() : null; Rational q1 = i1.getUpper().isPresent() ? i1.getUpper().get() : null; Rational p2 = i2.getLower().isPresent() ? i2.getLower().get() : null; Rational q2 = i2.getUpper().isPresent() ? i2.getUpper().get() : null; assertTrue(p, p1 == null); assertTrue(p, q2 == null); if (p2 == Rational.ZERO) { assertTrue(p, q1.signum() == -1); } else if (q1 == Rational.ZERO) { assertTrue(p, p2.signum() == 1); } else { assertTrue(p, q1.signum() == -1); assertTrue(p, p2.signum() == 1); } } } Iterable<Pair<Interval, Interval>> ps = P.pairs(P.intervals(), filter(a -> !a.equals(ZERO), P.intervals())); for (Pair<Interval, Interval> p : take(LIMIT, ps)) { List<Interval> quotient = p.a.divide(p.b); assertTrue(p, convexHull(toList(map(a -> a.multiply(p.b), quotient))).contains(p.a)); assertTrue(p, convexHull(toList(map(p.a::multiply, p.b.invert()))).contains(convexHull(quotient))); } for (Pair<Interval, Interval> p : take(LIMIT, P.pairs(filter(a -> !a.equals(ZERO), P.intervals())))) { assertTrue( p, convexHull(toList(concatMap(Interval::invert, p.b.divide(p.a)))) .contains(convexHull(p.a.divide(p.b))) ); } for (Interval a : take(LIMIT, P.intervals())) { assertTrue(a, any(b -> b.contains(a), a.divide(ONE))); } for (Interval a : take(LIMIT, filter(b -> !b.equals(ZERO), P.intervals()))) { assertEquals(a, ONE.divide(a), a.invert()); assertTrue(a, any(b -> b.contains(ONE), a.divide(a))); } } private void propertiesDivideHull() { initialize(""); System.out.println("\t\ttesting divideHull(Interval) properties..."); Iterable<Pair<Interval, Interval>> ps = P.pairs(P.intervals(), filter(a -> !a.equals(ZERO), P.intervals())); for (Pair<Interval, Interval> p : take(LIMIT, ps)) { Interval quotient = p.a.divideHull(p.b); quotient.validate(); Iterable<Pair<Rational, Rational>> qs = P.pairs( P.rationalsIn(p.a), filter(r -> r != Rational.ZERO, P.rationalsIn(p.b)) ); for (Pair<Rational, Rational> q : take(TINY_LIMIT, qs)) { assertTrue(p, quotient.contains(q.a.divide(q.b))); } assertTrue(p, quotient.multiply(p.b).contains(p.a)); assertTrue(p, p.a.multiply(p.b.invertHull()).contains(quotient)); } for (Pair<Interval, Interval> p : take(LIMIT, P.pairs(filter(a -> !a.equals(ZERO), P.intervals())))) { assertTrue(p, p.b.divideHull(p.a).invertHull().contains(p.a.divideHull(p.b))); } for (Interval a : take(LIMIT, P.intervals())) { assertTrue(a, a.divideHull(ONE).contains(a)); } for (Interval a : take(LIMIT, filter(b -> !b.equals(ZERO), P.intervals()))) { assertEquals(a, ONE.divideHull(a), a.invertHull()); assertTrue(a, a.divideHull(a).contains(ONE)); } for (Interval a : take(LIMIT, P.intervals())) { try { a.divideHull(ZERO); fail(a); } catch (ArithmeticException ignored) {} } } private void propertiesDivide_Rational() { initialize(""); System.out.println("\t\ttesting divide(Rational) properties..."); Iterable<Pair<Interval, Rational>> ps = P.pairs(P.intervals(), filter(r -> r != Rational.ZERO, P.rationals())); for (Pair<Interval, Rational> p : take(LIMIT, ps)) { Interval quotient = p.a.divide(p.b); quotient.validate(); for (Rational r : take(TINY_LIMIT, P.rationalsIn(p.a))) { assertTrue(p, quotient.contains(r.divide(p.b))); } assertTrue(p, quotient.multiply(p.b).contains(p.a)); assertTrue(p, p.a.multiply(p.b.invert()).contains(quotient)); } for (Interval a : take(LIMIT, P.intervals())) { assertTrue(a, a.divide(Rational.ONE).contains(a)); } for (Rational r : take(LIMIT, filter(s -> s != Rational.ZERO, P.rationals()))) { assertEquals(r, ONE.divide(r), of(r.invert())); } for (Interval a : take(LIMIT, P.intervals())) { try { a.divide(Rational.ZERO); fail(a); } catch (ArithmeticException ignored) {} } } private void propertiesDivide_BigInteger() { initialize(""); System.out.println("\t\ttesting divide(BigInteger) properties..."); Iterable<Pair<Interval, BigInteger>> ps = P.pairs( P.intervals(), filter(i -> !i.equals(BigInteger.ZERO), P.bigIntegers()) ); for (Pair<Interval, BigInteger> p : take(LIMIT, ps)) { Interval quotient = p.a.divide(p.b); quotient.validate(); for (Rational r : take(TINY_LIMIT, P.rationalsIn(p.a))) { assertTrue(p, quotient.contains(r.divide(p.b))); } assertTrue(p, quotient.multiply(p.b).contains(p.a)); assertTrue(p, p.a.multiply(Rational.of(p.b).invert()).contains(quotient)); } for (Interval a : take(LIMIT, P.intervals())) { assertTrue(a, a.divide(BigInteger.ONE).contains(a)); } for (BigInteger i : take(LIMIT, filter(j -> !j.equals(BigInteger.ZERO), P.bigIntegers()))) { assertEquals(i, ONE.divide(i), of(Rational.of(i).invert())); } for (Interval a : take(LIMIT, P.intervals())) { try { a.divide(BigInteger.ZERO); fail(a); } catch (ArithmeticException ignored) {} } } private void propertiesDivide_int() { initialize(""); System.out.println("\t\ttesting divide(int) properties..."); for (Pair<Interval, Integer> p : take(LIMIT, P.pairs(P.intervals(), filter(i -> i != 0, P.integers())))) { Interval quotient = p.a.divide(p.b); quotient.validate(); for (Rational r : take(TINY_LIMIT, P.rationalsIn(p.a))) { assertTrue(p, quotient.contains(r.divide(p.b))); } assertTrue(p, quotient.multiply(p.b).contains(p.a)); assertTrue(p, p.a.multiply(Rational.of(p.b).invert()).contains(quotient)); } for (Interval a : take(LIMIT, P.intervals())) { assertTrue(a, a.divide(1).contains(a)); } for (int i : take(LIMIT, filter(j -> j != 0, P.integers()))) { assertEquals(i, ONE.divide(i), of(Rational.of(i).invert())); } for (Interval a : take(LIMIT, P.intervals())) { try { a.divide(0); fail(a); } catch (ArithmeticException ignored) {} } } private static @NotNull Interval shiftLeft_simplest(@NotNull Interval a, int bits) { if (bits < 0) { return a.divide(BigInteger.ONE.shiftLeft(-bits)); } else { return a.multiply(BigInteger.ONE.shiftLeft(bits)); } } private void propertiesShiftLeft() { initialize(""); System.out.println("\t\ttesting shiftLeft(int) properties..."); Iterable<Integer> is; if (P instanceof QBarExhaustiveProvider) { is = P.integers(); } else { is = ((QBarRandomProvider) P).integersGeometric(); } for (Pair<Interval, Integer> p : take(LIMIT, P.pairs(P.intervals(), is))) { Interval shifted = p.a.shiftLeft(p.b); shifted.validate(); for (Rational r : take(TINY_LIMIT, P.rationalsIn(p.a))) { assertTrue(p, shifted.contains(r.shiftLeft(p.b))); } assertEquals(p, shifted, shiftLeft_simplest(p.a, p.b)); assertEquals(p, p.a.signum(), shifted.signum()); assertEquals(p, p.a.isFinitelyBounded(), shifted.isFinitelyBounded()); assertEquals(p, p.a.negate().shiftLeft(p.b), shifted.negate()); assertEquals(p, shifted, p.a.shiftRight(-p.b)); } for (Interval a : take(LIMIT, P.intervals())) { assertEquals(a, a.shiftLeft(0), a); } if (P instanceof QBarExhaustiveProvider) { is = P.naturalIntegers(); } else { is = ((QBarRandomProvider) P).naturalIntegersGeometric(); } for (Pair<Interval, Integer> p : take(LIMIT, P.pairs(P.intervals(), is))) { Interval shifted = p.a.shiftLeft(p.b); assertEquals(p, shifted, p.a.multiply(BigInteger.ONE.shiftLeft(p.b))); } } private void compareImplementationsShiftLeft() { initialize(""); System.out.println("\t\tcomparing shiftLeft(int) implementations..."); long totalTime = 0; Iterable<Integer> is; if (P instanceof QBarExhaustiveProvider) { is = P.integers(); } else { is = ((QBarRandomProvider) P).integersGeometric(); } for (Pair<Interval, Integer> p : take(LIMIT, P.pairs(P.intervals(), is))) { long time = System.nanoTime(); shiftLeft_simplest(p.a, p.b); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s"); totalTime = 0; for (Pair<Interval, Integer> p : take(LIMIT, P.pairs(P.intervals(), is))) { long time = System.nanoTime(); p.a.shiftLeft(p.b); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s"); } private static @NotNull Interval shiftRight_simplest(@NotNull Interval a, int bits) { if (bits < 0) { return a.multiply(BigInteger.ONE.shiftLeft(-bits)); } else { return a.divide(BigInteger.ONE.shiftLeft(bits)); } } private void propertiesShiftRight() { initialize(""); System.out.println("\t\ttesting shiftRight(int) properties..."); Iterable<Integer> is; if (P instanceof QBarExhaustiveProvider) { is = P.integers(); } else { is = ((QBarRandomProvider) P).integersGeometric(); } for (Pair<Interval, Integer> p : take(LIMIT, P.pairs(P.intervals(), is))) { Interval shifted = p.a.shiftRight(p.b); shifted.validate(); for (Rational r : take(TINY_LIMIT, P.rationalsIn(p.a))) { assertTrue(p, shifted.contains(r.shiftRight(p.b))); } assertEquals(p, shifted, shiftRight_simplest(p.a, p.b)); assertEquals(p, p.a.signum(), shifted.signum()); assertEquals(p, p.a.isFinitelyBounded(), shifted.isFinitelyBounded()); assertEquals(p, p.a.negate().shiftRight(p.b), shifted.negate()); assertEquals(p, shifted, p.a.shiftLeft(-p.b)); } for (Interval a : take(LIMIT, P.intervals())) { assertEquals(a, a.shiftRight(0), a); } if (P instanceof QBarExhaustiveProvider) { is = P.naturalIntegers(); } else { is = ((QBarRandomProvider) P).naturalIntegersGeometric(); } for (Pair<Interval, Integer> p : take(LIMIT, P.pairs(P.intervals(), is))) { Interval shifted = p.a.shiftRight(p.b); assertEquals(p, shifted, p.a.divide(BigInteger.ONE.shiftLeft(p.b))); } } private void compareImplementationsShiftRight() { initialize(""); System.out.println("\t\tcomparing shiftRight(int) implementations..."); long totalTime = 0; Iterable<Integer> is; if (P instanceof QBarExhaustiveProvider) { is = P.integers(); } else { is = ((QBarRandomProvider) P).integersGeometric(); } for (Pair<Interval, Integer> p : take(LIMIT, P.pairs(P.intervals(), is))) { long time = System.nanoTime(); shiftRight_simplest(p.a, p.b); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s"); totalTime = 0; for (Pair<Interval, Integer> p : take(LIMIT, P.pairs(P.intervals(), is))) { long time = System.nanoTime(); p.a.shiftRight(p.b); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s"); } private void propertiesSum() { initialize(""); System.out.println("\t\ttesting sum(Iterable<Interval>) properties..."); propertiesFoldHelper(LIMIT, P.getWheelsProvider(), P.intervals(), Interval::add, Interval::sum, a -> {}, true); for (List<Interval> is : take(LIMIT, P.lists(P.intervals()))) { Interval sum = sum(is); for (List<Rational> rs : take(TINY_LIMIT, transposeTruncating(map(P::rationalsIn, is)))) { assertTrue(is, sum.contains(Rational.sum(rs))); } assertEquals(is, sum.isFinitelyBounded(), is.isEmpty() || all(Interval::isFinitelyBounded, is)); } } private void propertiesProduct() { initialize(""); System.out.println("\t\ttesting product(Iterable<Interval>) properties..."); propertiesFoldHelper( LIMIT, P.getWheelsProvider(), P.intervals(), Interval::multiply, Interval::product, a -> {}, true ); for (List<Interval> is : take(LIMIT, P.lists(P.intervals()))) { Interval product = product(is); for (List<Rational> rs : take(TINY_LIMIT, transposeTruncating(map(P::rationalsIn, is)))) { assertTrue(is, product.contains(Rational.product(rs))); } assertEquals( is, product.isFinitelyBounded(), is.isEmpty() || is.contains(ZERO) || all(Interval::isFinitelyBounded, is) ); } } private void propertiesDelta() { initialize(""); System.out.println("\t\ttesting delta(Iterable<Interval>) properties..."); propertiesDeltaHelper( LIMIT, P.getWheelsProvider(), QEP.intervals(), P.intervals(), Interval::negate, Interval::subtract, Interval::delta, a -> {} ); for (List<Interval> is : take(LIMIT, P.listsAtLeast(1, P.intervals()))) { Iterable<Interval> deltas = delta(is); for (List<Rational> rs : take(TINY_LIMIT, transposeTruncating(map(P::rationalsIn, is)))) { assertTrue(is, and(zipWith(Interval::contains, deltas, Rational.delta(rs)))); } } } private void propertiesPow() { initialize(""); System.out.println("\t\ttesting pow(int) properties..."); Iterable<Pair<Interval, Integer>> ps = P.pairs(P.intervals(), P.withScale(20).integersGeometric()); for (Pair<Interval, Integer> p : take(LIMIT, ps)) { List<Interval> pow = p.a.pow(p.b); pow.forEach(Interval::validate); //todo fix hanging // Iterable<Rational> rs = p.b < 0 ? filter(r -> r != Rational.ZERO, P.rationals(p.a)) : P.rationals(p.a); // for (Rational r : take(TINY_LIMIT, rs)) { // assertTrue(p, any(s -> s.contains(r.pow(p.b)), pow)); int size = pow.size(); assertTrue(p, size == 0 || size == 1 || size == 2); if (size == 2) { Interval i1 = pow.get(0); Interval i2 = pow.get(1); Rational p1 = i1.getLower().isPresent() ? i1.getLower().get() : null; Rational q1 = i1.getUpper().isPresent() ? i1.getUpper().get() : null; Rational p2 = i2.getLower().isPresent() ? i2.getLower().get() : null; Rational q2 = i2.getUpper().isPresent() ? i2.getUpper().get() : null; assertTrue(p, p1 == null); assertTrue(p, q2 == null); if (p2 == Rational.ZERO) { assertTrue(p, q1.signum() == -1); } else if (q1 == Rational.ZERO) { assertTrue(p, p2.signum() == 1); } else { assertTrue(p, q1.signum() == -1); assertTrue(p, p2.signum() == 1); } } } ps = filter( p -> p.b >= 0 || !p.a.equals(ZERO), P.pairs(P.intervals(), P.withScale(20).integersGeometric()) ); for (Pair<Interval, Integer> p : take(LIMIT, ps)) { List<Interval> pow = p.a.pow(p.b); Interval x = product(replicate(Math.abs(p.b), p.a)); Interval product = p.b < 0 ? x.invertHull() : x; assertTrue(p, all(product::contains, pow)); } ps = P.pairs(filter(a -> !a.equals(ZERO), P.intervals()), P.withScale(20).integersGeometric()); for (Pair<Interval, Integer> p : take(LIMIT, ps)) { List<Interval> a = p.a.pow(p.b); assertTrue( p, any(c -> convexHull(toList(concatMap(Interval::invert, p.a.pow(-p.b)))).contains(c), a) ); assertTrue( p, any(c -> convexHull(toList(concatMap(b -> b.pow(-p.b), p.a.invert()))).contains(c), a) ); } for (int i : take(LIMIT, P.withScale(20).positiveIntegersGeometric())) { assertTrue(i, ZERO.pow(i).equals(Collections.singletonList(ZERO))); } for (Interval a : take(LIMIT, P.intervals())) { assertTrue(a, a.pow(0).equals(Collections.singletonList(ONE))); assertEquals(a, a.pow(1), Collections.singletonList(a)); Interval product = a.multiply(a); assertTrue(a, all(product::contains, a.pow(2))); assertEquals(a, a.pow(-1), a.invert()); } Iterable<Triple<Interval, Integer, Integer>> ts1 = filter( p -> p.b >= 0 && p.c >= 0 || !p.a.equals(ZERO), P.triples(P.intervals(), P.withScale(20).integersGeometric(), P.withScale(20).integersGeometric()) ); for (Triple<Interval, Integer, Integer> t : take(LIMIT, ts1)) { Interval expression1 = convexHull(toList(concatMap(a -> map(a::multiply, t.a.pow(t.c)), t.a.pow(t.b)))); Interval expression2 = convexHull(t.a.pow(t.b + t.c)); assertTrue(t, expression1.contains(expression2)); } ts1 = filter( t -> !t.a.equals(ZERO) || t.c == 0 && t.b >= 0, P.triples(P.intervals(), P.withScale(20).integersGeometric(), P.withScale(20).integersGeometric()) ); for (Triple<Interval, Integer, Integer> t : take(LIMIT, ts1)) { Interval expression1 = convexHull( toList(concatMap(a -> concatMap(a::divide, t.a.pow(t.c)), t.a.pow(t.b))) ); Interval expression2 = convexHull(t.a.pow(t.b - t.c)); assertTrue(t, expression1.contains(expression2)); } ts1 = filter( t -> !t.a.equals(ZERO) || t.b >= 0 && t.c >= 0, P.triples(P.intervals(), P.withScale(20).integersGeometric(), P.withScale(20).integersGeometric()) ); for (Triple<Interval, Integer, Integer> t : take(LIMIT, ts1)) { Interval expression5 = convexHull(toList(concatMap(a -> a.pow(t.c), t.a.pow(t.b)))); Interval expression6 = convexHull(t.a.pow(t.b * t.c)); assertTrue(t, expression5.contains(expression6)); } Iterable<Triple<Interval, Interval, Integer>> ts2 = filter( t -> !t.a.equals(ZERO) && !t.b.equals(ZERO) || t.c >= 0, P.triples(P.intervals(), P.intervals(), P.withScale(20).integersGeometric()) ); for (Triple<Interval, Interval, Integer> t : take(LIMIT, ts2)) { Interval expression1 = convexHull(t.a.multiply(t.b).pow(t.c)); Interval expression2 = convexHull(toList(concatMap(a -> map(a::multiply, t.b.pow(t.c)), t.a.pow(t.c)))); assertEquals(t, expression1, expression2); } ts2 = filter( t -> !t.a.equals(ZERO) || t.c >= 0, P.triples( P.intervals(), filter(a -> !a.equals(ZERO), P.intervals()), P.withScale(20).integersGeometric() ) ); for (Triple<Interval, Interval, Integer> t : take(LIMIT, ts2)) { Interval expression1 = convexHull(toList(concatMap(a -> a.pow(t.c), t.a.divide(t.b)))); Interval expression2 = convexHull( toList(concatMap(a -> concatMap(a::divide, t.b.pow(t.c)), t.a.pow(t.c))) ); assertTrue(t, expression1.contains(expression2)); } } private void propertiesPowHull() { initialize(""); System.out.println("\t\ttesting powHull(int) properties..."); Iterable<Pair<Interval, Integer>> ps = filter( p -> p.b >= 0 || !p.a.equals(ZERO), P.pairs(P.intervals(), P.withScale(20).integersGeometric()) ); for (Pair<Interval, Integer> p : take(LIMIT, ps)) { Interval pow = p.a.powHull(p.b); pow.validate(); //todo fix hanging // Iterable<Rational> rs = p.b < 0 ? filter(r -> r != Rational.ZERO, P.rationals(p.a)) : P.rationals(p.a); // for (Rational r : take(TINY_LIMIT, rs)) { // assertTrue(p, pow.contains(r.pow(p.b))); Interval product = product(replicate(Math.abs(p.b), p.a)); if (p.b < 0) product = product.invertHull(); assertTrue(p, product.contains(pow)); } ps = P.pairs(filter(a -> !a.equals(ZERO), P.intervals()), P.withScale(20).integersGeometric()); for (Pair<Interval, Integer> p : take(LIMIT, ps)) { Interval a = p.a.powHull(p.b); assertTrue(p, p.a.powHull(-p.b).invertHull().contains(a)); assertTrue(p, p.a.invertHull().powHull(-p.b).contains(a)); } for (int i : take(LIMIT, P.withScale(20).positiveIntegersGeometric())) { assertTrue(Integer.toString(i), ZERO.powHull(i).equals(ZERO)); } for (Interval a : take(LIMIT, P.intervals())) { assertTrue(a, a.powHull(0).equals(ONE)); assertEquals(a, a.powHull(1), a); assertTrue(a, a.multiply(a).contains(a.powHull(2))); } Iterable<Interval> rs = filter(a -> !a.equals(ZERO), P.intervals()); for (Interval a : take(LIMIT, rs)) { assertEquals(a, a.powHull(-1), a.invertHull()); } Iterable<Triple<Interval, Integer, Integer>> ts1 = filter( p -> p.b >= 0 && p.c >= 0 || !p.a.equals(ZERO), P.triples(P.intervals(), P.withScale(20).integersGeometric(), P.withScale(20).integersGeometric()) ); for (Triple<Interval, Integer, Integer> t : take(LIMIT, ts1)) { Interval expression1 = t.a.powHull(t.b).multiply(t.a.powHull(t.c)); Interval expression2 = t.a.powHull(t.b + t.c); assertTrue(t, expression1.contains(expression2)); } ts1 = filter( t -> !t.a.equals(ZERO) || t.c == 0 && t.b >= 0, P.triples(P.intervals(), P.withScale(20).integersGeometric(), P.withScale(20).integersGeometric()) ); for (Triple<Interval, Integer, Integer> t : take(LIMIT, ts1)) { Interval expression1 = t.a.powHull(t.b).divideHull(t.a.powHull(t.c)); Interval expression2 = t.a.powHull(t.b - t.c); assertTrue(t, expression1.contains(expression2)); } ts1 = filter( t -> !t.a.equals(ZERO) || t.b >= 0 && t.c >= 0, P.triples(P.intervals(), P.withScale(20).integersGeometric(), P.withScale(20).integersGeometric()) ); for (Triple<Interval, Integer, Integer> t : take(LIMIT, ts1)) { Interval expression5 = t.a.powHull(t.b).powHull(t.c); Interval expression6 = t.a.powHull(t.b * t.c); assertTrue(t, expression5.contains(expression6)); } Iterable<Triple<Interval, Interval, Integer>> ts2 = filter( t -> !t.a.equals(ZERO) && !t.b.equals(ZERO) || t.c >= 0, P.triples(P.intervals(), P.intervals(), P.withScale(20).integersGeometric()) ); for (Triple<Interval, Interval, Integer> t : take(LIMIT, ts2)) { Interval expression1 = t.a.multiply(t.b).powHull(t.c); Interval expression2 = t.a.powHull(t.c).multiply(t.b.powHull(t.c)); assertEquals(t, expression1, expression2); } ts2 = filter( t -> !t.a.equals(ZERO) || t.c >= 0, P.triples( P.intervals(), filter(a -> !a.equals(ZERO), P.intervals()), P.withScale(20).integersGeometric() ) ); for (Triple<Interval, Interval, Integer> t : take(LIMIT, ts2)) { Interval expression1 = t.a.divideHull(t.b).powHull(t.c); Interval expression2 = t.a.powHull(t.c).divideHull(t.b.powHull(t.c)); assertTrue(t, expression1.contains(expression2)); } for (int i : take(LIMIT, P.negativeIntegers())) { try { ZERO.powHull(i); fail(i); } catch (ArithmeticException ignored) {} } } private void propertiesElementCompare() { initialize(""); System.out.println("\t\ttesting elementCompare(Interval) properties..."); for (Pair<Interval, Interval> p : take(LIMIT, P.pairs(P.intervals()))) { @SuppressWarnings("UnusedDeclaration") Optional<Ordering> compare = p.a.elementCompare(p.b); } Iterable<Pair<Interval, Interval>> ps = filter( q -> q.a.elementCompare(q.b).isPresent(), P.pairs(P.intervals()) ); for (Pair<Interval, Interval> p : take(LIMIT, ps)) { Ordering compare = p.a.elementCompare(p.b).get(); assertEquals(p, p.b.elementCompare(p.a).get(), compare.invert()); } ps = filter( q -> !q.a.elementCompare(q.b).isPresent(), P.pairs(P.intervals()) ); for (Pair<Interval, Interval> p : take(LIMIT, ps)) { assertFalse(p, p.b.elementCompare(p.a).isPresent()); } for (Interval a : take(LIMIT, P.intervals())) { Optional<Ordering> compare = a.elementCompare(a); assertTrue(a, !compare.isPresent() || compare.get() == EQ); assertEquals(a, a.elementCompare(ZERO).map(Ordering::toInt), a.signum()); } Iterable<Triple<Interval, Interval, Interval>> ts = filter( t -> t.a.elementCompare(t.b).equals(Optional.of(LT)) && t.b.elementCompare(t.c).equals(Optional.of(LT)), P.triples(P.intervals()) ); for (Triple<Interval, Interval, Interval> t : take(LIMIT, ts)) { assertEquals(t, t.a.elementCompare(t.c), Optional.of(LT)); } } private void propertiesEquals() { initialize(""); System.out.println("\t\ttesting equals(Object) properties..."); propertiesEqualsHelper(LIMIT, P, QBarIterableProvider::intervals); } private void propertiesHashCode() { initialize(""); System.out.println("\t\ttesting hashCode() properties..."); propertiesHashCodeHelper(LIMIT, P, QBarIterableProvider::intervals); } private void propertiesCompareTo() { initialize(""); System.out.println("\t\ttesting compareTo(Interval) properties..."); propertiesCompareToHelper(LIMIT, P, QBarIterableProvider::intervals); } private void propertiesRead() { initialize(""); System.out.println("\t\ttesting read(String) properties..."); for (String s : take(LIMIT, P.strings())) { read(s); } for (Interval a : take(LIMIT, P.intervals())) { Optional<Interval> oi = read(a.toString()); assertEquals(a, oi.get(), a); } } private void propertiesFindIn() { initialize(""); System.out.println("\t\ttesting findIn(String) properties..."); propertiesFindInHelper(LIMIT, P.getWheelsProvider(), P.intervals(), Interval::read, Interval::findIn, a -> {}); } private void propertiesToString() { initialize(""); System.out.println("\t\ttesting toString() properties..."); for (Interval a : take(LIMIT, P.intervals())) { String s = a.toString(); assertTrue(a, isSubsetOf(s, INTERVAL_CHARS)); Optional<Interval> readI = read(s); assertTrue(a, readI.isPresent()); assertEquals(a, readI.get(), a); } } }
package mho.wheels.math; import mho.wheels.iterables.ExhaustiveProvider; import mho.wheels.iterables.IterableProvider; import mho.wheels.iterables.RandomProvider; import mho.wheels.structures.Pair; import org.jetbrains.annotations.NotNull; import org.junit.Test; import java.math.BigInteger; import java.util.Arrays; import java.util.List; import java.util.Random; import static mho.wheels.iterables.IterableUtils.*; import static mho.wheels.math.MathUtils.*; import static org.junit.Assert.*; public class MathUtilsProperties { private static boolean USE_RANDOM; private static int LIMIT; private static IterableProvider P; private static void initialize() { if (USE_RANDOM) { P = new RandomProvider(new Random(0x6af477d9a7e54fcaL)); LIMIT = 1000; } else { P = ExhaustiveProvider.INSTANCE; LIMIT = 10000; } } @Test public void testAllProperties() { System.out.println("MathUtils properties"); for (boolean useRandom : Arrays.asList(false, true)) { System.out.println("\ttesting " + (useRandom ? "randomly" : "exhaustively")); USE_RANDOM = useRandom; propertiesGcd_int_int(); compareImplementationsGcd_int_int(); propertiesGcd_long_long(); compareImplementationsGcd_long_long(); propertiesBits_int(); compareImplementationsBits_int(); } System.out.println("Done"); } private static int gcd_int_int_simplest(int x, int y) { return BigInteger.valueOf(x).gcd(BigInteger.valueOf(y)).intValue(); } private static int gcd_int_int_explicit(int x, int y) { x = Math.abs(x); y = Math.abs(y); if (x == 0) return y; if (y == 0) return x; return maximum(intersect(factors(x), factors(y))); } private static void propertiesGcd_int_int() { initialize(); System.out.println("\t\ttesting gcd(int, int) properties..."); Iterable<Pair<Integer, Integer>> ps = filter(p -> p.a != 0 || p.b != 0, P.pairs(P.integers())); for (Pair<Integer, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; int gcd = gcd(p.a, p.b); assertEquals(p.toString(), gcd, gcd_int_int_simplest(p.a, p.b)); assertEquals(p.toString(), gcd, gcd_int_int_explicit(p.a, p.b)); assertTrue(p.toString(), gcd >= 0); assertEquals(p.toString(), gcd, gcd(Math.abs(p.a), Math.abs(p.b))); } } private static void compareImplementationsGcd_int_int() { initialize(); System.out.println("\t\tcomparing gcd(int, int) implementations..."); long totalTime = 0; Iterable<Pair<Integer, Integer>> ps = filter(p -> p.a != 0 || p.b != 0, P.pairs(P.integers())); for (Pair<Integer, Integer> p : take(LIMIT, ps)) { long time = System.nanoTime(); assert p.a != null; assert p.b != null; gcd_int_int_simplest(p.a, p.b); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s"); for (Pair<Integer, Integer> p : take(LIMIT, ps)) { long time = System.nanoTime(); assert p.a != null; assert p.b != null; gcd_int_int_explicit(p.a, p.b); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\texplicit: " + ((double) totalTime) / 1e9 + " s"); totalTime = 0; for (Pair<Integer, Integer> p : take(LIMIT, ps)) { long time = System.nanoTime(); assert p.a != null; assert p.b != null; gcd(p.a, p.b); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s"); } private static long gcd_long_long_simplest(long x, long y) { return BigInteger.valueOf(x).gcd(BigInteger.valueOf(y)).longValue(); } private static long gcd_long_long_explicit(long x, long y) { x = Math.abs(x); y = Math.abs(y); if (x == 0) return y; if (y == 0) return x; return maximum(intersect(factors(BigInteger.valueOf(x)), factors(BigInteger.valueOf(y)))).longValue(); } private static void propertiesGcd_long_long() { initialize(); System.out.println("\t\ttesting gcd(long, long) properties..."); Iterable<Pair<Long, Long>> ps = filter(p -> p.a != 0 || p.b != 0, P.pairs(P.longs())); for (Pair<Long, Long> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; long gcd = gcd(p.a, p.b); assertEquals(p.toString(), gcd, gcd_long_long_simplest(p.a, p.b)); if (Math.abs(p.a) <= Integer.MAX_VALUE && Math.abs(p.b) <= Integer.MAX_VALUE) { assertEquals(p.toString(), gcd, gcd_long_long_explicit(p.a, p.b)); } assertTrue(p.toString(), gcd >= 0); assertEquals(p.toString(), gcd, gcd(Math.abs(p.a), Math.abs(p.b))); } } private static void compareImplementationsGcd_long_long() { initialize(); System.out.println("\t\tcomparing gcd(long, long) implementations..."); long totalTime = 0; Iterable<Pair<Long, Long>> ps = filter(p -> p.a != 0 || p.b != 0, P.pairs(P.longs())); for (Pair<Long, Long> p : take(LIMIT, ps)) { long time = System.nanoTime(); assert p.a != null; assert p.b != null; gcd_long_long_simplest(p.a, p.b); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s"); if (P instanceof ExhaustiveProvider) { for (Pair<Long, Long> p : take(LIMIT, ps)) { long time = System.nanoTime(); assert p.a != null; assert p.b != null; gcd_long_long_explicit(p.a, p.b); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\texplicit: " + ((double) totalTime) / 1e9 + " s"); } else { System.out.println("\t\t\texplicit: too long"); } totalTime = 0; for (Pair<Long, Long> p : take(LIMIT, ps)) { long time = System.nanoTime(); assert p.a != null; assert p.b != null; gcd(p.a, p.b); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s"); } private static @NotNull Iterable<Boolean> bits_int_simplest(int n) { return bits(BigInteger.valueOf(n)); } private static void propertiesBits_int() { initialize(); System.out.println("\t\ttesting bits(int) properties..."); for (int i : take(LIMIT, P.naturalIntegers())) { List<Boolean> bits = toList(bits(i)); aeq(Integer.toString(i), bits, bits_int_simplest(i)); assertTrue(Integer.toString(i), all(b -> b != null, bits)); assertEquals(Integer.toString(i), fromBits(bits).intValueExact(), i); } for (int i : take(LIMIT, P.positiveIntegers())) { List<Boolean> bits = toList(bits(i)); assertFalse(Integer.toString(i), bits.isEmpty()); assertEquals(Integer.toString(i), last(bits), true); } for (int i : take(LIMIT, P.negativeIntegers())) { try { bits(i); fail(Integer.toString(i)); } catch (ArithmeticException ignored) {} } } private static void compareImplementationsBits_int() { initialize(); System.out.println("\t\tcomparing bits(int) implementations..."); long totalTime = 0; for (int i : take(LIMIT, P.naturalIntegers())) { long time = System.nanoTime(); toList(bits_int_simplest(i)); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s"); totalTime = 0; for (int i : take(LIMIT, P.naturalIntegers())) { long time = System.nanoTime(); toList(bits(i)); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s"); } private static <T> void aeq(String message, Iterable<T> xs, Iterable<T> ys) { assertTrue(message, equal(xs, ys)); } }
package net.lshift.spki.convert; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.math.BigInteger; import net.lshift.spki.ParseException; import net.lshift.spki.SExp; import org.junit.Test; public class ConvertTest { @Test public void convertTest() throws ParseException, IOException { ConvertExample test = new ConvertExample( BigInteger.valueOf(3), BigInteger.valueOf(17)); SExp sexp = Convert.toSExp(test); //PrettyPrinter.prettyPrint(System.out, sexp); ConvertExample changeBack = Convert.fromSExp( ConvertExample.class, sexp); assertEquals(test, changeBack); } }
package operias.coverage; import static org.junit.Assert.*; import java.io.File; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import operias.OperiasStatus; import operias.coverage.CoberturaClass; import operias.coverage.CoberturaLine; import operias.coverage.CoberturaPackage; import operias.coverage.CoverageReport; import operias.test.general.ExitException; import operias.test.general.NoExitSecurityManager; import org.junit.After; import org.junit.Before; import org.junit.Test; public class CoverageReportTest { /** * Set up the security manager */ @Before public void setUp() { System.setSecurityManager(new NoExitSecurityManager()); } /** * Tear down the security manager */ @After public void tearDown() { System.setSecurityManager(null); } /** * Test invalid coverage XML files */ @Test public void testInvalidCoverageXML() { boolean exceptionThrown = false; try { new CoverageReport((File)null, "").constructReport();; } catch(ExitException e) { exceptionThrown = true; assertEquals("Wrong exit code", OperiasStatus.ERROR_COBERTURA_INVALID_XML.ordinal(), e.status); } assertTrue("No exception was thrown", exceptionThrown); exceptionThrown = false; try { new CoverageReport(new File(""), "").constructReport();; } catch(ExitException e) { exceptionThrown = true; assertEquals("Wrong exit code", OperiasStatus.ERROR_COBERTURA_INVALID_XML.ordinal(), e.status); } assertTrue("No exception was thrown", exceptionThrown); exceptionThrown = false; try { new CoverageReport(new File("src/test/resources/nonExistingFile.xml"), "").constructReport();; } catch(ExitException e) { exceptionThrown = true; assertEquals("Wrong exit code", OperiasStatus.ERROR_COBERTURA_INVALID_XML.ordinal(), e.status); } assertTrue("No exception was thrown", exceptionThrown); } /** * Test the loading of a coverage xml */ @Test public void testLoadXML() { double delta = 0.0001; File file = new File("src/test/resources/coverage.xml"); CoverageReport report = new CoverageReport(file, "src/test/resources/sureFireReports/").constructReport(); assertEquals("Line rate not equal", 0.7578125, report.getLineRate(), delta); assertEquals(0.75,report.getConditionRate(), delta); ArrayList<CoberturaPackage> packages = (ArrayList<CoberturaPackage>) report.getPackages(); assertEquals(2, packages.size()); CoberturaPackage cPackage = packages.get(0); assertEquals("operias", cPackage.getName()); assertEquals(0.6376811594202898, cPackage.getLineRate(), delta); assertEquals(0.6, cPackage.getConditionRate(), delta); // Check classes ArrayList<CoberturaClass> classes = (ArrayList<CoberturaClass>) cPackage.getClasses(); assertEquals(4, classes.size()); CoberturaClass cClass = classes.get(0); assertEquals("operias.Configuration", cClass.getName()); assertEquals("operias/Configuration.java", cClass.getFileName()); assertEquals(0.9230769230769231, cClass.getLineRate(), delta); assertEquals(1.0, cClass.getConditionRate(), delta); // Check lines in class LinkedList<CoberturaLine> classLines = (LinkedList<CoberturaLine>) cClass.getLines(); assertEquals(26, classLines.size()); List<TestReport> testcases = report.getTests(); assertEquals(3, testcases.size()); for(TestReport tReport : testcases) { if (tReport.getResult() == TestResultType.SUCCESS) { assertEquals("example.MusicTest", tReport.getClassName()); assertEquals("testMusic", tReport.getCaseName()); } else if (tReport.getResult() == TestResultType.ERROR) { assertEquals("example.CalculationsTest", tReport.getClassName()); assertEquals("testSomeCalcution", tReport.getCaseName()); } else if (tReport.getResult() == TestResultType.FAILURE) { assertEquals("example.LoopsTest", tReport.getClassName()); assertEquals("testLoop", tReport.getCaseName()); } } } }
package org.jspec.runner; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; import static org.jspec.util.Assertions.assertListEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Stack; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jspec.proto.JSpecExamples; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.Description; import org.junit.runner.RunWith; import org.junit.runners.model.InitializationError; import com.google.common.collect.ImmutableList; import de.bechte.junit.runners.context.HierarchicalContextRunner; @RunWith(HierarchicalContextRunner.class) public class NewJSpecRunnerTest { public class constructor { @Test public void givenAConfigurationWithoutErrors_raisesNoError() { runnerFor(configFinding()); } @Test public void givenAConfigurationWith1OrMoreErrors_raisesInitializationErrorWithThoseErrors() { TestConfiguration config = configFinding(new IllegalArgumentException(), new AssertionError()); assertInitializationError(config, ImmutableList.of(IllegalArgumentException.class, AssertionError.class)); } @Test public void givenAContextClassSuitableForJSpecButNotForJUnit_raisesNoError() { runnerFor(JSpecExamples.MultiplePublicConstructors.class); } private void assertInitializationError(TestConfiguration config, List<Class<? extends Throwable>> expectedCauses) { try { new NewJSpecRunner(config); } catch (InitializationError ex) { assertListEquals(expectedCauses, flattenCauses(ex).map(Throwable::getClass).collect(Collectors.toList())); return; } fail(String.format("Expected causes of initialization error to be <%s>, but nothing was thrown", expectedCauses)); } } public class getDescription { public class givenAContextClass { private final NewJSpecRunner runner = runnerFor(JSpecExamples.IgnoredClass.class); private final Description description = runner.getDescription(); @Test public void describesTheConfiguredClass() { assertThat(description.getTestClass(), equalTo(JSpecExamples.IgnoredClass.class)); assertThat(description.getAnnotation(Ignore.class), notNullValue()); } } public class givenATestConfiguration { private final NewJSpecRunner runner = runnerFor(configOf(JSpecExamples.IgnoredClass.class)); private final Description description = runner.getDescription(); @Test public void describesTheConfiguredClass() { assertThat(description.getTestClass(), equalTo(JSpecExamples.IgnoredClass.class)); assertThat(description.getAnnotation(Ignore.class), notNullValue()); } } public class givenATestConfigurationWith1OrMoreChildren { @Test public void describesChildrenUsingTheProtectedMethods() { fail("pending"); } } } public class run { public class givenAContextClass { @Test @Ignore public void createsAClassTestConfigurationForTheGivenClass() { fail("pending"); } } } private static TestConfiguration configOf(Class<?> contextClass) { return new TestConfiguration() { @Override public List<Throwable> findInitializationErrors() { return Collections.emptyList(); } @Override public boolean hasInitializationErrors() { return false; } @Override public Class<?> getContextClass() { return contextClass; } }; } private static TestConfiguration configFinding(Throwable... errors) { return new TestConfiguration() { @Override public List<Throwable> findInitializationErrors() { return Arrays.asList(errors); } @Override public boolean hasInitializationErrors() { return errors.length > 0; } @Override public Class<?> getContextClass() { return JSpecExamples.One.class; } }; } private static NewJSpecRunner runnerFor(Class<?> contextClass) { try { return new NewJSpecRunner(contextClass); } catch (InitializationError e) { return failForInitializationError(e); } } private static NewJSpecRunner runnerFor(TestConfiguration config) { try { return new NewJSpecRunner(config); } catch (InitializationError e) { return failForInitializationError(e); } } private static NewJSpecRunner failForInitializationError(InitializationError e) { System.out.println("\nInitialization error(s)"); flattenCauses(e).forEach(x -> { System.out.printf("[%s]\n", x.getClass()); x.printStackTrace(System.out); }); fail("Failed to create JSpecRunner"); return null; } private static Stream<Throwable> flattenCauses(InitializationError root) { List<Throwable> causes = new LinkedList<Throwable>(); Stack<InitializationError> nodesWithChildren = new Stack<InitializationError>(); nodesWithChildren.push(root); while (!nodesWithChildren.isEmpty()) { InitializationError parent = nodesWithChildren.pop(); for(Throwable child : parent.getCauses()) { if(child instanceof InitializationError) { nodesWithChildren.push((InitializationError) child); } else { causes.add(child); } } } return causes.stream(); } }
package seedu.todo.guitests; import static org.junit.Assert.assertEquals; import java.time.LocalDateTime; import org.junit.Before; import org.junit.Test; import seedu.todo.commons.util.DateUtil; import seedu.todo.models.Event; import seedu.todo.models.Task; /* * @@author A0139922Y */ public class FindCommandTest extends GuiTest { // Date variables to be use to initialise DB private static final LocalDateTime TODAY = LocalDateTime.now(); private static final String TODAY_STRING = DateUtil.formatDate(TODAY); private static final String TODAY_ISO_STRING = DateUtil.formatIsoDate(TODAY); private static final LocalDateTime TOMORROW = LocalDateTime.now().plusDays(1); private static final String TOMORROW_STRING = DateUtil.formatDate(TOMORROW); private static final String TOMORROW_ISO_STRING = DateUtil.formatIsoDate(TOMORROW); private static final LocalDateTime THE_DAY_AFTER_TOMORROW_ = LocalDateTime.now().plusDays(2); private static final String THE_DAY_AFTER_TOMORROW_STRING = DateUtil.formatDate(THE_DAY_AFTER_TOMORROW_); private static final String THE_DAY_AFTER_TOMORROW__ISO_STRING = DateUtil.formatIsoDate(THE_DAY_AFTER_TOMORROW_); // Command to be use to initialise DB private String commandAdd1 = String.format("add task Buy Coco by \"%s 8pm\" tag personal", TODAY_STRING); private Task task1 = new Task(); private String commandAdd2 = String.format("add task Buy Milk by \"%s 9pm\" tag personal", TOMORROW_STRING); private Task task2 = new Task(); private String commandAdd3 = String.format("add event CS2103 V0.5 Demo from \"%s 4pm\" to \"%s 5pm\" tag event", TOMORROW_STRING, TOMORROW_STRING); private Event event3 = new Event(); private String commandAdd4 = String.format("add event buying workshop from \"%s 8pm\" to \"%s 9pm\" tag buy", THE_DAY_AFTER_TOMORROW_STRING, THE_DAY_AFTER_TOMORROW_STRING); private Event event4 = new Event(); // Set up DB public FindCommandTest() { task1.setName("Buy Coco"); task1.setCalendarDateTime(DateUtil.parseDateTime( String.format("%s 20:00:00", TODAY_ISO_STRING))); task1.addTag("personal"); task1.setCompleted(); task2.setName("Buy Milk"); task2.setDueDate(DateUtil.parseDateTime( String.format("%s 21:00:00", TOMORROW_ISO_STRING))); task2.addTag("personal"); event3.setName("CS2103 V0.5 Demo"); event3.setStartDate(DateUtil.parseDateTime( String.format("%s 16:00:00", TOMORROW_ISO_STRING))); event3.setEndDate(DateUtil.parseDateTime( String.format("%s 17:00:00", TOMORROW_ISO_STRING))); event3.addTag("event"); event4.setName("buying workshop"); event4.setStartDate(DateUtil.parseDateTime( String.format("%s 20:00:00", THE_DAY_AFTER_TOMORROW__ISO_STRING))); event4.setEndDate(DateUtil.parseDateTime( String.format("%s 21:00:00", THE_DAY_AFTER_TOMORROW__ISO_STRING))); event4.addTag("buy"); } // Re-use @Before public void initFixtures() { console.runCommand("clear"); assertTaskVisibleAfterCmd(commandAdd1, task1); assertTaskVisibleAfterCmd(commandAdd2, task2); assertEventVisibleAfterCmd(commandAdd3, event3); assertEventVisibleAfterCmd(commandAdd4, event4); } // Re-use @Test public void fixtures_test() { console.runCommand("clear"); assertTaskNotVisibleAfterCmd("list", task1); assertTaskNotVisibleAfterCmd("list", task2); assertEventNotVisibleAfterCmd("list", event3); assertEventNotVisibleAfterCmd("list", event4); } @Test public void find_by_name() { String command = "find name buy"; assertTaskVisibleAfterCmd(command, task1); assertTaskVisibleAfterCmd(command, task2); assertEventNotVisibleAfterCmd(command, event3); assertEventVisibleAfterCmd(command, event4); } @Test public void find_task_by_name() { String command = "find name buy task"; assertTaskVisibleAfterCmd(command, task1); assertTaskVisibleAfterCmd(command, task2); assertEventNotVisibleAfterCmd(command, event3); assertEventNotVisibleAfterCmd(command, event4); } @Test public void find_event_by_name() { String command = "find name buy event"; assertTaskNotVisibleAfterCmd(command, task1); assertTaskNotVisibleAfterCmd(command, task2); assertEventNotVisibleAfterCmd(command, event3); assertEventVisibleAfterCmd(command, event4); } @Test public void find_by_invalid_name() { String command = "find name tester"; assertTaskVisibleAfterCmd(command, task1); assertTaskVisibleAfterCmd(command, task2); assertEventVisibleAfterCmd(command, event3); assertEventVisibleAfterCmd(command, event4); } @Test public void find_by_tag() { String command = "find tagName buy"; assertTaskNotVisibleAfterCmd(command, task1); assertTaskNotVisibleAfterCmd(command, task2); assertEventNotVisibleAfterCmd(command, event3); assertEventVisibleAfterCmd(command, event4); } @Test public void find_task_by_tag() { String command = "find tagName personal task"; assertTaskVisibleAfterCmd(command, task1); assertTaskVisibleAfterCmd(command, task2); assertEventNotVisibleAfterCmd(command, event3); assertEventNotVisibleAfterCmd(command, event4); } @Test public void find_event_by_tag() { String command = "find tagName buy event"; assertTaskNotVisibleAfterCmd(command, task1); assertTaskNotVisibleAfterCmd(command, task2); assertEventNotVisibleAfterCmd(command, event3); assertEventVisibleAfterCmd(command, event4); } @Test public void find_by_invalid_tag() { String command = "find tagName tester"; assertTaskVisibleAfterCmd(command, task1); assertTaskVisibleAfterCmd(command, task2); assertEventVisibleAfterCmd(command, event3); assertEventVisibleAfterCmd(command, event4); } @Test public void find_by_keyword() { String command = "find buy"; assertTaskVisibleAfterCmd(command, task1); assertTaskVisibleAfterCmd(command, task2); assertEventNotVisibleAfterCmd(command, event3); assertEventVisibleAfterCmd(command, event4); } @Test public void find_task_by_keyword() { String command = "find buy task"; assertTaskVisibleAfterCmd(command, task1); assertTaskVisibleAfterCmd(command, task2); assertEventNotVisibleAfterCmd(command, event3); assertEventNotVisibleAfterCmd(command, event4); } @Test public void find_event_by_keyword() { String command = "find buy event"; assertTaskNotVisibleAfterCmd(command, task1); assertTaskNotVisibleAfterCmd(command, task2); assertEventNotVisibleAfterCmd(command, event3); assertEventVisibleAfterCmd(command, event4); } @Test public void find_by_invalid_keyword() { String command = "find tester"; assertTaskVisibleAfterCmd(command, task1); assertTaskVisibleAfterCmd(command, task2); assertEventVisibleAfterCmd(command, event3); assertEventVisibleAfterCmd(command, event4); } @Test public void find_by_task_complete_status() { console.runCommand("complete 1"); String command = "find buy complete"; assertTaskVisibleAfterCmd(command, task1); assertTaskNotVisibleAfterCmd(command, task2); assertEventNotVisibleAfterCmd(command, event3); assertEventNotVisibleAfterCmd(command, event4); } @Test public void find_by_task_incomplete_status() { String command = "find buy incomplete"; assertTaskVisibleAfterCmd(command, task1); assertTaskVisibleAfterCmd(command, task2); assertEventNotVisibleAfterCmd(command, event3); assertEventNotVisibleAfterCmd(command, event4); } @Test public void find_by_event_current_status() { String command = "find buy current"; assertTaskNotVisibleAfterCmd(command, task1); assertTaskNotVisibleAfterCmd(command, task2); assertEventNotVisibleAfterCmd(command, event3); assertEventVisibleAfterCmd(command, event4); } @Test public void find_by_event_over_status() { String command = "find buy over"; assertTaskVisibleAfterCmd(command, task1); assertTaskVisibleAfterCmd(command, task2); assertEventVisibleAfterCmd(command, event3); assertEventVisibleAfterCmd(command, event4); } @Test public void find_by_single_date() { String command = "find buy on today"; assertTaskVisibleAfterCmd(command, task1); assertTaskNotVisibleAfterCmd(command, task2); assertEventNotVisibleAfterCmd(command, event3); assertEventNotVisibleAfterCmd(command, event4); } @Test public void find_by_date_range() { String command = "find buy from today"; assertTaskVisibleAfterCmd(command, task1); assertTaskVisibleAfterCmd(command, task2); assertEventNotVisibleAfterCmd(command, event3); assertEventVisibleAfterCmd(command, event4); } @Test public void find_task_by_single_date() { String command = "find buy task on today"; assertTaskVisibleAfterCmd(command, task1); assertTaskNotVisibleAfterCmd(command, task2); assertEventNotVisibleAfterCmd(command, event3); assertEventNotVisibleAfterCmd(command, event4); } @Test public void find_task_by_date_range() { String command = "find buy task from today"; assertTaskVisibleAfterCmd(command, task1); assertTaskVisibleAfterCmd(command, task2); assertEventNotVisibleAfterCmd(command, event3); assertEventNotVisibleAfterCmd(command, event4); } @Test public void find_event_by_single_date() { String command = "find CS2103 event on tomorrow"; assertTaskNotVisibleAfterCmd(command, task1); assertTaskNotVisibleAfterCmd(command, task2); assertEventVisibleAfterCmd(command, event3); assertEventNotVisibleAfterCmd(command, event4); } @Test public void find_event_by_date_range() { String command = "find buy event from today"; assertTaskNotVisibleAfterCmd(command, task1); assertTaskNotVisibleAfterCmd(command, task2); assertEventNotVisibleAfterCmd(command, event3); assertEventVisibleAfterCmd(command, event4); } @Test public void find_missingKeywords_disambiguate() { String command = "find"; console.runCommand(command); String expectedDisambiguation = "find \"name\" tagName \"tag\" on \"date\" \"task/event\""; assertEquals(console.getConsoleInputText(), expectedDisambiguation); } @Test public void find_invalidTaskSyntax_disambiguate() { String command = "find buy task over"; console.runCommand(command); String expectedDisambiguation = "find \"name\" task \"complete/incomplete\""; assertEquals(console.getConsoleInputText(), expectedDisambiguation); } @Test public void find_invalidEventSyntax_disambiguate() { String command = "find buy event complete"; console.runCommand(command); String expectedDisambiguation = "find \"name\" event \"over/ongoing\""; assertEquals(console.getConsoleInputText(), expectedDisambiguation); } }
package org.eclipse.birt.report.engine.api.impl; import java.io.IOException; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.birt.core.archive.IDocArchiveReader; import org.eclipse.birt.core.data.DataTypeUtil; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.data.engine.api.IQueryResults; import org.eclipse.birt.report.data.adapter.api.DataRequestSession; import org.eclipse.birt.report.engine.api.EngineConstants; import org.eclipse.birt.report.engine.api.EngineException; import org.eclipse.birt.report.engine.api.HTMLRenderContext; import org.eclipse.birt.report.engine.api.HTMLRenderOption; import org.eclipse.birt.report.engine.api.IEngineConfig; import org.eclipse.birt.report.engine.api.IEngineTask; import org.eclipse.birt.report.engine.api.IPDFRenderOption; import org.eclipse.birt.report.engine.api.IRenderOption; import org.eclipse.birt.report.engine.api.IReportEngine; import org.eclipse.birt.report.engine.api.IReportRunnable; import org.eclipse.birt.report.engine.api.PDFRenderContext; import org.eclipse.birt.report.engine.api.PDFRenderOption; import org.eclipse.birt.report.engine.api.RenderOption; import org.eclipse.birt.report.engine.api.UnsupportedFormatException; import org.eclipse.birt.report.engine.api.script.IReportContext; import org.eclipse.birt.report.engine.emitter.EngineEmitterServices; import org.eclipse.birt.report.engine.emitter.IContentEmitter; import org.eclipse.birt.report.engine.executor.ExecutionContext; import org.eclipse.birt.report.engine.executor.IReportExecutor; import org.eclipse.birt.report.engine.extension.internal.ExtensionManager; import org.eclipse.birt.report.engine.i18n.MessageConstants; import org.eclipse.birt.report.engine.layout.IReportLayoutEngine; import org.eclipse.birt.report.engine.layout.LayoutEngineFactory; import org.eclipse.birt.report.engine.script.internal.ReportContextImpl; import org.eclipse.birt.report.engine.script.internal.ReportScriptExecutor; import org.eclipse.birt.report.model.api.CascadingParameterGroupHandle; import org.eclipse.birt.report.model.api.DataSetHandle; import org.eclipse.birt.report.model.api.IncludeScriptHandle; import org.eclipse.birt.report.model.api.ParameterGroupHandle; import org.eclipse.birt.report.model.api.ReportDesignHandle; import org.eclipse.birt.report.model.api.ScalarParameterHandle; import org.eclipse.birt.report.model.api.SlotHandle; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; import com.ibm.icu.util.TimeZone; import com.ibm.icu.util.ULocale; /** * Defines an engine task that could be executed, debugged (runs step by step), * inform caller for progress, etc. */ public abstract class EngineTask implements IEngineTask { public final static String TASK_TYPE = "task_type"; protected static int id = 0; protected String pagination; protected final static String FORMAT_HTML = "html"; /** * is cancel called */ protected boolean cancelFlag; protected int runningStatus; /** * a reference to the report engine */ protected ReportEngine engine; /** * logger used to output the message */ protected Logger log; /** * Comment for <code>locale</code> */ protected Locale locale = Locale.getDefault( ); /** * define a time zone, and set a default value */ protected TimeZone timeZone = TimeZone.getDefault( ); /** * the execution context */ protected ExecutionContext executionContext; /** * task identifier. Could be used for logging */ protected int taskID; protected IReportRunnable runnable; /** * options used to render the report design. */ protected IRenderOption renderOptions; /** * emitter id */ protected String emitterID; /** * does the parameter has been changed by the user. */ protected boolean parameterChanged = true; /** * The parameter values that the caller has set explicitly */ protected HashMap inputValues = new HashMap( ); /** * The parameter values that will be used to run the report. It is a merged * map between the input value and the default values. */ protected HashMap runValues = new HashMap( ); /** * Engine task type. for usage in BIRT scripting. */ protected int taskType = IEngineTask.TASK_UNKNOWN; /** * @param engine * reference to report engine * @param appContext * a user-defined object that capsulates the context for running * a task. The context object is passed to callback functions * (i.e., functions in image handlers, action handlers, etc. ) * that are written by those who embeds engine in their * applications */ protected EngineTask( ReportEngine engine, IReportRunnable runnable ) { taskID = id++; this.engine = engine; this.log = engine.getLogger( ); // create execution context used by java-script executionContext = new ExecutionContext( this ); // Create IReportContext used by java-based script executionContext.setReportContext( new ReportContextImpl( executionContext ) ); setReportRunnable( runnable ); // set the default app context setAppContext( engine.getConfig( ).getAppContext( ) ); cancelFlag = false; runningStatus = STATUS_NOT_STARTED; } protected EngineTask( ReportEngine engine, IReportRunnable runnable, int taskType ) { this( engine, runnable ); this.taskType = taskType; } /** * @return Returns the locale. */ public Locale getLocale( ) { return locale; } /** * @return Returns the ulocale. */ public ULocale getULocale( ) { return ULocale.forLocale( locale ); } /** * sets the task locale * * The locale must be called in the same thread which create the engine task * * @param locale * the task locale */ public void setLocale( Locale locale ) { log.log( Level.FINE, "EngineTask.setLocale: locale={0}", locale == null ? null : locale.getDisplayName( ) ); doSetLocale( locale ); } private void doSetLocale( Locale locale ) { this.locale = locale; executionContext.setLocale( locale ); EngineException.setULocale( ULocale.forLocale( locale ) ); } /** * sets the task locale * * @param locale * the task locale */ public void setLocale( ULocale uLocale ) { log.log( Level.FINE, "EngineTask.setLocale: uLocale={0}", uLocale == null ? null : uLocale.getDisplayName( ) ); doSetLocale( uLocale.toLocale( ) ); } public void setTimeZone( TimeZone timeZone ) { this.timeZone = timeZone; executionContext.setTimeZone( timeZone ); } /** * sets the task context * * @param context * the task context */ public void setAppContext( Map context ) { HashMap appContext = new HashMap( ); HashMap sysAppContext = engine.getConfig( ).getAppContext( ); if ( sysAppContext != null ) { appContext.putAll( sysAppContext ); } addAppContext( context, appContext ); executionContext.setAppContext( appContext ); StringBuffer logStr = null; if ( log.isLoggable( Level.FINE ) ) logStr = new StringBuffer( ); // add the contexts into ScriptableJavaObject if ( !appContext.isEmpty( ) ) { Set entries = appContext.entrySet( ); for ( Iterator iter = entries.iterator( ); iter.hasNext( ); ) { Map.Entry entry = (Map.Entry) iter.next( ); if ( entry.getKey( ) instanceof String ) { executionContext.registerBean( (String) entry.getKey( ), entry.getValue( ) ); if ( logStr != null ) { logStr.append( entry.getKey( ) ); logStr.append( "=" ); logStr.append( entry.getValue( ) ); logStr.append( ";" ); } } else { log .log( Level.WARNING, "Map entry {0} is invalid and ignored, because its key is a not string.", //$NON-NLS-1$ entry.getKey( ).toString( ) ); } } } if ( logStr != null ) log.log( Level.FINE, "EngineTask.setAppContext: context={0}", logStr ); } /** * Merges user specified app context to that of EngineTask. The context * variables in entry with following keys will be ignored: * * <ul> * <li><code>EngineConstants.APPCONTEXT_CLASSLOADER_KEY</code> * <li><code>EngineConstants.WEBAPP_CLASSPATH_KEY</code> * <li><code>EngineConstants.PROJECT_CLASSPATH_KEY</code> * <li><code>EngineConstants.WORKSPACE_CLASSPATH_KEY</code> * </ul> * * @param from * the source app contexts. * @param to * the destination app contexts. */ private void addAppContext( Map from, Map to ) { if ( to == null ) { return; } Iterator iterator = from.entrySet( ).iterator( ); while ( iterator.hasNext( ) ) { Map.Entry entry = (Map.Entry) iterator.next( ); //Ignore the entry that should not be set from engine task. if ( !isDeprecatedEntry( entry ) ) { to.put( entry.getKey( ), entry.getValue( ) ); } } } private boolean isDeprecatedEntry( Map.Entry entry ) { Object key = entry.getKey( ); if ( EngineConstants.APPCONTEXT_CLASSLOADER_KEY.equals( key ) || EngineConstants.WEBAPP_CLASSPATH_KEY.equals( key ) || EngineConstants.PROJECT_CLASSPATH_KEY.equals( key ) || EngineConstants.WORKSPACE_CLASSPATH_KEY.equals( key ) ) { log .log( Level.WARNING, key + " could not be set in appContext of IEngineTask, please set it in appContext of IReportEngine" ); return true; } return false; } /** * returns the object that encapsulates the context for running the task * * @return Returns the context. */ public Map getAppContext( ) { return executionContext.getAppContext( ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.api2.IEngineTask#getEngine() */ public IReportEngine getEngine( ) { return engine; } public void setReportRunnable( IReportRunnable runnable ) { if ( runnable != null ) { this.runnable = runnable; executionContext.setRunnable( runnable ); // register the properties into the scope, so the user can // access the config through the property name directly. executionContext.registerBeans( System.getProperties( ) ); executionContext.registerBeans( runnable.getTestConfig( ) ); // put the properties into the configs also, so the user can // access the config through config["name"]. executionContext.getConfigs( ).putAll( System.getProperties( ) ); executionContext.getConfigs( ).putAll( runnable.getTestConfig( ) ); } } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.api2.IEngineTask#getReportRunnable() */ public IReportRunnable getReportRunnable( ) { return runnable; } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.api.IRenderTask#setRenderOption(org.eclipse.birt.report.engine.api.IRenderOption) */ public void setRenderOption( IRenderOption options ) { if ( options == null ) { throw new NullPointerException( "options can't be null" ); } renderOptions = options; } public IRenderOption getRenderOption( ) { return renderOptions; } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.api.IRenderTask#setEmitterID(java.lang.String) */ /** * @deprecated */ public void setEmitterID( String id ) { this.emitterID = id; } /** * @deprecated * @return the emitter ID to be used to render this report. Could be null, * in which case the engine will choose one emitter that matches the * requested output format. */ public String getEmitterID( ) { return this.emitterID; } public DataRequestSession getDataSession( ) { return executionContext.getDataEngine( ).getDTESession( ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.api2.IEngineTask#addScriptableJavaObject(java.lang.String, * java.lang.Object) */ public void addScriptableJavaObject( String jsName, Object obj ) { executionContext.registerBean( jsName, obj ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.api2.IEngineTask#getID() */ public int getID( ) { return taskID; } protected Object convertToType( Object value, String type ) { try { return convertParameterType( value, type ); } catch ( BirtException e ) { log.log( Level.SEVERE, e.getLocalizedMessage( ), e ); } return null; } public static Object convertParameterType( Object value, String type ) throws BirtException { if ( DesignChoiceConstants.PARAM_TYPE_BOOLEAN.equals( type ) ) { return DataTypeUtil.toBoolean( value ); } else if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( type ) ) { return DataTypeUtil.toDate( value ); } else if ( DesignChoiceConstants.PARAM_TYPE_DATE.equals( type ) ) { return DataTypeUtil.toSqlDate( value ); } else if ( DesignChoiceConstants.PARAM_TYPE_TIME.equals( type ) ) { return DataTypeUtil.toSqlTime( value ); } else if ( DesignChoiceConstants.PARAM_TYPE_DECIMAL.equals( type ) ) { return DataTypeUtil.toBigDecimal( value ); } else if ( DesignChoiceConstants.PARAM_TYPE_FLOAT.equals( type ) ) { return DataTypeUtil.toDouble( value ); } else if ( DesignChoiceConstants.PARAM_TYPE_STRING.equals( type ) ) { return DataTypeUtil.toString( value ); } else if ( DesignChoiceConstants.PARAM_TYPE_INTEGER.equals( type ) ) { return DataTypeUtil.toInteger( value ); } return value; } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.api2.IRunAndRenderTask#validateParameters() */ public boolean validateParameters( ) { if ( runnable == null ) { return false; } // set the parameter values into the execution context try { doValidateParameters( ); return true; } catch(ParameterValidationException ex) { log.log( Level.SEVERE, ex.getMessage( ), ex ); } return false; } protected boolean doValidateParameters() throws ParameterValidationException { // set the parameter values into the execution context usingParameterValues( ); if ( log.isLoggable( Level.FINE ) ) { loggerParamters( ); } // validate each parameter to see if it is validate ParameterValidationVisitor pv = new ParameterValidationVisitor( ); boolean result = pv.visit( (ReportDesignHandle) runnable .getDesignHandle( ), null ); if ( pv.engineException != null ) { throw pv.engineException; } return result; } private class ParameterValidationVisitor extends ParameterVisitor { ParameterValidationException engineException; boolean visitScalarParameter( ScalarParameterHandle param, Object value ) { try { return validateScalarParameter( param ); } catch ( ParameterValidationException pe ) { engineException = pe; } return false; } boolean visitParameterGroup( ParameterGroupHandle group, Object value ) { return visitParametersInGroup( group, value ); } }; protected void loggerParamters( ) { if ( log.isLoggable( Level.FINE ) ) { final StringBuffer buffer = new StringBuffer( ); // validate each parameter to see if it is validate new ParameterVisitor( ) { boolean visitScalarParameter( ScalarParameterHandle param, Object value ) { String paramName = param.getName( ); Object paramValue = runValues.get( paramName ); buffer.append( paramName ); buffer.append( ":" ); buffer.append( paramValue ); buffer.append( "\n" ); return true; } boolean visitParameterGroup( ParameterGroupHandle group, Object value ) { return visitParametersInGroup( group, value ); } }.visit( (ReportDesignHandle) runnable.getDesignHandle( ), null ); log.log( Level.FINE, "Running the report with paramters: {0}", buffer ); } } /** * validate whether the parameter value is a valid value for the parameter * * @param p * the parameter to be verified * @param paramValue * the value for the parameter * @return true if the given parameter value is valid; false otherwise */ private boolean validateScalarParameter( ScalarParameterHandle paramHandle ) throws ParameterValidationException { String paramName = paramHandle.getName( ); Object paramValue = runValues.get( paramName ); String type = paramHandle.getDataType( ); // Handle null parameter values if ( paramValue == null ) { if ( !paramHandle.isRequired( ) ) return true; throw new ParameterValidationException( MessageConstants.NULL_PARAMETER_EXCEPTION, new String[]{paramName} ); } String source = paramHandle.getValidate(); if (source != null && source.length() != 0) { Object result = executionContext.evaluate(source); if (!(result instanceof Boolean) || !((Boolean) result).booleanValue()) { throw new ParameterValidationException( MessageConstants.PARAMETER_SCRIPT_VALIDATION_EXCEPTION, new String[] { paramName }); } } String paramType = paramHandle.getParamType( ); if ( DesignChoiceConstants.SCALAR_PARAM_TYPE_MULTI_VALUE .equals( paramType ) ) { if ( paramValue instanceof Object[] ) { boolean isValid = true; Object[] paramValueList = (Object[]) paramValue; for ( int i = 0; i < paramValueList.length; i++ ) { if ( paramValueList[i] != null ) { if ( !validateParameterValueType( paramName, paramValueList[i], type, paramHandle ) ) { isValid = false; } } } return isValid; } throw new ParameterValidationException( MessageConstants.INVALID_PARAMETER_TYPE_EXCEPTION, new String[] { paramName, "Object[]", paramValue.getClass().getName() }); } else { return validateParameterValueType( paramName, paramValue, type, paramHandle ); } } /* * Validate parameter value based on parameter type */ private boolean validateParameterValueType( String paramName, Object paramValue, String type, ScalarParameterHandle paramHandle ) throws ParameterValidationException { /* * Validate based on parameter type */ if ( DesignChoiceConstants.PARAM_TYPE_DECIMAL.equals( type ) || DesignChoiceConstants.PARAM_TYPE_FLOAT.equals( type ) ) { if ( paramValue instanceof Number ) return true; throw new ParameterValidationException( MessageConstants.INVALID_PARAMETER_TYPE_EXCEPTION, new String[]{paramName, type, paramValue.getClass( ).getName( )} ); } else if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( type ) ) { if ( paramValue instanceof Date ) return true; throw new ParameterValidationException( MessageConstants.INVALID_PARAMETER_TYPE_EXCEPTION, new String[]{paramName, type, paramValue.getClass( ).getName( )} ); } else if ( DesignChoiceConstants.PARAM_TYPE_DATE.equals( type ) ) { if ( paramValue instanceof java.sql.Date ) return true; throw new ParameterValidationException( MessageConstants.INVALID_PARAMETER_TYPE_EXCEPTION, new String[]{paramName, type, paramValue.getClass( ).getName( )} ); } else if ( DesignChoiceConstants.PARAM_TYPE_TIME.equals( type ) ) { if ( paramValue instanceof java.sql.Time ) return true; throw new ParameterValidationException( MessageConstants.INVALID_PARAMETER_TYPE_EXCEPTION, new String[]{paramName, type, paramValue.getClass( ).getName( )} ); } else if ( DesignChoiceConstants.PARAM_TYPE_STRING.equals( type ) ) { if ( paramHandle.isRequired( ) ) //$NON-NLS-1$ { String value = paramValue.toString( ).trim( ); if ( value.length( ) == 0 ) { throw new ParameterValidationException( MessageConstants.BLANK_PARAMETER_EXCEPTION, new String[]{paramName} ); } } return true; } else if ( DesignChoiceConstants.PARAM_TYPE_BOOLEAN.equals( type ) ) { if ( paramValue instanceof Boolean ) return true; throw new ParameterValidationException( MessageConstants.INVALID_PARAMETER_TYPE_EXCEPTION, new String[]{paramName, type, paramValue.getClass( ).getName( )} ); } return true; } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.api.IEngineTask#setParameterValues(java.util.HashMap) */ public void setParameterValues( Map params ) { Iterator iterator = params.entrySet( ).iterator( ); while ( iterator.hasNext( ) ) { Map.Entry entry = (Map.Entry) iterator.next( ); String name = (String) entry.getKey( ); Object value = entry.getValue( ); setParameterValue( name, value ); } } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.api.IEngineTask#setParameterValue(java.lang.String, * java.lang.Object) */ public void setParameterValue( String name, Object value ) { log.log( Level.FINE, "EngineTask.setParameterValue: {0}={1} [{2}]", new Object[]{name, value, value == null ? null : value.getClass( ).getName( )} ); parameterChanged = true; Object parameter = inputValues.get( name ); if ( parameter != null ) { assert parameter instanceof ParameterAttribute; ( (ParameterAttribute) parameter ).setValue( value ); } else { inputValues.put( name, new ParameterAttribute( value, null ) ); } } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.api.IEngineTask#setParameterValue(java.lang.String, * java.lang.Object) */ public void setValue( String name, Object value ) { setParameterValue( name, value ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.api.IEngineTask#getParameterValues() */ public HashMap getParameterValues( ) { HashMap result = new HashMap( ); Iterator iterator = inputValues.entrySet( ).iterator( ); while ( iterator.hasNext( ) ) { Map.Entry entry = (Map.Entry) iterator.next( ); ParameterAttribute parameter = (ParameterAttribute) entry .getValue( ); result.put( entry.getKey( ), parameter.getValue( ) ); } return result; } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.api.IEngineTask#getParameterValue(java.lang.String) */ public Object getParameterValue( String name ) { Object parameter = inputValues.get( name ); if ( parameter == null ) { return null; } assert parameter instanceof ParameterAttribute; return ( (ParameterAttribute) parameter ).getValue( ); } public void setParameter( String name, Object value, String displayText ) { parameterChanged = true; inputValues.put( name, new ParameterAttribute( value, displayText ) ); } public String getParameterDisplayText( String name ) { Object parameter = inputValues.get( name ); if ( parameter != null ) { assert parameter instanceof ParameterAttribute; return ( (ParameterAttribute) parameter ).getDisplayText( ); } return null; } public void setParameterDisplayTexts( Map params ) { Iterator iterator = params.entrySet( ).iterator( ); while ( iterator.hasNext( ) ) { Map.Entry entry = (Map.Entry) iterator.next( ); String name = (String) entry.getKey( ); String text = (String) entry.getValue( ); setParameterDisplayText( name, text ); } } public void setParameterDisplayText( String name, String displayText ) { parameterChanged = true; Object parameter = inputValues.get( name ); if ( parameter != null ) { assert parameter instanceof ParameterAttribute; ( (ParameterAttribute) parameter ).setDisplayText( displayText ); } else { inputValues.put( name, new ParameterAttribute( null, displayText ) ); } } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.api.IEngineTask#cancel() */ public void cancel( ) { cancelFlag = true; executionContext.cancel( ); } public void cancel( Object signal ) { if ( signal == null ) { throw new IllegalArgumentException( "signal can't be null" ); } cancelFlag = true; long waitingTime = 0; do { waitingTime += 100; try { Thread.sleep( 100 ); } catch ( Exception ex ) { } if ( runningStatus != STATUS_RUNNING ) { return; } } while ( waitingTime < 5000 ); return; } public boolean getCancelFlag( ) { return cancelFlag; } public void setErrorHandlingOption( int option ) { if ( option == CANCEL_ON_ERROR ) { executionContext.setCancelOnError( true ); } else { executionContext.setCancelOnError( false ); } } /** * class used to visit all parameters * */ static abstract class ParameterVisitor { boolean visitParametersInGroup( ParameterGroupHandle group, Object value ) { SlotHandle parameters = group.getParameters( ); Iterator iter = parameters.iterator( ); while ( iter.hasNext( ) ) { Object param = iter.next( ); if ( param instanceof CascadingParameterGroupHandle ) { if ( !visitCascadingParamterGroup( (CascadingParameterGroupHandle) param, value ) ) { return false; } } else if ( param instanceof ParameterGroupHandle ) { if ( !visitParameterGroup( (ParameterGroupHandle) param, value ) ) { return false; } } else if ( param instanceof ScalarParameterHandle ) { if ( !visitScalarParameter( (ScalarParameterHandle) param, value ) ) { return false; } } } return true; } boolean visitCascadingParamterGroup( CascadingParameterGroupHandle group, Object value ) { return visitParameterGroup( group, value ); } boolean visitParameterGroup( ParameterGroupHandle group, Object value ) { return false; } boolean visitScalarParameter( ScalarParameterHandle param, Object value ) { return false; } boolean visit( ReportDesignHandle report ) { return visit( report, null ); } boolean visit( ReportDesignHandle report, Object value ) { SlotHandle parameters = report.getParameters( ); Iterator iter = parameters.iterator( ); while ( iter.hasNext( ) ) { Object param = iter.next( ); if ( param instanceof CascadingParameterGroupHandle ) { if ( !visitCascadingParamterGroup( (CascadingParameterGroupHandle) param, value ) ) { return false; } } else if ( param instanceof ParameterGroupHandle ) { if ( !visitParameterGroup( (ParameterGroupHandle) param, value ) ) { return false; } } else if ( param instanceof ScalarParameterHandle ) { if ( !visitScalarParameter( (ScalarParameterHandle) param, value ) ) { return false; } } } return true; } } protected IQueryResults executeDataSet( DataSetHandle hDataSet, HashMap parameters ) { return null; } /** * use the user setting parameters values to setup the execution context. * the user setting values and default values are merged here. */ protected void usingParameterValues( ) { if ( !parameterChanged ) { return; } parameterChanged = false; // clear previous settings executionContext.clearParameters( ); runValues.clear( ); // set the user setting values into the execution context Iterator iterator = inputValues.entrySet( ).iterator( ); while ( iterator.hasNext( ) ) { Map.Entry entry = (Map.Entry) iterator.next( ); Object key = entry.getKey( ); ParameterAttribute attribute = (ParameterAttribute) entry .getValue( ); runValues.put( key, attribute.getValue( ) ); executionContext.setParameter( (String) key, attribute.getValue( ), attribute.getDisplayText( ) ); } if ( runnable == null ) { return; } // use default value for the parameter without user value. new ParameterVisitor( ) { boolean visitScalarParameter( ScalarParameterHandle param, Object userData ) { String name = param.getName( ); if ( !inputValues.containsKey( name ) ) { Object value = convertToType( param.getDefaultValue( ), param.getDataType( ) ); executionContext.setParameterValue( name, value ); runValues.put( name, value ); } return true; } boolean visitParameterGroup( ParameterGroupHandle group, Object value ) { return visitParametersInGroup( group, value ); } }.visit( (ReportDesignHandle) runnable.getDesignHandle( ) ); } public void close( ) { executionContext.close( ); EngineLoggerHandler.setLogger( null ); } protected IContentEmitter createContentEmitter( ) throws EngineException { String format = renderOptions.getOutputFormat( ); if ( format == null ) { format = RenderOption.OUTPUT_FORMAT_HTML; } ExtensionManager extManager = ExtensionManager.getInstance( ); boolean supported = false; Collection supportedFormats = extManager.getSupportedFormat( ); Iterator iter = supportedFormats.iterator( ); while ( iter.hasNext( ) ) { String supportedFormat = (String) iter.next( ); if ( supportedFormat != null && supportedFormat.equalsIgnoreCase( format ) ) { supported = true; break; } } if ( !supported ) { log.log( Level.SEVERE, MessageConstants.FORMAT_NOT_SUPPORTED_EXCEPTION, format ); throw new UnsupportedFormatException( MessageConstants.FORMAT_NOT_SUPPORTED_EXCEPTION, format ); } pagination = extManager.getPagination( format ); Boolean outputDisplayNone = extManager.getOutputDisplayNone( format ); if ( !renderOptions.hasOption( IRenderOption.OUTPUT_DISPLAY_NONE ) ) { renderOptions.setOption( IRenderOption.OUTPUT_DISPLAY_NONE, outputDisplayNone ); } IContentEmitter emitter = null; try { emitter = extManager.createEmitter( format, emitterID ); } catch ( Throwable t ) { log.log( Level.SEVERE, "Report engine can not create {0} emitter.", //$NON-NLS-1$ format ); // $NON-NLS-1$ throw new EngineException( MessageConstants.CANNOT_CREATE_EMITTER_EXCEPTION, format, t ); } if ( emitter == null ) { log.log( Level.SEVERE, "Report engine can not create {0} emitter.", //$NON-NLS-1$ format ); // $NON-NLS-1$ throw new EngineException( MessageConstants.CANNOT_CREATE_EMITTER_EXCEPTION, format ); } return emitter; } protected IReportLayoutEngine createReportLayoutEngine( String pagination, IRenderOption options ) { IReportLayoutEngine layoutEngine = LayoutEngineFactory .createLayoutEngine( pagination ); if ( options != null ) { Object fitToPage = renderOptions .getOption( IPDFRenderOption.FIT_TO_PAGE ); if ( fitToPage != null ) { layoutEngine .setOption( IPDFRenderOption.FIT_TO_PAGE, fitToPage ); } Object pagebreakOnly = renderOptions .getOption( IPDFRenderOption.PAGEBREAK_PAGINATION_ONLY ); if ( pagebreakOnly != null ) { layoutEngine.setOption( IPDFRenderOption.PAGEBREAK_PAGINATION_ONLY, pagebreakOnly ); } Object pageOverflow = renderOptions .getOption( IPDFRenderOption.PAGE_OVERFLOW ); if ( pageOverflow != null ) { layoutEngine.setOption( IPDFRenderOption.PAGE_OVERFLOW, pageOverflow ); } Object outputDisplayNone = renderOptions .getOption( IPDFRenderOption.OUTPUT_DISPLAY_NONE ); if ( outputDisplayNone != null ) { layoutEngine.setOption( IPDFRenderOption.OUTPUT_DISPLAY_NONE, outputDisplayNone ); } Object pdfTextWrapping = renderOptions .getOption( IPDFRenderOption.PDF_TEXT_WRAPPING ); if ( pdfTextWrapping != null ) { layoutEngine.setOption( IPDFRenderOption.PDF_TEXT_WRAPPING, pdfTextWrapping ); } Object pdfFontSubstitution = renderOptions .getOption( IPDFRenderOption.PDF_FONT_SUBSTITUTION ); if ( pdfFontSubstitution != null ) { layoutEngine.setOption( IPDFRenderOption.PDF_FONT_SUBSTITUTION, pdfFontSubstitution ); } Object pdfBidiProcessing = renderOptions .getOption( IPDFRenderOption.PDF_BIDI_PROCESSING ); if ( pdfBidiProcessing != null ) { layoutEngine.setOption( IPDFRenderOption.PDF_BIDI_PROCESSING, pdfBidiProcessing ); } } layoutEngine.setOption( TASK_TYPE, new Integer(taskType)); return layoutEngine; } protected void loadDesign( ) { if ( runnable != null ) { ReportDesignHandle reportDesign = executionContext.getDesign( ); // execute scripts defined in include-script element of the libraries Iterator iter = reportDesign.includeLibraryScriptsIterator( ); while ( iter.hasNext( ) ) { IncludeScriptHandle includeScript = (IncludeScriptHandle) iter .next( ); String fileName = includeScript.getFileName( ); executionContext.loadScript( fileName ); } // execute scripts defined in include-script element of this report iter = reportDesign.includeScriptsIterator( ); while ( iter.hasNext( ) ) { IncludeScriptHandle includeScript = (IncludeScriptHandle) iter .next( ); String fileName = includeScript.getFileName( ); executionContext.loadScript( fileName ); } // Intialize the report ReportScriptExecutor.handleInitialize( reportDesign, executionContext ); } } protected void prepareDesign( ) { ReportDesignHandle reportDesign = executionContext.getDesign( ); ScriptedDesignVisitor visitor = new ScriptedDesignVisitor( reportDesign, executionContext ); visitor.apply( reportDesign.getRoot( ) ); runnable.setDesignHandle( reportDesign ); } protected void startFactory( ) { ReportDesignHandle reportDesign = executionContext.getDesign( ); ReportScriptExecutor.handleBeforeFactory( reportDesign, executionContext ); } protected void closeFactory( ) { ReportDesignHandle reportDesign = executionContext.getDesign( ); ReportScriptExecutor .handleAfterFactory( reportDesign, executionContext ); } protected void startRender( ) { ReportDesignHandle reportDesign = executionContext.getDesign( ); ReportScriptExecutor .handleBeforeRender( reportDesign, executionContext ); } protected void closeRender( ) { ReportDesignHandle reportDesign = executionContext.getDesign( ); ReportScriptExecutor.handleAfterRender( reportDesign, executionContext ); } // TODO: throw out the IOException public void setDataSource( IDocArchiveReader dataSource ) { // try to open the dataSource as report document try { ReportDocumentReader document = new ReportDocumentReader( engine, dataSource, true ); Map values = document.getParameterValues( ); Map texts = document.getParameterDisplayTexts( ); setParameterValues( values ); setParameterDisplayTexts( texts ); document.close( ); } catch ( EngineException ex ) { log.log( Level.WARNING, "failed to load the paremters in the data source", ex ); } try { executionContext.setDataSource( dataSource ); } catch ( IOException ioex ) { log.log( Level.WARNING, "failed to open the data source document", ioex ); } } public int getStatus( ) { return runningStatus; } public List getErrors( ) { return executionContext.getErrors( ); } public IReportContext getReportContext( ) { return executionContext.getReportContext( ); } private void mergeOption( IRenderOption options, String name, Object value ) { if ( options != null ) { if ( value != null && !options.hasOption( name ) ) { options.setOption( name, value ); } } } /** * intialize the render options used to render the report. * * the render options are load from: * <li> engine level default options</li> * <li> engine level format options</li> * <li> engine level emitter options</li> * <li> task level options </li> * */ protected void setupRenderOption( ) { String format = RenderOption.OUTPUT_FORMAT_HTML;; if ( renderOptions != null ) { format = renderOptions.getOutputFormat( ); if ( format == null || format.length( ) == 0 ) { format = RenderOption.OUTPUT_FORMAT_HTML; renderOptions.setOutputFormat( format ); } } // copy the old setting to render options Map appContext = executionContext.getAppContext( ); if ( IRenderOption.OUTPUT_FORMAT_PDF.equals( format ) ) { Object renderContext = appContext .get( EngineConstants.APPCONTEXT_PDF_RENDER_CONTEXT ); if ( renderContext instanceof PDFRenderContext ) { PDFRenderContext pdfContext = (PDFRenderContext) renderContext; mergeOption( renderOptions, PDFRenderOption.BASE_URL, pdfContext.getBaseURL( ) ); mergeOption( renderOptions, PDFRenderOption.FONT_DIRECTORY, pdfContext.getFontDirectory( ) ); mergeOption( renderOptions, PDFRenderOption.SUPPORTED_IMAGE_FORMATS, pdfContext .getSupportedImageFormats( ) ); mergeOption( renderOptions, PDFRenderOption.IS_EMBEDDED_FONT, new Boolean( pdfContext.isEmbededFont( ) ) ); } } else { Object renderContext = appContext .get( EngineConstants.APPCONTEXT_HTML_RENDER_CONTEXT ); if ( renderContext instanceof HTMLRenderContext ) { HTMLRenderContext htmlContext = (HTMLRenderContext) renderContext; mergeOption( renderOptions, HTMLRenderOption.BASE_IMAGE_URL, htmlContext.getBaseImageURL( ) ); mergeOption( renderOptions, HTMLRenderOption.BASE_URL, htmlContext.getBaseURL( ) ); mergeOption( renderOptions, HTMLRenderOption.IMAGE_DIRECTROY, htmlContext.getImageDirectory( ) ); mergeOption( renderOptions, HTMLRenderOption.SUPPORTED_IMAGE_FORMATS, htmlContext .getSupportedImageFormats( ) ); } } // setup the render options from: // engine default, format default, emitter default and task options HashMap options = new HashMap( ); // try to get the default render option from the engine config. HashMap configs = engine.getConfig( ).getEmitterConfigs( ); // get the default format of the emitters, the default format key is // IRenderOption.OUTPUT_FORMAT; IRenderOption defaultOptions = (IRenderOption) configs .get( IEngineConfig.DEFAULT_RENDER_OPTION ); if ( defaultOptions == null ) { defaultOptions = (IRenderOption) configs .get( IRenderOption.OUTPUT_FORMAT_HTML ); } if ( defaultOptions != null ) { options.putAll( defaultOptions.getOptions( ) ); } // try to get the render options by the format IRenderOption formatOptions = (IRenderOption) configs.get( format ); if ( formatOptions != null ) { options.putAll( formatOptions.getOptions( ) ); } // try to load the configs through the emitter id if ( emitterID != null ) { IRenderOption emitterOptions = (IRenderOption) configs .get( emitterID ); if ( emitterOptions != null ) { options.putAll( emitterOptions.getOptions( ) ); } } // load the options from task level options if ( renderOptions != null ) { options.putAll( renderOptions.getOptions( ) ); } // setup the render options used by this task IRenderOption allOptions = new RenderOption( options ); executionContext.setRenderOption( allOptions ); // copy the new setting to old APIs if ( IRenderOption.OUTPUT_FORMAT_PDF.equals( format ) ) { Object renderContext = appContext .get( EngineConstants.APPCONTEXT_PDF_RENDER_CONTEXT ); if ( renderContext == null ) { PDFRenderOption pdfOptions = new PDFRenderOption( allOptions ); PDFRenderContext pdfContext = new PDFRenderContext( ); pdfContext.setBaseURL( pdfOptions.getBaseURL( ) ); pdfContext.setEmbededFont( pdfOptions.isEmbededFont( ) ); pdfContext.setFontDirectory( pdfOptions.getFontDirectory( ) ); pdfContext.setSupportedImageFormats( pdfOptions .getSupportedImageFormats( ) ); appContext.put( EngineConstants.APPCONTEXT_PDF_RENDER_CONTEXT, pdfContext ); } } else { Object renderContext = appContext .get( EngineConstants.APPCONTEXT_HTML_RENDER_CONTEXT ); if ( renderContext == null ) { HTMLRenderContext htmlContext = new HTMLRenderContext( ); HTMLRenderOption htmlOptions = new HTMLRenderOption( allOptions ); htmlContext.setBaseImageURL( htmlOptions.getBaseImageURL( ) ); htmlContext.setBaseURL( htmlOptions.getBaseURL( ) ); htmlContext .setImageDirectory( htmlOptions.getImageDirectory( ) ); htmlContext.setSupportedImageFormats( htmlOptions .getSupportedImageFormats( ) ); htmlContext.SetRenderOption( allOptions ); appContext.put( EngineConstants.APPCONTEXT_HTML_RENDER_CONTEXT, htmlContext ); } } } protected void initializeContentEmitter( IContentEmitter emitter, IReportExecutor executor ) { // create the emitter services object that is needed in the emitters. HashMap configs = engine.getConfig( ).getEmitterConfigs( ); IReportContext reportContext = executionContext.getReportContext( ); IRenderOption options = executionContext.getRenderOption( ); EngineEmitterServices services = new EngineEmitterServices( reportContext, options, configs ); // emitter is not null emitter.initialize( services ); } public int getTaskType( ) { return taskType; } protected void changeStatusToRunning( ) { runningStatus = STATUS_RUNNING; } protected void changeStatusToStopped( ) { if ( cancelFlag ) { runningStatus = STATUS_CANCELLED; } else if ( executionContext.hasErrors( ) ) { runningStatus = STATUS_FAILED; } else { runningStatus = STATUS_SUCCEEDED; } } public Logger getLogger( ) { return log; } public void setLogger( Logger logger ) { if ( logger == null || !EngineLogger.isValidLogger( logger ) ) { throw new IllegalArgumentException( "the logger can't be NULL or children or in namespace of org.eclipse.birt" ); } EngineLoggerHandler.setLogger( logger ); this.log = logger; this.executionContext.setLogger( logger ); } }
package br.net.mirante.singular.view.page.peticao; import br.net.mirante.singular.form.mform.*; import br.net.mirante.singular.form.mform.basic.ui.AtrBasic; import br.net.mirante.singular.form.mform.basic.view.*; import br.net.mirante.singular.form.mform.core.MTipoString; import br.net.mirante.singular.form.mform.core.attachment.MTipoAttachment; import br.net.mirante.singular.form.mform.util.comuns.MTipoCNPJ; import br.net.mirante.singular.form.wicket.AtrWicket; import java.util.Optional; public class MPacotePeticaoGGTOX extends MPacote { public static final String PACOTE = "mform.peticao"; public static final String TIPO = "PeticionamentoGGTOX"; public static final String NOME_COMPLETO = PACOTE + "." + TIPO; private MTipoComposto<MIComposto> dadosResponsavel; private MTipoString dadosResponsavel_responsavelTecnico; private MTipoString dadosResponsavel_concordo; public MPacotePeticaoGGTOX() { super(PACOTE); } @Override protected void carregarDefinicoes(PacoteBuilder pb) { final MTipoComposto<?> peticionamento = pb.createTipoComposto(TIPO); //TODO solicitar criacao de validacao para esse exemplo: addTipoDocumento(pb, peticionamento); addDadosRequerente(pb, peticionamento); addDadosResponsavel(pb, peticionamento); addComponentes(pb, peticionamento); addValidacaoResponsavel(pb, peticionamento); addResponsavelTransacao(pb, peticionamento); addImpressaoPeticao(pb, peticionamento); } private void addTipoDocumento(PacoteBuilder pb, MTipoComposto<?> peticionamento) { //TODO adicionar variavel como texto na tela } private void addDadosRequerente(PacoteBuilder pb, MTipoComposto<?> peticionamento) { } private void addDadosResponsavel(PacoteBuilder pb, MTipoComposto<?> peticionamento) { dadosResponsavel = peticionamento.addCampoComposto("dadosResponsavel"); dadosResponsavel.as(AtrBasic::new).label("Dados do Responsável"); dadosResponsavel_responsavelTecnico = dadosResponsavel.addCampoString("responsavelTecnico", true); dadosResponsavel_responsavelTecnico .withSelectionOf(getResponsaveis()) .withView(MSelecaoPorSelectView::new) .as(AtrBasic::new).label("Responsável Técnico") .as(AtrWicket::new).larguraPref(3); dadosResponsavel.addCampoString("representanteLegal", true) .withSelectionOf(getResponsaveis()) .withView(MSelecaoPorSelectView::new) .as(AtrBasic::new).label("Representante Legal") .as(AtrWicket::new).larguraPref(3); // TODO preciso de um campo boolean mas as labels devem ser as descritas abaixo //TODO deve ser possivel alinhar o texto: text-left text-right text-justify text-nowrap (dadosResponsavel_concordo = dadosResponsavel.addCampoString("concordo", true)) .withSelectionOf("Concordo", "Não Concordo") .withView(MSelecaoPorRadioView::new); } private String[] getResponsaveis() { return new String[] { "Daniel", "Delfino", "Fabrício", "Lucas", "Tetsuo", "Vinícius" }; } private void addComponentes(PacoteBuilder pb, MTipoComposto<?> peticionamento) { // TODO como fazer uma tabela de componentes, com botao novo (aguardando mestre-detalhe) final MTipoLista<MTipoComposto<MIComposto>, MIComposto> componentes = peticionamento.addCampoListaOfComposto("componentes", "componente"); MTipoComposto<MIComposto> componente = componentes.getTipoElementos(); componentes .withView(MPanelListaView::new) .as(AtrBasic::new) .label("Componente") .enabled((ins) -> { Optional<Object> agreed = ins.findNearestValue(dadosResponsavel_concordo); if(agreed.isPresent()) return "Concordo".equals(agreed.get()); return false; }) .dependsOn(dadosResponsavel_concordo); componente.as(AtrBasic::new).label("Registro de Componente"); MTipoComposto<MIComposto> identificacaoComponente = componente.addCampoComposto("identificacaoComponente"); identificacaoComponente.as(AtrBasic::new).label("Identificação de Componente") .as(AtrWicket::new).larguraPref(4); identificacaoComponente.addCampoString("tipoComponente", true) .withSelectionOf("Substância", "Mistura") .withView(MSelecaoPorRadioView::new) .as(AtrBasic::new).label("Tipo componente"); MTipoComposto<MIComposto> restricoesComponente = componente.addCampoComposto("restricoesComponente"); restricoesComponente.as(AtrBasic::new).label("Restrições") .as(AtrWicket::new).larguraPref(4); restricoesComponente.addCampoListaOf("restricoes", pb.createTipo("restricao", MTipoString.class) .withSelectionOf("Impureza relevante presente", "Controle de impureza determinado", "Restrição de uso em algum país", "Restrição de uso em alimentos", "Sem restrições")) .withView(MSelecaoMultiplaPorCheckView::new) .as(AtrBasic::new).label("Restrições"); MTipoComposto<MIComposto> sinonimiaComponente = componente.addCampoComposto("sinonimiaComponente"); sinonimiaComponente.as(AtrBasic::new).label("Sinonímia") .as(AtrWicket::new).larguraPref(4); sinonimiaComponente.addCampoListaOf("sinonimiaAssociada", pb.createTipo("sinonimia", MTipoString.class) .withSelectionOf("Sinonímia teste", "Sinonímia teste 2", "Sinonímia teste 3")) .withView(MSelecaoMultiplaPorSelectView::new) .as(AtrBasic::new) .label("Sinonímias já associadas a esta substância/mistura") .enabled(false); final MTipoLista<MTipoComposto<MIComposto>, MIComposto> sinonimias = sinonimiaComponente.addCampoListaOfComposto("sinonimias", "sinonimia"); final MTipoComposto<?> sinonimia = sinonimias.getTipoElementos(); sinonimia.addCampoString("nomeSinonimia", true) .as(AtrBasic::new).label("Sinonímia sugerida") .tamanhoMaximo(100); sinonimias .withView(MTableListaView::new) .as(AtrBasic::new).label("Lista de sinonímias sugeridas para esta substância/mistura"); MTipoComposto<MIComposto> finalidadesComponente = componente.addCampoComposto("finalidadesComponente"); finalidadesComponente.as(AtrBasic::new).label("Finalidades") .as(AtrWicket::new).larguraPref(4); finalidadesComponente.addCampoListaOf("finalidades", pb.createTipo("finalidade", MTipoString.class) .withSelectionOf("Produção", "Importação", "Exportação", "Comercialização", "Utilização")) .withView(MSelecaoMultiplaPorCheckView::new); //TODO falta criar modal para cadastrar novo uso pretendido MTipoComposto<MIComposto> usosPretendidosComponente = componente.addCampoComposto("usosPretendidosComponente"); usosPretendidosComponente.as(AtrBasic::new).label("Uso pretendido") .as(AtrWicket::new).larguraPref(4); usosPretendidosComponente.addCampoListaOf("usosPretendidos", pb.createTipo("usoPretendido", MTipoString.class) .withSelectionOf("Uso 1", "Uso 2", "Uso 3")) .withView(MSelecaoMultiplaPorPicklistView::new) .as(AtrBasic::new).label("Lista de uso pretendido/mistura"); final MTipoLista<MTipoComposto<MIComposto>, MIComposto> nomesComerciais = componente.addCampoListaOfComposto("nomesComerciais", "nomeComercial"); MTipoComposto<MIComposto> nomeComercial = nomesComerciais.getTipoElementos(); nomeComercial.addCampoString("nome", true) .as(AtrBasic::new).label("Nome comercial") .tamanhoMaximo(80); MTipoLista<MTipoComposto<MIComposto>, MIComposto> fabricantes = nomeComercial.addCampoListaOfComposto("fabricantes", "fabricante"); //TODO Fabricante deve ser uma pesquisa MTipoComposto<MIComposto> fabricante = fabricantes.getTipoElementos(); //TODO como usar o tipo cnpj fabricante.addCampo("cnpj", MTipoCNPJ.class).as(AtrBasic::new).label("CNPJ").as(AtrWicket::new).larguraPref(4); fabricante.addCampoString("razaoSocial").as(AtrBasic::new).label("Razão social").as(AtrWicket::new).larguraPref(4); fabricante.addCampoString("cidade").as(AtrBasic::new).label("Cidade").as(AtrWicket::new).larguraPref(2); fabricante.addCampoString("pais").as(AtrBasic::new).label("País").as(AtrWicket::new).larguraPref(2); fabricantes .withView(MPanelListaView::new) .as(AtrBasic::new).label("Fabricante(s)"); nomesComerciais .withView(MPanelListaView::new) .as(AtrBasic::new).label("Nome comercial"); final MTipoLista<MTipoComposto<MIComposto>, MIComposto> embalagens = componente.addCampoListaOfComposto("embalagens", "embalagem"); MTipoComposto<MIComposto> embalagem = embalagens.getTipoElementos(); //TODO converter sim nao para true false embalagem.addCampoString("produtoExterior", true) .withSelectionOf("Sim", "Não") .withView(MSelecaoPorRadioView::new) .as(AtrBasic::new).label("Produto formulado no exterior?") .as(AtrWicket::new).larguraPref(2); embalagem.addCampoString("tipo", true) .withSelectionOf(getTiposEmbalagem()) .withView(MSelecaoPorSelectView::new) .as(AtrBasic::new).label("Tipo") .as(AtrWicket::new).larguraPref(3); embalagem.addCampoString("material", true) .withSelectionOf(getMateriais()) .withView(MSelecaoPorSelectView::new) .as(AtrBasic::new).label("Material") .as(AtrWicket::new).larguraPref(3); embalagem.addCampoInteger("capacidade", true) .as(AtrBasic::new).label("Capacidade") .tamanhoMaximo(15) .as(AtrWicket::new).larguraPref(3); //TODO caso o array tenha uma string vazia, ocorre um NPE embalagem.addCampoString("unidadeMedida", true) .withSelectionOf(getUnidadesMedida()) .withView(MSelecaoPorSelectView::new) .as(AtrBasic::new).label("Unidade medida") .as(AtrWicket::new).larguraPref(1); embalagens .withView(MTableListaView::new) .as(AtrBasic::new).label("Embalagem"); final MTipoLista<MTipoComposto<MIComposto>, MIComposto> anexos = componente.addCampoListaOfComposto("anexos", "anexo"); MTipoComposto<MIComposto> anexo = anexos.getTipoElementos(); anexos .withView(MPanelListaView::new) .as(AtrBasic::new).label("Anexos"); MTipoAttachment arquivo = anexo.addCampo("arquivo", MTipoAttachment.class); arquivo.as(AtrBasic.class).label("Informe o caminho do arquivo para o anexo") .as(AtrWicket::new).larguraPref(3); anexo.addCampoString("tipoArquivo") .withSelectionOf("Ficha de emergência", "Ficha de segurança", "Outros") .withView(MSelecaoPorSelectView::new) .as(AtrBasic::new).label("Tipo do arquivo a ser anexado") .as(AtrWicket::new).larguraPref(3); addTestes(pb, componente); } private String[] getTiposEmbalagem() { return new String[] { "Balde", "Barrica", "Bombona", "Caixa", "Carro tanque", "Cilindro", "Container", "Frasco", "Galão", "Garrafa", "Lata", "Saco", "Tambor" }; } private String[] getMateriais() { return new String[] { "Papel", "Alumínio", "Ferro", "Madeira" }; } private String[] getUnidadesMedida() { return new String[] { "cm" }; } private void addTestes(PacoteBuilder pb, MTipoComposto<?> componente) { //TODO deve ser encontrado uma maneira de vincular o teste ao componente addTesteCaracteristicasFisicoQuimicas(pb, componente); addTesteIrritacaoOcular(pb, componente); addTesteTeratogenicidade(pb, componente); addTesteNeurotoxicidade(pb, componente); } private void addTesteCaracteristicasFisicoQuimicas(PacoteBuilder pb, MTipoComposto<?> componente) { final MTipoLista<MTipoComposto<MIComposto>, MIComposto> testes = componente.addCampoListaOfComposto("testesCaracteristicasFisicoQuimicas", "caracteristicasFisicoQuimicas"); MTipoComposto<MIComposto> teste = testes.getTipoElementos(); testes // .withView(MPanelListaView::new) .as(AtrBasic::new).label("Testes Características fisíco-químicas"); teste.as(AtrBasic::new).label("Características fisíco-químicas"); MTipoString estadoFisico = teste.addCampoString("estadoFisico", true); estadoFisico.withSelectionOf("Líquido", "Sólido", "Gasoso") .withView(MSelecaoPorSelectView::new) .as(AtrBasic::new).label("Estado físico") .as(AtrWicket::new).larguraPref(2); MTipoString aspecto = teste.addCampoString("aspecto", true); aspecto.as(AtrBasic::new).label("Aspecto") .tamanhoMaximo(50) .as(AtrWicket::new).larguraPref(4); MTipoString cor = teste.addCampoString("cor", true); cor.as(AtrBasic::new).label("Cor") .tamanhoMaximo(40) .as(AtrWicket::new).larguraPref(3); MTipoString odor = teste.addCampoString("odor"); odor.as(AtrBasic::new).label("Odor") .tamanhoMaximo(40) .as(AtrWicket::new).larguraPref(3); testes.withView(new MListMasterDetailView() .col(estadoFisico) .col(aspecto) .col(cor) .col(odor) ); MTipoComposto<MIComposto> faixaFusao = teste.addCampoComposto("faixaFusao"); faixaFusao.as(AtrWicket::new).larguraPref(6); //TODO cade as mascaras para campos decimais faixaFusao.as(AtrBasic::new).label("Fusão"); faixaFusao.addCampoDecimal("pontoFusao") .as(AtrBasic::new).label("Ponto de fusão").subtitle("ºC") .as(AtrWicket::new).larguraPref(4); //TODO o campo faixa de fusao precisa de um tipo intervalo // Exemplo: Faixa De 10 a 20 faixaFusao.addCampoDecimal("faixaFusaoDe") .as(AtrBasic::new).label("Início").subtitle("da Faixa") .as(AtrWicket::new).larguraPref(4); faixaFusao.addCampoDecimal("faixaFusaoA") .as(AtrBasic::new).label("Fim").subtitle("da Faixa") .as(AtrWicket::new).larguraPref(4); MTipoComposto<MIComposto> faixaEbulicao = teste.addCampoComposto("faixaEbulicao"); faixaEbulicao.as(AtrBasic::new).label("Ebulição") .as(AtrWicket::new).larguraPref(6); faixaEbulicao.addCampoDecimal("pontoEbulicao") .as(AtrBasic::new).label("Ebulição").subtitle("ºC") .as(AtrWicket::new).larguraPref(4); faixaEbulicao.addCampoDecimal("faixaEbulicaoDe") .as(AtrBasic::new).label("Início").subtitle("da Faixa") .as(AtrWicket::new).larguraPref(4); faixaEbulicao.addCampoDecimal("faixaEbulicaoA") .as(AtrBasic::new).label("Fim").subtitle("da Faixa") .as(AtrWicket::new).larguraPref(4); MTipoComposto<MIComposto> pressaoVapor = teste.addCampoComposto("pressaoVapor"); pressaoVapor.as(AtrBasic::new).label("Pressão do vapor") .as(AtrWicket::new).larguraPref(6); pressaoVapor.addCampoDecimal("valor") .as(AtrBasic::new).label("Valor") .as(AtrWicket::new).larguraPref(6); pressaoVapor.addCampoString("unidade") .withSelectionOf("mmHg", "Pa", "mPa") .withView(MSelecaoPorSelectView::new) .as(AtrBasic::new).label("Unidade") .as(AtrWicket::new).larguraPref(6); MTipoComposto<MIComposto> solubilidade = teste.addCampoComposto("solubilidade"); solubilidade.as(AtrBasic::new).label("Solubilidade") .as(AtrWicket::new).larguraPref(6); solubilidade.addCampoDecimal("solubilidadeAgua") .as(AtrBasic::new).label("em água").subtitle("mg/L a 20 ou 25 ºC") .as(AtrWicket::new).larguraPref(6); solubilidade.addCampoDecimal("solubilidadeOutrosSolventes") .as(AtrBasic::new).label("em outros solventes").subtitle("mg/L a 20 ou 25 ºC") .as(AtrWicket::new).larguraPref(6); teste.addCampoString("hidrolise") .as(AtrBasic::new).label("Hidrólise") .as(AtrWicket::new).larguraPref(6); teste.addCampoString("estabilidade") .as(AtrBasic::new).label("Estabilidade às temperaturas normal e elevada") .as(AtrWicket::new).larguraPref(6); teste.addCampoDecimal("pontoFulgor") .as(AtrBasic::new).label("Ponto de fulgor").subtitle("ºC") .as(AtrWicket::new).larguraPref(3); teste.addCampoDecimal("constanteDissociacao") .as(AtrBasic::new).label("Constante de dissociação") .as(AtrWicket::new).larguraPref(3); final MTipoLista<MTipoComposto<MIComposto>, MIComposto> phs = teste.addCampoListaOfComposto("phs", "ph"); MTipoComposto<MIComposto> ph = phs.getTipoElementos(); ph.addCampoDecimal("valorPh", true) .as(AtrBasic::new).label("pH") .as(AtrWicket::new).larguraPref(4); ph.addCampoDecimal("solucao", true) .as(AtrBasic::new).label("Solução").subtitle("%") .as(AtrWicket::new).larguraPref(4); ph.addCampoDecimal("temperatura", true) .as(AtrBasic::new).label("Temperatura").subtitle("ºC") .as(AtrWicket::new).larguraPref(4); phs .withView(MPanelListaView::new) .as(AtrBasic::new).label("Embalagem"); teste.addCampoDecimal("coeficienteParticao") .as(AtrBasic::new).label("Coeficiente de partição octanol/Água").subtitle("a 20-25 ºC") .as(AtrWicket::new).larguraPref(4); teste.addCampoDecimal("densidade") .as(AtrBasic::new).label("Densidade").subtitle("g/cm³ a 20ºC") .as(AtrWicket::new).larguraPref(4); teste.addCampoString("observacoes") .withView(MTextAreaView::new) .as(AtrBasic::new).label("Observações"); } private void addTesteIrritacaoOcular(PacoteBuilder pb, MTipoComposto<?> componente) { final MTipoLista<MTipoComposto<MIComposto>, MIComposto> testes = componente.addCampoListaOfComposto("testesIrritacaoOcular", "irritacaoOcular"); MTipoComposto<MIComposto> teste = testes.getTipoElementos(); //TODO criar regra para pelo menos um campo preenchido testes .withView(MPanelListaView::new) .as(AtrBasic::new).label("Testes Irritação / Corrosão ocular"); teste.as(AtrBasic::new).label("Irritação / Corrosão ocular") .as(AtrWicket::new).larguraPref(4); teste.addCampoString("laboratorio") .as(AtrBasic::new).label("Laboratório") .tamanhoMaximo(50); teste.addCampoString("protocoloReferencia") .as(AtrBasic::new).label("Protocolo de referência") .tamanhoMaximo(50); teste.addCampoData("dataInicioEstudo") .as(AtrBasic::new).label("Data de início do estudo") .as(AtrWicket::new).larguraPref(3); teste.addCampoData("dataFimEstudo") .as(AtrBasic::new).label("Data final do estudo") .as(AtrWicket::new).larguraPref(3); teste.addCampoString("purezaProdutoTestado") .as(AtrBasic::new).label("Pureza do produto testado") .as(AtrWicket::new).larguraPref(6); teste.addCampoString("unidadeMedida") .withSelectionOf("g/Kg", "g/L") .as(AtrBasic::new).label("Unidade de medida") .as(AtrWicket::new).larguraPref(2); teste.addCampoString("especies") .withSelectionOf("Càes", "Camundongos", "Cobaia", "Coelho", "Galinha", "Informação não disponível", "Peixe", "Primatas", "Rato") .as(AtrBasic::new).label("Espécies") .as(AtrWicket::new).larguraPref(4); teste.addCampoString("linhagem") .as(AtrBasic::new).label("Linhagem") .as(AtrWicket::new).larguraPref(6); teste.addCampoDecimal("numeroAnimais") .as(AtrBasic::new).label("Número de animais") .as(AtrWicket::new).larguraPref(3); teste.addCampoString("veiculo") .as(AtrBasic::new).label("Veículo") .as(AtrWicket::new).larguraPref(3); teste.addCampoString("fluoresceina") .withSelectionOf("Sim", "Não") .as(AtrBasic::new).label("Fluoresceína") .as(AtrWicket::new).larguraPref(3); teste.addCampoString("testeRealizado") .withSelectionOf("Com lavagem", "Sem lavagem") .as(AtrBasic::new).label("Teste realizado") .as(AtrWicket::new).larguraPref(3); MTipoComposto<MIComposto> alteracoes = teste.addCampoComposto("alteracoes"); alteracoes.as(AtrBasic::new).label("Alterações") .as(AtrWicket::new); alteracoes.addCampoString("cornea") .withSelectionOf("Sem alterações", "Opacidade persistente", "Opacidade reversível em...") .as(AtrBasic::new).label("Córnea") .as(AtrWicket::new).larguraPref(6); alteracoes.addCampoString("tempoReversibilidadeCornea") .as(AtrBasic::new).label("Tempo de reversibilidade") .as(AtrWicket::new).larguraPref(6); alteracoes.addCampoString("conjuntiva") .withSelectionOf("Sem alterações", "Opacidade persistente", "Opacidade reversível em...") .as(AtrBasic::new).label("Conjuntiva") .as(AtrWicket::new).larguraPref(6); alteracoes.addCampoString("tempoReversibilidadeConjuntiva") .as(AtrBasic::new).label("Tempo de reversibilidade") .as(AtrWicket::new).larguraPref(6); alteracoes.addCampoString("iris") .withSelectionOf("Sem alterações", "Opacidade persistente", "Opacidade reversível em...") .as(AtrBasic::new).label("Íris") .as(AtrWicket::new).larguraPref(6); alteracoes.addCampoString("tempoReversibilidadeIris") .as(AtrBasic::new).label("Tempo de reversibilidade") .as(AtrWicket::new).larguraPref(6); teste.addCampoString("observacoes") .withView(MTextAreaView::new) .as(AtrBasic::new).label("Observações"); } private void addTesteTeratogenicidade(PacoteBuilder pb, MTipoComposto<?> componente) { } private void addTesteNeurotoxicidade(PacoteBuilder pb, MTipoComposto<?> componente) { } private void addValidacaoResponsavel(PacoteBuilder pb, MTipoComposto<?> peticionamento) { } private void addResponsavelTransacao(PacoteBuilder pb, MTipoComposto<?> peticionamento) {} private void addImpressaoPeticao(PacoteBuilder pb, MTipoComposto<?> peticionamento) {} }
package net.somethingdreadful.MAL; import android.annotation.SuppressLint; import android.app.FragmentManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.SearchManager; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.support.v4.view.MenuItemCompat; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.widget.SearchView; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.crashlytics.android.Crashlytics; import com.squareup.picasso.Picasso; import net.somethingdreadful.MAL.account.AccountService; import net.somethingdreadful.MAL.adapters.IGFPagerAdapter; import net.somethingdreadful.MAL.adapters.NavigationDrawerAdapter; import net.somethingdreadful.MAL.api.MALApi; import net.somethingdreadful.MAL.api.response.User; import net.somethingdreadful.MAL.dialog.LogoutConfirmationDialogFragment; import net.somethingdreadful.MAL.dialog.UpdateImageDialogFragment; import net.somethingdreadful.MAL.dialog.UpdatePasswordDialogFragment; import net.somethingdreadful.MAL.sql.MALSqlHelper; import net.somethingdreadful.MAL.tasks.APIAuthenticationErrorListener; import net.somethingdreadful.MAL.tasks.TaskJob; import net.somethingdreadful.MAL.tasks.UserNetworkTask; import net.somethingdreadful.MAL.tasks.UserNetworkTaskFinishedListener; public class Home extends ActionBarActivity implements SwipeRefreshLayout.OnRefreshListener, IGFCallbackListener, APIAuthenticationErrorListener, View.OnClickListener, UserNetworkTaskFinishedListener, ViewPager.OnPageChangeListener { IGF af; IGF mf; /** * The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the * sections. We use a {@link android.support.v4.app.FragmentPagerAdapter} derivative, which will * keep every loaded fragment in memory. If this becomes too memory intensive, it may be best * to switch to a {@link android.support.v4.app.FragmentStatePagerAdapter}. */ IGFPagerAdapter mIGFPagerAdapter; /** * The {@link ViewPager} that will host the section contents. */ ViewPager mViewPager; Context context; Menu menu; BroadcastReceiver networkReceiver; DrawerLayout DrawerLayout; ListView DrawerList; ActionBarDrawerToggle mDrawerToggle; View mPreviousView; ActionBar actionBar; NavigationDrawerAdapter mNavigationDrawerAdapter; RelativeLayout logout; RelativeLayout settings; RelativeLayout about; String username; boolean instanceExists; boolean networkAvailable; boolean myList = true; //tracks if the user is on 'My List' or not boolean callbackAnimeError = false; boolean callbackMangaError = false; int callbackCounter = 0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); context = getApplicationContext(); if (AccountService.getAccount() != null) { actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } //The following is state handling code instanceExists = savedInstanceState != null && savedInstanceState.getBoolean("instanceExists", false); networkAvailable = savedInstanceState == null || savedInstanceState.getBoolean("networkAvailable", true); if (savedInstanceState != null) { myList = savedInstanceState.getBoolean("myList"); } setContentView(R.layout.activity_home); // Creates the adapter to return the Animu and Mango fragments mIGFPagerAdapter = new IGFPagerAdapter(getFragmentManager()); LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); DrawerLayout = (DrawerLayout) inflater.inflate(R.layout.record_home_navigationdrawer, (DrawerLayout) findViewById(R.id.drawer_layout)); DrawerLayout.setDrawerListener(new DrawerListener()); DrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, Gravity.START); username = AccountService.getUsername(); ((TextView) DrawerLayout.findViewById(R.id.name)).setText(username); ((TextView) DrawerLayout.findViewById(R.id.siteName)).setText(getString(AccountService.isMAL() ? R.string.init_hint_myanimelist : R.string.init_hint_anilist)); new UserNetworkTask(context, false, this).execute(username); logout = (RelativeLayout) DrawerLayout.findViewById(R.id.logout); settings = (RelativeLayout) DrawerLayout.findViewById(R.id.settings); about = (RelativeLayout) DrawerLayout.findViewById(R.id.about); logout.setOnClickListener(this); settings.setOnClickListener(this); about.setOnClickListener(this); DrawerList = (ListView) DrawerLayout.findViewById(R.id.listview); NavigationItems mNavigationContent = new NavigationItems(DrawerList, context); mNavigationDrawerAdapter = new NavigationDrawerAdapter(this, mNavigationContent.ITEMS); DrawerList.setAdapter(mNavigationDrawerAdapter); DrawerList.setOnItemClickListener(new DrawerItemClickListener()); DrawerList.setOverScrollMode(View.OVER_SCROLL_NEVER); mDrawerToggle = new ActionBarDrawerToggle(this, DrawerLayout, R.string.drawer_open, R.string.drawer_close); mDrawerToggle.syncState(); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mIGFPagerAdapter); mViewPager.setPageMargin(32); mViewPager.setOnPageChangeListener(this); networkReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { checkNetworkAndDisplayCrouton(); } }; } else { Intent firstRunInit = new Intent(this, FirstTimeInit.class); startActivity(firstRunInit); finish(); } NfcHelper.disableBeam(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_home, menu); SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); MenuItem searchItem = menu.findItem(R.id.action_search); SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem); ComponentName cn = new ComponentName(this, SearchActivity.class); searchView.setSearchableInfo(searchManager.getSearchableInfo(cn)); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } switch (item.getItemId()) { case R.id.listType_all: getRecords(true, TaskJob.GETLIST, 0); setChecked(item); break; case R.id.listType_inprogress: getRecords(true, TaskJob.GETLIST, 1); setChecked(item); break; case R.id.listType_completed: getRecords(true, TaskJob.GETLIST, 2); setChecked(item); break; case R.id.listType_onhold: getRecords(true, TaskJob.GETLIST, 3); setChecked(item); break; case R.id.listType_dropped: getRecords(true, TaskJob.GETLIST, 4); setChecked(item); break; case R.id.listType_planned: getRecords(true, TaskJob.GETLIST, 5); setChecked(item); break; case R.id.listType_rewatching: getRecords(true, TaskJob.GETLIST, 6); setChecked(item); break; case R.id.forceSync: synctask(true); break; case R.id.menu_inverse: if (af != null && mf != null) { if (!AccountService.isMAL() && af.taskjob == TaskJob.GETMOSTPOPULAR) { af.toggleAiringTime(); } else { af.inverse(); mf.inverse(); } } break; } return super.onOptionsItemSelected(item); } public void getRecords(boolean clear, TaskJob task, int list) { if (af != null && mf != null) { af.getRecords(clear, task, list); mf.getRecords(clear, task, list); if (task == TaskJob.FORCESYNC) syncNotify(); } } @Override public void onResume() { super.onResume(); checkNetworkAndDisplayCrouton(); registerReceiver(networkReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE")); } @SuppressLint("NewApi") @Override public void onPause() { super.onPause(); if (menu != null) menu.findItem(R.id.action_search).collapseActionView(); instanceExists = true; unregisterReceiver(networkReceiver); } public void synctask(boolean clear) { getRecords(clear, TaskJob.FORCESYNC, af.list); } @Override public void onSaveInstanceState(Bundle state) { //This is telling out future selves that we already have some things and not to do them state.putBoolean("instanceExists", true); state.putBoolean("networkAvailable", networkAvailable); state.putBoolean("myList", myList); super.onSaveInstanceState(state); } @Override public boolean onPrepareOptionsMenu(Menu menu) { this.menu = menu; if (af != null) { //All this is handling the ticks in the switch list menu switch (af.list) { case 0: setChecked(menu.findItem(R.id.listType_all)); break; case 1: setChecked(menu.findItem(R.id.listType_inprogress)); break; case 2: setChecked(menu.findItem(R.id.listType_completed)); break; case 3: setChecked(menu.findItem(R.id.listType_onhold)); break; case 4: setChecked(menu.findItem(R.id.listType_dropped)); break; case 5: setChecked(menu.findItem(R.id.listType_planned)); break; case 6: setChecked(menu.findItem(R.id.listType_rewatching)); break; } } return true; } public void setChecked(MenuItem item) { item.setChecked(true); } public void myListChanged() { menu.findItem(R.id.menu_listType).setVisible(myList); menu.findItem(R.id.menu_inverse).setVisible(myList || (!AccountService.isMAL() && af.taskjob == TaskJob.GETMOSTPOPULAR)); menu.findItem(R.id.forceSync).setVisible(myList && networkAvailable); menu.findItem(R.id.action_search).setVisible(networkAvailable); } @SuppressLint("NewApi") public void onLogoutConfirmed() { if (af != null) af.cancelNetworkTask(); if (mf != null) mf.cancelNetworkTask(); MALSqlHelper.getHelper(context).deleteDatabase(context); AccountService.deleteAccount(); startActivity(new Intent(this, Home.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); finish(); } private void syncNotify() { Intent notificationIntent = new Intent(context, Home.class); PendingIntent contentIntent = PendingIntent.getActivity(context, 1, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT); NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Notification.Builder syncNotificationBuilder = new Notification.Builder(context).setOngoing(true) .setContentIntent(contentIntent) .setSmallIcon(R.drawable.notification_icon) .setContentTitle(getString(R.string.app_name)) .setContentText(getString(R.string.toast_info_SyncMessage)); Notification syncNotification; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { syncNotificationBuilder.setVisibility(Notification.VISIBILITY_PUBLIC); } syncNotification = syncNotificationBuilder.build(); } else { syncNotification = syncNotificationBuilder.getNotification(); } nm.notify(R.id.notification_sync, syncNotification); } private void showLogoutDialog() { FragmentManager fm = getFragmentManager(); LogoutConfirmationDialogFragment lcdf = new LogoutConfirmationDialogFragment(); lcdf.show(fm, "fragment_LogoutConfirmationDialog"); } public void checkNetworkAndDisplayCrouton() { if (MALApi.isNetworkAvailable(context) && !networkAvailable) { synctask(false); } networkAvailable = MALApi.isNetworkAvailable(context); } @Override public void onRefresh() { if (networkAvailable) synctask(false); else { if (af != null && mf != null) { af.toggleSwipeRefreshAnimation(false); mf.toggleSwipeRefreshAnimation(false); } Toast.makeText(context, R.string.toast_error_noConnectivity, Toast.LENGTH_SHORT).show(); } } @Override public void onIGFReady(IGF igf) { igf.setUsername(AccountService.getUsername()); if (igf.listType.equals(MALApi.ListType.ANIME)) af = igf; else mf = igf; // do forced sync after FirstInit if (PrefManager.getForceSync()) { if (af != null && mf != null) { PrefManager.setForceSync(false); PrefManager.commitChanges(); synctask(true); } } else { if (igf.taskjob == null) { igf.getRecords(true, TaskJob.GETLIST, PrefManager.getDefaultList()); } } } @Override public void onRecordsLoadingFinished(MALApi.ListType type, TaskJob job, boolean error, boolean resultEmpty, boolean cancelled) { if (cancelled && !job.equals(TaskJob.FORCESYNC)) { return; } callbackCounter++; if (type.equals(MALApi.ListType.ANIME)) callbackAnimeError = error; else callbackMangaError = error; if (callbackCounter >= 2) { callbackCounter = 0; if (job.equals(TaskJob.FORCESYNC)) { NotificationManager nm = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE); nm.cancel(R.id.notification_sync); if (callbackAnimeError && callbackMangaError) // the sync failed completely Toast.makeText(context, R.string.toast_error_SyncFailed, Toast.LENGTH_SHORT).show(); else if (callbackAnimeError || callbackMangaError) // one list failed to sync Toast.makeText(context, callbackAnimeError ? R.string.toast_error_Anime_Sync : R.string.toast_error_Manga_Sync, Toast.LENGTH_SHORT).show(); } else { if (callbackAnimeError && callbackMangaError) // the sync failed completely Toast.makeText(context, R.string.toast_error_Records, Toast.LENGTH_SHORT).show(); else if (callbackAnimeError || callbackMangaError) // one list failed to sync Toast.makeText(context, callbackAnimeError ? R.string.toast_error_Anime_Records : R.string.toast_error_Manga_Records, Toast.LENGTH_SHORT).show(); // no else here, there is nothing to be shown when everything went well } } } @Override public void onAPIAuthenticationError(MALApi.ListType type, TaskJob job) { // check if it is already showing if (getFragmentManager().findFragmentByTag("fragment_updatePassword") == null) { FragmentManager fm = getFragmentManager(); UpdatePasswordDialogFragment passwordFragment = new UpdatePasswordDialogFragment(); passwordFragment.show(fm, "fragment_updatePassword"); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.logout: showLogoutDialog(); break; case R.id.settings: startActivity(new Intent(this, Settings.class)); break; case R.id.about: startActivity(new Intent(this, AboutActivity.class)); break; case R.id.Image: Intent Profile = new Intent(context, ProfileActivity.class); Profile.putExtra("username", username); startActivity(Profile); break; case R.id.NDimage: UpdateImageDialogFragment lcdf = new UpdateImageDialogFragment(); lcdf.show(getFragmentManager(), "fragment_NDImage"); break; } DrawerLayout.closeDrawers(); } @Override public void onUserNetworkTaskFinished(User result) { ImageView image = (ImageView) findViewById(R.id.Image); ImageView image2 = (ImageView) findViewById(R.id.NDimage); try { Picasso.with(context) .load(result.getProfile().getAvatarUrl()) .transform(new RoundedTransformation(result.getName())) .into(image); } catch (Exception e) { Crashlytics.log(Log.ERROR, "MALX", "Home.onUserNetworkTaskFinished(): " + e.getMessage()); } if (PrefManager.getNavigationBackground() != null) Picasso.with(context) .load(PrefManager.getNavigationBackground()) .into(image2); image.setOnClickListener(this); image2.setOnClickListener(this); } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { if (menu != null) menu.findItem(R.id.listType_rewatching).setTitle(getString(position == 0 ? R.string.listType_rewatching : R.string.listType_rereading)); } @Override public void onPageSelected(int position) {} @Override public void onPageScrollStateChanged(int state) {} public class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (!networkAvailable && position > 2) { position = 0; Toast.makeText(context, R.string.toast_error_noConnectivity, Toast.LENGTH_SHORT).show(); } myList = ((position <= 3 && myList) || position == 0); // disable swipeRefresh for other lists if (af == null || mf == null) { af = mIGFPagerAdapter.getIGF(0); mf = mIGFPagerAdapter.getIGF(1); } af.setSwipeRefreshEnabled(myList); mf.setSwipeRefreshEnabled(myList); switch (position) { case 0: getRecords(true, TaskJob.GETLIST, af.list); break; case 1: Intent Profile = new Intent(context, ProfileActivity.class); Profile.putExtra("username", username); startActivity(Profile); break; case 2: Intent Friends = new Intent(context, ProfileActivity.class); Friends.putExtra("username", username); Friends.putExtra("friends", username); startActivity(Friends); break; case 3: if (AccountService.isMAL()) { Intent Forum = new Intent(context, ForumActivity.class); startActivity(Forum); } else { Toast.makeText(context, getString(R.string.toast_info_disabled), Toast.LENGTH_SHORT).show(); } break; case 4: getRecords(true, TaskJob.GETTOPRATED, af.list); break; case 5: getRecords(true, TaskJob.GETMOSTPOPULAR, af.list); break; case 6: getRecords(true, TaskJob.GETJUSTADDED, af.list); break; case 7: getRecords(true, TaskJob.GETUPCOMING, af.list); break; } myListChanged(); /* * This part is for figuring out which item in the nav drawer is selected and highlighting it with colors. */ if (position != 1 && position != 2 && position != 3) { if (mPreviousView != null) mPreviousView.setBackgroundColor(Color.parseColor("#00000000")); view.setBackgroundColor(Color.parseColor("#E8E8E8")); mPreviousView = view; } DrawerLayout.closeDrawers(); } } private class DrawerListener implements DrawerLayout.DrawerListener { @Override public void onDrawerOpened(View drawerView) { mDrawerToggle.onDrawerOpened(drawerView); actionBar.setTitle(getTitle()); } @Override public void onDrawerClosed(View drawerView) { mDrawerToggle.onDrawerClosed(drawerView); actionBar.setTitle(getTitle()); } @Override public void onDrawerSlide(View drawerView, float slideOffset) { mDrawerToggle.onDrawerSlide(drawerView, slideOffset); } @Override public void onDrawerStateChanged(int newState) { mDrawerToggle.onDrawerStateChanged(newState); } } }
package net.somethingdreadful.MAL; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import net.somethingdreadful.MAL.SearchActivity.networkThread; import net.somethingdreadful.MAL.api.BaseMALApi; import net.somethingdreadful.MAL.api.MALApi; import net.somethingdreadful.MAL.record.AnimeRecord; import net.somethingdreadful.MAL.record.MangaRecord; import net.somethingdreadful.MAL.sql.MALSqlHelper; import android.annotation.SuppressLint; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Color; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.NotificationCompat; import android.support.v4.view.GravityCompat; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockActivity; import com.actionbarsherlock.app.SherlockDialogFragment; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.sherlock.navigationdrawer.compat.SherlockActionBarDrawerToggle; import de.keyboardsurfer.android.widget.crouton.Crouton; import de.keyboardsurfer.android.widget.crouton.Style; public class Home extends BaseActionBarSearchView implements ActionBar.TabListener, ItemGridFragment.IItemGridFragment, LogoutConfirmationDialogFragment.LogoutConfirmationDialogListener { /** * The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the * sections. We use a {@link android.support.v4.app.FragmentPagerAdapter} derivative, which will * keep every loaded fragment in memory. If this becomes too memory intensive, it may be best * to switch to a {@link android.support.v4.app.FragmentStatePagerAdapter}. */ HomeSectionsPagerAdapter mSectionsPagerAdapter; /** * The {@link ViewPager} that will host the section contents. */ ViewPager mViewPager; Context context; PrefManager mPrefManager; public MALManager mManager; private boolean init = false; ItemGridFragment af; ItemGridFragment mf; public boolean instanceExists; boolean networkAvailable; BroadcastReceiver networkReceiver; MenuItem searchItem; int AutoSync = 0; //run or not to run. static final String state_sync = "AutoSync"; //to solve bugs. static final String state_mylist = "myList"; int listType = 0; //remembers the list_type. private DrawerLayout mDrawerLayout; private ListView listView; private SherlockActionBarDrawerToggle mDrawerToggle; private ActionBarHelper mActionBar; View mActiveView; View mPreviousView; boolean myList = true; //tracks if the user is on 'My List' or not public static final String[] DRAWER_OPTIONS = { "My List", "Top Rated", "Most Popular", "Just Added", "Upcoming" }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); context = getApplicationContext(); mPrefManager = new PrefManager(context); init = mPrefManager.getInit(); //The following is state handling code instanceExists = savedInstanceState != null && savedInstanceState.getBoolean("instanceExists", false); networkAvailable = savedInstanceState == null || savedInstanceState.getBoolean("networkAvailable", true); if (savedInstanceState != null) { AutoSync = savedInstanceState.getInt(state_sync); listType = savedInstanceState.getInt(state_mylist); } if (init) { setContentView(R.layout.activity_home); // Creates the adapter to return the Animu and Mango fragments mSectionsPagerAdapter = new HomeSectionsPagerAdapter(getSupportFragmentManager()); mDrawerLayout= (DrawerLayout)findViewById(R.id.drawer_layout); listView = (ListView)findViewById(R.id.left_drawer); mDrawerLayout.setDrawerListener(new DemoDrawerListener()); mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); HomeListViewArrayAdapter adapter = new HomeListViewArrayAdapter(this,R.layout.list_item,DRAWER_OPTIONS); listView.setAdapter(adapter); listView.setOnItemClickListener(new DrawerItemClickListener()); listView.setCacheColorHint(0); listView.setScrollingCacheEnabled(false); listView.setScrollContainer(false); listView.setFastScrollEnabled(true); listView.setSmoothScrollbarEnabled(true); mActionBar = createActionBarHelper(); mActionBar.init(); mDrawerToggle = new SherlockActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer_light, R.string.drawer_open, R.string.drawer_close); mDrawerToggle.syncState(); mManager = new MALManager(context); if (!instanceExists) { } // Set up the action bar. final ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); mViewPager.setPageMargin(32); // When swiping between different sections, select the corresponding // tab. // We can also use ActionBar.Tab#select() to do this if we have a // reference to the // Tab. mViewPager .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } }); // Add tabs for the animu and mango lists for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { // Create a tab with text corresponding to the page title // defined by the adapter. // Also specify this Activity object, which implements the // TabListener interface, as the // listener for when this tab is selected. actionBar.addTab(actionBar.newTab() .setText(mSectionsPagerAdapter.getPageTitle(i)) .setTabListener(this)); } networkReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { checkNetworkAndDisplayCrouton(); } }; listType = mPrefManager.getDefaultList(); //get chosen list :D autosynctask(); } else { //If the app hasn't been configured, take us to the first run screen to sign in. Intent firstRunInit = new Intent(this, FirstTimeInit.class); firstRunInit.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(firstRunInit); finish(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getSupportMenuInflater().inflate(R.menu.activity_home, menu); searchItem = menu.findItem(R.id.action_search); super.onCreateOptionsMenu(menu); return true; } @Override public BaseMALApi.ListType getCurrentListType() { String listName = getSupportActionBar().getSelectedTab().getText().toString(); return BaseMALApi.getListTypeByString(listName); } public boolean isConnectedWifi() { ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkInfo Wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (Wifi.isConnected()&& mPrefManager.getonly_wifiEnabled() ) { return true; } else { return false; } } public void autosynctask(){ try { af = (net.somethingdreadful.MAL.ItemGridFragment) mSectionsPagerAdapter.instantiateItem(mViewPager, 0); mf = (net.somethingdreadful.MAL.ItemGridFragment) mSectionsPagerAdapter.instantiateItem(mViewPager, 1); if (AutoSync == 0 && isNetworkAvailable() && networkAvailable == true && mPrefManager.getsynchronisationEnabled()){ if (mPrefManager.getsynchronisationEnabled() && mPrefManager.getonly_wifiEnabled() == false){ //connected to Wi-Fi and sync only on Wi-Fi checked. af.getRecords(af.currentList, "anime", true, this.context); mf.getRecords(af.currentList, "manga", true, this.context); syncNotify(); AutoSync = 1; }else if (mPrefManager.getonly_wifiEnabled() && isConnectedWifi() && mPrefManager.getsynchronisationEnabled()){ //connected and sync always. af.getRecords(af.currentList, "anime", true, this.context); mf.getRecords(af.currentList, "manga", true, this.context); syncNotify(); AutoSync = 1; } }else{ //will do nothing, sync is turned off or (sync only on Wi-Fi checked) and there is no Wi-Fi. } }catch (Exception e){ Crouton.makeText(this, "Error: autosynctask faild!", Style.ALERT).show(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } switch (item.getItemId()) { case R.id.menu_settings: startActivity(new Intent(this, Settings.class)); break; case R.id.menu_logout: showLogoutDialog(); break; case R.id.menu_about: startActivity(new Intent(this, AboutActivity.class)); break; case R.id.listType_all: if (af != null && mf != null) { af.getRecords(0, "anime", false, this.context); mf.getRecords(0, "manga", false, this.context); listType = 0; supportInvalidateOptionsMenu(); } break; case R.id.listType_inprogress: if (af != null && mf != null) { af.getRecords(1, "anime", false, this.context); mf.getRecords(1, "manga", false, this.context); listType = 1; supportInvalidateOptionsMenu(); } break; case R.id.listType_completed: if (af != null && mf != null) { af.getRecords(2, "anime", false, this.context); mf.getRecords(2, "manga", false, this.context); listType = 2; supportInvalidateOptionsMenu(); } break; case R.id.listType_onhold: if (af != null && mf != null) { af.getRecords(3, "anime", false, this.context); mf.getRecords(3, "manga", false, this.context); listType = 3; supportInvalidateOptionsMenu(); } break; case R.id.listType_dropped: if (af != null && mf != null) { af.getRecords(4, "anime", false, this.context); mf.getRecords(4, "manga", false, this.context); listType = 4; supportInvalidateOptionsMenu(); } break; case R.id.listType_planned: if (af != null && mf != null) { af.getRecords(5, "anime", false, this.context); mf.getRecords(5, "manga", false, this.context); listType = 5; supportInvalidateOptionsMenu(); } break; case R.id.forceSync: if (af != null && mf != null) { af.getRecords(af.currentList, "anime", true, this.context); mf.getRecords(af.currentList, "manga", true, this.context); syncNotify(); } break; } return super.onOptionsItemSelected(item); } @Override public void onResume() { super.onResume(); if (instanceExists && af.getMode()== 0) { af.getRecords(af.currentList, "anime", false, this.context); mf.getRecords(af.currentList, "manga", false, this.context); } checkNetworkAndDisplayCrouton(); registerReceiver(networkReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE")); if (mSearchView != null) { mSearchView.clearFocus(); mSearchView.setFocusable(false); mSearchView.setQuery("", false); searchItem.collapseActionView(); } } @Override public void onPause() { super.onPause(); instanceExists = true; unregisterReceiver(networkReceiver); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { // When the given tab is selected, switch to the corresponding page in the ViewPager. mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void fragmentReady() { //Interface implementation for knowing when the dynamically created fragment is finished loading //We use instantiateItem to return the fragment. Since the fragment IS instantiated, the method returns it. af = (net.somethingdreadful.MAL.ItemGridFragment) mSectionsPagerAdapter.instantiateItem(mViewPager, 0); mf = (net.somethingdreadful.MAL.ItemGridFragment) mSectionsPagerAdapter.instantiateItem(mViewPager, 1); try { // if a error comes up it will not force close getIntent().removeExtra("net.somethingdreadful.MAL.firstSync"); }catch (Exception e){ } } @Override public void onSaveInstanceState(Bundle state) { //This is telling out future selves that we already have some things and not to do them state.putBoolean("instanceExists", true); state.putBoolean("networkAvailable", networkAvailable); state.putInt(state_sync, AutoSync); state.putInt(state_mylist, listType); super.onSaveInstanceState(state); } @Override public boolean onPrepareOptionsMenu(Menu menu) { MenuItem item = menu.findItem(R.id.menu_listType); if(!myList){//if not on my list then disable menu items like listType, etc item.setEnabled(false); item.setVisible(false); } else{ item.setEnabled(true); item.setVisible(true); } if (af != null) { //All this is handling the ticks in the switch list menu switch (af.currentList) { case 0: menu.findItem(R.id.listType_all).setChecked(true); break; case 1: menu.findItem(R.id.listType_inprogress).setChecked(true); break; case 2: menu.findItem(R.id.listType_completed).setChecked(true); break; case 3: menu.findItem(R.id.listType_onhold).setChecked(true); break; case 4: menu.findItem(R.id.listType_dropped).setChecked(true); break; case 5: menu.findItem(R.id.listType_planned).setChecked(true); } } if (networkAvailable) { if (myList){ menu.findItem(R.id.forceSync).setVisible(true); }else{ menu.findItem(R.id.forceSync).setVisible(false); } menu.findItem(R.id.action_search).setVisible(true); } else { menu.findItem(R.id.forceSync).setVisible(false); menu.findItem(R.id.action_search).setVisible(false); AutoSync = 1; } return true; } @SuppressLint("NewApi") @Override public void onLogoutConfirmed() { mPrefManager.setInit(false); mPrefManager.setUser(""); mPrefManager.setPass(""); mPrefManager.commitChanges(); context.deleteDatabase(MALSqlHelper.getHelper(context).getDatabaseName()); new ImageDownloader(context).wipeCache(); startActivity(new Intent(this, Home.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); finish(); } private void syncNotify() { Crouton.makeText(this, R.string.toast_SyncMessage, Style.INFO).show(); Intent notificationIntent = new Intent(context, Home.class); PendingIntent contentIntent = PendingIntent.getActivity(context, 1, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT); NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Notification syncNotification = new NotificationCompat.Builder(context).setOngoing(true) .setContentIntent(contentIntent) .setSmallIcon(R.drawable.icon) .setContentTitle(getString(R.string.app_name)) .setContentText(getString(R.string.toast_SyncMessage)) .getNotification(); nm.notify(R.id.notification_sync, syncNotification); myList = true; supportInvalidateOptionsMenu(); } private void showLogoutDialog() { FragmentManager fm = getSupportFragmentManager(); LogoutConfirmationDialogFragment lcdf = new LogoutConfirmationDialogFragment(); if (Build.VERSION.SDK_INT >= 11) { lcdf.setStyle(SherlockDialogFragment.STYLE_NORMAL, android.R.style.Theme_Holo_Dialog); } else { lcdf.setStyle(SherlockDialogFragment.STYLE_NORMAL, 0); } lcdf.show(fm, "fragment_LogoutConfirmationDialog"); } public boolean isNetworkAvailable() { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnected()) { return true; } else { return false; } } public void maketext(String string) { Crouton.makeText(this, string, Style.INFO).show(); } public void checkNetworkAndDisplayCrouton() { if (!isNetworkAvailable() && networkAvailable == true) { Crouton.makeText(this, R.string.crouton_noConnectivityOnRun, Style.ALERT).show(); if (af.getMode() > 0) { mActiveView.setBackgroundColor(Color.parseColor("#333333")); //dark color af.getRecords(listType, "anime", false, Home.this.context); mf.getRecords(listType, "manga", false, Home.this.context); myList = true; af.setMode(0); mf.setMode(0); } } else if (isNetworkAvailable() && networkAvailable == false) { Crouton.makeText(this, R.string.crouton_connectionRestored, Style.INFO).show(); //TODO: Sync here, but first sync any records marked DIRTY af.getRecords(af.currentList, "anime", true, this.context); mf.getRecords(af.currentList, "manga", true, this.context); syncNotify(); } if (!isNetworkAvailable()) { networkAvailable = false; } else { networkAvailable = true; } supportInvalidateOptionsMenu(); } /* thread & methods to fetch most popular anime/manga*/ //in order to reuse the code , 1 signifies a getPopular job and 2 signifies a getTopRated job. Probably a better way to do this public void getMostPopular(BaseMALApi.ListType listType){ networkThread animethread = new networkThread(1); animethread.setListType(BaseMALApi.ListType.ANIME); animethread.execute(query); /*networkThread mangathread = new networkThread(1); mangathread.setListType(BaseMALApi.ListType.MANGA); mangathread.execute(query);*/ //API doesn't support getting popular manga :/ } public void getTopRated(BaseMALApi.ListType listType){ networkThread animethread = new networkThread(2); animethread.setListType(BaseMALApi.ListType.ANIME); animethread.execute(query); /*networkThread mangathread = new networkThread(2); mangathread.setListType(BaseMALApi.ListType.MANGA); mangathread.execute(query);*/ //API doesn't support getting top rated manga :/ } public void getJustAdded(BaseMALApi.ListType listType){ networkThread animethread = new networkThread(3); animethread.setListType(BaseMALApi.ListType.ANIME); animethread.execute(query); /*networkThread mangathread = new networkThread(3); mangathread.setListType(BaseMALApi.ListType.MANGA); mangathread.execute(query);*/ //API doesn't support getting popular manga :/ } public void getUpcoming(BaseMALApi.ListType listType){ networkThread animethread = new networkThread(4); animethread.setListType(BaseMALApi.ListType.ANIME); animethread.execute(query); /*networkThread mangathread = new networkThread(4); mangathread.setListType(BaseMALApi.ListType.MANGA); mangathread.execute(query);*/ //API doesn't support getting popular manga :/ } public class networkThread extends AsyncTask<String, Void, Void> { JSONArray _result; int job; public networkThread(int job){ this.job = job; } public MALApi.ListType getListType() { return listType; } public void setListType(MALApi.ListType listType) { this.listType = listType; } MALApi.ListType listType; @Override protected Void doInBackground(String... params) { try{ String query = params[0]; MALApi api = new MALApi(context); switch (job){ case 1: _result = api.getMostPopular(getListType(),1); //if job == 1 then get the most popular break; case 2: _result = api.getTopRated(getListType(),1); //if job == 2 then get the top rated break; case 3: _result = api.getJustAdded(getListType(),1); //if job == 3 then get the Just Added break; case 4: _result = api.getUpcoming(getListType(),1); //if job == 4 then get the upcoming break; } }catch (Exception e){ System.out.println("ERROR: doInBackground() at home.java"); } return null; } @Override protected void onPostExecute(Void result) { String type = MALApi.getListTypeString(getListType()); try { switch (listType) { case ANIME: { ArrayList<AnimeRecord> list = new ArrayList<AnimeRecord>(); if (_result.length() == 0) { System.out.println("No records, retry! (Home.java)");//TODO shouldnt return nothing, but... af.scrollToTop(); mf.scrollToTop(); if (af.getMode()== 1){ getTopRated(BaseMALApi.ListType.ANIME); } else if (af.getMode()== 2){ getMostPopular(BaseMALApi.ListType.ANIME); } else if (af.getMode()== 3){ getJustAdded(BaseMALApi.ListType.ANIME); } else if (af.getMode()== 4){ getUpcoming(BaseMALApi.ListType.ANIME); } af.scrollListener.resetPageNumber(); } else { for (int i = 0; i < _result.length(); i++) { JSONObject genre = (JSONObject) _result.get(i); AnimeRecord record = new AnimeRecord(mManager.getRecordDataFromJSONObject(genre, type)); list.add(record); } } af.setAnimeRecords(list); break; } case MANGA: { ArrayList<MangaRecord> list = new ArrayList<MangaRecord>(); if (_result.length() == 0) { System.out.println("No records");//TODO shouldnt return nothing, but... } else { for (int i = 0; i < _result.length(); i++) { JSONObject genre = (JSONObject) _result.get(i); MangaRecord record = new MangaRecord(mManager.getRecordDataFromJSONObject(genre, type)); list.add(record); } } mf.setMangaRecords(list); break; } } } catch (Exception e) { Log.e(SearchActivity.class.getName(), Log.getStackTraceString(e)); } Home.this.af.scrollListener.notifyMorePages(); } } /*private classes for nav drawer*/ private ActionBarHelper createActionBarHelper() { return new ActionBarHelper(); } public class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { /* do stuff when drawer item is clicked here */ af.scrollToTop(); mf.scrollToTop(); if (!isNetworkAvailable() && position > 0) { position = 0; maketext("No network connection available!"); } switch (position){ case 0: af.getRecords(listType, "anime", false, Home.this.context); mf.getRecords(listType, "manga", false, Home.this.context); myList = true; af.setMode(0); mf.setMode(0); break; case 1: getTopRated(BaseMALApi.ListType.ANIME); mf.setMangaRecords(new ArrayList<MangaRecord>()); ////basically, since you can't get popular manga this is just a temporary measure to make the manga set empty, otherwise it would continue to display YOUR manga list myList = false; af.setMode(1); mf.setMode(1); af.scrollListener.resetPageNumber(); mf.scrollListener.resetPageNumber(); break; case 2: getMostPopular(BaseMALApi.ListType.ANIME); mf.setMangaRecords(new ArrayList<MangaRecord>()); //basically, since you can't get popular manga this is just a temporary measure to make the manga set empty, otherwise it would continue to display YOUR manga list myList = false; af.setMode(2); mf.setMode(2); af.scrollListener.resetPageNumber(); mf.scrollListener.resetPageNumber(); break; case 3: getJustAdded(BaseMALApi.ListType.ANIME); mf.setMangaRecords(new ArrayList<MangaRecord>()); //basically, since you can't get popular manga this is just a temporary measure to make the manga set empty, otherwise it would continue to display YOUR manga list myList = false; af.setMode(3); mf.setMode(3); af.scrollListener.resetPageNumber(); mf.scrollListener.resetPageNumber(); break; case 4: getUpcoming(BaseMALApi.ListType.ANIME); mf.setMangaRecords(new ArrayList<MangaRecord>()); //basically, since you can't get popular manga this is just a temporary measure to make the manga set empty, otherwise it would continue to display YOUR manga list myList = false; af.setMode(4); mf.setMode(4); af.scrollListener.resetPageNumber(); mf.scrollListener.resetPageNumber(); break; } //af.scrollToTop(); //mf.scrollToTop(); Home.this.supportInvalidateOptionsMenu(); //This part is for figuring out which item in the nav drawer is selected and highlighting it with colors mPreviousView = mActiveView; if (mPreviousView != null) mPreviousView.setBackgroundColor(Color.parseColor("#333333")); //dark color mActiveView = view; if (isNetworkAvailable()){ mActiveView.setBackgroundColor(Color.parseColor("#38B2E1")); //blue color }else if (!isNetworkAvailable() && af.getMode() < 1){ mActiveView.setBackgroundColor(Color.parseColor("#38B2E1")); //blue color } mDrawerLayout.closeDrawer(listView); } } private class DemoDrawerListener implements DrawerLayout.DrawerListener { final ActionBar actionBar = getSupportActionBar(); @Override public void onDrawerOpened(View drawerView) { mDrawerToggle.onDrawerOpened(drawerView); mActionBar.onDrawerOpened(); } @Override public void onDrawerClosed(View drawerView) { mDrawerToggle.onDrawerClosed(drawerView); mActionBar.onDrawerClosed(); } @Override public void onDrawerSlide(View drawerView, float slideOffset) { mDrawerToggle.onDrawerSlide(drawerView, slideOffset); } @Override public void onDrawerStateChanged(int newState) { mDrawerToggle.onDrawerStateChanged(newState); } } private class ActionBarHelper { private final ActionBar mActionBar; private CharSequence mDrawerTitle; private CharSequence mTitle; private ActionBarHelper() { mActionBar = getSupportActionBar(); } public void init() { mActionBar.setDisplayHomeAsUpEnabled(true); mActionBar.setHomeButtonEnabled(true); mTitle = mDrawerTitle = getTitle(); } /** * When the drawer is closed we restore the action bar state reflecting * the specific contents in view. */ public void onDrawerClosed() { mActionBar.setTitle(mTitle); } /** * When the drawer is open we set the action bar to a generic title. The * action bar should only contain data relevant at the top level of the * nav hierarchy represented by the drawer, as the rest of your content * will be dimmed down and non-interactive. */ public void onDrawerOpened() { mActionBar.setTitle(mDrawerTitle); } public void setTitle(CharSequence title) { mTitle = title; } } }
package net.somethingdreadful.MAL; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.NotificationCompat; import android.support.v4.view.ViewPager; import android.widget.Toast; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockDialogFragment; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; public class Home extends SherlockFragmentActivity implements ActionBar.TabListener, ItemGridFragment.IItemGridFragment, LogoutConfirmationDialogFragment.LogoutConfirmationDialogListener { /** * The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the * sections. We use a {@link android.support.v4.app.FragmentPagerAdapter} derivative, which will * keep every loaded fragment in memory. If this becomes too memory intensive, it may be best * to switch to a {@link android.support.v4.app.FragmentStatePagerAdapter}. */ HomeSectionsPagerAdapter mSectionsPagerAdapter; /** * The {@link ViewPager} that will host the section contents. */ ViewPager mViewPager; Context context; PrefManager mPrefManager; public MALManager mManager; private boolean init = false; private boolean upgradeInit = false; ItemGridFragment af; ItemGridFragment mf; public boolean instanceExists; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); context = getApplicationContext(); mPrefManager = new PrefManager(context); init = mPrefManager.getInit(); upgradeInit = mPrefManager.getUpgradeInit(); //The following is state handling code if (savedInstanceState != null) { instanceExists = savedInstanceState.getBoolean("instanceExists", false); } else { instanceExists = false; } if (init == true) { setContentView(R.layout.activity_home); // Creates the adapter to return the Animu and Mango fragments mSectionsPagerAdapter = new HomeSectionsPagerAdapter( getSupportFragmentManager()); mManager = new MALManager(context); if (!instanceExists) { } // Set up the action bar. final ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); mViewPager.setPageMargin(32); // When swiping between different sections, select the corresponding // tab. // We can also use ActionBar.Tab#select() to do this if we have a // reference to the // Tab. mViewPager .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } }); // Add tabs for the animu and mango lists for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { // Create a tab with text corresponding to the page title // defined by the adapter. // Also specify this Activity object, which implements the // TabListener interface, as the // listener for when this tab is selected. actionBar.addTab(actionBar.newTab() .setText(mSectionsPagerAdapter.getPageTitle(i)) .setTabListener(this)); } } else //If the app hasn't been configured, take us to the first run screen to sign in { Intent firstRunInit = new Intent(this, FirstTimeInit.class); firstRunInit.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(firstRunInit); finish(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getSupportMenuInflater().inflate(R.menu.activity_home, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.menu_settings: startActivity(new Intent (this, Settings.class)); break; case R.id.menu_logout: showLogoutDialog(); break; case R.id.menu_about: startActivity(new Intent(this, About.class)); break; //The following is the code that handles switching the list. It calls the fragment to update, then update the menu by invalidating case R.id.listType_all: if (af != null && mf != null) { af.getRecords(0, "anime", false); mf.getRecords(0, "manga", false); invalidateOptionsMenu(); } break; case R.id.listType_inprogress: if (af != null && mf != null) { af.getRecords(1, "anime", false); mf.getRecords(1, "manga", false); invalidateOptionsMenu(); } break; case R.id.listType_completed: if (af != null && mf != null) { af.getRecords(2, "anime", false); mf.getRecords(2, "manga", false); invalidateOptionsMenu(); } break; case R.id.listType_onhold: if (af != null && mf != null) { af.getRecords(3, "anime", false); mf.getRecords(3, "manga", false); invalidateOptionsMenu(); } break; case R.id.listType_dropped: if (af != null && mf != null) { af.getRecords(4, "anime", false); mf.getRecords(4, "manga", false); invalidateOptionsMenu(); } break; case R.id.listType_planned: if (af != null && mf != null) { af.getRecords(5, "anime", false); mf.getRecords(5, "manga", false); invalidateOptionsMenu(); } break; case R.id.forceSync: if (af != null && mf != null) { af.getRecords(af.currentList, "anime", true); mf.getRecords(af.currentList, "manga", true); syncNotify(); } break; } return super.onOptionsItemSelected(item); } @Override public void onResume() { super.onResume(); if (instanceExists == true) { af.getRecords(af.currentList, "anime", false); mf.getRecords(af.currentList, "manga", false); } } @Override public void onPause() { super.onPause(); instanceExists = true; } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { // When the given tab is selected, switch to the corresponding page in the ViewPager. mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void fragmentReady() { //Interface implementation for knowing when the dynamically created fragment is finished loading //We use instantiateItem to return the fragment. Since the fragment IS instantiated, the method returns it. af = (ItemGridFragment) mSectionsPagerAdapter.instantiateItem(mViewPager, 0); mf = (ItemGridFragment) mSectionsPagerAdapter.instantiateItem(mViewPager, 1); //Logic to check if we have just signed in. If yes, automatically do a sync if (getIntent().getBooleanExtra("net.somethingdreadful.MAL.firstSync", false)) { af.getRecords(af.currentList, "anime", true); mf.getRecords(mf.currentList, "manga", true); getIntent().removeExtra("net.somethingdreadful.MAL.firstSync"); syncNotify(); } } @Override public void onSaveInstanceState(Bundle state) { //This is telling out future selves that we already have some things and not to do them state.putBoolean("instanceExists", true); super.onSaveInstanceState(state); } @Override public boolean onPrepareOptionsMenu(Menu menu) { if (af != null) { //All this is handling the ticks in the switch list menu switch (af.currentList) { case 0: menu.findItem(R.id.listType_all).setChecked(true); break; case 1: menu.findItem(R.id.listType_inprogress).setChecked(true); break; case 2: menu.findItem(R.id.listType_completed).setChecked(true); break; case 3: menu.findItem(R.id.listType_onhold).setChecked(true); break; case 4: menu.findItem(R.id.listType_dropped).setChecked(true); break; case 5: menu.findItem(R.id.listType_planned).setChecked(true); } } return true; } @Override public void onLogoutConfirmed() { mPrefManager.setInit(false); mPrefManager.setUser(""); mPrefManager.setPass(""); mPrefManager.commitChanges(); context.deleteDatabase(MALSqlHelper.DATABASE_NAME); new ImageDownloader(context).wipeCache(); startActivity(new Intent(this, Home.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); finish(); } private void syncNotify() { Toast.makeText(context, R.string.toast_SyncMessage, Toast.LENGTH_LONG).show(); Intent notificationIntent = new Intent(context, Home.class); PendingIntent contentIntent = PendingIntent.getActivity(context, 1, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT); NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Notification syncNotification = new NotificationCompat.Builder(context).setOngoing(true) .setContentIntent(contentIntent) .setSmallIcon(R.drawable.icon) .setContentTitle(getString(R.string.app_name)) .setContentText(getString(R.string.toast_SyncMessage)) .getNotification(); nm.notify(R.id.notification_sync, syncNotification); } private void showLogoutDialog() { FragmentManager fm = getSupportFragmentManager(); LogoutConfirmationDialogFragment lcdf = new LogoutConfirmationDialogFragment(); if (Build.VERSION.SDK_INT >= 11) { lcdf.setStyle(SherlockDialogFragment.STYLE_NORMAL, android.R.style.Theme_Holo_Dialog); } else { lcdf.setStyle(SherlockDialogFragment.STYLE_NORMAL, 0); } lcdf.show(fm, "fragment_LogoutConfirmationDialog"); } }
package view; import parser.Tokenizer; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.control.Button; import javafx.scene.control.TextArea; import javafx.scene.layout.Pane; public class InputView extends Pane { private static final double VIEW_WIDTH = 1000; private static final double VIEW_HEIGHT = 500; private TextArea myInput; private Button mySubmitButton; private Tokenizer myToken; private String myText="Let's gooooo\nXD"; public InputView() { setPrefWidth(VIEW_WIDTH); setPrefHeight(VIEW_HEIGHT); setMaxSize(VIEW_WIDTH, VIEW_HEIGHT); update(); this.getChildren().add(myInput); this.getChildren().add(mySubmitButton); } private void update() { myInput=new TextArea(); myInput.setPrefWidth(VIEW_WIDTH-70); myInput.setPrefHeight(VIEW_HEIGHT); myInput.setMaxSize(VIEW_WIDTH-70, VIEW_HEIGHT); mySubmitButton=new Button(); mySubmitButton.setText("Submit"); mySubmitButton.setLayoutX(930); mySubmitButton.setLayoutY(0); mySubmitButton.setMinSize(70, 70); mySubmitButton.setOnAction(new EventHandler<ActionEvent>(){ // give the string to the back end parser @Override public void handle(ActionEvent event) { myToken=new Tokenizer(); myToken.tokenize(myInput.getText()); System.out.println(myInput.getText()); myInput.clear(); } }); } public void addAndShowText(String text){ myText+=text+"\n"; myInput.setText(myText); } }
/* * $Id: ParamDoclet.java,v 1.10 2010-02-22 07:05:52 tlipkis Exp $ */ package org.lockss.doclet; import java.util.*; import java.io.*; import java.lang.reflect.*; import com.sun.javadoc.*; import org.lockss.util.*; /** * A JavaDoc doclet that prints configuration parameter information. * */ public class ParamDoclet { private static PrintStream out = null; private static boolean closeOut = false; public static boolean start(RootDoc root) { handleOptions(root); if (out == null) { out = System.out; } ClassDoc[] classDocs = root.classes(); HashMap params = new HashMap(); TreeMap sortedParams = new TreeMap(); for (int i = 0; i < classDocs.length; i++) { ClassDoc classDoc = classDocs[i]; String className = classDoc.qualifiedName(); FieldDoc[] fields = classDoc.fields(); for (int j = 0; j < fields.length; j++) { FieldDoc field = fields[j]; String name = field.name(); if (isParam(name)) { String key = getParamKey(classDoc, name); ParamInfo info = (ParamInfo)params.get(key); if (info == null) { info = new ParamInfo(); params.put(key, info); } if (name.startsWith("PARAM_")) { // This is a PARAM, not a DEFAULT if (info.usedIn.size() == 0) { // This is the first occurance we've encountered. Object value = field.constantValue(); if (value instanceof String) { String paramName = HtmlUtil.htmlEncode((String)value); String comment = field.getRawCommentText(); info.paramName = paramName; info.comment = comment; info.usedIn.add(className); // Add to the sorted map we'll use for printing. sortedParams.put(paramName, info); } } else { // We've already visited this parameter before, this is // just another use. info.usedIn.add(className); } } else if (name.startsWith("DEFAULT_")) { info.defaultValue = HtmlUtil.htmlEncode(getDefaultValue(field, root)); } } } } printDocHeader(); out.println("<h3>" + sortedParams.size() + " total parameters</h3>"); for (Iterator iter = sortedParams.keySet().iterator(); iter.hasNext(); ) { String key = (String)iter.next(); ParamInfo info = (ParamInfo)sortedParams.get(key); printParamInfo(info); } printDocFooter(); if (closeOut) { out.close(); } return true; } private static void printDocHeader() { out.println("<html>"); out.println("<head>"); out.println(" <title>Parameters</title>"); out.println(" <style type=\"text/css\">"); out.println(" .paramName { font-weight: bold; font-family: sans-serif;"); out.println(" font-size: 14pt; }"); out.println(" .defaultValue { font-family: monospace; font-size: 14pt; }"); out.println(" table { border-collapse: collapse; margin-left: 20px;"); out.println(" margin-right: 20px; padding: 0px; width: auto; }"); out.println(" tr { margin: 0px; padding: 0px; border: 0px; }"); out.println(" td { margin: 0px; padding-left: 6px; padding-right: 6px;"); out.println(" border: 0px; padding-left: 0px; padding-top: 0px; padding-right: 0px;}"); out.println(" td.paramHeader { padding-top: 5px; }"); out.println(" td.comment { }"); out.println(" td.usedIn { font-family: monospace; }"); out.println(" td.header { padding-left: 30px; padding-right: 10px; font-style: italic; text-align: right; }"); out.println(" </style>"); out.println("</head>"); out.println("<body>"); out.println("<div align=\"center\">"); out.println("<h1>LOCKSS Configuration Parameters</h1>"); out.println("<table>"); out.flush(); } private static void printDocFooter() { out.println("</table>"); out.println("</div>"); out.println("</body>"); out.println("</html>"); out.flush(); } private static void printParamInfo(ParamInfo info) { String pname = info.paramName.trim(); out.println("<tr>\n <td colspan=\"2\" class=\"paramHeader\">"); out.print(" <span class=\"paramName\" id=\"" + pname + "\">" + pname + "</span> &nbsp; "); out.print("<span class=\"defaultValue\">["); out.print(info.defaultValue == null ? "" : info.defaultValue.toString()); out.println("]</span>\n </td>"); out.println("</tr>"); out.println("<tr>"); out.println(" <td class=\"header\" valign=\"top\">Comment:</td>"); out.print(" <td class=\"comment\">"); if (info.comment.trim().length() == 0) { out.print(""); } else { out.print(info.comment.trim()); } out.println("</td>"); out.println("</tr>"); out.println("<tr>"); out.println(" <td class=\"header\" valign=\"top\">Used in:</td>"); out.println(" <td class=\"usedIn\">"); for (Iterator iter = info.usedIn.iterator(); iter.hasNext();) { out.println( (String)iter.next() + "<br/>"); } out.println(" </td>"); out.println("</tr>"); // out.println("<tr><td colspan=\"3\">&nbsp;</td></tr>"); out.flush(); } /** * Return true if the specified string is a parameter name. */ private static boolean isParam(String s) { return (s.startsWith("PARAM_") || s.startsWith("DEFAULT_")); } /** * Given a parameter or default name, return the key used to look up * its info object in the unsorted hashmap. */ private static String getParamKey(ClassDoc doc, String s) { StringBuffer sb = new StringBuffer(doc.qualifiedName() + "."); if (s.startsWith("DEFAULT_")) { sb.append(s.replaceFirst("DEFAULT_", "")); } else if (s.startsWith("PARAM_")) { sb.append(s.replaceFirst("PARAM_", "")); } else { sb.append(s); } return sb.toString(); } /** * Cheesily use reflection to obtain the default value. */ public static String getDefaultValue(FieldDoc field, RootDoc root) { String defaultVal = null; try { ClassDoc classDoc = field.containingClass(); Class c = Class.forName(classDoc.qualifiedName()); Field fld = c.getDeclaredField(field.name()); fld.setAccessible(true); Class cls = fld.getType(); if (int.class == cls) { defaultVal = (new Integer(fld.getInt(null))).toString(); } else if (long.class == cls) { long timeVal = fld.getLong(null); if (timeVal > 0) { defaultVal = timeVal + " (" + StringUtil.timeIntervalToString(timeVal) + ")"; } else { defaultVal = Long.toString(timeVal); } } else if (boolean.class == cls) { defaultVal = (new Boolean(fld.getBoolean(null))).toString(); } else { try { // This will throw NPE if the field isn't static; don't know how // to get initial value in that case Object dval = fld.get(null); defaultVal = (dval != null) ? dval.toString() : "(null)"; } catch (NullPointerException e) { defaultVal = "(unknown: non-static default)"; } } } catch (Exception e) { root.printError(field.position(), field.name() + ": " + e); root.printError(StringUtil.stackTraceString(e)); } return defaultVal; } /** * Required for Doclet options. */ public static int optionLength(String option) { if (option.equals("-o")) { return 2; } else if (option.equals("-d")) { return 2; } return 0; } public static boolean validOptions(String[][] options, DocErrorReporter reporter) { return true; } private static boolean handleOptions(RootDoc root) { String outDir = null; String[][] options = root.options(); for (int i = 0 ; i < options.length; i++) { if (options[i][0].equals("-d")) { outDir = options[i][1]; } else if (options[i][0].equals("-o")) { String outFile = options[i][1]; try { File f = null; if (outDir != null) { f = new File(outDir, outFile); } else { f = new File(outFile); } out = new PrintStream(new BufferedOutputStream(new FileOutputStream(f))); closeOut = true; return true; } catch (IOException ex) { root.printError("Unable to open output file: " + outFile); } } } return false; } /** * Simple wrapper class to hold information about parameters. */ private static class ParamInfo { public String paramName = ""; public Object defaultValue = null; public String comment = ""; // Sorted list of uses. public Set usedIn = new TreeSet(); } }
package org.intermine.web.struts; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.QueryClass; import org.intermine.objectstore.query.QueryField; import org.intermine.objectstore.query.Results; import org.intermine.objectstore.query.ResultsRow; import org.intermine.metadata.ClassDescriptor; import org.intermine.metadata.FieldDescriptor; import org.intermine.metadata.Model; import org.intermine.metadata.ReferenceDescriptor; import org.intermine.model.userprofile.Tag; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreSummary; import org.intermine.util.TypeUtil; import org.intermine.web.logic.ClassKeyHelper; import org.intermine.web.logic.Constants; import org.intermine.web.logic.bag.BagQueryConfig; import org.intermine.web.logic.profile.ProfileManager; import org.intermine.web.logic.session.SessionMethods; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.collections.iterators.IteratorChain; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.tiles.actions.TilesAction; /** * Controller Action for buildBag.jsp * * @author Kim Rutherford */ public class BagBuildController extends TilesAction { /** * Set up environment for the buildBag page. * * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * @return an ActionForward object defining where control goes next * * @exception Exception if an error occurs */ @Override public ActionForward execute(@SuppressWarnings("unused") ActionMapping mapping, @SuppressWarnings("unused") ActionForm form, HttpServletRequest request, @SuppressWarnings("unused") HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); ServletContext servletContext = session.getServletContext(); Model model = ((ObjectStore) servletContext.getAttribute(Constants.OBJECTSTORE)).getModel(); ProfileManager pm = SessionMethods.getProfileManager(servletContext); ObjectStore os = (ObjectStore) servletContext.getAttribute(Constants.OBJECTSTORE); ObjectStoreSummary oss = (ObjectStoreSummary) servletContext.getAttribute(Constants.OBJECT_STORE_SUMMARY); Collection<String> qualifiedTypes = os.getModel().getClassNames(); ArrayList<String> typeList = new ArrayList<String>(); ArrayList<String> preferedTypeList = new ArrayList<String>(); String superUserName = (String) servletContext.getAttribute(Constants.SUPERUSER_ACCOUNT); List<Tag> preferredBagTypeTags = pm.getTags("im:preferredBagType", null, "class", superUserName); for (Iterator<Tag> iter = preferredBagTypeTags.iterator(); iter.hasNext();) { Tag tag = iter.next(); preferedTypeList.add(TypeUtil.unqualifiedName(tag.getObjectIdentifier())); } Map<String, List<FieldDescriptor>> classKeys = (Map<String, List<FieldDescriptor>>) servletContext.getAttribute(Constants.CLASS_KEYS); for (Iterator<String> iter = qualifiedTypes.iterator(); iter.hasNext();) { String className = iter.next(); String unqualifiedName = TypeUtil.unqualifiedName(className); if (ClassKeyHelper.hasKeyFields(classKeys, unqualifiedName) && oss.getClassCount(className) > 0) { typeList.add(unqualifiedName); } } Collections.sort(preferedTypeList); Collections.sort(typeList); request.setAttribute("typeList", typeList); request.setAttribute("preferredTypeList", preferedTypeList); BagQueryConfig bagQueryConfig = (BagQueryConfig) servletContext.getAttribute(Constants.BAG_QUERY_CONFIG); String extraClassName = bagQueryConfig.getExtraConstraintClassName(); if (extraClassName != null) { request.setAttribute("extraBagQueryClass", TypeUtil.unqualifiedName(extraClassName)); List extraClassFieldValues = getFieldValues(os, oss, extraClassName, bagQueryConfig.getConstrainField()); request.setAttribute("extraClassFieldValues", extraClassFieldValues); // find the types in typeList that contain a field with the name given by // bagQueryConfig.getConnectField() List<String> typesWithConnectingField = new ArrayList<String>(); Iterator<String> allTypesIterator = new IteratorChain(typeList.iterator(), preferedTypeList.iterator()); while (allTypesIterator.hasNext()) { String connectFieldName = bagQueryConfig.getConnectField(); String typeName = allTypesIterator.next(); String qualifiedTypeName = model.getPackageName() + "." + typeName; ClassDescriptor cd = model.getClassDescriptorByName(qualifiedTypeName); FieldDescriptor fd = cd.getFieldDescriptorByName(connectFieldName); if (fd != null && fd instanceof ReferenceDescriptor) { typesWithConnectingField.add(typeName); } } request.setAttribute("typesWithConnectingField", typesWithConnectingField); } return null; } /** * Return a list of the possible field values for the given class/field name combination. * @param os the ObjectStore to query if the field values aren't available from the summary * @param oss the summary of the object store * @param extraClassName the class name * @param constrainField the field name * @return a List of the feild values */ public static List<Object> getFieldValues(ObjectStore os, ObjectStoreSummary oss, String extraClassName, String constrainField) { List<Object> fieldValues = oss.getFieldValues(extraClassName, constrainField); if (fieldValues == null) { Query q = new Query(); q.setDistinct(true); QueryClass qc; try { qc = new QueryClass(Class.forName(extraClassName)); } catch (ClassNotFoundException e) { throw new RuntimeException("Can't find class for: " + extraClassName); } q.addToSelect(new QueryField(qc, constrainField)); q.addFrom(qc); Results results = os.execute(q); fieldValues = new ArrayList<Object>(); for (Iterator j = results.iterator(); j.hasNext();) { Object fieldValue = ((ResultsRow) j.next()).get(0); fieldValues.add(fieldValue == null ? null : fieldValue.toString()); } } return fieldValues; } }
package org.intermine.webservice.lists; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.intermine.metadata.Model; import org.intermine.model.InterMineObject; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.query.ConstraintOp; import org.intermine.objectstore.query.Results; import org.intermine.objectstore.query.ResultsRow; import org.intermine.web.logic.Constants; import org.intermine.web.logic.query.Constraint; import org.intermine.web.logic.query.PathNode; import org.intermine.web.logic.query.PathQuery; import org.intermine.webservice.WebService; import org.intermine.webservice.WebServiceConstants; import org.intermine.webservice.WebServiceException; import org.intermine.webservice.core.ListManager; import org.intermine.webservice.core.PathQueryExecutor; import org.intermine.webservice.output.HTMLTable; import org.intermine.webservice.output.MemoryOutput; import org.intermine.webservice.output.Output; /** * Web service that returns all public lists (bags) that contain object with * specified id. * See {@link ListsRequestProcessor} for parameter description * URL examples: * Get all public lists with specified intermine id * /listswithobject?output=xml&id=1343743 * Get all public lists with specified id, corresponding intermine id is found with lookup * /listswithobject?output=xml&publicId=1343743 * @author Jakub Kulaviak **/ public class ListsService extends WebService { /** * Executes service specific logic. * @param request request * @param response response */ @Override protected void execute(HttpServletRequest request, HttpServletResponse response) { ListsServiceInput input = getInput(); if (!validate(input)) { return; } Integer objectId = null; if (input.getMineId() == null) { objectId = resolveMineId(request, input); if (objectId == null) { return; } } else { objectId = input.getMineId(); if (!objectExists(request, objectId)) { output.addError("object with specified id doesn't exist."); output.flush(); return; } } List<String> listNames = new ListManager(request).getListsNames(objectId); addListsToOutput(listNames); forward(input, output); } private boolean objectExists(HttpServletRequest request, Integer objectId) { ObjectStore os = (ObjectStore) request.getSession(). getServletContext().getAttribute(Constants.OBJECTSTORE); try { InterMineObject objectById = os.getObjectById(objectId); return objectById != null; } catch (ObjectStoreException e) { throw new RuntimeException("Getting object with id " + objectId + " failed."); } } private void addListsToOutput(List<String> listNames) { for (String name : listNames) { List<String> result = new ArrayList<String>(); result.add(name); output.addResultItem(result); } } private Integer resolveMineId(HttpServletRequest request, ListsServiceInput input) { ObjectStore os = (ObjectStore) request.getSession().getServletContext(). getAttribute(Constants.OBJECTSTORE); Model model = os.getModel(); // checks type if (model.getClassDescriptorByName(input.getType()) == null) { output.addError("invalid " + ListsRequestParser.TYPE_PARAMETER + " parameter." + " Specified type of the object doesn't exist: " + input.getType()); output.flush(); return null; } PathQuery pathQuery = new PathQuery(model); PathNode node = new PathNode(input.getType()); Constraint constraint = new Constraint(ConstraintOp.LOOKUP, input.getPublicId()); node.getConstraints().add(constraint); pathQuery.getNodes().put(input.getType(), node); pathQuery.addPathStringToView(input.getType()); PathQueryExecutor executor = new PathQueryExecutor(request, pathQuery); Results results = executor.getResults(); if (results.size() != 1) { if (results.size() == 0) { output.addError("No objects of type " + input.getType() + " with public id " + input.getPublicId() + " were found."); } else { output.addError("Multiple objects of type " + input.getType() + " with public id " + input.getPublicId() + " were found."); } output.flush(); return null; } else { ResultsRow row = (ResultsRow) results.get(0); return ((InterMineObject) row.get(0)).getId(); } } private void forward(ListsServiceInput input, Output output) { if (getFormat() == HTML_FORMAT) { MemoryOutput mout = (MemoryOutput) output; HTMLTable table = new HTMLTable(); table.setRows(mout.getResults()); List<String> columnNames = new ArrayList<String>(); columnNames.add("List"); table.setColumnNames(columnNames); table.setTitle("Lists with " + input.getPublicId()); request.setAttribute(WebServiceConstants.HTML_TABLE_ATTRIBUTE, table); try { getHtmlForward().forward(request, response); } catch (Exception e) { throw new WebServiceException(WebServiceConstants.SERVICE_FAILED_MSG, e); } } } private ListsServiceInput getInput() { return new ListsRequestParser(request).getInput(); } }
package eu.hbp.mip.container.rapidminer.db; import java.io.IOException; import java.sql.* ; import eu.hbp.mip.container.rapidminer.RapidMinerExperiment; /** * * @author Arnaud Jutzeler * */ public class DBConnector { private static final String IN_URL = System.getenv("IN_JDBC_URL"); private static final String IN_USER = System.getenv("IN_JDBC_USER"); private static final String IN_PASS = System.getenv("IN_JDBC_PASSWORD"); private static final String OUT_URL = System.getenv("OUT_JDBC_URL"); private static final String OUT_USER = System.getenv("OUT_JDBC_USER"); private static final String OUT_PASS = System.getenv("OUT_JDBC_PASSWORD"); private static final String OUT_TABLE = System.getenv().getOrDefault("RESULT_TABLE", "job_result"); private String query = null; private Direction direction = null; private transient Connection conn = null; private transient Statement stmt = null; private transient ResultSet rs = null; public enum Direction { DATA_IN (IN_URL, IN_USER, IN_PASS), DATA_OUT (OUT_URL, OUT_USER, OUT_PASS); private final String url; private final String user; private final String pass; Direction(String url, String user, String pass) { this.url = url; this.user = user; this.pass = pass; } private Connection getConnection() throws SQLException { return DriverManager.getConnection(url,user, pass); } } public DBConnector(String query, Direction direction) { this.query = query; this.direction = direction; } public ResultSet connect() throws DBException { try { //conn = DriverManager.getConnection(IN_URL, IN_USER, IN_PASS); conn = direction.getConnection(); conn.setAutoCommit(false); // TODO The seed must be passed as a query parameters and generated above conn.prepareStatement("SELECT setseed(0.67)").execute(); stmt = conn.createStatement(); rs = stmt.executeQuery(query); conn.commit(); conn.setAutoCommit(true); return rs; } catch (SQLException e) { if (conn != null) { try { conn.close(); } catch (SQLException e2) {} } if (stmt != null) { try { stmt.close(); } catch (SQLException e2) {} } if (rs != null) { try { rs.close(); } catch (SQLException e2) {} } throw new DBException(e); } } public void disconnect() { if (conn != null) { try { conn.close(); } catch (SQLException e) {} conn = null; } if (stmt != null) { try { stmt.close(); } catch (SQLException e) {} stmt = null; } if (rs != null) { try { rs.close(); } catch (SQLException e) {} rs = null; } } public static void saveResults(RapidMinerExperiment experiment) throws DBException { Connection conn = null; Statement stmt = null; try { conn = DriverManager.getConnection(OUT_URL, OUT_USER, OUT_PASS); String jobId = System.getProperty("JOB_ID", System.getenv("JOB_ID")); String node = System.getenv("NODE"); //String outFormat = System.getenv("OUT_FORMAT"); String function = System.getenv().getOrDefault("FUNCTION", "JAVA"); String shape = "pfa_json"; // Escape single quote with another single quote (SQL) String pfa = experiment.toPFA().replaceAll("'", "''"); String statement = "INSERT INTO " + OUT_TABLE + " (job_id, node, data, shape, function)" + "VALUES ('" + jobId + "', '" + node + "', '" + pfa + "', '" + shape + "', '" + function + "')"; Statement st = conn.createStatement(); st.executeUpdate(statement); } catch (SQLException | IOException e) { throw new DBException(e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) {} } if (stmt != null) { try { stmt.close(); } catch (SQLException e) {} } } } public static class DBResults { public String node; public String shape; public String data; public DBResults(String node, String shape, String data) { this.node = node; this.shape = shape; this.data = data; } } public static DBResults getDBResult(String jobId) throws DBException { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { String URL = System.getenv("OUT_JDBC_URL"); String USER = System.getenv("OUT_JDBC_USER"); String PASS = System.getenv("OUT_JDBC_PASSWORD"); String TABLE = System.getenv().getOrDefault("RESULT_TABLE", "job_result"); conn = DriverManager.getConnection(URL, USER, PASS); Statement st = conn.createStatement(); rs = st.executeQuery("select node, data, shape from " + TABLE + " where job_id ='" + jobId + "'"); DBResults results = null; while (rs.next()) { results = new DBResults(rs.getString("node"), rs.getString("shape"), rs.getString("data")); } return results; } catch (SQLException e) { e.printStackTrace(); throw new DBException(e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) {} } if (stmt != null) { try { stmt.close(); } catch (SQLException e) {} } if (rs != null) { try { rs.close(); } catch (SQLException e) {} } } } }
package example; import java.io.IOException; import java.io.InputStream; import java.io.File; import java.io.FileWriter; import java.io.BufferedWriter; import java.util.Iterator; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.ObjectWritable; import org.apache.hadoop.mapred.FileInputFormat; import org.apache.hadoop.mapred.FileOutputFormat; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.MapReduceBase; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reducer; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.apache.hadoop.fs.FSDataInputStream; import rapcap.hadoop.mr1.lzo.LzoInputFormat; import rapcap.hadoop.mr1.RecordInputFormat; import rapcap.hadoop.mr1.lzo.PublicLzopInputStream; import rapcap.lib.lzo.LzopBoundaryDetector; public class ParallelDecompress extends Configured implements Tool{ public static String fileName; public static class ParallelDecompressMapper extends MapReduceBase implements Mapper<LongWritable, LongWritable, LongWritable, ObjectWritable>{ private LzopBoundaryDetector detect; private static final LongWritable point = new LongWritable(2); private long pointerLong; private byte bytebuff[] = new byte[(256*1024)]; private ObjectWritable outputbuff = new ObjectWritable(bytebuff); private FSDataInputStream stream = RecordInputFormat.baseStream; private InputStream istream = stream.getWrappedStream(); private PublicLzopInputStream dstream = (PublicLzopInputStream) istream; private long offset(){ return detect.getRecordStartOffset(); } int incl_len; public void map(LongWritable index, LongWritable pointer, OutputCollector<LongWritable, ObjectWritable> output, Reporter reporter) throws IOException { pointerLong = pointer.get(); stream.seek((offset() + 4)); incl_len = stream.readInt(); dstream.seek(pointerLong); dstream.decompress(bytebuff, 0, incl_len); outputbuff.set(bytebuff); output.collect(point, outputbuff); } } public static class ParallelDecompressReducer extends MapReduceBase implements Reducer<LongWritable, ObjectWritable, IntWritable, ObjectWritable>{ public void reduce(LongWritable keys, Iterator<ObjectWritable> values, OutputCollector<IntWritable, ObjectWritable> output, Reporter reporter) throws IOException { File file = new File(fileName); FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); BufferedWriter bw = new BufferedWriter(fw); while (values.hasNext()){ bw.write(values.toString()); values.next(); } bw.close(); } } public static void main(String[] args) throws Exception { fileName = args[2]; int res = ToolRunner.run(new JobConf(), new ParallelDecompress(), args); System.exit(res); } public int run(String[] args) throws Exception { JobConf job = (JobConf)this.getConf(); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); job.setJobName("parallel decompress"); job.setJarByClass(CountPackets.class); job.setMapperClass(ParallelDecompressMapper.class); job.setReducerClass(ParallelDecompressReducer.class); job.setInputFormat(LzoInputFormat.class); job.setOutputKeyClass(LongWritable.class); job.setOutputValueClass(ObjectWritable.class); job.setNumReduceTasks(1); JobClient.runJob(job); return 0; } }
package views; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.Observable; import java.util.Observer; import javax.swing.AbstractAction; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBoxMenuItem; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.WindowConstants; import viewModels.BookTableModel; import viewModels.CustomerTableModel; import viewModels.LoanTableModel; import domain.Library; public class MainView extends javax.swing.JFrame implements Observer { private static final long serialVersionUID = 1L; private JTabbedPane tbsMain; private BooksTab booksTab; private LoansTab loansTab; private CustomerTab customerTab; private Library library; // Models private BookTableModel bookTableModel; private LoanTableModel loanTableModel; private CustomerTableModel customerTableModel; private JPanel pnlMainButtons; private JButton btnCloseApp; /** * Create the application. * @param library * @author PCHR */ public MainView( Library library ) { /* * This View should listen to changes in the book list and the loans list! * Also: customerList */ super(); this.library = library; bookTableModel = new BookTableModel( this.library ); loanTableModel = new LoanTableModel( this.library ); customerTableModel = new CustomerTableModel( library.getCustomerList() ); initialize(); library.addObserver( this ); setLocationRelativeTo(null); setVisible(true); } /** * Initialize the contents of the frames. * @author PFORSTER * @author PCHR */ private void initialize() { try { setMinimumSize( new Dimension(800, 600) ); // ACTIONS // CLOSE AbstractAction close = new CloseAction( Messages.getString( "MainView.btnExit.text"), "Close the application, disregard all unsaved changes" ); // INITIAL SETUP setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); this.setTitle(Messages.getString("MainView.title")); this.setBounds(100, 100, 700, 550); pnlMainButtons = new JPanel(); FlowLayout fl_pnlMainButtons = (FlowLayout) pnlMainButtons.getLayout(); fl_pnlMainButtons.setAlignment(FlowLayout.RIGHT); getContentPane().add(pnlMainButtons, BorderLayout.SOUTH); btnCloseApp = new JButton( close ); btnCloseApp.setIcon( new ImageIcon("icons/close_32.png") ); pnlMainButtons.add(btnCloseApp); tbsMain = new JTabbedPane(JTabbedPane.TOP); getContentPane().add(tbsMain, BorderLayout.CENTER); // BOOKS TAB booksTab = new BooksTab( bookTableModel, library ); tbsMain.addTab( Messages.getString("BookMaster.Tab.Books" ), new ImageIcon("icons/book_32.png"), booksTab, null ); tbsMain.setMnemonicAt(0, KeyEvent.VK_1); // LOANS TAB loansTab = new LoansTab( loanTableModel, library ); tbsMain.addTab( Messages.getString("BookMaster.Tab.Loans" ), new ImageIcon("icons/basket_32.png"), loansTab, null ); tbsMain.setMnemonicAt(1, KeyEvent.VK_2); // CUSTOMERS TAB customerTab = new CustomerTab(customerTableModel, library); tbsMain.addTab( Messages.getString( "MainView.Tab.Customers"), new ImageIcon("icons/user_32.png"), customerTab, null ); tbsMain.setMnemonicAt(2, KeyEvent.VK_3); // Initialize the buttons, actions, etc. updateButtons(); updateStatistics(); } catch (Exception e) { e.printStackTrace(); } } @Override public void update(Observable o, Object arg) { updateButtons(); booksTab.updateShowUnavailableCheckbox(); updateStatistics(); } /** * Updates the labels that contain statistical information. * @author PCHR */ private void updateStatistics() { booksTab.updateStatistics(); loansTab.updateStatistics(); customerTab.updateStatistics(); } /** * Updates all buttons on the view * @author PCHR */ public void updateButtons() { booksTab.updateListButtons(); loansTab.updateListButtons(); customerTab.updateListButtons(); } // Action Subclasses /** * Closes the current dialog. * @author PCHR */ class CloseAction extends AbstractAction { private static final long serialVersionUID = 1L; public CloseAction( String text, String desc ) { super( text ); putValue( SHORT_DESCRIPTION, desc ); putValue( MNEMONIC_KEY, KeyEvent.VK_S ); } public void actionPerformed(ActionEvent e) { System.exit(0); } } }
package net.bull.javamelody; import java.awt.BorderLayout; import java.awt.Desktop; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.text.DecimalFormat; import java.util.Arrays; import java.util.Collections; import java.util.List; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import net.bull.javamelody.swing.MButton; import net.bull.javamelody.swing.Utilities; import net.bull.javamelody.swing.table.MMultiLineTableCellRenderer; import net.bull.javamelody.swing.table.MTable; import net.bull.javamelody.swing.util.MWaitCursor; /** * Panel des statistiques. * @author Emeric Vernat */ class StatisticsPanel extends MelodyPanel { static final ImageIcon PLUS_ICON = ImageIconCache.getImageIcon("bullets/plus.png"); static final ImageIcon MINUS_ICON = ImageIconCache.getImageIcon("bullets/minus.png"); private static final long serialVersionUID = 1L; @SuppressWarnings("all") private final CounterRequestAggregation counterRequestAggregation; private final Counter counter; private final Range range; private final StatisticsTablePanel tablePanel; private final JPanel mainPanel; private StatisticsPanel detailsPanel; private CounterErrorPanel lastErrorsPanel; StatisticsPanel(RemoteCollector remoteCollector, Counter counter, Range range, boolean includeGraph) { this(remoteCollector, counter, range, null, includeGraph); } private StatisticsPanel(RemoteCollector remoteCollector, Counter counter, Range range, CounterRequestAggregation counterRequestAggregation, boolean includeGraph) { super(remoteCollector); assert counter != null; assert range != null; this.counter = counter; this.range = range; if (counter.getRequestsCount() == 0) { this.tablePanel = null; this.counterRequestAggregation = null; } else { if (counterRequestAggregation == null) { this.counterRequestAggregation = new CounterRequestAggregation(counter); } else { this.counterRequestAggregation = counterRequestAggregation; } this.tablePanel = new StatisticsTablePanel(getRemoteCollector(), counter, this.counterRequestAggregation, includeGraph); } this.mainPanel = new JPanel(new BorderLayout()); this.mainPanel.setOpaque(false); add(this.mainPanel, BorderLayout.NORTH); } public void showGlobalRequests() { if (counter.getRequestsCount() == 0) { final JLabel noRequestsLabel = createNoRequestsLabel(); mainPanel.add(noRequestsLabel, BorderLayout.CENTER); } else { List<CounterRequest> requests = counterRequestAggregation.getRequests(); final CounterRequest globalRequest = counterRequestAggregation.getGlobalRequest(); if (isErrorAndNotJobCounter()) { // il y a au moins une "request" d'erreur puisque la liste n'est pas vide assert !requests.isEmpty(); requests = Collections.singletonList(requests.get(0)); final MTable<CounterRequest> myTable = tablePanel.getTable(); addMouseClickedListener(myTable); } else { requests = Arrays.asList(globalRequest, counterRequestAggregation.getWarningRequest(), counterRequestAggregation.getSevereRequest()); } showRequests(requests); final JPanel requestsSizeAndButtonsPanel = createRequestsSizeAndButtonsPanel(); mainPanel.add(requestsSizeAndButtonsPanel, BorderLayout.EAST); } } void showDetailRequests() { if (detailsPanel == null) { final boolean includeGraph = CounterRequestTable.isRequestGraphDisplayed(counter); detailsPanel = new StatisticsPanel(getRemoteCollector(), counter, range, counterRequestAggregation, includeGraph); detailsPanel.setVisible(false); final List<CounterRequest> requests = counterRequestAggregation.getRequests(); detailsPanel.showRequests(requests); final MTable<CounterRequest> myTable = detailsPanel.tablePanel.getTable(); myTable.setColumnCellRenderer("name", new MMultiLineTableCellRenderer()); // avec le MMultiLineTableCellRenderer (tester par exemple l'erreur de compilation dans la page jsp avec tomcat) SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Utilities.adjustTableHeight(myTable); } }); addMouseClickedListener(myTable); add(detailsPanel, BorderLayout.CENTER); } detailsPanel.setVisible(!detailsPanel.isVisible()); detailsPanel.validate(); } void showRequestsAggregatedOrFilteredByClassName(String requestId, final MButton detailsButton) { final List<CounterRequest> requests = new CounterRequestAggregation(counter) .getRequestsAggregatedOrFilteredByClassName(requestId); tablePanel.setList(requests); add(tablePanel, BorderLayout.CENTER); final MTable<CounterRequest> myTable = tablePanel.getTable(); if (detailsButton != null) { myTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { detailsButton.setEnabled(myTable.getSelectedObject() != null); } }); detailsButton.setEnabled(myTable.getSelectedObject() != null); myTable.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { detailsButton.doClick(); } } }); detailsButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { actionCounterSummaryPerClass(true); } }); } else { addMouseClickedListener(myTable); } } private void addMouseClickedListener(final MTable<CounterRequest> myTable) { myTable.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { final MWaitCursor waitCursor = new MWaitCursor(myTable); final CounterRequest request = myTable.getSelectedObject(); try { showRequestDetail(request); } catch (final IOException ex) { showException(ex); } finally { waitCursor.restore(); } } } }); } void showLastErrors() { if (lastErrorsPanel == null) { lastErrorsPanel = new CounterErrorPanel(counter); lastErrorsPanel.setVisible(false); add(lastErrorsPanel, BorderLayout.SOUTH); } lastErrorsPanel.setVisible(!lastErrorsPanel.isVisible()); lastErrorsPanel.validate(); } private JLabel createNoRequestsLabel() { final String key; if (isJobCounter()) { key = "Aucun_job"; } else if (isErrorCounter()) { key = "Aucune_erreur"; } else { key = "Aucune_requete"; } return new JLabel(' ' + I18N.getString(key)); } private void showRequests(List<CounterRequest> requests) { tablePanel.setList(requests); Utilities.adjustTableHeight(tablePanel.getTable()); mainPanel.add(tablePanel, BorderLayout.NORTH); } private JPanel createRequestsSizeAndButtonsPanel() { final CounterRequest globalRequest = this.counterRequestAggregation.getGlobalRequest(); final long end; if (range.getEndDate() != null) { end = Math.min(range.getEndDate().getTime(), System.currentTimeMillis()); } else { end = System.currentTimeMillis(); } final long deltaMillis = Math.max(end - counter.getStartDate().getTime(), 1); final long hitsParMinute = 60 * 1000 * globalRequest.getHits() / deltaMillis; final String nbKey; if (isJobCounter()) { nbKey = "nb_jobs"; } else if (isErrorCounter()) { nbKey = "nb_erreurs"; } else { nbKey = "nb_requetes"; } final DecimalFormat integerFormat = I18N.createIntegerFormat(); final String text = I18N.getFormattedString(nbKey, integerFormat.format(hitsParMinute), integerFormat.format(counterRequestAggregation.getRequests().size())); final JPanel panel = Utilities.createButtonsPanel(new JLabel(text)); if (counter.isBusinessFacadeCounter()) { panel.add(createCounterSummaryPerClassButton()); panel.add(createRuntimeDependenciesButton()); } panel.add(createDetailsButton()); if (isErrorCounter()) { panel.add(createLastErrorsButton()); } if (range.getPeriod() == Period.TOUT) { panel.add(createClearCounterButton()); } return panel; } private MButton createCounterSummaryPerClassButton() { final MButton counterSummaryPerClassButton = new MButton( I18N.getString("Resume_par_classe")); counterSummaryPerClassButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { actionCounterSummaryPerClass(false); } }); return counterSummaryPerClassButton; } private MButton createRuntimeDependenciesButton() { final MButton runtimeDependenciesButton = new MButton(I18N.getString("Dependances"), ImageIconCache.getImageIcon("pdf.png")); runtimeDependenciesButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { actionRuntimeDependencies(); } catch (final IOException ex) { showException(ex); } } }); return runtimeDependenciesButton; } private MButton createDetailsButton() { final MButton detailsButton = new MButton(I18N.getString("Details"), PLUS_ICON); detailsButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showDetailRequests(); changePlusMinusIcon(detailsButton); } }); return detailsButton; } private MButton createLastErrorsButton() { final MButton lastErrorsButton = new MButton(I18N.getString("Dernieres_erreurs"), PLUS_ICON); lastErrorsButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showLastErrors(); changePlusMinusIcon(lastErrorsButton); } }); return lastErrorsButton; } private MButton createClearCounterButton() { final MButton clearCounterButton = new MButton(I18N.getString("Reinitialiser")); clearCounterButton .setToolTipText(I18N.getFormattedString("Vider_stats", counter.getName())); final Counter myCounter = counter; clearCounterButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (confirm(I18N.getFormattedString("confirm_vider_stats", myCounter.getName()))) { actionClearCounter(myCounter); } } }); return clearCounterButton; } final void actionClearCounter(Counter myCounter) { try { final String message = getRemoteCollector().executeActionAndCollectData( Action.CLEAR_COUNTER, myCounter.getName(), null, null, null); showMessage(message); MainPanel.refreshMainTabFromChild(this); } catch (final IOException ex) { showException(ex); } } final void actionCounterSummaryPerClass(boolean detailsForAClass) { final String requestId; if (detailsForAClass) { requestId = tablePanel.getTable().getSelectedObject().getId(); } else { requestId = null; } final CounterSummaryPerClassPanel panel = new CounterSummaryPerClassPanel( getRemoteCollector(), counter, range, requestId); MainPanel.addOngletFromChild(this, panel); } final void actionRuntimeDependencies() throws IOException { final File tempFile = createTempFileForPdf(); final OutputStream output = createFileOutputStream(tempFile); try { final PdfOtherReport pdfOtherReport = new PdfOtherReport(getRemoteCollector() .getApplication(), output); pdfOtherReport.writeRuntimeDependencies(counter, range); } finally { output.close(); } Desktop.getDesktop().open(tempFile); } final void changePlusMinusIcon(MButton detailsButton) { if (detailsButton.getIcon() == PLUS_ICON) { detailsButton.setIcon(MINUS_ICON); } else { detailsButton.setIcon(PLUS_ICON); } } private boolean isErrorCounter() { return counter.isErrorCounter(); } private boolean isJobCounter() { return counter.isJobCounter(); } private boolean isErrorAndNotJobCounter() { return isErrorCounter() && !isJobCounter(); } void showRequestDetail(CounterRequest request) throws IOException { final CounterRequestDetailPanel panel = new CounterRequestDetailPanel(getRemoteCollector(), request, range); MainPanel.addOngletFromChild(this, panel); } }
package vo; public class Reservation { private String resNum; private String resDateTime; private String resStatus; private Document document; private Branch branch; private Reader reader; public Document getDocument() { return document; } public void setDocument(Document document) { this.document = document; } public Branch getBranch() { return branch; } public void setBranch(Branch branch) { this.branch = branch; } public Reader getReader() { return reader; } public void setReader(Reader reader) { this.reader = reader; } public String getResNum() { return resNum; } public String getResDateTime() { return resDateTime; } public String getResStatus() { return resStatus; } }
package com.jenjinstudios.core.util; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.util.logging.Level; import java.util.logging.Logger; /** * This class contains security utility methods. * * @author Caleb Brinkman */ public class SecurityUtil { private static final Logger LOGGER = Logger.getLogger(SecurityUtil.class.getName()); private static final int KEYSIZE = 512; /** * Generate an RSA-512 Public-Private Key Pair. * * @return The generated {@code KeyPair}, or null if the KeyPair could not be created. */ public static KeyPair generateRSAKeyPair() { KeyPair keyPair = null; try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(KEYSIZE); keyPair = keyPairGenerator.generateKeyPair(); } catch (NoSuchAlgorithmException e) { LOGGER.log(Level.SEVERE, "Unable to create RSA key pair!", e); } return keyPair; } }
package com.appspot.relaxe.ent.value; import com.appspot.relaxe.ent.Attribute; import com.appspot.relaxe.ent.EntityRuntimeException; import com.appspot.relaxe.rpc.LongHolder; import com.appspot.relaxe.rpc.PrimitiveHolder; import com.appspot.relaxe.types.LongType; import com.appspot.relaxe.types.PrimitiveType; public final class LongKey< A extends Attribute, E extends HasLong<A, E> > extends AbstractPrimitiveKey<A, E, Long, LongType, LongHolder, LongKey<A, E>> { private static final long serialVersionUID = 3465654564903987460L; /** * No-argument constructor for GWT Serialization */ private LongKey() { } private LongKey(HasLongKey<A, E> meta, A name) { super(name); meta.register(this); } public static < X extends Attribute, T extends HasLong<X, T> > LongKey<X, T> get(HasLongKey<X, T> meta, X a) { LongKey<X, T> k = meta.getLongKey(a); if (k == null) { PrimitiveType<?> t = a.type(); if (t != null && t.getSqlType() == PrimitiveType.BIGINT) { k = new LongKey<X, T>(meta, a); } } return k; } @Override public LongType type() { return LongType.TYPE; } @Override public void set(E e, LongHolder newValue) throws EntityRuntimeException { e.setLong(this, newValue); } @Override public LongHolder get(E e) throws EntityRuntimeException { return e.getLong(self()); } @Override public LongHolder newHolder(Long newValue) { return LongHolder.valueOf(newValue); } @Override public void copy(E src, E dest) throws EntityRuntimeException { dest.setLong(this, src.getLong(this)); } @Override public LongKey<A, E> self() { return this; } @Override public void reset(E dest) throws EntityRuntimeException { dest.setLong(this, LongHolder.NULL_HOLDER); } @Override public LongHolder as(PrimitiveHolder<?, ?, ?> holder) { return LongHolder.of(holder); } }
package org.eclipse.jetty.servlets; import java.io.IOException; import java.util.HashSet; import java.util.Locale; import java.util.Set; import java.util.StringTokenizer; import java.util.regex.Pattern; import java.util.zip.Deflater; import java.util.zip.DeflaterOutputStream; import java.util.zip.GZIPOutputStream; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.ServletResponseWrapper; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import org.eclipse.jetty.continuation.Continuation; import org.eclipse.jetty.continuation.ContinuationListener; import org.eclipse.jetty.continuation.ContinuationSupport; import org.eclipse.jetty.http.HttpMethods; import org.eclipse.jetty.http.gzip.CompressedResponseWrapper; import org.eclipse.jetty.http.gzip.AbstractCompressedStream; import org.eclipse.jetty.util.StringUtil; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; public class GzipFilter extends UserAgentFilter { private static final Logger LOG = Log.getLogger(GzipFilter.class); public final static String GZIP="gzip"; public final static String ETAG_GZIP="--gzip\""; public final static String DEFLATE="deflate"; public final static String ETAG_DEFLATE="--deflate\""; public final static String ETAG="o.e.j.s.GzipFilter.ETag"; protected ServletContext _context; protected Set<String> _mimeTypes; protected int _bufferSize=8192; protected int _minGzipSize=256; protected int _deflateCompressionLevel=Deflater.DEFAULT_COMPRESSION; protected boolean _deflateNoWrap = true; protected final Set<String> _methods=new HashSet<String>(); protected Set<String> _excludedAgents; protected Set<Pattern> _excludedAgentPatterns; protected Set<String> _excludedPaths; protected Set<Pattern> _excludedPathPatterns; protected String _vary="Accept-Encoding, User-Agent"; private static final int STATE_SEPARATOR = 0; private static final int STATE_Q = 1; private static final int STATE_QVALUE = 2; private static final int STATE_DEFAULT = 3; /** * @see org.eclipse.jetty.servlets.UserAgentFilter#init(javax.servlet.FilterConfig) */ @Override public void init(FilterConfig filterConfig) throws ServletException { super.init(filterConfig); _context=filterConfig.getServletContext(); String tmp=filterConfig.getInitParameter("bufferSize"); if (tmp!=null) _bufferSize=Integer.parseInt(tmp); tmp=filterConfig.getInitParameter("minGzipSize"); if (tmp!=null) _minGzipSize=Integer.parseInt(tmp); tmp=filterConfig.getInitParameter("deflateCompressionLevel"); if (tmp!=null) _deflateCompressionLevel=Integer.parseInt(tmp); tmp=filterConfig.getInitParameter("deflateNoWrap"); if (tmp!=null) _deflateNoWrap=Boolean.parseBoolean(tmp); tmp=filterConfig.getInitParameter("methods"); if (tmp!=null) { StringTokenizer tok = new StringTokenizer(tmp,",",false); while (tok.hasMoreTokens()) _methods.add(tok.nextToken().trim().toUpperCase()); } else _methods.add(HttpMethods.GET); tmp=filterConfig.getInitParameter("mimeTypes"); if (tmp!=null) { _mimeTypes=new HashSet<String>(); StringTokenizer tok = new StringTokenizer(tmp,",",false); while (tok.hasMoreTokens()) _mimeTypes.add(tok.nextToken()); } tmp=filterConfig.getInitParameter("excludedAgents"); if (tmp!=null) { _excludedAgents=new HashSet<String>(); StringTokenizer tok = new StringTokenizer(tmp,",",false); while (tok.hasMoreTokens()) _excludedAgents.add(tok.nextToken()); } tmp=filterConfig.getInitParameter("excludeAgentPatterns"); if (tmp!=null) { _excludedAgentPatterns=new HashSet<Pattern>(); StringTokenizer tok = new StringTokenizer(tmp,",",false); while (tok.hasMoreTokens()) _excludedAgentPatterns.add(Pattern.compile(tok.nextToken())); } tmp=filterConfig.getInitParameter("excludePaths"); if (tmp!=null) { _excludedPaths=new HashSet<String>(); StringTokenizer tok = new StringTokenizer(tmp,",",false); while (tok.hasMoreTokens()) _excludedPaths.add(tok.nextToken()); } tmp=filterConfig.getInitParameter("excludePathPatterns"); if (tmp!=null) { _excludedPathPatterns=new HashSet<Pattern>(); StringTokenizer tok = new StringTokenizer(tmp,",",false); while (tok.hasMoreTokens()) _excludedPathPatterns.add(Pattern.compile(tok.nextToken())); } tmp=filterConfig.getInitParameter("vary"); if (tmp!=null) _vary=tmp; } /** * @see org.eclipse.jetty.servlets.UserAgentFilter#destroy() */ @Override public void destroy() { } /** * @see org.eclipse.jetty.servlets.UserAgentFilter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) */ @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request=(HttpServletRequest)req; HttpServletResponse response=(HttpServletResponse)res; // If not a supported method or it is an Excluded URI - no Vary because no matter what client, this URI is always excluded String requestURI = request.getRequestURI(); if (!_methods.contains(request.getMethod()) || isExcludedPath(requestURI)) { super.doFilter(request,response,chain); return; } // Exclude non compressible mime-types known from URI extension. - no Vary because no matter what client, this URI is always excluded if (_mimeTypes!=null && _mimeTypes.size()>0) { String mimeType = _context.getMimeType(request.getRequestURI()); if (mimeType!=null && !_mimeTypes.contains(mimeType)) { // handle normally without setting vary header super.doFilter(request,response,chain); return; } } // Excluded User-Agents String ua = getUserAgent(request); boolean ua_excluded=ua!=null&&isExcludedAgent(ua); // Acceptable compression type String compressionType = ua_excluded?null:selectCompression(request.getHeader("accept-encoding")); // Special handling for etags String etag = request.getHeader("If-None-Match"); if (etag!=null) { int dd=etag.indexOf(" if (dd>0) request.setAttribute(ETAG,etag.substring(0,dd)+(etag.endsWith("\"")?"\"":"")); } CompressedResponseWrapper wrappedResponse = createWrappedResponse(request,response,compressionType); boolean exceptional=true; try { super.doFilter(request,wrappedResponse,chain); exceptional=false; } finally { Continuation continuation = ContinuationSupport.getContinuation(request); if (continuation.isSuspended() && continuation.isResponseWrapped()) { continuation.addContinuationListener(new ContinuationListenerWaitingForWrappedResponseToFinish(wrappedResponse)); } else if (exceptional && !response.isCommitted()) { wrappedResponse.resetBuffer(); wrappedResponse.noCompression(); } else wrappedResponse.finish(); } } private String selectCompression(String encodingHeader) { // TODO, this could be a little more robust. // prefer gzip over deflate String compression = null; if (encodingHeader!=null) { String[] encodings = getEncodings(encodingHeader); if (encodings != null) { for (int i=0; i< encodings.length; i++) { if (encodings[i].toLowerCase(Locale.ENGLISH).contains(GZIP)) { if (isEncodingAcceptable(encodings[i])) { compression = GZIP; break; //prefer Gzip over deflate } } if (encodings[i].toLowerCase(Locale.ENGLISH).contains(DEFLATE)) { if (isEncodingAcceptable(encodings[i])) { compression = DEFLATE; //Keep checking in case gzip is acceptable } } } } } return compression; } private String[] getEncodings (String encodingHeader) { if (encodingHeader == null) return null; return encodingHeader.split(","); } private boolean isEncodingAcceptable(String encoding) { int state = STATE_DEFAULT; int qvalueIdx = -1; for (int i=0;i<encoding.length();i++) { char c = encoding.charAt(i); switch (state) { case STATE_DEFAULT: { if (';' == c) state = STATE_SEPARATOR; break; } case STATE_SEPARATOR: { if ('q' == c || 'Q' == c) state = STATE_Q; break; } case STATE_Q: { if ('=' == c) state = STATE_QVALUE; break; } case STATE_QVALUE: { if (qvalueIdx < 0 && '0' == c || '1' == c) qvalueIdx = i; break; } } } if (qvalueIdx < 0) return true; if ("0".equals(encoding.substring(qvalueIdx).trim())) return false; return true; } protected CompressedResponseWrapper createWrappedResponse(HttpServletRequest request, HttpServletResponse response, final String compressionType) { CompressedResponseWrapper wrappedResponse = null; if (compressionType==null) { wrappedResponse = new CompressedResponseWrapper(request,response) { @Override protected AbstractCompressedStream newCompressedStream(HttpServletRequest request,HttpServletResponse response) throws IOException { return new AbstractCompressedStream(null,request,this,_vary) { @Override protected DeflaterOutputStream createStream() throws IOException { return null; } }; } }; } else if (compressionType.equals(GZIP)) { wrappedResponse = new CompressedResponseWrapper(request,response) { @Override protected AbstractCompressedStream newCompressedStream(HttpServletRequest request,HttpServletResponse response) throws IOException { return new AbstractCompressedStream(compressionType,request,this,_vary) { @Override protected DeflaterOutputStream createStream() throws IOException { return new GZIPOutputStream(_response.getOutputStream(),_bufferSize) { /** * Work around a bug in the jvm GzipOutputStream whereby it is not * thread safe when thread A calls finish, but thread B is writing * @see java.util.zip.GZIPOutputStream#finish() */ @Override public synchronized void finish() throws IOException { super.finish(); } /** * Work around a bug in the jvm GzipOutputStream whereby it is not * thread safe when thread A calls close(), but thread B is writing * @see java.util.zip.GZIPOutputStream#finish() */ @Override public void close() throws IOException { super.close(); } }; } }; } }; } else if (compressionType.equals(DEFLATE)) { wrappedResponse = new CompressedResponseWrapper(request,response) { @Override protected AbstractCompressedStream newCompressedStream(HttpServletRequest request,HttpServletResponse response) throws IOException { return new AbstractCompressedStream(compressionType,request,this,_vary) { @Override protected DeflaterOutputStream createStream() throws IOException { return new DeflaterOutputStream(_response.getOutputStream(),new Deflater(_deflateCompressionLevel,_deflateNoWrap)); } }; } }; } else { throw new IllegalStateException(compressionType + " not supported"); } configureWrappedResponse(wrappedResponse); return wrappedResponse; } protected void configureWrappedResponse(CompressedResponseWrapper wrappedResponse) { wrappedResponse.setMimeTypes(_mimeTypes); wrappedResponse.setBufferSize(_bufferSize); wrappedResponse.setMinCompressSize(_minGzipSize); } private class ContinuationListenerWaitingForWrappedResponseToFinish implements ContinuationListener { private CompressedResponseWrapper wrappedResponse; public ContinuationListenerWaitingForWrappedResponseToFinish(CompressedResponseWrapper wrappedResponse) { this.wrappedResponse = wrappedResponse; } public void onComplete(Continuation continuation) { try { wrappedResponse.finish(); } catch (IOException e) { LOG.warn(e); } } public void onTimeout(Continuation continuation) { } } /** * Checks to see if the userAgent is excluded * * @param ua * the user agent * @return boolean true if excluded */ private boolean isExcludedAgent(String ua) { if (ua == null) return false; if (_excludedAgents != null) { if (_excludedAgents.contains(ua)) { return true; } } if (_excludedAgentPatterns != null) { for (Pattern pattern : _excludedAgentPatterns) { if (pattern.matcher(ua).matches()) { return true; } } } return false; } /** * Checks to see if the path is excluded * * @param requestURI * the request uri * @return boolean true if excluded */ private boolean isExcludedPath(String requestURI) { if (requestURI == null) return false; if (_excludedPaths != null) { for (String excludedPath : _excludedPaths) { if (requestURI.startsWith(excludedPath)) { return true; } } } if (_excludedPathPatterns != null) { for (Pattern pattern : _excludedPathPatterns) { if (pattern.matcher(requestURI).matches()) { return true; } } } return false; } }
package com.esotericsoftware.yamlbeans; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import com.esotericsoftware.yamlbeans.YamlConfig.ConstructorParameters; /** Utility for dealing with beans and public fields. * @author <a href="mailto:misc@n4te.com">Nathan Sweet</a> */ class Beans { private Beans () { } static public boolean isScalar (Class c) { return c.isPrimitive() || c == String.class || c == Integer.class || c == Boolean.class || c == Float.class || c == Long.class || c == Double.class || c == Short.class || c == Byte.class || c == Character.class; } static public DeferredConstruction getDeferredConstruction (Class type, YamlConfig config) { ConstructorParameters parameters = config.readConfig.constructorParameters.get(type); if (parameters != null) return new DeferredConstruction(parameters.constructor, parameters.parameterNames); try { Class constructorProperties = Class.forName("java.beans.ConstructorProperties"); for (Constructor typeConstructor : type.getConstructors()) { Annotation annotation = typeConstructor.getAnnotation(constructorProperties); if (annotation == null) continue; String[] parameterNames = (String[])constructorProperties.getMethod("value").invoke(annotation, (Object[])null); return new DeferredConstruction(typeConstructor, parameterNames); } } catch (Exception ignored) { } return null; } static public Object createObject (Class type, boolean privateConstructors) throws InvocationTargetException { // Use no-arg constructor. Constructor constructor = null; for (Constructor typeConstructor : type.getConstructors()) { if (typeConstructor.getParameterTypes().length == 0) { constructor = typeConstructor; break; } } if (constructor == null && privateConstructors) { // Try a private constructor. try { constructor = type.getDeclaredConstructor(); constructor.setAccessible(true); } catch (SecurityException ignored) { } catch (NoSuchMethodException ignored) { } } // Otherwise try to use a common implementation. if (constructor == null) { try { if (List.class.isAssignableFrom(type)) { constructor = ArrayList.class.getConstructor(new Class[0]); } else if (Set.class.isAssignableFrom(type)) { constructor = HashSet.class.getConstructor(new Class[0]); } else if (Map.class.isAssignableFrom(type)) { constructor = HashMap.class.getConstructor(new Class[0]); } } catch (Exception ex) { throw new InvocationTargetException(ex, "Error getting constructor for class: " + type.getName()); } } if (constructor == null) throw new InvocationTargetException(null, "Unable to find a no-arg constructor for class: " + type.getName()); try { return constructor.newInstance(); } catch (Exception ex) { throw new InvocationTargetException(ex, "Error constructing instance of class: " + type.getName()); } } static public Set<Property> getProperties (Class type, boolean beanProperties, boolean privateFields, YamlConfig config) { if (type == null) throw new IllegalArgumentException("type cannot be null."); Class[] noArgs = new Class[0], oneArg = new Class[1]; Set<Property> properties = new TreeSet(); for (Field field : getAllFields(type)) { String name = field.getName(); if (beanProperties) { DeferredConstruction deferredConstruction = getDeferredConstruction(type, config); boolean constructorProperty = deferredConstruction != null && deferredConstruction.hasParameter(name); String nameUpper = Character.toUpperCase(name.charAt(0)) + name.substring(1); Method getMethod = null, setMethod = null; try { oneArg[0] = field.getType(); setMethod = type.getMethod("set" + nameUpper, oneArg); } catch (Exception ignored) { } try { getMethod = type.getMethod("get" + nameUpper, noArgs); } catch (Exception ignored) { } if (getMethod == null && (field.getType().equals(Boolean.class) || field.getType().equals(boolean.class))) { try { getMethod = type.getMethod("is" + nameUpper, noArgs); } catch (Exception ignored) { } } if (getMethod != null && (setMethod != null || constructorProperty)) { properties.add(new MethodProperty(name, setMethod, getMethod)); continue; } } int modifiers = field.getModifiers(); if (Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers)) continue; if (!Modifier.isPublic(modifiers) && !privateFields) continue; try { field.setAccessible(true); } catch (Exception ignored) { } properties.add(new FieldProperty(field)); } return properties; } static public Property getProperty (Class type, String name, boolean beanProperties, boolean privateFields, YamlConfig config) { if (type == null) throw new IllegalArgumentException("type cannot be null."); if (name == null || name.length() == 0) throw new IllegalArgumentException("name cannot be null or empty."); name = name.replace(" ", ""); Class[] noArgs = new Class[0], oneArg = new Class[1]; for (Field field : getAllFields(type)) { if (!field.getName().equals(name)) continue; if (beanProperties) { DeferredConstruction deferredConstruction = getDeferredConstruction(type, config); boolean constructorProperty = deferredConstruction != null && deferredConstruction.hasParameter(name); String nameUpper = Character.toUpperCase(name.charAt(0)) + name.substring(1); Method getMethod = null, setMethod = null; try { oneArg[0] = field.getType(); setMethod = type.getMethod("set" + nameUpper, oneArg); } catch (Exception ignored) { } try { getMethod = type.getMethod("get" + nameUpper, noArgs); } catch (Exception ignored) { } if (getMethod == null && (field.getType().equals(Boolean.class) || field.getType().equals(boolean.class))) { try { getMethod = type.getMethod("is" + nameUpper, noArgs); } catch (Exception ignored) { } } if (getMethod != null && (setMethod != null || constructorProperty)) return new MethodProperty(name, setMethod, getMethod); } int modifiers = field.getModifiers(); if (Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers)) continue; if (!Modifier.isPublic(modifiers) && !privateFields) continue; try { field.setAccessible(true); } catch (Exception ignored) { } return new FieldProperty(field); } return null; } static private ArrayList<Field> getAllFields (Class type) { ArrayList<Field> allFields = new ArrayList(); Class nextClass = type; while (nextClass != null && nextClass != Object.class) { Collections.addAll(allFields, nextClass.getDeclaredFields()); nextClass = nextClass.getSuperclass(); } return allFields; } static public class MethodProperty extends Property { private final Method setMethod, getMethod; public MethodProperty (String name, Method setMethod, Method getMethod) { super(getMethod.getDeclaringClass(), name, getMethod.getReturnType(), getMethod.getGenericReturnType()); this.setMethod = setMethod; this.getMethod = getMethod; } public void set (Object object, Object value) throws Exception { if (object instanceof DeferredConstruction) { ((DeferredConstruction)object).storeProperty(this, value); return; } setMethod.invoke(object, value); } public Object get (Object object) throws Exception { return getMethod.invoke(object); } } static public class FieldProperty extends Property { private final Field field; public FieldProperty (Field field) { super(field.getDeclaringClass(), field.getName(), field.getType(), field.getGenericType()); this.field = field; } public void set (Object object, Object value) throws Exception { if (object instanceof DeferredConstruction) { ((DeferredConstruction)object).storeProperty(this, value); return; } field.set(object, value); } public Object get (Object object) throws Exception { return field.get(object); } } static public abstract class Property implements Comparable<Property> { private final Class declaringClass; private final String name; private final Class type; private final Class elementType; Property (Class declaringClass, String name, Class type, Type genericType) { this.declaringClass = declaringClass; this.name = name; this.type = type; this.elementType = getElementTypeFromGenerics(genericType); } private Class getElementTypeFromGenerics (Type type) { if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType)type; Type rawType = parameterizedType.getRawType(); if (isCollection(rawType) || isMap(rawType)) { Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); if (actualTypeArguments.length > 0) { return (Class)actualTypeArguments[actualTypeArguments.length - 1]; } } } return null; } private boolean isMap (Type type) { return Map.class.isAssignableFrom((Class)type); } private boolean isCollection (Type type) { return Collection.class.isAssignableFrom((Class)type); } public int hashCode () { final int prime = 31; int result = 1; result = prime * result + ((declaringClass == null) ? 0 : declaringClass.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode()); result = prime * result + ((elementType == null) ? 0 : elementType.hashCode()); return result; } public boolean equals (Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Property other = (Property)obj; if (declaringClass == null) { if (other.declaringClass != null) return false; } else if (!declaringClass.equals(other.declaringClass)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; if (elementType == null) { if (other.elementType != null) return false; } else if (!elementType.equals(other.elementType)) return false; return true; } public Class getDeclaringClass () { return declaringClass; } public Class getElementType () { return elementType; } public Class getType () { return type; } public String getName () { return name; } public String toString () { return name; } public int compareTo (Property o) { int comparison = name.compareTo(o.name); if (comparison != 0) { // Sort id and name above all other fields. if (name.equals("id")) return -1; if (o.name.equals("id")) return 1; if (name.equals("name")) return -1; if (o.name.equals("name")) return 1; } return comparison; } abstract public void set (Object object, Object value) throws Exception; abstract public Object get (Object object) throws Exception; } }
package org.jmock.test.acceptance; import junit.framework.TestCase; import org.hamcrest.StringDescription; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.api.ExpectationError; import org.jmock.test.unit.support.AssertThat; public class ErrorMessagesAcceptanceTests extends TestCase { Mockery context = new Mockery(); MockedType mock = context.mock(MockedType.class, "mock"); public void testShowsExpectedAndCurrentNumberOfCallsInErrorMessage() { context.checking(new Expectations() {{ exactly(1).of (mock).method1(); exactly(1).of (mock).method2(); atLeast(1).of (mock).method3(); allowing (mock).method4(); }}); mock.method2(); mock.method3(); mock.method4(); try { context.assertIsSatisfied(); } catch (ExpectationError e) { String message = StringDescription.toString(e); AssertThat.stringIncludes("should include expectation that has not been invoked at all", "method1", message); AssertThat.stringIncludes("should include expectation that has been fully satisfied", "method2", message); AssertThat.stringIncludes("should include expectation that has been satisfied but can still be invoked", "method3", message); AssertThat.stringIncludes("should include expectation that is allowed", "method4", message); } } // See issue JMOCK-132 public void testErrorMessageIncludesNotInvokedInsteadOfInvokedExactly0Times() { context.checking(new Expectations() {{ exactly(1).of (mock).method1(); }}); try { context.assertIsSatisfied(); } catch (ExpectationError e) { String message = StringDescription.toString(e); AssertThat.stringIncludes("should include 'never invoked'", "never invoked", message); } } // See JIRA-153 public void testErrorMessageIncludesOnceInsteadOfExactly1Time() { context.checking(new Expectations() {{ exactly(1).of (mock).method1(); }}); try { context.assertIsSatisfied(); } catch (ExpectationError e) { String message = StringDescription.toString(e); AssertThat.stringIncludes("should include 'once'", "once", message); } } }
package com.haskforce.parsing; import com.haskforce.parsing.jsonParser.JsonParser; import com.haskforce.parsing.srcExtsDatatypes.*; import com.intellij.lang.ASTNode; import com.intellij.lang.PsiBuilder; import com.intellij.lang.PsiParser; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; import static com.haskforce.parsing.HaskellTypes2.*; // These can be imported as * when the old parser is removed. import static com.haskforce.psi.HaskellTypes.OPENPRAGMA; import static com.haskforce.psi.HaskellTypes.CLOSEPRAGMA; import static com.haskforce.psi.HaskellTypes.OPENCOM; import static com.haskforce.psi.HaskellTypes.CLOSECOM; import static com.haskforce.psi.HaskellTypes.CPPIF; import static com.haskforce.psi.HaskellTypes.CPPELSE; import static com.haskforce.psi.HaskellTypes.CPPENDIF; import static com.haskforce.psi.HaskellTypes.COMMENT; import static com.haskforce.psi.HaskellTypes.COMMENTTEXT; import static com.haskforce.psi.HaskellTypes.DOUBLEQUOTE; import static com.haskforce.psi.HaskellTypes.STRINGTOKEN; import static com.haskforce.psi.HaskellTypes.BADSTRINGTOKEN; import static com.haskforce.psi.HaskellTypes.MODULE; import static com.haskforce.psi.HaskellTypes.WHERE; import static com.haskforce.psi.HaskellTypes.PRAGMA; import static com.haskforce.psi.HaskellTypes.EQUALS; import static com.haskforce.psi.HaskellTypes.IMPORT; import static com.haskforce.psi.HaskellTypes.QUALIFIED; import static com.haskforce.psi.HaskellTypes.HIDING; import static com.haskforce.psi.HaskellTypes.PERIOD; import static com.haskforce.psi.HaskellTypes.RPAREN; import static com.haskforce.psi.HaskellTypes.LPAREN; import static com.haskforce.psi.HaskellTypes.RBRACKET; import static com.haskforce.psi.HaskellTypes.LBRACKET; import static com.haskforce.psi.HaskellTypes.AS; import static com.haskforce.psi.HaskellTypes.TYPE; import static com.haskforce.psi.HaskellTypes.DATA; import static com.haskforce.psi.HaskellTypes.IN; import static com.haskforce.psi.HaskellTypes.DOUBLECOLON; import static com.haskforce.psi.HaskellTypes.COMMA; import static com.haskforce.psi.HaskellTypes.RIGHTARROW; import static com.haskforce.psi.HaskellTypes.LEFTARROW; import static com.haskforce.psi.HaskellTypes.MINUS; import static com.haskforce.psi.HaskellTypes.DO; import static com.haskforce.psi.HaskellTypes.BACKSLASH; import static com.haskforce.psi.HaskellTypes.HASH; import static com.haskforce.psi.HaskellTypes.FOREIGN; import static com.haskforce.psi.HaskellTypes.EXPORTTOKEN; import static com.haskforce.psi.HaskellTypes.DOUBLEARROW; import static com.haskforce.psi.HaskellTypes.BACKTICK; import static com.haskforce.psi.HaskellTypes.INSTANCE; import static com.haskforce.psi.HaskellTypes.LBRACE; import static com.haskforce.psi.HaskellTypes.RBRACE; import static com.haskforce.psi.HaskellTypes.EXLAMATION; // FIXME: Rename. import static com.haskforce.psi.HaskellTypes.PIPE; import static com.haskforce.psi.HaskellTypes.CHARTOKEN; import static com.haskforce.psi.HaskellTypes.LET; /** * New Parser using parser-helper. */ public class HaskellParser2 implements PsiParser { private static final Logger LOG = Logger.getInstance(HaskellParser2.class); private final Project myProject; private final JsonParser myJsonParser; public HaskellParser2(@NotNull Project project) { myProject = project; myJsonParser = new JsonParser(project); } @NotNull @Override public ASTNode parse(IElementType root, PsiBuilder builder) { PsiBuilder.Marker rootMarker = builder.mark(); TopPair tp = myJsonParser.parse(builder.getOriginalText()); if (tp.error != null && !tp.error.isEmpty()) { // TODO: Parse failed. Possibly warn. Could be annoying. } IElementType e = builder.getTokenType(); while (!builder.eof() && (isInterruption(e) && e != OPENPRAGMA)) { if (e == COMMENT || e == OPENCOM) { parseComment(e, builder, tp.comments); e = builder.getTokenType(); } else if (e == CPPIF || e == CPPELSE || e == CPPENDIF) { // Ignore CPP-tokens, they are not fed to parser-helper anyways. builder.advanceLexer(); e = builder.getTokenType(); } else { throw new RuntimeException("Unexpected failure on:" + e.toString()); } } parseModule(builder, (Module) tp.moduleType, tp.comments); return chewEverything(rootMarker, root, builder); } private static ASTNode chewEverything(PsiBuilder.Marker marker, IElementType e, PsiBuilder builder) { while (!builder.eof()) { builder.advanceLexer(); } marker.done(e); ASTNode result = builder.getTreeBuilt(); // System.out.println("Psifile:" + builder.getTreeBuilt().getPsi().getContainingFile().getName()); return result; } /** * Parses a complete module. */ private static void parseModule(PsiBuilder builder, Module module, Comment[] comments) { parseModulePragmas(builder, module == null ? null : module.modulePragmas, comments); parseModuleHead(builder, module == null ? null : module.moduleHeadMaybe, comments); parseImportDecls(builder, module == null ? null : module.importDecls, comments); parseBody(builder, module == null ? null : module.decls, comments); } /** * Parses "module NAME [modulepragmas] [exportSpecList] where". */ private static void parseModuleHead(PsiBuilder builder, ModuleHead head, Comment[] comments) { IElementType e = builder.getTokenType(); if (e != MODULE) return; PsiBuilder.Marker moduleMark = builder.mark(); consumeToken(builder, MODULE); parseModuleName(builder, head == null ? null : head.moduleName, comments); // TODO: parseExportSpecList(builder, head.exportSpecList, comments); IElementType e2 = builder.getTokenType(); while (e2 != WHERE) { if (e2 == OPENPRAGMA) { parseGenericPragma(builder, null, comments); } else { builder.advanceLexer(); } e2 = builder.getTokenType(); } consumeToken(builder, WHERE); moduleMark.done(e); } private static void parseModuleName(PsiBuilder builder, ModuleName name, Comment[] comments) { builder.getTokenType(); // Need to getTokenType to advance lexer over whitespace. int startPos = builder.getCurrentOffset(); IElementType e = builder.getTokenType(); while ((name != null && (builder.getCurrentOffset() - startPos) < name.name.length()) || name == null && e != WHERE) { builder.remapCurrentToken(NAME); consumeToken(builder, NAME); e = builder.getTokenType(); if (e == PERIOD) builder.advanceLexer(); } } /** * Parses a list of import statements. */ private static void parseImportDecls(PsiBuilder builder, ImportDecl[] importDecls, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (isInterruption(e) || importDecls != null && i < importDecls.length) { if (e == CPPIF || e == CPPELSE || e == CPPENDIF) { builder.advanceLexer(); e = builder.getTokenType(); continue; } else if (e == OPENCOM) { parseComment(e, builder, comments); e = builder.getTokenType(); continue; } else if (e == OPENPRAGMA) { parseGenericPragma(builder, null, comments); e = builder.getTokenType(); continue; } if (e != IMPORT) return; parseImportDecl(builder, importDecls[i], comments); i++; e = builder.getTokenType(); } } /** * Returns true for elements that can occur anywhere in the tree, * for example comments or pragmas. */ private static boolean isInterruption(IElementType e) { return (e == CPPIF || e == CPPELSE || e == CPPENDIF || e == OPENCOM || e == OPENPRAGMA); } /** * Parses an import statement. */ private static void parseImportDecl(PsiBuilder builder, ImportDecl importDecl, Comment[] comments) { IElementType e = builder.getTokenType(); PsiBuilder.Marker importMark = builder.mark(); consumeToken(builder, IMPORT); IElementType e2 = builder.getTokenType(); if (e2 == QUALIFIED || (importDecl != null && importDecl.importQualified)) { consumeToken(builder, QUALIFIED); } parseModuleName(builder, importDecl == null ? null : importDecl.importModule, comments); e2 = builder.getTokenType(); if (e2 == AS || false) { // TODO: Update. consumeToken(builder, AS); e2 = builder.getTokenType(); parseModuleName(builder, importDecl == null ? null : importDecl.importAs, comments); e2 = builder.getTokenType(); } if (e2 == HIDING || false) { // (importDecl != null && importDecl.importSpecs)) { TODO: FIXME consumeToken(builder, HIDING); e2 = builder.getTokenType(); } int nest = e2 == LPAREN ? 1 : 0; while (nest > 0) { builder.advanceLexer(); e2 = builder.getTokenType(); if (e2 == LPAREN) { nest++; } else if (e2 == RPAREN) { nest } } if (e2 == RPAREN) consumeToken(builder, RPAREN); importMark.done(e); } /** * Parses a foreign import statement. */ private static void parseForeignImportDecl(PsiBuilder builder, ForImp importDecl, Comment[] comments) { IElementType e = builder.getTokenType(); consumeToken(builder, FOREIGN); consumeToken(builder, IMPORT); IElementType e2 = builder.getTokenType(); builder.advanceLexer(); // TODO: Parse 'ccall' etc. e2 = builder.getTokenType(); if (e2 != DOUBLEQUOTE) { // TODO: Parse safety. builder.advanceLexer(); e2 = builder.getTokenType(); } if (e2 == DOUBLEQUOTE || false) { parseStringLiteral(builder); } e2 = builder.getTokenType(); parseName(builder, importDecl.name, comments); e2 = builder.getTokenType(); consumeToken(builder, DOUBLECOLON); parseTypeTopType(builder, importDecl.type, comments); } /** * Parses a foreign export statement. */ private static void parseForeignExportDecl(PsiBuilder builder, ForExp forExp, Comment[] comments) { IElementType e = builder.getTokenType(); consumeToken(builder, FOREIGN); e = builder.getTokenType(); consumeToken(builder, EXPORTTOKEN); IElementType e2 = builder.getTokenType(); builder.advanceLexer(); // TODO: Parse 'ccall' etc. e2 = builder.getTokenType(); if (e2 == DOUBLEQUOTE || false) { parseStringLiteral(builder); } e2 = builder.getTokenType(); parseName(builder, forExp.name, comments); e2 = builder.getTokenType(); consumeToken(builder, DOUBLECOLON); parseTypeTopType(builder, forExp.type, comments); } private static void parseBody(PsiBuilder builder, DeclTopType[] decls, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (isInterruption(e) || decls != null && i < decls.length) { if (e == CPPIF || e == CPPELSE || e == CPPENDIF) { builder.advanceLexer(); e = builder.getTokenType(); continue; } else if (e == OPENCOM) { parseComment(e, builder, comments); e = builder.getTokenType(); continue; } else if (e == OPENPRAGMA) { parseGenericPragma(builder, null, comments); e = builder.getTokenType(); continue; } parseDecl(builder, decls[i], comments); e = builder.getTokenType(); i++; } } /** * Parse a list of declarations. */ private static void parseDecls(PsiBuilder builder, DeclTopType[] decl, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (decl != null && i < decl.length) { parseDecl(builder, decl[i], comments); i++; e = builder.getTokenType(); } } /** * Parse a single declaration. */ private static void parseDecl(PsiBuilder builder, DeclTopType decl, Comment[] comments) { IElementType e = builder.getTokenType(); // Pragmas are handled by the outer loop in parseBody, so they are no-ops. if (decl instanceof PatBind) { PsiBuilder.Marker declMark = builder.mark(); parsePatBind(builder, (PatBind) decl, comments); declMark.done(e); } else if (decl instanceof FunBind) { PsiBuilder.Marker declMark = builder.mark(); parseFunBind(builder, (FunBind) decl, comments); declMark.done(e); } else if (decl instanceof DataDecl) { PsiBuilder.Marker declMark = builder.mark(); parseDataDecl(builder, (DataDecl) decl, comments); declMark.done(e); } else if (decl instanceof TypeDecl) { PsiBuilder.Marker declMark = builder.mark(); parseTypeDecl(builder, (TypeDecl) decl, comments); declMark.done(e); } else if (decl instanceof DataInsDecl) { PsiBuilder.Marker declMark = builder.mark(); parseDataInstanceDecl(builder, (DataInsDecl) decl, comments); declMark.done(e); } else if (decl instanceof SpliceDecl) { PsiBuilder.Marker declMark = builder.mark(); parseExpTopType(builder, ((SpliceDecl) decl).exp, comments); declMark.done(e); } else if (decl instanceof TypeSig) { PsiBuilder.Marker declMark = builder.mark(); parseTypeSig(builder, (TypeSig) decl, comments); declMark.done(e); } else if (decl instanceof ForImp) { PsiBuilder.Marker declMark = builder.mark(); parseForeignImportDecl(builder, (ForImp) decl, comments); declMark.done(e); } else if (decl instanceof ForExp) { PsiBuilder.Marker declMark = builder.mark(); parseForeignExportDecl(builder, (ForExp) decl, comments); declMark.done(e); } else if (decl instanceof InlineSig) { // parseGenericPragma(builder, (InlineSig) decl, comments); } else if (decl instanceof InlineConlikeSig) { // parseGenericPragma(builder, (InlineConlikeSig) decl, comments); } else if (decl instanceof SpecSig) { // parseGenericPragma(builder, (SpecSig) decl, comments); } else if (decl instanceof SpecInlineSig) { // parseGenericPragma(builder, (SpecSig) decl, comments); } else if (decl instanceof RulePragmaDecl) { // parseGenericPragma(builder, (SpecSig) decl, comments); } else if (decl instanceof DeprPragmaDecl) { // parseGenericPragma(builder, (DeprPragmaDecl) decl, comments); } else if (decl instanceof WarnPragmaDecl) { // parseGenericPragma(builder, (WarnPragmaDecl) decl, comments); } else if (decl instanceof AnnPragma) { // parseGenericPragma(builder, (AnnPragma) decl, comments); } else { throw new RuntimeException("Unexpected decl type: " + decl.toString()); } } private static void parsePatBind(PsiBuilder builder, PatBind patBind, Comment[] comments) { IElementType e = builder.getTokenType(); parsePatTopType(builder, patBind.pat, comments); if (patBind.type != null) throw new RuntimeException("Unexpected type in patbind"); // TODO: parseType(builder, patBind.type, comments); parseRhsTopType(builder, patBind.rhs, comments); if (patBind.binds != null) throw new RuntimeException("Unexpected binds in patbind"); } private static void parseFunBind(PsiBuilder builder, FunBind funBind, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (funBind.match != null && i < funBind.match.length) { parseMatchTop(builder, funBind.match[i], comments); i++; } } /** * Parses a data declaration. */ private static void parseDataDecl(PsiBuilder builder, DataDecl dataDecl, Comment[] comments) { IElementType e = builder.getTokenType(); consumeToken(builder, DATA); parseDeclHead(builder, dataDecl.declHead, comments); e = builder.getTokenType(); if (e == EQUALS) consumeToken(builder, EQUALS); int i = 0; e = builder.getTokenType(); while (dataDecl.qualConDecls != null && i < dataDecl.qualConDecls.length) { parseQualConDecl(builder, dataDecl.qualConDecls[i], comments); i++; if (i < dataDecl.qualConDecls.length) { builder.advanceLexer(); e = builder.getTokenType(); } } } /** * Parses a data instance declaration. */ private static void parseDataInstanceDecl(PsiBuilder builder, DataInsDecl dataDecl, Comment[] comments) { IElementType e = builder.getTokenType(); consumeToken(builder, DATA); e = builder.getTokenType(); consumeToken(builder, INSTANCE); e = builder.getTokenType(); parseTypeTopType(builder, dataDecl.type, comments); e = builder.getTokenType(); if (e == EQUALS) consumeToken(builder, EQUALS); int i = 0; e = builder.getTokenType(); while (dataDecl.qualConDecls != null && i < dataDecl.qualConDecls.length) { parseQualConDecl(builder, dataDecl.qualConDecls[i], comments); i++; if (i < dataDecl.qualConDecls.length) { builder.advanceLexer(); e = builder.getTokenType(); } } e = builder.getTokenType(); if (dataDecl.derivingMaybe != null) throw new RuntimeException("TODO: deriving unimplemeted"); } /** * Parses the left side of '=' in a data/type declaration. */ private static void parseDeclHead(PsiBuilder builder, DeclHeadTopType declHead, Comment[] comments) { IElementType e = builder.getTokenType(); if (declHead instanceof DHead) { parseName(builder, ((DHead) declHead).name, comments); e = builder.getTokenType(); parseTyVarBinds(builder, ((DHead) declHead).tyVars, comments); } else if (declHead instanceof DHInfix) { throw new RuntimeException("DHInfix:" + declHead.toString()); } else if (declHead instanceof DHParen) { throw new RuntimeException("DHParen:" + declHead.toString()); } } /** * Parses the type variables in a data declaration. */ private static void parseTyVarBinds(PsiBuilder builder, TyVarBindTopType[] tyVarBindTopType, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (tyVarBindTopType != null && i < tyVarBindTopType.length) { parseTyVarBind(builder, tyVarBindTopType[i], comments); i++; } e = builder.getTokenType(); } /** * Parses the type variables in a data declaration. */ private static void parseTyVarBind(PsiBuilder builder, TyVarBindTopType tyVarBindTopType, Comment[] comments) { IElementType e = builder.getTokenType(); if (tyVarBindTopType instanceof KindedVar) { parseName(builder, ((KindedVar) tyVarBindTopType).name, comments); throw new RuntimeException("TODO: Implement parseKindVar()"); } else if (tyVarBindTopType instanceof UnkindedVar) { parseName(builder, ((UnkindedVar) tyVarBindTopType).name, comments); } e = builder.getTokenType(); } /** * Parses a type declaration. */ private static void parseTypeDecl(PsiBuilder builder, TypeDecl typeDecl, Comment[] comments) { IElementType e = builder.getTokenType(); consumeToken(builder, TYPE); parseDeclHead(builder, typeDecl.declHead, comments); e = builder.getTokenType(); if (e == EQUALS) consumeToken(builder, EQUALS); parseTypeTopType(builder, typeDecl.type, comments); e = builder.getTokenType(); } /** * Parses a type signature. */ private static void parseTypeSig(PsiBuilder builder, TypeSig dataDecl, Comment[] comments) { IElementType e = builder.getTokenType(); parseNames(builder, dataDecl.names, comments); e = builder.getTokenType(); consumeToken(builder, DOUBLECOLON); e = builder.getTokenType(); parseTypeTopType(builder, dataDecl.type, comments); } /** * Parses a qualified constructor declaration. */ private static void parseQualConDecl(PsiBuilder builder, QualConDecl qualConDecl, Comment[] comments) { IElementType e = builder.getTokenType(); parseConDecl(builder, qualConDecl == null ? null : qualConDecl.conDecl, comments); } /** * Parses a constructor declaration. */ private static void parseConDecl(PsiBuilder builder, ConDeclTopType conDecl, Comment[] comments) { if (conDecl instanceof ConDecl) { parseName(builder, ((ConDecl) conDecl).name, comments); IElementType e = builder.getTokenType(); parseBangTypes(builder, conDecl == null ? null : ((ConDecl) conDecl).bangTypes, comments); } else if (conDecl instanceof InfixConDecl) { IElementType e = builder.getTokenType(); parseBangType(builder, ((InfixConDecl) conDecl).b1, comments); e = builder.getTokenType(); parseName(builder, ((InfixConDecl) conDecl).name, comments); parseBangType(builder, ((InfixConDecl) conDecl).b2, comments); } else if (conDecl instanceof RecDecl) { parseName(builder, ((RecDecl) conDecl).name, comments); boolean layouted = false; IElementType e = builder.getTokenType(); if (e == LBRACE) { consumeToken(builder, LBRACE); e = builder.getTokenType(); layouted = true; } parseFieldDecls(builder, ((RecDecl) conDecl).fields, comments); e = builder.getTokenType(); if (layouted) { consumeToken(builder, RBRACE); e = builder.getTokenType(); } } } /** * Parses the field declarations in a GADT-style declaration. */ private static void parseFieldDecls(PsiBuilder builder, FieldDecl[] fieldDecls, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (fieldDecls != null && i < fieldDecls.length) { parseFieldDecl(builder, fieldDecls[i], comments); i++; } e = builder.getTokenType(); } /** * Parses a field declaration. */ private static void parseFieldDecl(PsiBuilder builder, FieldDecl fieldDecl, Comment[] comments) { IElementType e = builder.getTokenType(); parseNames(builder, fieldDecl.names, comments); e = builder.getTokenType(); consumeToken(builder, DOUBLECOLON); e = builder.getTokenType(); parseBangType(builder, fieldDecl.bang, comments); e = builder.getTokenType(); } /** * Parses a list of bang types. */ private static void parseBangTypes(PsiBuilder builder, BangTypeTopType[] bangTypes, Comment[] comments) { int i = 0; while (bangTypes != null && i < bangTypes.length) { parseBangType(builder, bangTypes[i], comments); i++; } } /** * Parses one bang type. */ private static void parseBangType(PsiBuilder builder, BangTypeTopType bangType, Comment[] comments) { IElementType e = builder.getTokenType(); // TODO: Refine bangType. if (bangType instanceof UnBangedTy) { parseTypeTopType(builder, ((UnBangedTy) bangType).type, comments); } else if (bangType instanceof BangedTy) { consumeToken(builder, EXLAMATION); parseTypeTopType(builder, ((BangedTy) bangType).type, comments); e = builder.getTokenType(); } else if (bangType instanceof UnpackedTy) { parseGenericPragma(builder, null, comments); consumeToken(builder, EXLAMATION); e = builder.getTokenType(); parseTypeTopType(builder, ((UnpackedTy) bangType).type, comments); e = builder.getTokenType(); } } private static void parseMatchTop(PsiBuilder builder, MatchTopType matchTopType, Comment[] comments) { IElementType e = builder.getTokenType(); if (matchTopType instanceof Match) { parseMatch(builder, (Match) matchTopType, comments); } else if (matchTopType instanceof InfixMatch) { //TODO: parseInfixMatch(builder, (InfixMatch) matchTopType, comments); throw new RuntimeException("infixmatch"); } } private static void parseMatch(PsiBuilder builder, Match match, Comment[] comments) { IElementType e = builder.getTokenType(); parseName(builder, match.name, comments); int i = 0; while (match.pats != null && i < match.pats.length) { parsePatTopType(builder, match.pats[i], comments); i++; } parseRhsTopType(builder, match.rhs, comments); e = builder.getTokenType(); if (e == WHERE) { consumeToken(builder, WHERE); parseBindsTopType(builder, match.bindsMaybe, comments); e = builder.getTokenType(); } } /** * Parses one binding. */ private static void parseBindsTopType(PsiBuilder builder, BindsTopType bindsTopType, Comment[] comments) { IElementType e = builder.getTokenType(); if (bindsTopType instanceof BDecls) { parseDecls(builder, ((BDecls) bindsTopType).decls, comments); } else if (bindsTopType instanceof IPBinds) { throw new RuntimeException("TODO: Implement IPBinds:" + bindsTopType.toString()); } } /** * Parses several patterns. */ private static void parsePatTopTypes(PsiBuilder builder, PatTopType[] pats, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while(pats != null && i < pats.length) { parsePatTopType(builder, pats[i], comments); i++; e = builder.getTokenType(); if (e == COMMA) { consumeToken(builder, COMMA); e = builder.getTokenType(); } } } /** * Parses one pattern. */ private static void parsePatTopType(PsiBuilder builder, PatTopType patTopType, Comment[] comments) { IElementType e = builder.getTokenType(); if (patTopType instanceof PVar) { parsePVar(builder, (PVar) patTopType, comments); } else if (patTopType instanceof PLit) { parseLiteralTop(builder, ((PLit) patTopType).lit, comments); e = builder.getTokenType(); } else if (patTopType instanceof PTuple) { consumeToken(builder, LPAREN); e = builder.getTokenType(); boolean unboxed = parseBoxed(builder, ((PTuple) patTopType).boxed, comments); parsePatTopTypes(builder, ((PTuple) patTopType).pats, comments); e = builder.getTokenType(); if (unboxed) { consumeToken(builder, HASH); e = builder.getTokenType(); } consumeToken(builder, RPAREN); e = builder.getTokenType(); } else if (patTopType instanceof PList) { consumeToken(builder, LBRACKET); parsePatTopTypes(builder, ((PList) patTopType).pats, comments); e = builder.getTokenType(); consumeToken(builder, RBRACKET); e = builder.getTokenType(); } else if (patTopType instanceof PParen) { consumeToken(builder, LPAREN); e = builder.getTokenType(); parsePatTopType(builder, ((PParen) patTopType).pat, comments); consumeToken(builder, RPAREN); e = builder.getTokenType(); } else if (patTopType instanceof PRec) { parseQName(builder, ((PRec) patTopType).qName, comments); e = builder.getTokenType(); throw new RuntimeException("TODO: parsePatFields"); } else { throw new RuntimeException("parsePatTopType" + patTopType.toString()); } } private static void parseComment(IElementType start, PsiBuilder builder, Comment[] comments) { PsiBuilder.Marker startCom = builder.mark(); IElementType e = builder.getTokenType(); while (e == COMMENT || e == COMMENTTEXT || e == OPENCOM || e == CLOSECOM) { builder.advanceLexer(); e = builder.getTokenType(); } startCom.done(start); } /** * Parses a group of module pragmas. */ private static void parseModulePragmas(PsiBuilder builder, ModulePragmaTopType[] modulePragmas, Comment[] comments) { int i = 0; while(modulePragmas != null && i < modulePragmas.length) { parseModulePragma(builder, modulePragmas[i], comments); i++; } } /** * Parses a module pragma. */ private static void parseModulePragma(PsiBuilder builder, ModulePragmaTopType modulePragmaTopType, Comment[] comments) { int i = 0; if (modulePragmaTopType instanceof LanguagePragma) { LanguagePragma langPragma = (LanguagePragma) modulePragmaTopType; IElementType e = builder.getTokenType(); PsiBuilder.Marker pragmaMark = builder.mark(); consumeToken(builder, OPENPRAGMA); consumeToken(builder, PRAGMA); while (langPragma.names != null && i < langPragma.names.length) { // TODO: Improve precision of pragma lexing. // parseName(builder, langPragma.names[i], comments); i++; } consumeToken(builder, CLOSEPRAGMA); pragmaMark.done(e); } else if (modulePragmaTopType instanceof OptionsPragma) { // FIXME: Use optionsPragma information. OptionsPragma optionsPragma = (OptionsPragma) modulePragmaTopType; IElementType e = builder.getTokenType(); PsiBuilder.Marker pragmaMark = builder.mark(); chewPragma(builder); consumeToken(builder, CLOSEPRAGMA); pragmaMark.done(e); } else if (modulePragmaTopType instanceof AnnModulePragma) { // FIXME: Use annModulePragma information. AnnModulePragma annModulePragma = (AnnModulePragma) modulePragmaTopType; IElementType e = builder.getTokenType(); PsiBuilder.Marker pragmaMark = builder.mark(); chewPragma(builder); consumeToken(builder, CLOSEPRAGMA); pragmaMark.done(e); } } /** * Parses a pattern variable. */ private static void parsePVar(PsiBuilder builder, PVar pVar, Comment[] comments) { builder.remapCurrentToken(VARID); // FIXME: Should be PVARID consumeToken(builder, VARID); } /** * Parses a group of GuardedRhss. */ private static void parseGuardedRhss(PsiBuilder builder, GuardedRhs[] rhss, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while(rhss != null && i < rhss.length) { parseGuardedRhs(builder, rhss[i], comments); i++; e = builder.getTokenType(); } } /** * Parses one GuardedRhs. */ private static void parseGuardedRhs(PsiBuilder builder, GuardedRhs rhs, Comment[] comments) { IElementType e = builder.getTokenType(); consumeToken(builder, PIPE); e = builder.getTokenType(); parseStmtTopTypes(builder, rhs.stmts, comments); e = builder.getTokenType(); consumeToken(builder, EQUALS); parseExpTopType(builder, rhs.exp, comments); e = builder.getTokenType(); } /** * Parses one Rhs. */ private static void parseRhsTopType(PsiBuilder builder, RhsTopType rhsTopType, Comment[] comments) { IElementType e = builder.getTokenType(); if (rhsTopType instanceof UnGuardedRhs) { consumeToken(builder, EQUALS); parseExpTopType(builder, ((UnGuardedRhs) rhsTopType).exp, comments); } else if (rhsTopType instanceof GuardedRhss) { e = builder.getTokenType(); parseGuardedRhss(builder, ((GuardedRhss) rhsTopType).rhsses, comments); } } /** * Parses a qualified name. */ private static void parseQOp(PsiBuilder builder, QOpTopType qOpTopType, Comment[] comments) { IElementType e = builder.getTokenType(); boolean backticked = false; if (e == BACKTICK) { backticked = true; consumeToken(builder, BACKTICK); e = builder.getTokenType(); } if (qOpTopType instanceof QVarOp) { parseQName(builder, ((QVarOp) qOpTopType).qName, comments); } else if (qOpTopType instanceof QConOp) { parseQName(builder, ((QConOp) qOpTopType).qName, comments); } if (backticked) consumeToken(builder, BACKTICK); e = builder.getTokenType(); } /** * Parses a qualified name. */ private static void parseQName(PsiBuilder builder, QNameTopType qNameTopType, Comment[] comments) { if (qNameTopType instanceof Qual) { Qual name = (Qual) qNameTopType; parseModuleName(builder, name.moduleName, comments); parseName(builder, name.name, comments); } else if (qNameTopType instanceof UnQual) { parseName(builder, ((UnQual) qNameTopType).name, comments); } else if (qNameTopType instanceof Special) { parseSpecialConTopType(builder, ((Special) qNameTopType).specialCon, comments); } } /** * Parses a special constructor. */ private static void parseSpecialConTopType(PsiBuilder builder, SpecialConTopType specialConTopType, Comment[] comments) { IElementType e = builder.getTokenType(); if (specialConTopType instanceof UnitCon) { consumeToken(builder, LPAREN); e = builder.getTokenType(); consumeToken(builder, RPAREN); e = builder.getTokenType(); } else if (specialConTopType instanceof ListCon) { consumeToken(builder, LBRACKET); e = builder.getTokenType(); consumeToken(builder, RBRACKET); e = builder.getTokenType(); } else if (specialConTopType instanceof FunCon) { consumeToken(builder, LPAREN); e = builder.getTokenType(); consumeToken(builder, RIGHTARROW); e = builder.getTokenType(); consumeToken(builder, RPAREN); e = builder.getTokenType(); } else if (specialConTopType instanceof TupleCon) { throw new RuntimeException("TODO: implement TupleCon"); } else if (specialConTopType instanceof Cons) { throw new RuntimeException("TODO: implement Cons"); } else if (specialConTopType instanceof UnboxedSingleCon) { consumeToken(builder, LPAREN); e = builder.getTokenType(); consumeToken(builder, HASH); e = builder.getTokenType(); consumeToken(builder, HASH); e = builder.getTokenType(); consumeToken(builder, RPAREN); } } /** * Parses a list of names. */ private static void parseNames(PsiBuilder builder, NameTopType[] names, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (names != null && i < names.length) { parseName(builder, names[i], comments); i++; e = builder.getTokenType(); if (e == COMMA) consumeToken(builder, COMMA); } } /** * Parses a name. */ private static void parseName(PsiBuilder builder, NameTopType nameTopType, Comment[] comments) { if (nameTopType instanceof Ident) { builder.remapCurrentToken(NAME); consumeToken(builder, NAME); } else if (nameTopType instanceof Symbol) { IElementType e = builder.getTokenType(); builder.remapCurrentToken(SYMBOL); consumeToken(builder, SYMBOL); } } /** * Parses a literal */ private static void parseLiteralTop(PsiBuilder builder, LiteralTopType literalTopType, Comment[] comments) { IElementType e = builder.getTokenType(); if (literalTopType instanceof CharLit) { consumeToken(builder, CHARTOKEN); e = builder.getTokenType(); } else if (literalTopType instanceof StringLit) { parseStringLiteral(builder); } else if (literalTopType instanceof IntLit) { builder.advanceLexer(); e = builder.getTokenType(); } else { throw new RuntimeException("LiteralTop: " + literalTopType.toString()); } } /** * Parse a string literal. */ private static void parseStringLiteral(PsiBuilder builder) { IElementType e = builder.getTokenType(); PsiBuilder.Marker marker = builder.mark(); consumeToken(builder, DOUBLEQUOTE); IElementType e2 = builder.getTokenType(); while (e2 != DOUBLEQUOTE) { if (e2 == BADSTRINGTOKEN) { builder.error("Bad stringtoken"); builder.advanceLexer(); } else { consumeToken(builder, STRINGTOKEN); } e2 = builder.getTokenType(); } consumeToken(builder, DOUBLEQUOTE); marker.done(e); } /** * Parses a list of statements. */ private static void parseStmtTopTypes(PsiBuilder builder, StmtTopType[] stmtTopTypes, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (stmtTopTypes != null && i < stmtTopTypes.length) { parseStmtTopType(builder, stmtTopTypes[i], comments); i++; } } /** * Parses a statement. */ private static void parseStmtTopType(PsiBuilder builder, StmtTopType stmtTopType, Comment[] comments) { IElementType e = builder.getTokenType(); PsiBuilder.Marker stmtMark = builder.mark(); if (stmtTopType instanceof Generator) { parsePatTopType(builder, ((Generator) stmtTopType).pat, comments); consumeToken(builder, LEFTARROW); parseExpTopType(builder, ((Generator) stmtTopType).exp, comments); } else if (stmtTopType instanceof Qualifier) { parseExpTopType(builder, ((Qualifier) stmtTopType).exp, comments); } else if (stmtTopType instanceof LetStmt) { consumeToken(builder, LET); parseBindsTopType(builder, ((LetStmt) stmtTopType).binds, comments); } else if (stmtTopType instanceof RecStmt) { builder.advanceLexer(); IElementType e1 = builder.getTokenType(); parseStmtTopTypes(builder, ((RecStmt) stmtTopType).stmts, comments); e1 = builder.getTokenType(); } stmtMark.done(e); } /** * Parses a list of expressions. */ private static void parseExpTopTypes(PsiBuilder builder, ExpTopType[] expTopType, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (expTopType != null && i < expTopType.length) { parseExpTopType(builder, expTopType[i], comments); i++; e = builder.getTokenType(); if (e == COMMA) consumeToken(builder, COMMA); } } /** * Parses an expression. */ private static void parseExpTopType(PsiBuilder builder, ExpTopType expTopType, Comment[] comments) { IElementType e1 = builder.getTokenType(); if (expTopType instanceof App) { parseExpTopType(builder, ((App) expTopType).e1, comments); parseExpTopType(builder, ((App) expTopType).e2, comments); } else if (expTopType instanceof Var) { parseQName(builder, ((Var) expTopType).qName, comments); } else if (expTopType instanceof Con) { parseQName(builder, ((Con) expTopType).qName, comments); } else if (expTopType instanceof Lit) { parseLiteralTop(builder, ((Lit) expTopType).literal, comments); } else if (expTopType instanceof InfixApp) { parseExpTopType(builder, ((InfixApp) expTopType).e1, comments); IElementType e = builder.getTokenType(); builder.advanceLexer(); e = builder.getTokenType(); parseExpTopType(builder, ((InfixApp) expTopType).e2, comments); e = builder.getTokenType(); } else if (expTopType instanceof List) { builder.advanceLexer(); parseExpTopTypes(builder, ((List) expTopType).exps, comments); IElementType e = builder.getTokenType(); builder.advanceLexer(); } else if (expTopType instanceof NegApp) { consumeToken(builder, MINUS); parseExpTopType(builder, ((NegApp) expTopType).e1, comments); } else if (expTopType instanceof Do) { IElementType e = builder.getTokenType(); PsiBuilder.Marker doMark = builder.mark(); consumeToken(builder, DO); parseStmtTopTypes(builder, ((Do) expTopType).stmts, comments); doMark.done(e); } else if (expTopType instanceof Lambda) { consumeToken(builder, BACKSLASH); IElementType e = builder.getTokenType(); parsePatTopTypes(builder, ((Lambda) expTopType).pats, comments); e = builder.getTokenType(); consumeToken(builder, RIGHTARROW); parseExpTopType(builder, ((Lambda) expTopType).exp, comments); e = builder.getTokenType(); } else if (expTopType instanceof Tuple) { consumeToken(builder, LPAREN); IElementType e = builder.getTokenType(); boolean unboxed = parseBoxed(builder, ((Tuple) expTopType).boxed, comments); e = builder.getTokenType(); parseExpTopTypes(builder, ((Tuple) expTopType).exps, comments); e = builder.getTokenType(); if (unboxed) { consumeToken(builder, HASH); e = builder.getTokenType(); } consumeToken(builder, RPAREN); e1 = builder.getTokenType(); } else if (expTopType instanceof TupleSection) { TupleSection ts = (TupleSection) expTopType; consumeToken(builder, LPAREN); IElementType e = builder.getTokenType(); boolean unboxed = parseBoxed(builder, ((TupleSection) expTopType).boxed, comments); e = builder.getTokenType(); int i = 0; while (ts.expMaybes != null && i < ts.expMaybes.length) { if (ts.expMaybes[i] != null) parseExpTopType(builder, ts.expMaybes[i], comments); i++; e = builder.getTokenType(); if (e == COMMA) consumeToken(builder, COMMA); } e = builder.getTokenType(); if (unboxed) { consumeToken(builder, HASH); e = builder.getTokenType(); } consumeToken(builder, RPAREN); e1 = builder.getTokenType(); } else if (expTopType instanceof Paren) { consumeToken(builder, LPAREN); e1 = builder.getTokenType(); parseExpTopType(builder, ((Paren) expTopType).exp, comments); e1 = builder.getTokenType(); consumeToken(builder, RPAREN); e1 = builder.getTokenType(); } else if (expTopType instanceof RightSection) { e1 = builder.getTokenType(); consumeToken(builder, LPAREN); parseQOp(builder, ((RightSection) expTopType).qop, comments); parseExpTopType(builder, ((RightSection) expTopType).exp, comments); e1 = builder.getTokenType(); consumeToken(builder, RPAREN); e1 = builder.getTokenType(); } else if (expTopType instanceof Let) { builder.advanceLexer(); IElementType e = builder.getTokenType(); // TODO: parseBinds(builder, ((Let) expTopType).binds, comments); while (e != IN) { builder.advanceLexer(); e = builder.getTokenType(); } consumeToken(builder, IN); parseExpTopType(builder, ((Let) expTopType).exp, comments); } else if (expTopType instanceof QuasiQuote) { IElementType e = builder.getTokenType(); consumeToken(builder, LBRACKET); builder.advanceLexer(); e = builder.getTokenType(); consumeToken(builder, PIPE); e = builder.getTokenType(); while (e != PIPE) { builder.advanceLexer(); e = builder.getTokenType(); } consumeToken(builder, PIPE); consumeToken(builder, RBRACKET); e = builder.getTokenType(); } else if (expTopType instanceof CorePragma) { parseGenericPragma(builder, null, comments); parseExpTopType(builder, ((CorePragma) expTopType).exp, comments); } else if (expTopType instanceof Proc) { e1 = builder.getTokenType(); builder.advanceLexer(); // TODO: consumeToken(builder, PROCTOKEN); e1 = builder.getTokenType(); parsePatTopType(builder, ((Proc) expTopType).pat, comments); consumeToken(builder, RIGHTARROW); parseExpTopType(builder, ((Proc) expTopType).exp, comments); } else { throw new RuntimeException("parseExpTopType: " + expTopType.toString()); } } /** * Parses a list of types. */ private static void parseTypeTopTypes(PsiBuilder builder, TypeTopType[] typeTopTypes, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (typeTopTypes != null && i < typeTopTypes.length) { parseTypeTopType(builder, typeTopTypes[i], comments); i++; e = builder.getTokenType(); if (e == COMMA) consumeToken(builder, COMMA); } } /** * Parses a type. */ private static void parseTypeTopType(PsiBuilder builder, TypeTopType typeTopType, Comment[] comments) { IElementType e = builder.getTokenType(); if (typeTopType instanceof TyForall) { // FIXME: No forall lexeme. TyForall t = (TyForall) typeTopType; e = builder.getTokenType(); if (t.tyVarBinds != null) { // Implicit foralls for typeclasses. builder.advanceLexer(); e = builder.getTokenType(); parseTyVarBinds(builder, t.tyVarBinds, comments); e = builder.getTokenType(); consumeToken(builder, PERIOD); } parseContextTopType(builder, t.context, comments); e = builder.getTokenType(); if (e == DOUBLEARROW) consumeToken(builder, DOUBLEARROW); parseTypeTopType(builder, t.type, comments); e = builder.getTokenType(); } else if (typeTopType instanceof TyFun) { parseTypeTopType(builder, ((TyFun) typeTopType).t1, comments); consumeToken(builder, RIGHTARROW); parseTypeTopType(builder, ((TyFun) typeTopType).t2, comments); } else if (typeTopType instanceof TyTuple) { consumeToken(builder, LPAREN); e = builder.getTokenType(); boolean unboxed = parseBoxed(builder, ((TyTuple) typeTopType).boxed, comments); e = builder.getTokenType(); parseTypeTopTypes(builder, ((TyTuple) typeTopType).types, comments); e = builder.getTokenType(); if (unboxed) { consumeToken(builder, HASH); e = builder.getTokenType(); } consumeToken(builder, RPAREN); e = builder.getTokenType(); } else if (typeTopType instanceof TyList) { consumeToken(builder, LBRACKET); e = builder.getTokenType(); parseTypeTopType(builder, ((TyList) typeTopType).t, comments); e = builder.getTokenType(); consumeToken(builder, RBRACKET); e = builder.getTokenType(); } else if (typeTopType instanceof TyApp) { parseTypeTopType(builder, ((TyApp) typeTopType).t1, comments); e = builder.getTokenType(); parseTypeTopType(builder, ((TyApp) typeTopType).t2, comments); e = builder.getTokenType(); } else if (typeTopType instanceof TyVar) { parseName(builder, ((TyVar) typeTopType).name, comments); e = builder.getTokenType(); } else if (typeTopType instanceof TyCon) { parseQName(builder, ((TyCon) typeTopType).qName, comments); } else if (typeTopType instanceof TyParen) { consumeToken(builder, LPAREN); e = builder.getTokenType(); parseTypeTopType(builder, ((TyParen) typeTopType).type, comments); e = builder.getTokenType(); consumeToken(builder, RPAREN); e = builder.getTokenType(); } else if (typeTopType instanceof TyInfix) { e = builder.getTokenType(); parseTypeTopType(builder, ((TyInfix) typeTopType).t1, comments); e = builder.getTokenType(); parseQName(builder, ((TyInfix) typeTopType).qName, comments); e = builder.getTokenType(); parseTypeTopType(builder, ((TyInfix) typeTopType).t2, comments); e = builder.getTokenType(); } else { throw new RuntimeException("parseTypeTopType: " + typeTopType.toString()); } } /** * Parses contexts. */ private static void parseContextTopType(PsiBuilder builder, ContextTopType context, Comment[] comments) { IElementType e = builder.getTokenType(); if (context instanceof CxSingle) { parseAsstTopType(builder, ((CxSingle) context).asst, comments); } else if (context instanceof CxTuple) { throw new RuntimeException("TODO: Implement CxTuple"); } else if (context instanceof CxParen) { consumeToken(builder, LPAREN); parseContextTopType(builder, ((CxParen) context).context, comments); e = builder.getTokenType(); consumeToken(builder, RPAREN); e = builder.getTokenType(); } else if (context instanceof CxEmpty) { throw new RuntimeException("TODO: Implement CxEmpty"); } } /** * Parses contexts. */ private static void parseAsstTopType(PsiBuilder builder, AsstTopType asst, Comment[] comments) { IElementType e = builder.getTokenType(); if (asst instanceof ClassA) { parseQName(builder, ((ClassA) asst).qName, comments); e = builder.getTokenType(); parseTypeTopTypes(builder, ((ClassA) asst).types, comments); e = builder.getTokenType(); } else if (asst instanceof InfixA) { throw new RuntimeException("TODO: Parse InfixA"); } else if (asst instanceof IParam) { throw new RuntimeException("TODO: Parse IParam"); /* Preliminary untested implementation: parseContextTopType(builder, ((IParam) asst).ipName, comments); e = builder.getTokenType(); parseTypeTopType(builder, ((IParam) asst).type, comments); e = builder.getTokenType(); */ } else if (asst instanceof EqualP) { throw new RuntimeException("TODO: Parse EqualP"); /* Preliminary untested implementation: parseTypeTopType(builder, ((EqualP) asst).t1, comments); consumeToken(builder, TILDETOKENHERE); e = builder.getTokenType(); parseTypeTopType(builder,((EqualP) asst).t2, comments); e = builder.getTokenType(); */ } } /** * Parses box annotations. */ public static boolean parseBoxed(PsiBuilder builder, BoxedTopType boxedTopType, Comment[] comments) { // TODO: Improve granularity. IElementType e = builder.getTokenType(); if (boxedTopType instanceof Boxed) { return false; } else if (boxedTopType instanceof Unboxed) { consumeToken(builder, HASH); return true; } throw new RuntimeException("Unexpected boxing: " + boxedTopType.toString()); } /** * Parses a generic pragma. */ public static void parseGenericPragma(PsiBuilder builder, DeclTopType annPragma, Comment[] comments) { // TODO: Improve granularity. PsiBuilder.Marker pragmaMark = builder.mark(); IElementType e = builder.getTokenType(); chewPragma(builder); consumeToken(builder, CLOSEPRAGMA); pragmaMark.done(e); } /** * Eats a complete pragma and leaves the builder at CLOSEPRAGMA token. */ public static void chewPragma(PsiBuilder builder) { IElementType e = builder.getTokenType(); while (e != CLOSEPRAGMA) { builder.advanceLexer(); e = builder.getTokenType(); } } public static boolean consumeToken(PsiBuilder builder_, IElementType token) { if (nextTokenIsInner(builder_, token)) { builder_.advanceLexer(); return true; } return false; } public static boolean nextTokenIsInner(PsiBuilder builder_, IElementType token) { IElementType tokenType = builder_.getTokenType(); if (token != tokenType) { System.out.println("Unexpected token: " + tokenType + " vs " + token); } return token == tokenType; } }
package org.jmxdatamart.Extractor; import java.util.Collections; import junit.framework.TestCase; import org.jmxdatamart.common.DataType; public class TestSettings extends TestCase { public void testJUnit() { int i = 42; } // commented out because function is not implemented // public void testWriteSettingsAsXml() { // Settings settings = new Settings(); // settings.setPollingRate(10); // settings.setFolderLocation("jmx-statistics"); // MBeanData bean = new MBeanData(); // bean.setName("org.jmxdatamart:Type=TestWebAppMBean"); // bean.setAlias("TestWebAppMBean"); // Attribute attr = new Attribute("age", "age", DataType.INT); // bean.setAttributes(Collections.singletonList(attr)); // settings.setBeans(Collections.singletonList(bean)); // String s = settings.toXML(); // Settings newSettings = Settings.fromXML(s); // assertEquals(settings, newSettings); }
package us.dot.its.jpo.ode.udp; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import org.junit.Test; import mockit.Expectations; import mockit.Injectable; import mockit.Mocked; import mockit.Tested; import us.dot.its.jpo.ode.OdeProperties; import us.dot.its.jpo.ode.j2735.semi.ServiceRequest; import us.dot.its.jpo.ode.j2735.semi.ServiceResponse; public class TrustManagerTest { @Tested TrustManager testTrustManager; @Injectable OdeProperties mockOdeProperties; @Injectable DatagramSocket mockDatagramSocket; @Test public void shouldCreateServiceResponse(@Injectable ServiceRequest mockServiceRequest) { assertNotNull(testTrustManager.createServiceResponse(mockServiceRequest)); } @Test public void testSettersAndGetters() { testTrustManager.setTrustEstablished(false); assertFalse(testTrustManager.isTrustEstablished()); testTrustManager.setTrustEstablished(true); assertTrue(testTrustManager.isTrustEstablished()); } @Test public void shouldSendServiceResponse(@Mocked final DatagramPacket mockDatagramPacket) { try { new Expectations() { { mockDatagramSocket.send((DatagramPacket) any); } }; } catch (IOException e) { fail("Unexpected exception in expectations block" + e); } testTrustManager.sendServiceResponse(new ServiceResponse(), "testIp", 0); } @Test public void shouldCatchSendServiceResponseError(@Mocked final DatagramPacket mockDatagramPacket) { try { new Expectations() { { mockDatagramSocket.send((DatagramPacket) any); result = new IOException("testException123"); } }; } catch (IOException e) { fail("Unexpected exception in expectations block" + e); } testTrustManager.sendServiceResponse(new ServiceResponse(), "testIp", 0); } @Test public void shouldSendServiceRequest(@Mocked final DatagramPacket mockDatagramPacket) { try { new Expectations() { { mockDatagramSocket.send((DatagramPacket) any); } }; } catch (IOException e) { fail("Unexpected exception in expectations block" + e); } testTrustManager.sendServiceRequest(new ServiceRequest(), "testIp", 0); } @Test public void shouldCatchSendServiceRequestError(@Mocked final DatagramPacket mockDatagramPacket) { try { new Expectations() { { mockDatagramSocket.send((DatagramPacket) any); result = new IOException("testException123"); } }; } catch (IOException e) { fail("Unexpected exception in expectations block" + e); } testTrustManager.sendServiceRequest(new ServiceRequest(), "testIp", 0); } @Test public void shouldReturnTrustAlreadyEstablished(@Mocked final DatagramPacket mockDatagramPacket) { testTrustManager.setTrustEstablished(true); assertTrue(testTrustManager.establishTrust(null, null)); } @Test public void establishTrustShouldReturnFalseZeroRetries(@Mocked final DatagramPacket mockDatagramPacket, @Mocked final InetSocketAddress mockInetSocketAddress) { new Expectations() { { mockOdeProperties.getTrustRetries(); result = 0; } }; testTrustManager.setTrustEstablished(false); assertFalse(testTrustManager.establishTrust(null, null)); } }
package com.ilearnrw.reader.utils; import java.io.IOException; import java.util.ArrayList; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpConnectionParams; import org.apache.http.protocol.HTTP; import com.ilearnrw.reader.R; import com.google.gson.Gson; import com.ilearnrw.reader.results.TokenResult; import com.ilearnrw.reader.tasks.LogTask; import android.content.Context; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.preference.PreferenceManager; import android.util.Base64; import android.util.Log; public class HttpHelper { private static final String authString = new String(Base64.encode("api:api".getBytes(), Base64.URL_SAFE|Base64.NO_WRAP)); public static HttpResponse post(String url, String data){ DefaultHttpClient client = new DefaultHttpClient(); HttpResponse response = null; //HttpConnectionParams.setSoTimeout(client.getParams(), 25000); HttpPost post = new HttpPost(url); post.setHeader("Accept", "application/json"); post.setHeader("Authorization", "Basic " + authString); post.setHeader("Content-Type", "application/json;charset=utf-8"); try { post.setEntity(new StringEntity(data, HTTP.UTF_8)); response = client.execute(post); } catch (ClientProtocolException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } return response; } public static HttpResponse get(String url){ DefaultHttpClient client = new DefaultHttpClient(); HttpResponse response = null; HttpConnectionParams.setSoTimeout(client.getParams(), 25000); HttpGet get = new HttpGet(url); get.setHeader("Authorization", "Basic " + authString); try { response = client.execute(get); } catch (ClientProtocolException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } return response; } public static ArrayList<String> handleResponse(HttpResponse response){ ArrayList<String> data = new ArrayList<String>(); if(response == null){ data.add("No response"); return data; } switch (response.getStatusLine().getStatusCode()) { case HttpStatus.SC_OK: try { String str = FileHelper.inputStreamToString(response.getEntity().getContent()); data.add(response.getStatusLine().toString()); data.add(str); } catch (IOException e) { e.printStackTrace(); } break; case HttpStatus.SC_UNAUTHORIZED: try { String str = FileHelper.inputStreamToString(response.getEntity().getContent()); if(str.contains("Token expired")) data.add("Token expired"); else data.add(response.getStatusLine().toString()); } catch (IOException e) { e.printStackTrace(); } break; case HttpStatus.SC_INTERNAL_SERVER_ERROR: Log.e("Internal Server Error", "Internal Server Error"); data.add(response.getStatusLine().toString()); break; default: data.add(response.getStatusLine().toString()); break; } return data; } public static boolean refreshTokens(Context context){ SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); String refreshToken = preferences.getString(context.getString(R.string.sp_refreshToken), ""); if(refreshToken.isEmpty()) return false; HttpResponse refreshResponse = HttpHelper.get("https://ssl.ilearnrw.eu/ilearnrw/user/newtokens?refresh="+refreshToken); ArrayList<String> refreshData = HttpHelper.handleResponse(refreshResponse); if(refreshData == null) return false; if(refreshData.size()>1){ try { TokenResult lr = new Gson().fromJson(refreshData.get(1), TokenResult.class); SharedPreferences.Editor editor = preferences.edit(); editor.putString(context.getString(R.string.sp_authToken), lr.authToken); editor.putString(context.getString(R.string.sp_refreshToken), lr.refreshToken); editor.apply(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } else { Log.e("Error", refreshData.get(0)); } return false; } public static boolean log(Context ctx, String msg, String tag){ if(msg.trim().isEmpty()) return false; if(!isNetworkAvailable(ctx)) return false; SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx); String username = prefs.getString(ctx.getString(R.string.sp_user_name), ""); if(username.isEmpty()) return false; new LogTask(tag).run(username, msg); return true; } public static boolean isNetworkAvailable(Context ctx){ ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getActiveNetworkInfo(); return (ni != null) && (ni.isConnected()); } }
package net.avalara.avatax.rest.client; import com.google.gson.reflect.TypeToken; import net.avalara.avatax.rest.client.models.*; import net.avalara.avatax.rest.client.enums.*; import org.apache.commons.codec.binary.Base64; import org.apache.http.impl.client.HttpClientBuilder; import java.math.BigDecimal; import java.util.Date; import java.util.HashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.ArrayList; public class AvaTaxClient { private final ExecutorService threadPool; private RestCallFactory restCallFactory; private AvaTaxClient() { this(null); } private AvaTaxClient(ExecutorService threadPool) { if (threadPool != null) { this.threadPool = threadPool; } else { this.threadPool = Executors.newFixedThreadPool(3); } } public AvaTaxClient(String appName, String appVersion, String machineName, AvaTaxEnvironment environment) { this(appName, appVersion, machineName, environment, null); } public AvaTaxClient(String appName, String appVersion, String machineName, String environmentUrl) { this(); this.restCallFactory = new RestCallFactory(appName, appVersion, machineName, environmentUrl); } public AvaTaxClient(String appName, String appVersion, String machineName, AvaTaxEnvironment environment, String proxyHost, int proxyPort, String proxySchema) { this(appName, appVersion, machineName, environment, proxyHost, proxyPort, proxySchema, null); } public AvaTaxClient(String appName, String appVersion, String machineName, String environmentUrl, String proxyHost, int proxyPort, String proxySchema) { this(); this.restCallFactory = new RestCallFactory(appName, appVersion, machineName, environmentUrl, proxyHost, proxyPort, proxySchema); } public AvaTaxClient(String appName, String appVersion, String machineName, AvaTaxEnvironment environment, ExecutorService threadPool) { this(appName, appVersion, machineName, environment == AvaTaxEnvironment.Production ? AvaTaxConstants.Production_Url : AvaTaxConstants.Sandbox_Url, threadPool); } public AvaTaxClient(String appName, String appVersion, String machineName, AvaTaxEnvironment environment, ExecutorService threadPool, HttpClientBuilder httpClientBuilder) { this(appName, appVersion, machineName, environment == AvaTaxEnvironment.Production ? AvaTaxConstants.Production_Url : AvaTaxConstants.Sandbox_Url, threadPool, httpClientBuilder); } public AvaTaxClient(String appName, String appVersion, String machineName, String environmentUrl, ExecutorService threadPool) { this(threadPool); this.restCallFactory = new RestCallFactory(appName, appVersion, machineName, environmentUrl); } public AvaTaxClient(String appName, String appVersion, String machineName, String environmentUrl, ExecutorService threadPool, HttpClientBuilder httpClientBuilder) { this(threadPool); this.restCallFactory = new RestCallFactory(appName, appVersion, machineName, environmentUrl, httpClientBuilder); } public AvaTaxClient(String appName, String appVersion, String machineName, AvaTaxEnvironment environment, String proxyHost, int proxyPort, String proxySchema, ExecutorService threadPool) { this(appName, appVersion, machineName, environment == AvaTaxEnvironment.Production ? AvaTaxConstants.Production_Url : AvaTaxConstants.Sandbox_Url, proxyHost, proxyPort, proxySchema, threadPool); } public AvaTaxClient(String appName, String appVersion, String machineName, String environmentUrl, String proxyHost, int proxyPort, String proxySchema, ExecutorService threadPool) { this(threadPool); this.restCallFactory = new RestCallFactory(appName, appVersion, machineName, environmentUrl, proxyHost, proxyPort, proxySchema); } public AvaTaxClient withSecurity(String securityHeader) { this.restCallFactory.addSecurityHeader(securityHeader); return this; } public AvaTaxClient withSecurity(String username, String password) { String header = null; try { header = Base64.encodeBase64String((username + ":" + password).getBytes("utf-8")); } catch (java.io.UnsupportedEncodingException ex) { System.out.println("Could not find encoding for UTF-8."); ex.printStackTrace(); } return withSecurity(header); } //region Methods @foreach(var m in SwaggerModel.Methods) { Write(JavadocComment(m, 4)); Write(" public " + JavaTypeName(m.ResponseTypeName) + " " + FirstCharLower(m.Name) + "("); bool any = false; foreach (var p in m.Params) { if (p.CleanParamName == "X-Avalara-Client") continue; Write(JavaTypeName(p.TypeName) + " " + p.CleanParamName + ", "); any = true; } if (any) { Backtrack(2); } WriteLine(") throws Exception {"); WriteLine(" AvaTaxPath path = new AvaTaxPath(\"" + m.URI + "\");"); foreach (var p in m.Params) { if (p.ParameterLocation == ParameterLocationType.UriPath) { WriteLine(" path.applyField(\"{0}\", {1});", p.ParamName, p.CleanParamName); } else if (p.ParameterLocation == ParameterLocationType.QueryString) { WriteLine(" path.addQuery(\"{0}\", {1});", p.ParamName, p.CleanParamName); } } if (m.ResponseTypeName == "String") { WriteLine(" return ((RestCall<" + JavaTypeName(m.ResponseTypeName) + ">)restCallFactory.createRestCall(\"" + m.HttpVerb + "\", path, " + (m.BodyParam == null ? "null" : "model") + ", new TypeToken<" + JavaTypeName(m.ResponseTypeName) + ">(){})).call();"); } else if (m.ResponseTypeName == "FileResult") { WriteLine(" return ((RestCall<" + JavaTypeName(m.ResponseTypeName) + ">)restCallFactory.createRestCall(\"" + m.HttpVerb + "\", path, " + (m.BodyParam == null ? "null" : "model") + ", new TypeToken<" + JavaTypeName(m.ResponseTypeName) + ">(){})).call();"); } else { WriteLine(" return ((RestCall<" + JavaTypeName(m.ResponseTypeName) + ">)restCallFactory.createRestCall(\"" + m.HttpVerb + "\", path, " + (m.BodyParam == null ? "null" : "model") + ", new TypeToken<" + JavaTypeName(m.ResponseTypeName) + ">(){})).call();"); } WriteLine(" }"); WriteLine(""); // Async version of the same API Write(JavadocComment(m, 4)); Write(" public Future<" + JavaTypeName(m.ResponseTypeName) + "> " + FirstCharLower(m.Name) + "Async("); foreach (var p in m.Params) { if (p.CleanParamName == "X-Avalara-Client") continue; Write(JavaTypeName(p.TypeName) + " " + p.CleanParamName + ", "); } if (any) { Backtrack(2); } WriteLine(") {"); WriteLine(" AvaTaxPath path = new AvaTaxPath(\"" + m.URI + "\");"); foreach (var p in m.Params) { if (p.ParameterLocation == ParameterLocationType.UriPath) { WriteLine(" path.applyField(\"{0}\", {1});", p.ParamName, p.CleanParamName); } else if (p.ParameterLocation == ParameterLocationType.QueryString) { WriteLine(" path.addQuery(\"{0}\", {1});", p.ParamName, p.CleanParamName); } } if (m.ResponseTypeName == "String") { WriteLine(" return this.threadPool.submit((RestCall<" + JavaTypeName(m.ResponseTypeName) + ">)restCallFactory.createRestCall(\"" + m.HttpVerb + "\", path, " + (m.BodyParam == null ? "null" : "model") + ", new TypeToken<" + JavaTypeName(m.ResponseTypeName) + ">(){}));"); } else if (m.ResponseTypeName == "FileResult") { WriteLine(" return this.threadPool.submit((RestCall<" + JavaTypeName(m.ResponseTypeName) + ">)restCallFactory.createRestCall(\"" + m.HttpVerb + "\", path, " + (m.BodyParam == null ? "null" : "model") + ", new TypeToken<" + JavaTypeName(m.ResponseTypeName) + ">(){}));"); } else { WriteLine(" return this.threadPool.submit((RestCall<" + JavaTypeName(m.ResponseTypeName) + ">)restCallFactory.createRestCall(\"" + m.HttpVerb + "\", path, " + (m.BodyParam == null ? "null" : "model") + ", new TypeToken<" + JavaTypeName(m.ResponseTypeName) + ">(){}));"); } WriteLine(" }"); WriteLine(""); } //endregion }
package com.irccloud.android; import java.util.ArrayList; import java.util.HashMap; import org.json.JSONException; import org.json.JSONObject; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.google.android.gcm.GCMRegistrar; import com.irccloud.android.BanListFragment.AddClickListener; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.PowerManager; import android.preference.PreferenceManager; import android.text.Editable; import android.text.SpannableString; import android.text.Spanned; import android.text.TextUtils; import android.text.TextWatcher; import android.text.method.LinkMovementMethod; import android.text.style.BackgroundColorSpan; import android.text.style.ForegroundColorSpan; import android.text.style.StyleSpan; import android.text.style.UnderlineSpan; import android.text.util.Linkify; import android.util.Log; import android.view.ContextThemeWrapper; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnFocusChangeListener; import android.view.View.OnKeyListener; import android.view.WindowManager; import android.view.View.OnClickListener; import android.view.animation.AlphaAnimation; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.HorizontalScrollView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import android.widget.TextView.OnEditorActionListener; public class MessageActivity extends BaseActivity implements UsersListFragment.OnUserSelectedListener, BuffersListFragment.OnBufferSelectedListener, MessageViewFragment.MessageViewListener { int cid = -1; int bid = -1; String name; String type; EditText messageTxt; View sendBtn; int joined; int archived; String status; UsersDataSource.User selected_user; View userListView; View buffersListView; TextView title; TextView subtitle; ImageView key; LinearLayout messageContainer; HorizontalScrollView scrollView; NetworkConnection conn; private boolean shouldFadeIn = false; ImageView upView; private RefreshUpIndicatorTask refreshUpIndicatorTask = null; private ShowNotificationsTask showNotificationsTask = null; private ArrayList<Integer> backStack = new ArrayList<Integer>(); PowerManager.WakeLock screenLock = null; private int launchBid = -1; private Uri launchURI = null; private AlertDialog channelsListDialog; private HashMap<Integer, EventsDataSource.Event> pendingEvents = new HashMap<Integer, EventsDataSource.Event>(); @SuppressLint("NewApi") @SuppressWarnings({ "deprecation", "unchecked" }) @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setBackgroundDrawable(null); setContentView(R.layout.activity_message); buffersListView = findViewById(R.id.BuffersList); messageContainer = (LinearLayout)findViewById(R.id.messageContainer); scrollView = (HorizontalScrollView)findViewById(R.id.scroll); if(scrollView != null) { LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)messageContainer.getLayoutParams(); params.width = getWindowManager().getDefaultDisplay().getWidth(); messageContainer.setLayoutParams(params); } messageTxt = (EditText)findViewById(R.id.messageTxt); messageTxt.setEnabled(false); messageTxt.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if(event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER && messageTxt.getText() != null && messageTxt.getText().length() > 0) { new SendTask().execute((Void)null); } return false; } }); messageTxt.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(scrollView != null && v == messageTxt && hasFocus) { scrollView.scrollTo((int)getResources().getDimension(R.dimen.drawer_width), 0); upView.setVisibility(View.VISIBLE); } } }); messageTxt.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(scrollView != null) { scrollView.scrollTo((int)getResources().getDimension(R.dimen.drawer_width), 0); upView.setVisibility(View.VISIBLE); } } }); messageTxt.setOnEditorActionListener(new OnEditorActionListener() { public boolean onEditorAction(TextView view, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEND && messageTxt.getText() != null && messageTxt.getText().length() > 0) { new SendTask().execute((Void)null); } return true; } }); messageTxt.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { Object[] spans = s.getSpans(0, s.length(), Object.class); for(Object o : spans) { if(((s.getSpanFlags(o) & Spanned.SPAN_COMPOSING) != Spanned.SPAN_COMPOSING) && (o.getClass() == StyleSpan.class || o.getClass() == ForegroundColorSpan.class || o.getClass() == BackgroundColorSpan.class || o.getClass() == UnderlineSpan.class)) { s.removeSpan(o); } } if(s.length() > 0) { sendBtn.setEnabled(true); if(Build.VERSION.SDK_INT >= 11) sendBtn.setAlpha(1); } else { sendBtn.setEnabled(false); if(Build.VERSION.SDK_INT >= 11) sendBtn.setAlpha(0.5f); } } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } }); sendBtn = findViewById(R.id.sendBtn); sendBtn.setFocusable(false); sendBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { new SendTask().execute((Void)null); } }); userListView = findViewById(R.id.usersListFragment); getSupportActionBar().setLogo(R.drawable.logo); getSupportActionBar().setHomeButtonEnabled(false); getSupportActionBar().setDisplayHomeAsUpEnabled(false); getSupportActionBar().setDisplayShowTitleEnabled(false); View v = getLayoutInflater().inflate(R.layout.actionbar_messageview, null); v.findViewById(R.id.actionTitleArea).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(bid); if(c != null) { AlertDialog.Builder builder = new AlertDialog.Builder(MessageActivity.this); builder.setTitle("Channel Topic"); if(c.topic_text.length() > 0) { builder.setMessage(ColorFormatter.html_to_spanned(TextUtils.htmlEncode(c.topic_text), true, ServersDataSource.getInstance().getServer(cid))); } else builder.setMessage("No topic set."); builder.setPositiveButton("Close", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); boolean canEditTopic; if(c.mode.contains("t")) { UsersDataSource.User self_user = UsersDataSource.getInstance().getUser(cid, name, ServersDataSource.getInstance().getServer(cid).nick); if(self_user != null && (self_user.mode.contains("q") || self_user.mode.contains("a") || self_user.mode.contains("o"))) { canEditTopic = true; } else { canEditTopic = false; } } else { canEditTopic = true; } if(canEditTopic) { builder.setNeutralButton("Edit", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); editTopic(); } }); } final AlertDialog dialog = builder.create(); dialog.setOwnerActivity(MessageActivity.this); dialog.show(); ((TextView)dialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance()); ((TextView)dialog.findViewById(android.R.id.message)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); } else if(archived == 0 && subtitle.getText().length() > 0){ AlertDialog.Builder builder = new AlertDialog.Builder(MessageActivity.this); builder.setTitle(title.getText().toString()); final SpannableString s = new SpannableString(subtitle.getText().toString()); Linkify.addLinks(s, Linkify.WEB_URLS | Linkify.EMAIL_ADDRESSES); builder.setMessage(s); builder.setPositiveButton("Close", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog dialog = builder.create(); dialog.setOwnerActivity(MessageActivity.this); dialog.show(); ((TextView)dialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance()); } } }); upView = (ImageView)v.findViewById(R.id.upIndicator); if(scrollView != null) { upView.setVisibility(View.VISIBLE); upView.setOnClickListener(upClickListener); ImageView icon = (ImageView)v.findViewById(R.id.upIcon); icon.setOnClickListener(upClickListener); if(refreshUpIndicatorTask != null) refreshUpIndicatorTask.cancel(true); refreshUpIndicatorTask = new RefreshUpIndicatorTask(); refreshUpIndicatorTask.execute((Void)null); } else { upView.setVisibility(View.INVISIBLE); } title = (TextView)v.findViewById(R.id.title); subtitle = (TextView)v.findViewById(R.id.subtitle); key = (ImageView)v.findViewById(R.id.key); getSupportActionBar().setCustomView(v); if(savedInstanceState != null && savedInstanceState.containsKey("cid")) { cid = savedInstanceState.getInt("cid"); bid = savedInstanceState.getInt("bid"); name = savedInstanceState.getString("name"); type = savedInstanceState.getString("type"); joined = savedInstanceState.getInt("joined"); archived = savedInstanceState.getInt("archived"); status = savedInstanceState.getString("status"); backStack = (ArrayList<Integer>) savedInstanceState.getSerializable("backStack"); } try { if(getSharedPreferences("prefs", 0).contains("session_key")) { GCMRegistrar.checkDevice(this); GCMRegistrar.checkManifest(this); final String regId = GCMRegistrar.getRegistrationId(this); if (regId.equals("")) { GCMRegistrar.register(this, GCMIntentService.GCM_ID); } else { if(!getSharedPreferences("prefs", 0).contains("gcm_registered")) GCMIntentService.scheduleRegisterTimer(30000); } } } catch (Exception e) { //GCM might not be available on the device } } @Override public void onSaveInstanceState(Bundle state) { super.onSaveInstanceState(state); state.putInt("cid", cid); state.putInt("bid", bid); state.putString("name", name); state.putString("type", type); state.putInt("joined", joined); state.putInt("archived", archived); state.putString("status", status); state.putSerializable("backStack", backStack); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { //Back key pressed if(scrollView != null && (scrollView.getScrollX() >= buffersListView.getWidth() + userListView.getWidth() || scrollView.getScrollX() < buffersListView.getWidth())) { scrollView.smoothScrollTo(buffersListView.getWidth(), 0); upView.setVisibility(View.VISIBLE); return true; } else if(backStack != null && backStack.size() > 0) { Integer bid = backStack.get(0); backStack.remove(0); BuffersDataSource.Buffer buffer = BuffersDataSource.getInstance().getBuffer(bid); if(buffer != null) { ServersDataSource.Server s = ServersDataSource.getInstance().getServer(buffer.cid); if(s != null) status = s.status; String name = buffer.name; if(buffer.type.equalsIgnoreCase("console")) { if(s != null) { if(s.name != null && s.name.length() > 0) name = s.name; else name = s.hostname; } } onBufferSelected(buffer.cid, buffer.bid, name, buffer.last_seen_eid, buffer.min_eid, buffer.type, 1, buffer.archived, status); if(backStack.size() > 0) backStack.remove(0); } else { return super.onKeyDown(keyCode, event); } return true; } } return super.onKeyDown(keyCode, event); } private class SendTask extends AsyncTaskEx<Void, Void, Void> { EventsDataSource.Event e = null; @Override protected void onPreExecute() { MessageViewFragment mvf = (MessageViewFragment)getSupportFragmentManager().findFragmentById(R.id.messageViewFragment); if(mvf != null && mvf.bid != bid) { Log.w("IRCCloud", "MessageViewFragment's bid differs from MessageActivity's, switching buffers again"); open_bid(mvf.bid); } if(conn.getState() == NetworkConnection.STATE_CONNECTED && messageTxt.getText() != null && messageTxt.getText().length() > 0) { ServersDataSource.Server s = ServersDataSource.getInstance().getServer(cid); if(s != null) { sendBtn.setEnabled(false); UsersDataSource.User u = UsersDataSource.getInstance().getUser(cid, name, s.nick); e = EventsDataSource.getInstance().new Event(); e.cid = cid; e.bid = bid; e.eid = (System.currentTimeMillis() + conn.clockOffset + 5000) * 1000L; e.self = true; e.from = s.nick; e.nick = s.nick; if(u != null) e.from_mode = u.mode; String msg = messageTxt.getText().toString(); if(msg.startsWith(" msg = msg.substring(1); else if(msg.startsWith("/") && !msg.startsWith("/me ")) msg = null; e.msg = msg; if(msg != null && msg.toLowerCase().startsWith("/me ")) { e.type = "buffer_me_msg"; e.msg = msg.substring(4); } else { e.type = "buffer_msg"; } e.color = R.color.timestamp; if(name.equals(s.nick)) e.bg_color = R.color.message_bg; else e.bg_color = R.color.self; e.row_type = 0; e.html = null; e.group_msg = null; e.linkify = true; e.target_mode = null; e.highlight = false; e.reqid = -1; e.pending = true; if(e.msg != null) { e.msg = TextUtils.htmlEncode(e.msg); EventsDataSource.getInstance().addEvent(e); conn.notifyHandlers(NetworkConnection.EVENT_BUFFERMSG, e, mHandler); } } } } @Override protected Void doInBackground(Void... arg0) { if(e != null && conn.getState() == NetworkConnection.STATE_CONNECTED && messageTxt.getText() != null && messageTxt.getText().length() > 0) { e.reqid = conn.say(cid, name, messageTxt.getText().toString()); if(e.msg != null) pendingEvents.put(e.reqid, e); } return null; } @Override protected void onPostExecute(Void result) { if(e != null && e.reqid != -1) { messageTxt.setText(""); } sendBtn.setEnabled(true); } } private class RefreshUpIndicatorTask extends AsyncTaskEx<Void, Void, Void> { int unread = 0; int highlights = 0; @Override protected Void doInBackground(Void... arg0) { ArrayList<ServersDataSource.Server> servers = ServersDataSource.getInstance().getServers(); JSONObject channelDisabledMap = null; JSONObject bufferDisabledMap = null; if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null) { try { if(conn.getUserInfo().prefs.has("channel-disableTrackUnread")) channelDisabledMap = conn.getUserInfo().prefs.getJSONObject("channel-disableTrackUnread"); if(conn.getUserInfo().prefs.has("buffer-disableTrackUnread")) bufferDisabledMap = conn.getUserInfo().prefs.getJSONObject("buffer-disableTrackUnread"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } for(int i = 0; i < servers.size(); i++) { ServersDataSource.Server s = servers.get(i); ArrayList<BuffersDataSource.Buffer> buffers = BuffersDataSource.getInstance().getBuffersForServer(s.cid); for(int j = 0; j < buffers.size(); j++) { BuffersDataSource.Buffer b = buffers.get(j); if(b.bid != bid) { if(unread == 0) { int u = 0; try { u = EventsDataSource.getInstance().getUnreadCountForBuffer(b.bid, b.last_seen_eid, b.type); if(b.type.equalsIgnoreCase("channel") && channelDisabledMap != null && channelDisabledMap.has(String.valueOf(b.bid)) && channelDisabledMap.getBoolean(String.valueOf(b.bid))) u = 0; else if(bufferDisabledMap != null && bufferDisabledMap.has(String.valueOf(b.bid)) && bufferDisabledMap.getBoolean(String.valueOf(b.bid))) u = 0; } catch (JSONException e) { e.printStackTrace(); } unread += u; } if(highlights == 0) { try { if(!b.type.equalsIgnoreCase("conversation") || bufferDisabledMap == null || !bufferDisabledMap.has(String.valueOf(b.bid)) || !bufferDisabledMap.getBoolean(String.valueOf(b.bid))) highlights += EventsDataSource.getInstance().getHighlightCountForBuffer(b.bid, b.last_seen_eid, b.type); } catch (JSONException e) { } } } } } return null; } @Override protected void onPostExecute(Void result) { if(!isCancelled()) { if(highlights > 0) { upView.setImageResource(R.drawable.up_highlight); } else if(unread > 0) { upView.setImageResource(R.drawable.up_unread); } else { upView.setImageResource(R.drawable.up); } refreshUpIndicatorTask = null; } } } private class ShowNotificationsTask extends AsyncTaskEx<Integer, Void, Void> { @Override protected Void doInBackground(Integer... params) { Notifications.getInstance().excludeBid(params[0]); if(params[0] > 0) Notifications.getInstance().showNotifications(null); showNotificationsTask = null; return null; } } private void setFromIntent(Intent intent) { long min_eid = 0; long last_seen_eid = 0; launchBid = -1; launchURI = null; if(intent.hasExtra("bid")) { int new_bid = intent.getIntExtra("bid", 0); if(NetworkConnection.getInstance().ready && BuffersDataSource.getInstance().getBuffer(new_bid) == null) { Log.w("IRCCloud", "Invalid bid requested by launch intent: " + new_bid); Notifications.getInstance().deleteNotificationsForBid(new_bid); if(showNotificationsTask != null) showNotificationsTask.cancel(true); showNotificationsTask = new ShowNotificationsTask(); showNotificationsTask.execute(bid); return; } else { if(bid >= 0) backStack.add(0, bid); bid = new_bid; } } if(intent.getData() != null && intent.getData().getScheme().startsWith("irc")) { if(open_uri(intent.getData())) return; launchURI = intent.getData(); } else if(intent.hasExtra("cid")) { cid = intent.getIntExtra("cid", 0); name = intent.getStringExtra("name"); type = intent.getStringExtra("type"); joined = intent.getIntExtra("joined", 0); archived = intent.getIntExtra("archived", 0); status = intent.getStringExtra("status"); min_eid = intent.getLongExtra("min_eid", 0); last_seen_eid = intent.getLongExtra("last_seen_eid", 0); if(bid == -1) { BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBufferByName(cid, name); if(b != null) { bid = b.bid; last_seen_eid = b.last_seen_eid; min_eid = b.min_eid; archived = b.archived; } } } else if(bid != -1) { BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBuffer(bid); if(b != null) { ServersDataSource.Server s = ServersDataSource.getInstance().getServer(b.cid); joined = 1; if(b.type.equalsIgnoreCase("channel")) { ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(b.bid); if(c == null) joined = 0; } if(b.type.equalsIgnoreCase("console")) b.name = s.name; cid = b.cid; name = b.name; type = b.type; archived = b.archived; min_eid = b.min_eid; last_seen_eid = b.last_seen_eid; status = s.status; } else { cid = -1; } } if(cid == -1) { launchBid = bid; } else { UsersListFragment ulf = (UsersListFragment)getSupportFragmentManager().findFragmentById(R.id.usersListFragment); MessageViewFragment mvf = (MessageViewFragment)getSupportFragmentManager().findFragmentById(R.id.messageViewFragment); Bundle b = new Bundle(); b.putInt("cid", cid); b.putInt("bid", bid); b.putLong("last_seen_eid", last_seen_eid); b.putLong("min_eid", min_eid); b.putString("name", name); b.putString("type", type); ulf.setArguments(b); mvf.setArguments(b); messageTxt.setEnabled(true); } } @Override protected void onNewIntent(Intent intent) { if(intent != null) { setFromIntent(intent); } } @SuppressLint("NewApi") @Override public void onResume() { conn = NetworkConnection.getInstance(); if(!conn.ready) { super.onResume(); Intent i = new Intent(this, MainActivity.class); if(getIntent() != null) { if(getIntent().getData() != null) i.setData(getIntent().getData()); if(getIntent().getExtras() != null) i.putExtras(getIntent().getExtras()); } startActivity(i); finish(); return; } conn.addHandler(mHandler); super.onResume(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if(prefs.getBoolean("screenlock", false)) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } else { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } if(conn.getState() != NetworkConnection.STATE_CONNECTED) { if(scrollView != null && !NetworkConnection.getInstance().ready) { scrollView.setEnabled(false); upView.setVisibility(View.INVISIBLE); } messageTxt.setEnabled(false); } else { if(scrollView != null) { scrollView.setEnabled(true); scrollView.scrollTo((int)getResources().getDimension(R.dimen.drawer_width), 0); upView.setVisibility(View.VISIBLE); } messageTxt.setEnabled(true); } if(cid == -1) { if(getIntent() != null && (getIntent().hasExtra("bid") || getIntent().getData() != null)) { setFromIntent(getIntent()); } else if(conn.getState() == NetworkConnection.STATE_CONNECTED && conn.getUserInfo() != null && NetworkConnection.getInstance().ready) { if(!open_bid(conn.getUserInfo().last_selected_bid)) { if(!open_bid(BuffersDataSource.getInstance().firstBid())) { if(scrollView != null && NetworkConnection.getInstance().ready) scrollView.scrollTo(0,0); } } } } updateUsersListFragmentVisibility(); title.setText(name); getSupportActionBar().setTitle(name); update_subtitle(); if(getSupportFragmentManager().findFragmentById(R.id.BuffersList) != null) ((BuffersListFragment)getSupportFragmentManager().findFragmentById(R.id.BuffersList)).setSelectedBid(bid); if(refreshUpIndicatorTask != null) refreshUpIndicatorTask.cancel(true); refreshUpIndicatorTask = new RefreshUpIndicatorTask(); refreshUpIndicatorTask.execute((Void)null); invalidateOptionsMenu(); if(NetworkConnection.getInstance().ready) { if(showNotificationsTask != null) showNotificationsTask.cancel(true); showNotificationsTask = new ShowNotificationsTask(); showNotificationsTask.execute(bid); } sendBtn.setEnabled(messageTxt.getText().length() > 0); if(Build.VERSION.SDK_INT >= 11 && messageTxt.getText().length() == 0) sendBtn.setAlpha(0.5f); } @Override public void onPause() { super.onPause(); if(showNotificationsTask != null) showNotificationsTask.cancel(true); showNotificationsTask = new ShowNotificationsTask(); showNotificationsTask.execute(-1); if(channelsListDialog != null) channelsListDialog.dismiss(); if(conn != null) conn.removeHandler(mHandler); } private boolean open_uri(Uri uri) { if(uri != null && NetworkConnection.getInstance().ready) { ServersDataSource.Server s = null; if(uri.getPort() > 0) s = ServersDataSource.getInstance().getServer(uri.getHost(), uri.getPort()); else if(uri.getScheme().equalsIgnoreCase("ircs")) s = ServersDataSource.getInstance().getServer(uri.getHost(), true); else s = ServersDataSource.getInstance().getServer(uri.getHost()); if(s != null) { if(uri.getPath().length() > 1) { String key = null; String channel = uri.getPath().substring(1); if(channel.contains(",")) { key = channel.substring(channel.indexOf(",") + 1); channel = channel.substring(0, channel.indexOf(",")); } BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBufferByName(s.cid, channel); if(b != null) return open_bid(b.bid); else conn.join(s.cid, channel, key); return true; } else { BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBufferByName(s.cid, "*"); if(b != null) return open_bid(b.bid); } } else { EditConnectionFragment connFragment = new EditConnectionFragment(); connFragment.default_hostname = uri.getHost(); if(uri.getPort() > 0) connFragment.default_port = uri.getPort(); else if(uri.getScheme().equalsIgnoreCase("ircs")) connFragment.default_port = 6697; if(uri.getPath().length() > 1) connFragment.default_channels = uri.getPath().substring(1).replace(",", " "); connFragment.show(getSupportFragmentManager(), "addnetwork"); return true; } } return false; } private boolean open_bid(int bid) { BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBuffer(bid); if(b != null) { ServersDataSource.Server s = ServersDataSource.getInstance().getServer(b.cid); int joined = 1; if(b.type.equalsIgnoreCase("channel")) { ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(b.bid); if(c == null) joined = 0; } String name = b.name; if(b.type.equalsIgnoreCase("console")) { if(s.name != null && s.name.length() > 0) name = s.name; else name = s.hostname; } onBufferSelected(b.cid, b.bid, name, b.last_seen_eid, b.min_eid, b.type, joined, b.archived, s.status); return true; } Log.w("IRCCloud", "Requested BID not found"); return false; } private void update_subtitle() { if(cid == -1 || !NetworkConnection.getInstance().ready) { getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setDisplayShowCustomEnabled(false); } else { getSupportActionBar().setDisplayShowHomeEnabled(false); getSupportActionBar().setDisplayShowCustomEnabled(true); if(archived > 0 && !type.equalsIgnoreCase("console")) { subtitle.setVisibility(View.VISIBLE); subtitle.setText("(archived)"); } else { if(type == null) { subtitle.setVisibility(View.GONE); } else if(type.equalsIgnoreCase("conversation")) { UsersDataSource.User user = UsersDataSource.getInstance().getUser(cid, name); BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBuffer(bid); if(user != null && user.away > 0) { subtitle.setVisibility(View.VISIBLE); if(user.away_msg != null && user.away_msg.length() > 0) { subtitle.setText("Away: " + user.away_msg); } else if(b != null && b.away_msg != null && b.away_msg.length() > 0) { subtitle.setText("Away: " + b.away_msg); } else { subtitle.setText("Away"); } } else { subtitle.setVisibility(View.GONE); } key.setVisibility(View.GONE); } else if(type.equalsIgnoreCase("channel")) { ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(bid); if(c != null && c.topic_text.length() > 0) { subtitle.setVisibility(View.VISIBLE); subtitle.setText(c.topic_text); } else { subtitle.setVisibility(View.GONE); } if(c != null && c.mode.contains("k")) { key.setVisibility(View.VISIBLE); } else { key.setVisibility(View.GONE); } } else if(type.equalsIgnoreCase("console")) { ServersDataSource.Server s = ServersDataSource.getInstance().getServer(cid); if(s != null) { subtitle.setVisibility(View.VISIBLE); subtitle.setText(s.hostname + ":" + s.port); } else { subtitle.setVisibility(View.GONE); } key.setVisibility(View.GONE); } } } invalidateOptionsMenu(); } private void updateUsersListFragmentVisibility() { boolean hide = false; if(userListView != null) { try { if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null) { JSONObject hiddenMap = conn.getUserInfo().prefs.getJSONObject("channel-hiddenMembers"); if(hiddenMap.has(String.valueOf(bid)) && hiddenMap.getBoolean(String.valueOf(bid))) hide = true; } } catch (Exception e) { e.printStackTrace(); } if(hide || type == null || !type.equalsIgnoreCase("channel") || joined == 0) userListView.setVisibility(View.GONE); else userListView.setVisibility(View.VISIBLE); } } @SuppressLint("HandlerLeak") private final Handler mHandler = new Handler() { String bufferToOpen = null; int cidToOpen = -1; public void handleMessage(Message msg) { Integer event_bid = 0; IRCCloudJSONObject event = null; Bundle args = null; switch (msg.what) { case NetworkConnection.EVENT_LINKCHANNEL: event = (IRCCloudJSONObject)msg.obj; if(cidToOpen == event.cid() && event.getString("invalid_chan").equalsIgnoreCase(bufferToOpen)) { bufferToOpen = event.getString("valid_chan"); msg.obj = BuffersDataSource.getInstance().getBuffer(event.bid()); } case NetworkConnection.EVENT_MAKEBUFFER: BuffersDataSource.Buffer b = (BuffersDataSource.Buffer)msg.obj; if(cidToOpen == b.cid && b.name.equalsIgnoreCase(bufferToOpen) && !bufferToOpen.equalsIgnoreCase(name)) { onBufferSelected(b.cid, b.bid, b.name, b.last_seen_eid, b.min_eid, b.type, 1, 0, "connected_ready"); bufferToOpen = null; cidToOpen = -1; } else if(bid == -1 && b.cid == cid && b.name.equalsIgnoreCase(name)) { bid = b.bid; if(getSupportFragmentManager().findFragmentById(R.id.BuffersList) != null) ((BuffersListFragment)getSupportFragmentManager().findFragmentById(R.id.BuffersList)).setSelectedBid(bid); if(showNotificationsTask != null) showNotificationsTask.cancel(true); showNotificationsTask = new ShowNotificationsTask(); showNotificationsTask.execute(bid); } break; case NetworkConnection.EVENT_OPENBUFFER: event = (IRCCloudJSONObject)msg.obj; try { bufferToOpen = event.getString("name"); cidToOpen = event.cid(); b = BuffersDataSource.getInstance().getBufferByName(cidToOpen, bufferToOpen); if(b != null && !bufferToOpen.equalsIgnoreCase(name)) { onBufferSelected(b.cid, b.bid, b.name, b.last_seen_eid, b.min_eid, b.type, 1, 0, "connected_ready"); bufferToOpen = null; cidToOpen = -1; } } catch (Exception e2) { // TODO Auto-generated catch block e2.printStackTrace(); } break; case NetworkConnection.EVENT_CONNECTIVITY: if(conn.getState() == NetworkConnection.STATE_CONNECTED) { for(EventsDataSource.Event e : pendingEvents.values()) { EventsDataSource.getInstance().deleteEvent(e.eid, e.bid); } pendingEvents.clear(); if(scrollView != null && NetworkConnection.getInstance().ready) { scrollView.setEnabled(true); if(scrollView.getScrollX() > 0) upView.setVisibility(View.VISIBLE); } if(cid != -1) messageTxt.setEnabled(true); } else { if(scrollView != null && NetworkConnection.getInstance().ready) { scrollView.setEnabled(false); scrollView.smoothScrollTo((int)getResources().getDimension(R.dimen.drawer_width), 0); upView.setVisibility(View.VISIBLE); } messageTxt.setEnabled(false); } break; case NetworkConnection.EVENT_BANLIST: event = (IRCCloudJSONObject)msg.obj; if(event.getString("channel").equalsIgnoreCase(name)) { args = new Bundle(); args.putInt("cid", cid); args.putInt("bid", bid); args.putString("event", event.toString()); BanListFragment banList = (BanListFragment)getSupportFragmentManager().findFragmentByTag("banlist"); if(banList == null) { banList = new BanListFragment(); banList.setArguments(args); banList.show(getSupportFragmentManager(), "banlist"); } else { banList.setArguments(args); } } break; case NetworkConnection.EVENT_WHOLIST: event = (IRCCloudJSONObject)msg.obj; args = new Bundle(); args.putString("event", event.toString()); WhoListFragment whoList = (WhoListFragment)getSupportFragmentManager().findFragmentByTag("wholist"); if(whoList == null) { whoList = new WhoListFragment(); whoList.setArguments(args); whoList.show(getSupportFragmentManager(), "wholist"); } else { whoList.setArguments(args); } break; case NetworkConnection.EVENT_WHOIS: event = (IRCCloudJSONObject)msg.obj; args = new Bundle(); args.putString("event", event.toString()); WhoisFragment whois = (WhoisFragment)getSupportFragmentManager().findFragmentByTag("whois"); if(whois == null) { whois = new WhoisFragment(); whois.setArguments(args); whois.show(getSupportFragmentManager(), "whois"); } else { whois.setArguments(args); } break; case NetworkConnection.EVENT_LISTRESPONSEFETCHING: event = (IRCCloudJSONObject)msg.obj; String dialogtitle = "List of channels on " + ServersDataSource.getInstance().getServer(event.cid()).hostname; if(channelsListDialog == null) { Context ctx = MessageActivity.this; if(Build.VERSION.SDK_INT < 11) ctx = new ContextThemeWrapper(ctx, android.R.style.Theme_Dialog); AlertDialog.Builder builder = new AlertDialog.Builder(ctx); builder.setView(getLayoutInflater().inflate(R.layout.dialog_channelslist, null)); builder.setTitle(dialogtitle); builder.setNegativeButton("Close", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); channelsListDialog = builder.create(); channelsListDialog.setOwnerActivity(MessageActivity.this); } else { channelsListDialog.setTitle(dialogtitle); } channelsListDialog.show(); ChannelListFragment channels = (ChannelListFragment)getSupportFragmentManager().findFragmentById(R.id.channelListFragment); args = new Bundle(); args.putInt("cid", event.cid()); channels.setArguments(args); break; case NetworkConnection.EVENT_BACKLOG_END: if(scrollView != null) { scrollView.setEnabled(true); if(scrollView.getScrollX() > 0) upView.setVisibility(View.VISIBLE); } if(cid == -1) { if(launchURI == null || !open_uri(launchURI)) { if(launchBid == -1 || !open_bid(launchBid)) { if(conn.getUserInfo() == null || !open_bid(conn.getUserInfo().last_selected_bid)) { if(!open_bid(BuffersDataSource.getInstance().firstBid())) { if(scrollView != null && NetworkConnection.getInstance().ready) { scrollView.scrollTo(0, 0); } } } } } } update_subtitle(); if(refreshUpIndicatorTask != null) refreshUpIndicatorTask.cancel(true); refreshUpIndicatorTask = new RefreshUpIndicatorTask(); refreshUpIndicatorTask.execute((Void)null); break; case NetworkConnection.EVENT_USERINFO: updateUsersListFragmentVisibility(); invalidateOptionsMenu(); if(refreshUpIndicatorTask != null) refreshUpIndicatorTask.cancel(true); refreshUpIndicatorTask = new RefreshUpIndicatorTask(); refreshUpIndicatorTask.execute((Void)null); if(launchBid == -1 && cid == -1) launchBid = conn.getUserInfo().last_selected_bid; break; case NetworkConnection.EVENT_STATUSCHANGED: try { event = (IRCCloudJSONObject)msg.obj; if(event.cid() == cid) { status = event.getString("new_status"); invalidateOptionsMenu(); } } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } break; case NetworkConnection.EVENT_MAKESERVER: ServersDataSource.Server server = (ServersDataSource.Server)msg.obj; if(server.cid == cid) { status = server.status; invalidateOptionsMenu(); } break; case NetworkConnection.EVENT_BUFFERARCHIVED: event_bid = (Integer)msg.obj; if(event_bid == bid) { archived = 1; invalidateOptionsMenu(); subtitle.setVisibility(View.VISIBLE); subtitle.setText("(archived)"); } break; case NetworkConnection.EVENT_BUFFERUNARCHIVED: event_bid = (Integer)msg.obj; if(event_bid == bid) { archived = 0; invalidateOptionsMenu(); subtitle.setVisibility(View.GONE); } break; case NetworkConnection.EVENT_JOIN: event = (IRCCloudJSONObject)msg.obj; if(event.bid() == bid && event.type().equalsIgnoreCase("you_joined_channel")) { joined = 1; invalidateOptionsMenu(); updateUsersListFragmentVisibility(); } break; case NetworkConnection.EVENT_PART: event = (IRCCloudJSONObject)msg.obj; if(event.bid() == bid && event.type().equalsIgnoreCase("you_parted_channel")) { joined = 0; invalidateOptionsMenu(); updateUsersListFragmentVisibility(); } break; case NetworkConnection.EVENT_CHANNELINIT: ChannelsDataSource.Channel channel = (ChannelsDataSource.Channel)msg.obj; if(channel.bid == bid) { joined = 1; archived = 0; update_subtitle(); invalidateOptionsMenu(); updateUsersListFragmentVisibility(); } break; case NetworkConnection.EVENT_CONNECTIONDELETED: case NetworkConnection.EVENT_DELETEBUFFER: Integer id = (Integer)msg.obj; if(msg.what==NetworkConnection.EVENT_DELETEBUFFER) { for(int i = 0; i < backStack.size(); i++) { if(backStack.get(i).equals(id)) { backStack.remove(i); i } } } if(id == ((msg.what==NetworkConnection.EVENT_CONNECTIONDELETED)?cid:bid)) { if(backStack != null && backStack.size() > 0) { Integer bid = backStack.get(0); backStack.remove(0); BuffersDataSource.Buffer buffer = BuffersDataSource.getInstance().getBuffer(bid); if(buffer != null) { ServersDataSource.Server s = ServersDataSource.getInstance().getServer(buffer.cid); if(s != null) status = s.status; String name = buffer.name; if(buffer.type.equalsIgnoreCase("console")) { if(s != null) { if(s.name != null && s.name.length() > 0) name = s.name; else name = s.hostname; } } onBufferSelected(buffer.cid, buffer.bid, name, buffer.last_seen_eid, buffer.min_eid, buffer.type, 1, buffer.archived, status); backStack.remove(0); } else { finish(); } } else { if(!open_bid(BuffersDataSource.getInstance().firstBid())) finish(); } } break; case NetworkConnection.EVENT_CHANNELTOPIC: event = (IRCCloudJSONObject)msg.obj; if(event.bid() == bid) { try { if(event.getString("topic").length() > 0) { subtitle.setVisibility(View.VISIBLE); subtitle.setText(event.getString("topic")); } else { subtitle.setVisibility(View.GONE); } } catch (Exception e1) { subtitle.setVisibility(View.GONE); e1.printStackTrace(); } } break; case NetworkConnection.EVENT_SELFBACK: try { event = (IRCCloudJSONObject)msg.obj; if(event.cid() == cid && event.getString("nick").equalsIgnoreCase(name)) { subtitle.setVisibility(View.GONE); subtitle.setText(""); } } catch (Exception e1) { e1.printStackTrace(); } break; case NetworkConnection.EVENT_AWAY: try { event = (IRCCloudJSONObject)msg.obj; if((event.bid() == bid || (event.type().equalsIgnoreCase("self_away") && event.cid() == cid)) && event.getString("nick").equalsIgnoreCase(name)) { subtitle.setVisibility(View.VISIBLE); if(event.has("away_msg")) subtitle.setText("Away: " + event.getString("away_msg")); else subtitle.setText("Away: " + event.getString("msg")); } } catch (Exception e1) { e1.printStackTrace(); } break; case NetworkConnection.EVENT_HEARTBEATECHO: if(refreshUpIndicatorTask != null) refreshUpIndicatorTask.cancel(true); refreshUpIndicatorTask = new RefreshUpIndicatorTask(); refreshUpIndicatorTask.execute((Void)null); break; case NetworkConnection.EVENT_FAILURE_MSG: event = (IRCCloudJSONObject)msg.obj; if(event.has("_reqid")) { int reqid = event.getInt("_reqid"); if(pendingEvents.containsKey(reqid)) { EventsDataSource.Event e = pendingEvents.get(reqid); EventsDataSource.getInstance().deleteEvent(e.eid, e.bid); pendingEvents.remove(event.getInt("_reqid")); e.msg = ColorFormatter.irc_to_html(e.msg + " \u00034(FAILED)\u000f"); conn.notifyHandlers(NetworkConnection.EVENT_BUFFERMSG, e); } } break; case NetworkConnection.EVENT_BUFFERMSG: try { EventsDataSource.Event e = (EventsDataSource.Event)msg.obj; if(e.bid != bid && upView != null) { if(refreshUpIndicatorTask != null) refreshUpIndicatorTask.cancel(true); refreshUpIndicatorTask = new RefreshUpIndicatorTask(); refreshUpIndicatorTask.execute((Void)null); } if(e.from.equalsIgnoreCase(name)) { for(EventsDataSource.Event e1 : pendingEvents.values()) { EventsDataSource.getInstance().deleteEvent(e1.eid, e1.bid); } pendingEvents.clear(); } else if(pendingEvents.containsKey(e.reqid)) { e = pendingEvents.get(e.reqid); EventsDataSource.getInstance().deleteEvent(e.eid, e.bid); pendingEvents.remove(e.reqid); } } catch (Exception e1) { } break; } } }; @Override public boolean onCreateOptionsMenu(Menu menu) { if(type != null && NetworkConnection.getInstance().ready) { if(type.equalsIgnoreCase("channel")) { getSupportMenuInflater().inflate(R.menu.activity_message_channel_userlist, menu); getSupportMenuInflater().inflate(R.menu.activity_message_channel, menu); } else if(type.equalsIgnoreCase("conversation")) getSupportMenuInflater().inflate(R.menu.activity_message_conversation, menu); else if(type.equalsIgnoreCase("console")) getSupportMenuInflater().inflate(R.menu.activity_message_console, menu); getSupportMenuInflater().inflate(R.menu.activity_message_archive, menu); } getSupportMenuInflater().inflate(R.menu.activity_main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onPrepareOptionsMenu (Menu menu) { if(type != null && NetworkConnection.getInstance().ready) { if(archived == 0) { menu.findItem(R.id.menu_archive).setTitle(R.string.menu_archive); } else { menu.findItem(R.id.menu_archive).setTitle(R.string.menu_unarchive); } if(type.equalsIgnoreCase("channel")) { if(joined == 0) { menu.findItem(R.id.menu_leave).setTitle(R.string.menu_rejoin); menu.findItem(R.id.menu_archive).setVisible(true); menu.findItem(R.id.menu_archive).setEnabled(true); menu.findItem(R.id.menu_delete).setVisible(true); menu.findItem(R.id.menu_delete).setEnabled(true); if(menu.findItem(R.id.menu_userlist) != null) { menu.findItem(R.id.menu_userlist).setEnabled(false); menu.findItem(R.id.menu_userlist).setVisible(false); } menu.findItem(R.id.menu_ban_list).setVisible(false); menu.findItem(R.id.menu_ban_list).setEnabled(false); } else { menu.findItem(R.id.menu_leave).setTitle(R.string.menu_leave); menu.findItem(R.id.menu_archive).setVisible(false); menu.findItem(R.id.menu_archive).setEnabled(false); menu.findItem(R.id.menu_delete).setVisible(false); menu.findItem(R.id.menu_delete).setEnabled(false); menu.findItem(R.id.menu_ban_list).setVisible(true); menu.findItem(R.id.menu_ban_list).setEnabled(true); if(menu.findItem(R.id.menu_userlist) != null) { boolean hide = false; try { if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null) { JSONObject hiddenMap = conn.getUserInfo().prefs.getJSONObject("channel-hiddenMembers"); if(hiddenMap.has(String.valueOf(bid)) && hiddenMap.getBoolean(String.valueOf(bid))) hide = true; } } catch (JSONException e) { } if(hide) { menu.findItem(R.id.menu_userlist).setEnabled(false); menu.findItem(R.id.menu_userlist).setVisible(false); } else { menu.findItem(R.id.menu_userlist).setEnabled(true); menu.findItem(R.id.menu_userlist).setVisible(true); } } } } else if(type.equalsIgnoreCase("console")) { menu.findItem(R.id.menu_archive).setVisible(false); menu.findItem(R.id.menu_archive).setEnabled(false); if(status != null && status.contains("connected") && !status.startsWith("dis")) { menu.findItem(R.id.menu_disconnect).setTitle(R.string.menu_disconnect); menu.findItem(R.id.menu_delete).setVisible(false); menu.findItem(R.id.menu_delete).setEnabled(false); } else { menu.findItem(R.id.menu_disconnect).setTitle(R.string.menu_reconnect); menu.findItem(R.id.menu_delete).setVisible(true); menu.findItem(R.id.menu_delete).setEnabled(true); } } } return super.onPrepareOptionsMenu(menu); } private OnClickListener upClickListener = new OnClickListener() { @Override public void onClick(View arg0) { if(scrollView != null) { if(scrollView.getScrollX() < buffersListView.getWidth() / 4) { scrollView.smoothScrollTo(buffersListView.getWidth(), 0); upView.setVisibility(View.VISIBLE); } else { scrollView.smoothScrollTo(0, 0); upView.setVisibility(View.INVISIBLE); } if(!getSharedPreferences("prefs", 0).getBoolean("bufferSwipeTip", false)) { Toast.makeText(MessageActivity.this, "Swipe right and left to quickly open and close channels and conversations list", Toast.LENGTH_LONG).show(); SharedPreferences.Editor editor = getSharedPreferences("prefs", 0).edit(); editor.putBoolean("bufferSwipeTip", true); editor.commit(); } } } }; @Override public boolean onOptionsItemSelected(MenuItem item) { AlertDialog.Builder builder; AlertDialog dialog; switch (item.getItemId()) { case R.id.menu_whois: conn.whois(cid, name, null); break; case R.id.menu_identify: NickservFragment nsFragment = new NickservFragment(); nsFragment.setCid(cid); nsFragment.show(getSupportFragmentManager(), "nickserv"); break; case R.id.menu_add_network: if(getWindowManager().getDefaultDisplay().getWidth() < 800) { Intent i = new Intent(this, EditConnectionActivity.class); startActivity(i); } else { EditConnectionFragment connFragment = new EditConnectionFragment(); connFragment.show(getSupportFragmentManager(), "addnetwork"); } break; case R.id.menu_channel_options: ChannelOptionsFragment newFragment = new ChannelOptionsFragment(cid, bid); newFragment.show(getSupportFragmentManager(), "channeloptions"); break; case R.id.menu_buffer_options: BufferOptionsFragment bufferFragment = new BufferOptionsFragment(cid, bid, type); bufferFragment.show(getSupportFragmentManager(), "bufferoptions"); break; case R.id.menu_userlist: if(scrollView != null) { if(scrollView.getScrollX() > buffersListView.getWidth()) { scrollView.smoothScrollTo(buffersListView.getWidth(), 0); } else { scrollView.smoothScrollTo(buffersListView.getWidth() + userListView.getWidth(), 0); } upView.setVisibility(View.VISIBLE); if(!getSharedPreferences("prefs", 0).getBoolean("userSwipeTip", false)) { Toast.makeText(this, "Swipe left and right to quickly open and close the user list", Toast.LENGTH_LONG).show(); SharedPreferences.Editor editor = getSharedPreferences("prefs", 0).edit(); editor.putBoolean("userSwipeTip", true); editor.commit(); } } return true; case R.id.menu_ignore_list: Bundle args = new Bundle(); args.putInt("cid", cid); IgnoreListFragment ignoreList = new IgnoreListFragment(); ignoreList.setArguments(args); ignoreList.show(getSupportFragmentManager(), "ignorelist"); return true; case R.id.menu_ban_list: conn.mode(cid, name, "b"); return true; case R.id.menu_leave: if(joined == 0) conn.join(cid, name, null); else conn.part(cid, name, null); return true; case R.id.menu_archive: if(archived == 0) conn.archiveBuffer(cid, bid); else conn.unarchiveBuffer(cid, bid); return true; case R.id.menu_delete: builder = new AlertDialog.Builder(MessageActivity.this); if(type.equalsIgnoreCase("console")) builder.setTitle("Delete Connection"); else builder.setTitle("Delete History"); if(type.equalsIgnoreCase("console")) builder.setMessage("Are you sure you want to remove this connection?"); else if(type.equalsIgnoreCase("channel")) builder.setMessage("Are you sure you want to clear your history in " + name + "?"); else builder.setMessage("Are you sure you want to clear your history with " + name + "?"); builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setNeutralButton("Delete", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if(type.equalsIgnoreCase("console")) { conn.deleteServer(cid); } else { conn.deleteBuffer(cid, bid); } dialog.dismiss(); } }); dialog = builder.create(); dialog.setOwnerActivity(MessageActivity.this); dialog.show(); return true; case R.id.menu_editconnection: if(getWindowManager().getDefaultDisplay().getWidth() < 800) { Intent i = new Intent(this, EditConnectionActivity.class); i.putExtra("cid", cid); startActivity(i); } else { EditConnectionFragment editFragment = new EditConnectionFragment(); editFragment.setCid(cid); editFragment.show(getSupportFragmentManager(), "editconnection"); } return true; case R.id.menu_disconnect: if(status != null && status.contains("connected") && !status.startsWith("dis")) { conn.disconnect(cid, null); } else { conn.reconnect(cid); } return true; } return super.onOptionsItemSelected(item); } void editTopic() { ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(bid); AlertDialog.Builder builder = new AlertDialog.Builder(this); LayoutInflater inflater = getLayoutInflater(); View view = inflater.inflate(R.layout.dialog_textprompt,null); TextView prompt = (TextView)view.findViewById(R.id.prompt); final EditText input = (EditText)view.findViewById(R.id.textInput); input.setText(c.topic_text); prompt.setVisibility(View.GONE); builder.setTitle("Channel Topic"); builder.setView(view); builder.setPositiveButton("Set Topic", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { conn.topic(cid, name, input.getText().toString()); dialog.dismiss(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog dialog = builder.create(); dialog.setOwnerActivity(this); dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); dialog.show(); } @Override public void onMessageDoubleClicked(EventsDataSource.Event event) { if(event == null) return; String from = event.from; if(from == null || from.length() == 0) from = event.nick; onUserDoubleClicked(from); } @Override public void onUserDoubleClicked(String from) { if(messageTxt == null || from == null || from.length() == 0) return; if(!getSharedPreferences("prefs", 0).getBoolean("mentionTip", false)) { SharedPreferences.Editor editor = getSharedPreferences("prefs", 0).edit(); editor.putBoolean("mentionTip", true); editor.commit(); } if(scrollView != null) scrollView.scrollTo((int)getResources().getDimension(R.dimen.drawer_width), 0); if(messageTxt.getText().length() == 0) { messageTxt.append(from + ": "); } else { int oldPosition = messageTxt.getSelectionStart(); String text = messageTxt.getText().toString(); int start = oldPosition - 1; if(start > 0 && text.charAt(start) == ' ') start while(start > 0 && text.charAt(start) != ' ') start int match = text.indexOf(from, start); int end = oldPosition + from.length(); if(end > text.length() - 1) end = text.length() - 1; if(match >= 0 && match < end) { String newtext = ""; if(match > 1 && text.charAt(match - 1) == ' ') newtext = text.substring(0, match - 1); else newtext = text.substring(0, match); if(match+from.length() < text.length() && text.charAt(match+from.length()) == ':' && match+from.length()+1 < text.length() && text.charAt(match+from.length()+1) == ' ') { if(match+from.length()+2 < text.length()) newtext += text.substring(match+from.length()+2, text.length()); } else if(match+from.length() < text.length()) { newtext += text.substring(match+from.length(), text.length()); } if(newtext.endsWith(" ")) newtext = newtext.substring(0, newtext.length() - 1); if(newtext.equals(":")) newtext = ""; messageTxt.setText(newtext); if(match < newtext.length()) messageTxt.setSelection(match); else messageTxt.setSelection(newtext.length()); } else { if(oldPosition == text.length() - 1) { text += " " + from; } else { String newtext = text.substring(0, oldPosition); if(!newtext.endsWith(" ")) from = " " + from; if(!text.substring(oldPosition, text.length()).startsWith(" ")) from += " "; newtext += from; newtext += text.substring(oldPosition, text.length()); if(newtext.endsWith(" ")) newtext = newtext.substring(0, newtext.length() - 1); text = newtext; } messageTxt.setText(text); if(text.length() > 0) { if(oldPosition + from.length() + 2 < text.length()) messageTxt.setSelection(oldPosition + from.length()); else messageTxt.setSelection(text.length()); } } } messageTxt.requestFocus(); InputMethodManager keyboard = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); keyboard.showSoftInput(messageTxt, 0); } @Override public boolean onBufferLongClicked(BuffersDataSource.Buffer b) { if(b == null) return false; ArrayList<String> itemList = new ArrayList<String>(); final String[] items; final BuffersDataSource.Buffer buffer = b; ServersDataSource.Server s = ServersDataSource.getInstance().getServer(buffer.cid); if(buffer.bid != bid) itemList.add("Open"); if(ChannelsDataSource.getInstance().getChannelForBuffer(b.bid) != null) { itemList.add("Leave"); itemList.add("Channel Options"); } else { if(b.type.equalsIgnoreCase("channel")) itemList.add("Join"); else if(b.type.equalsIgnoreCase("console")) { if(s.status.contains("connected") && !s.status.startsWith("dis")) { itemList.add("Disconnect"); } else { itemList.add("Connect"); itemList.add("Delete"); } itemList.add("Edit Connection"); } if(!b.type.equalsIgnoreCase("console")) { if(b.archived == 0) itemList.add("Archive"); else itemList.add("Unarchive"); itemList.add("Delete"); } if(!b.type.equalsIgnoreCase("channel")) { itemList.add("Buffer Options"); } } AlertDialog.Builder builder = new AlertDialog.Builder(this); if(b.type.equalsIgnoreCase("console")) builder.setTitle(s.name); else builder.setTitle(b.name); items = itemList.toArray(new String[itemList.size()]); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int item) { AlertDialog.Builder builder = new AlertDialog.Builder(MessageActivity.this); AlertDialog dialog; if(items[item].equals("Open")) { ServersDataSource.Server s = ServersDataSource.getInstance().getServer(buffer.cid); if(buffer.type.equalsIgnoreCase("console")) { onBufferSelected(buffer.cid, buffer.bid, s.name, buffer.last_seen_eid, buffer.min_eid, buffer.type, 1, buffer.archived, s.status); } else { onBufferSelected(buffer.cid, buffer.bid, buffer.name, buffer.last_seen_eid, buffer.min_eid, buffer.type, 1, buffer.archived, s.status); } } else if(items[item].equals("Join")) { conn.join(buffer.cid, buffer.name, null); } else if(items[item].equals("Leave")) { conn.part(buffer.cid, buffer.name, null); } else if(items[item].equals("Archive")) { conn.archiveBuffer(buffer.cid, buffer.bid); } else if(items[item].equals("Unarchive")) { conn.unarchiveBuffer(buffer.cid, buffer.bid); } else if(items[item].equals("Connect")) { conn.reconnect(buffer.cid); } else if(items[item].equals("Disconnect")) { conn.disconnect(buffer.cid, null); } else if(items[item].equals("Channel Options")) { ChannelOptionsFragment newFragment = new ChannelOptionsFragment(buffer.cid, buffer.bid); newFragment.show(getSupportFragmentManager(), "channeloptions"); } else if(items[item].equals("Buffer Options")) { BufferOptionsFragment newFragment = new BufferOptionsFragment(buffer.cid, buffer.bid, buffer.type); newFragment.show(getSupportFragmentManager(), "bufferoptions"); } else if(items[item].equals("Edit Connection")) { EditConnectionFragment editFragment = new EditConnectionFragment(); editFragment.setCid(buffer.cid); editFragment.show(getSupportFragmentManager(), "editconnection"); } else if(items[item].equals("Delete")) { builder = new AlertDialog.Builder(MessageActivity.this); if(buffer.type.equalsIgnoreCase("console")) builder.setTitle("Delete Connection"); else builder.setTitle("Delete History"); if(buffer.type.equalsIgnoreCase("console")) builder.setMessage("Are you sure you want to remove this connection?"); else if(buffer.type.equalsIgnoreCase("channel")) builder.setMessage("Are you sure you want to clear your history in " + buffer.name + "?"); else builder.setMessage("Are you sure you want to clear your history with " + buffer.name + "?"); builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setNeutralButton("Delete", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if(type.equalsIgnoreCase("console")) { conn.deleteServer(buffer.cid); } else { conn.deleteBuffer(buffer.cid, buffer.bid); } dialog.dismiss(); } }); dialog = builder.create(); dialog.setOwnerActivity(MessageActivity.this); dialog.show(); } } }); AlertDialog dialog = builder.create(); dialog.setOwnerActivity(this); dialog.show(); return true; } @Override public boolean onMessageLongClicked(EventsDataSource.Event event) { String from = event.from; if(from == null || from.length() == 0) from = event.nick; UsersDataSource.User user; if(type.equals("channel")) user = UsersDataSource.getInstance().getUser(cid, name, from); else user = UsersDataSource.getInstance().getUser(cid, from); if(user == null && from != null && event.hostmask != null) { user = UsersDataSource.getInstance().new User(); user.nick = from; user.hostmask = event.hostmask; user.mode = ""; } if(user == null && event.html == null) return false; if(event.html != null) showUserPopup(user, ColorFormatter.html_to_spanned(event.html)); else showUserPopup(user, null); return true; } @Override public void onUserSelected(int c, String chan, String nick) { UsersDataSource u = UsersDataSource.getInstance(); if(type.equals("channel")) showUserPopup(u.getUser(cid, name, nick), null); else showUserPopup(u.getUser(cid, nick), null); } @SuppressLint("NewApi") @SuppressWarnings("deprecation") private void showUserPopup(UsersDataSource.User user, Spanned message) { ArrayList<String> itemList = new ArrayList<String>(); final String[] items; final Spanned text_to_copy = message; selected_user = user; AlertDialog.Builder builder = new AlertDialog.Builder(this); if(message != null) itemList.add("Copy Message"); if(selected_user != null) { itemList.add("Whois"); itemList.add("Send a message"); itemList.add("Mention"); itemList.add("Invite to a channel"); itemList.add("Ignore"); if(type.equalsIgnoreCase("channel")) { UsersDataSource.User self_user = UsersDataSource.getInstance().getUser(cid, name, ServersDataSource.getInstance().getServer(cid).nick); if(self_user.mode.contains("q") || self_user.mode.contains("a") || self_user.mode.contains("o")) { if(selected_user.mode.contains("o")) itemList.add("Deop"); else itemList.add("Op"); } if(self_user.mode.contains("q") || self_user.mode.contains("a") || self_user.mode.contains("o") || self_user.mode.contains("h")) { itemList.add("Kick"); itemList.add("Ban"); } } } items = itemList.toArray(new String[itemList.size()]); if(selected_user != null) builder.setTitle(selected_user.nick + "\n(" + selected_user.hostmask + ")"); else builder.setTitle("Message"); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int item) { AlertDialog.Builder builder = new AlertDialog.Builder(MessageActivity.this); LayoutInflater inflater = getLayoutInflater(); ServersDataSource s = ServersDataSource.getInstance(); ServersDataSource.Server server = s.getServer(cid); View view; final TextView prompt; final EditText input; AlertDialog dialog; if(items[item].equals("Copy Message")) { if(Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) { android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setText(text_to_copy); } else { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); android.content.ClipData clip = android.content.ClipData.newPlainText("IRCCloud Message",text_to_copy); clipboard.setPrimaryClip(clip); } } else if(items[item].equals("Whois")) { conn.whois(cid, selected_user.nick, null); } else if(items[item].equals("Send a message")) { BuffersDataSource b = BuffersDataSource.getInstance(); BuffersDataSource.Buffer buffer = b.getBufferByName(cid, selected_user.nick); if(getSupportFragmentManager().findFragmentById(R.id.BuffersList) != null) { if(buffer != null) { onBufferSelected(buffer.cid, buffer.bid, buffer.name, buffer.last_seen_eid, buffer.min_eid, buffer.type, 1, buffer.archived, status); } else { onBufferSelected(cid, -1, selected_user.nick, 0, 0, "conversation", 1, 0, status); } } else { Intent i = new Intent(MessageActivity.this, MessageActivity.class); if(buffer != null) { i.putExtra("cid", buffer.cid); i.putExtra("bid", buffer.bid); i.putExtra("name", buffer.name); i.putExtra("last_seen_eid", buffer.last_seen_eid); i.putExtra("min_eid", buffer.min_eid); i.putExtra("type", buffer.type); i.putExtra("joined", 1); i.putExtra("archived", buffer.archived); i.putExtra("status", status); } else { i.putExtra("cid", cid); i.putExtra("bid", -1); i.putExtra("name", selected_user.nick); i.putExtra("last_seen_eid", 0L); i.putExtra("min_eid", 0L); i.putExtra("type", "conversation"); i.putExtra("joined", 1); i.putExtra("archived", 0); i.putExtra("status", status); } startActivity(i); } } else if(items[item].equals("Mention")) { if(!getSharedPreferences("prefs", 0).getBoolean("mentionTip", false)) { Toast.makeText(MessageActivity.this, "Double-tap a message to quickly reply to the sender", Toast.LENGTH_LONG).show(); SharedPreferences.Editor editor = getSharedPreferences("prefs", 0).edit(); editor.putBoolean("mentionTip", true); editor.commit(); } onUserDoubleClicked(selected_user.nick); } else if(items[item].equals("Invite to a channel")) { view = inflater.inflate(R.layout.dialog_textprompt,null); prompt = (TextView)view.findViewById(R.id.prompt); input = (EditText)view.findViewById(R.id.textInput); prompt.setText("Invite " + selected_user.nick + " to a channel"); builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")"); builder.setView(view); builder.setPositiveButton("Invite", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { conn.invite(cid, input.getText().toString(), selected_user.nick); dialog.dismiss(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog = builder.create(); dialog.setOwnerActivity(MessageActivity.this); dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); dialog.show(); } else if(items[item].equals("Ignore")) { view = inflater.inflate(R.layout.dialog_textprompt,null); prompt = (TextView)view.findViewById(R.id.prompt); input = (EditText)view.findViewById(R.id.textInput); input.setText("*!"+selected_user.hostmask); prompt.setText("Ignore messages for " + selected_user.nick + " at this hostmask"); builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")"); builder.setView(view); builder.setPositiveButton("Ignore", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { conn.ignore(cid, input.getText().toString()); dialog.dismiss(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog = builder.create(); dialog.setOwnerActivity(MessageActivity.this); dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); dialog.show(); } else if(items[item].equals("Op")) { conn.mode(cid, name, "+o " + selected_user.nick); } else if(items[item].equals("Deop")) { conn.mode(cid, name, "-o " + selected_user.nick); } else if(items[item].equals("Kick")) { view = inflater.inflate(R.layout.dialog_textprompt,null); prompt = (TextView)view.findViewById(R.id.prompt); input = (EditText)view.findViewById(R.id.textInput); prompt.setText("Give a reason for kicking"); builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")"); builder.setView(view); builder.setPositiveButton("Kick", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { conn.kick(cid, name, selected_user.nick, input.getText().toString()); dialog.dismiss(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog = builder.create(); dialog.setOwnerActivity(MessageActivity.this); dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); dialog.show(); } else if(items[item].equals("Ban")) { view = inflater.inflate(R.layout.dialog_textprompt,null); prompt = (TextView)view.findViewById(R.id.prompt); input = (EditText)view.findViewById(R.id.textInput); input.setText("*!"+selected_user.hostmask); prompt.setText("Add a banmask for " + selected_user.nick); builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")"); builder.setView(view); builder.setPositiveButton("Ban", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { conn.mode(cid, name, "+b " + input.getText().toString()); dialog.dismiss(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog = builder.create(); dialog.setOwnerActivity(MessageActivity.this); dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); dialog.show(); } dialogInterface.dismiss(); } }); AlertDialog dialog = builder.create(); dialog.setOwnerActivity(this); dialog.show(); } @Override public void onBufferSelected(int cid, int bid, String name, long last_seen_eid, long min_eid, String type, int joined, int archived, String status) { if(scrollView != null) { if(buffersListView.getWidth() > 0) scrollView.smoothScrollTo(buffersListView.getWidth(), 0); upView.setVisibility(View.VISIBLE); } if(bid != this.bid || this.cid == -1) { if(bid != -1 && conn != null && conn.getUserInfo() != null) conn.getUserInfo().last_selected_bid = bid; for(int i = 0; i < backStack.size(); i++) { if(backStack.get(i) == this.bid) backStack.remove(i); } if(this.bid >= 0) backStack.add(0, this.bid); this.cid = cid; this.bid = bid; this.name = name; this.type = type; this.joined = joined; this.archived = archived; this.status = status; title.setText(name); getSupportActionBar().setTitle(name); update_subtitle(); Bundle b = new Bundle(); b.putInt("cid", cid); b.putInt("bid", bid); b.putLong("last_seen_eid", last_seen_eid); b.putLong("min_eid", min_eid); b.putString("name", name); b.putString("type", type); BuffersListFragment blf = (BuffersListFragment)getSupportFragmentManager().findFragmentById(R.id.BuffersList); MessageViewFragment mvf = (MessageViewFragment)getSupportFragmentManager().findFragmentById(R.id.messageViewFragment); UsersListFragment ulf = (UsersListFragment)getSupportFragmentManager().findFragmentById(R.id.usersListFragment); if(blf != null) blf.setSelectedBid(bid); if(mvf != null) mvf.setArguments(b); if(ulf != null) ulf.setArguments(b); AlphaAnimation anim = new AlphaAnimation(1, 0); anim.setDuration(200); anim.setFillAfter(true); mvf.getListView().startAnimation(anim); ulf.getListView().startAnimation(anim); shouldFadeIn = true; updateUsersListFragmentVisibility(); invalidateOptionsMenu(); if(showNotificationsTask != null) showNotificationsTask.cancel(true); showNotificationsTask = new ShowNotificationsTask(); showNotificationsTask.execute(bid); if(upView != null) new RefreshUpIndicatorTask().execute((Void)null); } if(cid != -1) { if(scrollView != null) scrollView.setEnabled(true); messageTxt.setEnabled(true); } } public void showUpButton(boolean show) { if(upView != null) { if(show) { upView.setVisibility(View.VISIBLE); } else { upView.setVisibility(View.INVISIBLE); } } } @Override public void onMessageViewReady() { if(shouldFadeIn) { MessageViewFragment mvf = (MessageViewFragment)getSupportFragmentManager().findFragmentById(R.id.messageViewFragment); UsersListFragment ulf = (UsersListFragment)getSupportFragmentManager().findFragmentById(R.id.usersListFragment); AlphaAnimation anim = new AlphaAnimation(0, 1); anim.setDuration(200); anim.setFillAfter(true); mvf.getListView().startAnimation(anim); ulf.getListView().startAnimation(anim); shouldFadeIn = false; } } @Override public void addButtonPressed(int cid) { if(scrollView != null) scrollView.scrollTo(0,0); } }
/* * EDIT: 02/09/2004 - Renamed original WidgetViewport to WidgetViewRectangle. * GOP */ package com.jme.renderer.lwjgl; import java.io.File; import java.io.IOException; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.logging.Level; import java.util.Arrays; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.DisplayMode; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL15; import org.lwjgl.opengl.GLContext; import org.lwjgl.opengl.glu.GLU; import com.jme.bounding.BoundingVolume; import com.jme.curve.Curve; import com.jme.math.Quaternion; import com.jme.math.Vector2f; import com.jme.math.Vector3f; import com.jme.renderer.Camera; import com.jme.renderer.ColorRGBA; import com.jme.renderer.RenderQueue; import com.jme.renderer.Renderer; import com.jme.scene.CompositeMesh; import com.jme.scene.Geometry; import com.jme.scene.Line; import com.jme.scene.Point; import com.jme.scene.Spatial; import com.jme.scene.Text; import com.jme.scene.TriMesh; import com.jme.scene.state.AlphaState; import com.jme.scene.state.AttributeState; import com.jme.scene.state.CullState; import com.jme.scene.state.DitherState; import com.jme.scene.state.FogState; import com.jme.scene.state.FragmentProgramState; import com.jme.scene.state.GLSLShaderObjectsState; import com.jme.scene.state.LightState; import com.jme.scene.state.MaterialState; import com.jme.scene.state.ShadeState; import com.jme.scene.state.StencilState; import com.jme.scene.state.TextureState; import com.jme.scene.state.VertexProgramState; import com.jme.scene.state.WireframeState; import com.jme.scene.state.ZBufferState; import com.jme.scene.state.lwjgl.LWJGLAlphaState; import com.jme.scene.state.lwjgl.LWJGLAttributeState; import com.jme.scene.state.lwjgl.LWJGLCullState; import com.jme.scene.state.lwjgl.LWJGLDitherState; import com.jme.scene.state.lwjgl.LWJGLFogState; import com.jme.scene.state.lwjgl.LWJGLFragmentProgramState; import com.jme.scene.state.lwjgl.LWJGLLightState; import com.jme.scene.state.lwjgl.LWJGLMaterialState; import com.jme.scene.state.lwjgl.LWJGLShadeState; import com.jme.scene.state.lwjgl.LWJGLShaderObjectsState; import com.jme.scene.state.lwjgl.LWJGLStencilState; import com.jme.scene.state.lwjgl.LWJGLTextureState; import com.jme.scene.state.lwjgl.LWJGLVertexProgramState; import com.jme.scene.state.lwjgl.LWJGLWireframeState; import com.jme.scene.state.lwjgl.LWJGLZBufferState; import com.jme.system.JmeException; import com.jme.util.LoggingSystem; import com.jme.widget.WidgetRenderer; import com.jme.scene.state.RenderState; /** * <code>LWJGLRenderer</code> provides an implementation of the * <code>Renderer</code> interface using the LWJGL API. * * @see com.jme.renderer.Renderer * @author Mark Powell * @author Joshua Slack - Optimizations and Headless rendering * @version $Id: LWJGLRenderer.java,v 1.57 2005-02-10 19:04:54 renanse Exp $ */ public class LWJGLRenderer implements Renderer { //clear color private ColorRGBA backgroundColor; //width and height of renderer private int width; private int height; private Vector3f vRot = new Vector3f(); private LWJGLCamera camera; private LWJGLFont font; private long numberOfVerts; private long numberOfTris; private boolean statisticsOn; private boolean usingVBO = false; private LWJGLWireframeState boundsWireState = new LWJGLWireframeState(); private LWJGLTextureState boundsTextState = new LWJGLTextureState(); private LWJGLZBufferState boundsZState = new LWJGLZBufferState(); private boolean inOrthoMode; private boolean processingQueue; private RenderQueue queue; private Vector3f tempVa = new Vector3f(); private DisplayMode mode = Display.getDisplayMode(); private FloatBuffer prevVerts; private FloatBuffer prevNorms; private FloatBuffer prevColor; private FloatBuffer[] prevTex; private boolean headless = false; /** * Constructor instantiates a new <code>LWJGLRenderer</code> object. The * size of the rendering window is passed during construction. * * @param width * the width of the rendering context. * @param height * the height of the rendering context. */ public LWJGLRenderer(int width, int height) { if (width <= 0 || height <= 0) { LoggingSystem.getLogger().log(Level.WARNING, "Invalid width " + "and/or height values."); throw new JmeException("Invalid width and/or height values."); } this.width = width; this.height = height; LoggingSystem.getLogger().log(Level.INFO, "LWJGLRenderer created. W: " + width + "H: " + height); queue = new RenderQueue(this); prevTex = new FloatBuffer[createTextureState().getNumberOfUnits()]; } /** * Reinitialize the renderer with the given width/height. Also calls resize * on the attached camera if present. * * @param width * int * @param height * int */ public void reinit(int width, int height) { if (width <= 0 || height <= 0) { LoggingSystem.getLogger().log(Level.WARNING, "Invalid width " + "and/or height values."); throw new JmeException("Invalid width and/or height values."); } this.width = width; this.height = height; if (camera != null) camera.resize(width, height); mode = Display.getDisplayMode(); } /** * <code>setCamera</code> sets the camera this renderer is using. It * asserts that the camera is of type <code>LWJGLCamera</code>. * * @see com.jme.renderer.Renderer#setCamera(com.jme.renderer.Camera) */ public void setCamera(Camera camera) { if (camera instanceof LWJGLCamera) { this.camera = (LWJGLCamera) camera; } } /** * <code>getCamera</code> returns the camera used by this renderer. * * @see com.jme.renderer.Renderer#getCamera() */ public Camera getCamera() { return camera; } /** * <code>createCamera</code> returns a default camera for use with the * LWJGL renderer. * * @param width * the width of the frame. * @param height * the height of the frame. * @return a default LWJGL camera. */ public Camera createCamera(int width, int height) { return new LWJGLCamera(width, height, this); } /** * <code>createAlphaState</code> returns a new LWJGLAlphaState object as a * regular AlphaState. * * @return an AlphaState object. */ public AlphaState createAlphaState() { return new LWJGLAlphaState(); } /** * <code>createAttributeState</code> returns a new LWJGLAttributeState * object as a regular AttributeState. * * @return an AttributeState object. */ public AttributeState createAttributeState() { return new LWJGLAttributeState(); } /** * <code>createCullState</code> returns a new LWJGLCullState object as a * regular CullState. * * @return a CullState object. * @see com.jme.renderer.Renderer#createCullState() */ public CullState createCullState() { return new LWJGLCullState(); } /** * <code>createDitherState</code> returns a new LWJGLDitherState object as * a regular DitherState. * * @return an DitherState object. */ public DitherState createDitherState() { return new LWJGLDitherState(); } /** * <code>createFogState</code> returns a new LWJGLFogState object as a * regular FogState. * * @return an FogState object. */ public FogState createFogState() { return new LWJGLFogState(); } /** * <code>createLightState</code> returns a new LWJGLLightState object as a * regular LightState. * * @return an LightState object. */ public LightState createLightState() { return new LWJGLLightState(); } /** * <code>createMaterialState</code> returns a new LWJGLMaterialState * object as a regular MaterialState. * * @return an MaterialState object. */ public MaterialState createMaterialState() { return new LWJGLMaterialState(); } /** * <code>createShadeState</code> returns a new LWJGLShadeState object as a * regular ShadeState. * * @return an ShadeState object. */ public ShadeState createShadeState() { return new LWJGLShadeState(); } /** * <code>createTextureState</code> returns a new LWJGLTextureState object * as a regular TextureState. * * @return an TextureState object. */ public TextureState createTextureState() { return new LWJGLTextureState(); } /** * <code>createWireframeState</code> returns a new LWJGLWireframeState * object as a regular WireframeState. * * @return an WireframeState object. */ public WireframeState createWireframeState() { return new LWJGLWireframeState(); } /** * <code>createZBufferState</code> returns a new LWJGLZBufferState object * as a regular ZBufferState. * * @return a ZBufferState object. */ public ZBufferState createZBufferState() { return new LWJGLZBufferState(); } /** * <code>createVertexProgramState</code> returns a new * LWJGLVertexProgramState object as a regular VertexProgramState. * * @return a LWJGLVertexProgramState object. */ public VertexProgramState createVertexProgramState() { return new LWJGLVertexProgramState(); } /** * <code>createFragmentProgramState</code> returns a new * LWJGLFragmentProgramState object as a regular FragmentProgramState. * * @return a LWJGLFragmentProgramState object. */ public FragmentProgramState createFragmentProgramState() { return new LWJGLFragmentProgramState(); } /** * <code>createShaderObjectsState</code> returns a new * LWJGLShaderObjectsState object as a regular ShaderObjectsState. * * @return an ShaderObjectsState object. */ public GLSLShaderObjectsState createGLSLShaderObjectsState() { return new LWJGLShaderObjectsState(); } /** * <code>createStencilState</code> returns a new LWJGLStencilState object * as a regular StencilState. * * @return a StencilState object. */ public StencilState createStencilState() { return new LWJGLStencilState(); } /** * <code>setBackgroundColor</code> sets the OpenGL clear color to the * color specified. * * @see com.jme.renderer.Renderer#setBackgroundColor(com.jme.renderer.ColorRGBA) * @param c * the color to set the background color to. */ public void setBackgroundColor(ColorRGBA c) { //if color is null set background to white. if (c == null) { backgroundColor.a = 1.0f; backgroundColor.b = 1.0f; backgroundColor.g = 1.0f; backgroundColor.r = 1.0f; } else { backgroundColor = c; } GL11.glClearColor(backgroundColor.r, backgroundColor.g, backgroundColor.b, backgroundColor.a); } /** * <code>getBackgroundColor</code> retrieves the clear color of the * current OpenGL context. * * @see com.jme.renderer.Renderer#getBackgroundColor() * @return the current clear color. */ public ColorRGBA getBackgroundColor() { return backgroundColor; } /** * <code>clearZBuffer</code> clears the OpenGL depth buffer. * * @see com.jme.renderer.Renderer#clearZBuffer() */ public void clearZBuffer() { GL11.glDisable(GL11.GL_DITHER); GL11.glEnable(GL11.GL_SCISSOR_TEST); GL11.glScissor(0, 0, width, height); GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT); GL11.glDisable(GL11.GL_SCISSOR_TEST); GL11.glEnable(GL11.GL_DITHER); } /** * <code>clearBackBuffer</code> clears the OpenGL color buffer. * * @see com.jme.renderer.Renderer#clearBackBuffer() */ public void clearBackBuffer() { GL11.glDisable(GL11.GL_DITHER); GL11.glEnable(GL11.GL_SCISSOR_TEST); GL11.glScissor(0, 0, width, height); GL11.glClear(GL11.GL_COLOR_BUFFER_BIT); GL11.glDisable(GL11.GL_SCISSOR_TEST); GL11.glEnable(GL11.GL_DITHER); } /** * <code>clearBuffers</code> clears both the color and the depth buffer. * * @see com.jme.renderer.Renderer#clearBuffers() */ public void clearBuffers() { GL11.glDisable(GL11.GL_DITHER); GL11.glEnable(GL11.GL_SCISSOR_TEST); GL11.glScissor(0, 0, width, height); GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); GL11.glDisable(GL11.GL_SCISSOR_TEST); GL11.glEnable(GL11.GL_DITHER); } /** * <code>displayBackBuffer</code> renders any queued items then flips the * rendered buffer (back) with the currently displayed buffer. * * @see com.jme.renderer.Renderer#displayBackBuffer() */ public void displayBackBuffer() { // render queue if needed processingQueue = true; queue.renderBuckets(); if (Spatial.getCurrentState(RenderState.RS_ZBUFFER) != null && !((ZBufferState) Spatial .getCurrentState(RenderState.RS_ZBUFFER)).isWritable()) { if (Spatial.defaultStateList[RenderState.RS_ZBUFFER] != null) Spatial.defaultStateList[RenderState.RS_ZBUFFER].apply(); Spatial.clearCurrentState(RenderState.RS_ZBUFFER); } processingQueue = false; prevColor = prevNorms = prevVerts = null; Arrays.fill(prevTex, null); GL11.glFlush(); if (!headless) Display.update(); } public void setOrtho() { if (inOrthoMode) { throw new JmeException( "Already in Orthographic mode."); } //set up ortho mode GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glPushMatrix(); GL11.glLoadIdentity(); GLU.gluOrtho2D(0, mode.getWidth(), 0, mode.getHeight()); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glPushMatrix(); GL11.glLoadIdentity(); inOrthoMode = true; } public void setOrthoCenter() { if (inOrthoMode) { throw new JmeException( "Already in Orthographic mode."); } //set up ortho mode GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glPushMatrix(); GL11.glLoadIdentity(); GLU.gluOrtho2D(-mode.getWidth() / 2, mode.getWidth() / 2, -mode .getHeight() / 2, mode.getHeight() / 2); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glPushMatrix(); GL11.glLoadIdentity(); inOrthoMode = true; } public void unsetOrtho() { if (!inOrthoMode) { throw new JmeException("Not in Orthographic mode."); } //remove ortho mode, and go back to original // state GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glPopMatrix(); postdrawMesh(); inOrthoMode = false; } /** * <code>takeScreenShot</code> saves the current buffer to a file. The * file name is provided, and .png will be appended. True is returned if the * capture was successful, false otherwise. * * @param filename * the name of the file to save. * @return true if successful, false otherwise. */ public boolean takeScreenShot(String filename) { if (null == filename) { throw new JmeException( "Screenshot filename cannot be null"); } LoggingSystem.getLogger().log(Level.INFO, "Taking screenshot: " + filename + ".png"); //Create a pointer to the image info and create a buffered image to //hold it. IntBuffer buff = BufferUtils.createIntBuffer(width * height); grabScreenContents(buff, 0,0,width,height); BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //Grab each pixel information and set it to the BufferedImage info. for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { img.setRGB(x, y, buff.get((height - y - 1) * width + x)); } } //write out the screenshot image to a file. try { File out = new File(filename + ".png"); return ImageIO.write(img, "png", out); } catch (IOException e) { LoggingSystem.getLogger().log(Level.WARNING, "Could not create file: " + filename + ".png"); return false; } } /** * <code>grabScreenContents</code> reads a block of pixels from the * current framebuffer. * * @param buff * a buffer to store contents in. * @param x - * x starting point of block * @param y - * y starting point of block * @param w - * width of block * @param h - * height of block */ public void grabScreenContents(IntBuffer buff, int x, int y, int w, int h) { GL11.glReadPixels(x, y, w, h, GL12.GL_BGRA, GL11.GL_UNSIGNED_BYTE, buff); } /** * <code>draw</code> draws a point object where a point contains a * collection of vertices, normals, colors and texture coordinates. * * @see com.jme.renderer.Renderer#draw(com.jme.scene.Point) * @param p * the point object to render. */ public void draw(Point p) { // set world matrix Quaternion rotation = p.getWorldRotation(); Vector3f translation = p.getWorldTranslation(); Vector3f scale = p.getWorldScale(); float rot = rotation.toAngleAxis(vRot); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glPushMatrix(); GL11.glTranslatef(translation.x, translation.y, translation.z); GL11.glRotatef(rot, vRot.x, vRot.y, vRot.z); GL11.glScalef(scale.x, scale.y, scale.z); // render the object GL11.glBegin(GL11.GL_POINTS); // draw points Vector3f[] vertex = p.getVertices(); Vector3f[] normal = p.getNormals(); ColorRGBA[] color = p.getColors(); Vector2f[] texture = p.getTextures(); if (statisticsOn) { numberOfVerts += vertex.length; } if (normal != null) { if (color != null) { if (texture != null) { // N,C,T for (int i = 0; i < vertex.length; i++) { GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z); GL11.glColor4f(color[i].r, color[i].g, color[i].b, color[i].a); GL11.glTexCoord2f(texture[i].x, texture[i].y); GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z); } } else { for (int i = 0; i < vertex.length; i++) { GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z); GL11.glColor4f(color[i].r, color[i].g, color[i].b, color[i].a); GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z); } } } else { if (texture != null) { for (int i = 0; i < vertex.length; i++) { GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z); GL11.glTexCoord2f(texture[i].x, texture[i].y); GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z); } } else { for (int i = 0; i < vertex.length; i++) { GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z); GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z); } } } } else { if (color != null) { if (texture != null) { for (int i = 0; i < vertex.length; i++) { GL11.glColor4f(color[i].r, color[i].g, color[i].b, color[i].a); GL11.glTexCoord2f(texture[i].x, texture[i].y); GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z); } } else { for (int i = 0; i < vertex.length; i++) { GL11.glColor4f(color[i].r, color[i].g, color[i].b, color[i].a); GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z); } } } else { if (texture != null) { for (int i = 0; i < vertex.length; i++) { GL11.glTexCoord2f(texture[i].x, texture[i].y); GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z); } } else { // none for (int i = 0; i < vertex.length; i++) { GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z); } } } } GL11.glEnd(); postdrawMesh(); } /** * <code>draw</code> draws a line object where a line contains a * collection of vertices, normals, colors and texture coordinates. * * @see com.jme.renderer.Renderer#draw(com.jme.scene.Line) * @param l * the line object to render. */ public void draw(Line l) { // set world matrix Quaternion rotation = l.getWorldRotation(); Vector3f translation = l.getWorldTranslation(); Vector3f scale = l.getWorldScale(); float rot = rotation.toAngleAxis(vRot); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glPushMatrix(); GL11.glTranslatef(translation.x, translation.y, translation.z); GL11.glRotatef(rot, vRot.x, vRot.y, vRot.z); GL11.glScalef(scale.x, scale.y, scale.z); // render the object GL11.glBegin(GL11.GL_LINES); // draw line Vector3f[] vertex = l.getVertices(); Vector3f[] normal = l.getNormals(); ColorRGBA[] color = l.getColors(); Vector2f[] texture = l.getTextures(); if (statisticsOn) { numberOfVerts += vertex.length; } if (normal != null) { if (color != null) { if (texture != null) { // N,C,T for (int i = 0; i < vertex.length - 1; i++) { GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z); GL11.glColor4f(color[i].r, color[i].g, color[i].b, color[i].a); GL11.glTexCoord2f(texture[i].x, texture[i].y); GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z); i++; GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z); GL11.glColor4f(color[i].r, color[i].g, color[i].b, color[i].a); GL11.glTexCoord2f(texture[i].x, texture[i].y); GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z); } } else { for (int i = 0; i < vertex.length - 1; i++) { GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z); GL11.glColor4f(color[i].r, color[i].g, color[i].b, color[i].a); GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z); i++; GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z); GL11.glColor4f(color[i].r, color[i].g, color[i].b, color[i].a); GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z); } } } else { if (texture != null) { for (int i = 0; i < vertex.length - 1; i++) { GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z); GL11.glTexCoord2f(texture[i].x, texture[i].y); GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z); i++; GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z); GL11.glTexCoord2f(texture[i].x, texture[i].y); GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z); } } else { for (int i = 0; i < vertex.length - 1; i++) { GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z); GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z); i++; GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z); GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z); } } } } else { if (color != null) { if (texture != null) { for (int i = 0; i < vertex.length - 1; i++) { GL11.glColor4f(color[i].r, color[i].g, color[i].b, color[i].a); GL11.glTexCoord2f(texture[i].x, texture[i].y); GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z); i++; GL11.glColor4f(color[i].r, color[i].g, color[i].b, color[i].a); GL11.glTexCoord2f(texture[i].x, texture[i].y); GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z); } } else { for (int i = 0; i < vertex.length - 1; i++) { GL11.glColor4f(color[i].r, color[i].g, color[i].b, color[i].a); GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z); i++; GL11.glColor4f(color[i].r, color[i].g, color[i].b, color[i].a); GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z); } } } else { if (texture != null) { for (int i = 0; i < vertex.length - 1; i++) { GL11.glTexCoord2f(texture[i].x, texture[i].y); GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z); i++; GL11.glTexCoord2f(texture[i].x, texture[i].y); GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z); } } else { // none for (int i = 0; i < vertex.length - 1; i++) { GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z); i++; GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z); } } } } GL11.glEnd(); postdrawMesh(); } /** * <code>draw</code> renders a curve object. * * @param c * the curve object to render. */ public void draw(Curve c) { // set world matrix Quaternion rotation = c.getWorldRotation(); Vector3f translation = c.getWorldTranslation(); Vector3f scale = c.getWorldScale(); float rot = rotation.toAngleAxis(vRot); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glPushMatrix(); GL11.glTranslatef(translation.x, translation.y, translation.z); GL11.glRotatef(rot, vRot.x, vRot.y, vRot.z); GL11.glScalef(scale.x, scale.y, scale.z); // render the object GL11.glBegin(GL11.GL_LINE_STRIP); ColorRGBA[] color = c.getColors(); float colorInterval = 0; float colorModifier = 0; int colorCounter = 0; if (null != color) { GL11.glColor4f(color[0].r, color[0].g, color[0].b, color[0].a); colorInterval = 1f / c.getColors().length; colorModifier = colorInterval; colorCounter = 0; } Vector3f point; float limit = (1 + (1.0f / c.getSteps())); for (float t = 0; t <= limit; t += 1.0f / c.getSteps()) { if (t >= colorInterval && color != null) { colorInterval += colorModifier; GL11.glColor4f(c.getColors()[colorCounter].r, c.getColors()[colorCounter].g, c.getColors()[colorCounter].b, c.getColors()[colorCounter].a); colorCounter++; } point = c.getPoint(t, tempVa); GL11.glVertex3f(point.x, point.y, point.z); } if (statisticsOn) { numberOfVerts += limit; } GL11.glEnd(); postdrawMesh(); } /** * <code>draw</code> renders a <code>TriMesh</code> object including * it's normals, colors, textures and vertices. * * @see com.jme.renderer.Renderer#draw(com.jme.scene.TriMesh) * @param t * the mesh to render. */ public void draw(TriMesh t) { predrawMesh(t); IntBuffer indices = t.getIndexAsBuffer(); int verts = (t.getVertQuantity() >= 0 ? t.getVertQuantity() : t.getVertices().length); if (statisticsOn) { numberOfTris += (t.getTriangleQuantity() >= 0 ? t .getTriangleQuantity() : t.getIndices().length / 3); numberOfVerts += verts; } if (GLContext.OpenGL12) GL12.glDrawRangeElements(GL11.GL_TRIANGLES, 0, verts, indices); else GL11.glDrawElements(GL11.GL_TRIANGLES, indices); postdrawMesh(); } /** * <code>draw</code> renders a <code>CompositeMesh</code> object * including it's normals, colors, textures and vertices. * * @see com.jme.renderer.Renderer#draw(com.jme.scene.CompositeMesh) * @param t * the mesh to render. */ public void draw(CompositeMesh t) { predrawMesh(t); IntBuffer indices = t.getIndexAsBuffer().duplicate(); CompositeMesh.IndexRange[] ranges = t.getIndexRanges(); int verts = (t.getVertQuantity() >= 0 ? t.getVertQuantity() : t.getVertices().length); if (statisticsOn) { numberOfVerts += verts; numberOfTris += t.getTriangleQuantity(); } indices.position(0); for (int i = 0; i < ranges.length; i++) { int mode; switch (ranges[i].getKind()) { case CompositeMesh.IndexRange.TRIANGLES: mode = GL11.GL_TRIANGLES; break; case CompositeMesh.IndexRange.TRIANGLE_STRIP: mode = GL11.GL_TRIANGLE_STRIP; break; case CompositeMesh.IndexRange.TRIANGLE_FAN: mode = GL11.GL_TRIANGLE_FAN; break; case CompositeMesh.IndexRange.QUADS: mode = GL11.GL_QUADS; break; case CompositeMesh.IndexRange.QUAD_STRIP: mode = GL11.GL_QUAD_STRIP; break; default: throw new JmeException("Unknown index range type " + ranges[i].getKind()); } indices.limit(indices.position() + ranges[i].getCount()); if (GLContext.OpenGL12) GL12.glDrawRangeElements(mode, 0, verts, indices); else GL11.glDrawElements(mode, indices); indices.position(indices.limit()); } postdrawMesh(); } IntBuffer buf = BufferUtils.createIntBuffer(16); public void prepVBO(Geometry g) { if (!GLContext.OpenGL15) return; int verts = g.getVertices().length; if (g.isVBOVertexEnabled() && g.getVBOVertexID() <= 0) { g.updateVertexBuffer(g.getVertices().length); GL15.glGenBuffers(buf); g.setVBOVertexID(buf.get(0)); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, g.getVBOVertexID()); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, verts * 3 * 4, g .getVerticeAsFloatBuffer(), GL15.GL_STATIC_DRAW); buf.clear(); } if (g.isVBONormalEnabled() && g.getVBONormalID() <= 0) { g.updateNormalBuffer(g.getVertices().length); GL15.glGenBuffers(buf); g.setVBONormalID(buf.get(0)); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, g.getVBONormalID()); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, verts * 3 * 4, g .getNormalAsFloatBuffer(), GL15.GL_STATIC_DRAW); buf.clear(); } if (g.isVBOColorEnabled() && g.getVBOColorID() <= 0) { g.updateColorBuffer(g.getVertices().length); GL15.glGenBuffers(buf); g.setVBOColorID(buf.get(0)); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, g.getVBOColorID()); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, verts * 4 * 4, g .getColorAsFloatBuffer(), GL15.GL_STATIC_DRAW); buf.clear(); } if (g.isVBOTextureEnabled()) { for (int i = 0; i < g.getNumberOfUnits(); i++) { if (g.getVBOTextureID(i) <= 0 && g.getTextureAsFloatBuffer(i) != null) { g.updateTextureBuffer(i, g.getVertices().length); GL15.glGenBuffers(buf); g.setVBOTextureID(i, buf.get(0)); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, g .getVBOTextureID(i)); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, verts * 2 * 4, g .getTextureAsFloatBuffer(i), GL15.GL_STATIC_DRAW); buf.clear(); } } } buf.clear(); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); } /** * <code>draw</code> renders a <code>TriMesh</code> object including * it's normals, colors, textures and vertices. * * @see com.jme.renderer.Renderer#draw(com.jme.scene.TriMesh) * @param g * the mesh to render. */ public void drawBounds(Geometry g) { // get the bounds if (!(g.getWorldBound() instanceof TriMesh)) return; drawBounds(g.getWorldBound()); } /** * <code>draw</code> renders a <code>TriMesh</code> object including * it's normals, colors, textures and vertices. * * @see com.jme.renderer.Renderer#draw(com.jme.scene.TriMesh) * @param bv * the mesh to render. */ public void drawBounds(BoundingVolume bv) { // get the bounds if (!(bv instanceof TriMesh)) return; bv.recomputeMesh(); setBoundsStates(true); draw((TriMesh) bv); setBoundsStates(false); } /** * <code>draw</code> renders a scene by calling the nodes * <code>onDraw</code> method. * * @see com.jme.renderer.Renderer#draw(com.jme.scene.Spatial) */ public void draw(Spatial s) { if (s != null) { s.onDraw(this); } } /** * <code>drawBounds</code> renders a scene by calling the nodes * <code>onDraw</code> method. * * @see com.jme.renderer.Renderer#draw(com.jme.scene.Spatial) */ public void drawBounds(Spatial s) { if (s != null) { s.onDrawBounds(this); } } /** * <code>draw</code> renders a text object using a predefined font. * * @see com.jme.renderer.Renderer#draw(com.jme.scene.Text) */ public void draw(Text t) { if (font == null) { font = new LWJGLFont(); } font.setColor(t.getTextColor()); font.print((int) t.getWorldTranslation().x, (int) t .getWorldTranslation().y, t.getWorldScale(), t.getText(), 0); } /** * <code>draw</code> renders a WidgetRenderer object to the back buffer. * * @see com.jme.renderer.Renderer#draw(WidgetRenderer) */ public void draw(WidgetRenderer wr) { wr.render(); } /** * <code>enableStatistics</code> will turn on statistics gathering. * * @param value * true to use statistics, false otherwise. */ public void enableStatistics(boolean value) { statisticsOn = value; } /** * <code>clearStatistics</code> resets the vertices and triangles counter * for the statistics information. */ public void clearStatistics() { numberOfVerts = 0; numberOfTris = 0; } /** * <code>getStatistics</code> returns a string value of the rendering * statistics information (number of triangles and number of vertices). * * @return the string representation of the current statistics. */ public String getStatistics() { return "Number of Triangles: " + numberOfTris + " : Number of Vertices: " + numberOfVerts; } /** * <code>getStatistics</code> returns a string value of the rendering * statistics information (number of triangles and number of vertices). * * @return the string representation of the current statistics. */ public StringBuffer getStatistics(StringBuffer a) { a.setLength(0); a.append("Number of Triangles: ").append(numberOfTris).append( " : Number of Vertices: ").append(numberOfVerts); return a; } /** * See Renderer.isHeadless() * * @return boolean */ public boolean isHeadless() { return headless; } /** * See Renderer.setHeadless() * * @return boolean */ public void setHeadless(boolean headless) { this.headless = headless; } public boolean checkAndAdd(Spatial s) { int rqMode = s.getRenderQueueMode(); if (rqMode != Renderer.QUEUE_SKIP) { getQueue().addToQueue(s, rqMode); return true; } return false; } public RenderQueue getQueue() { return queue; } public boolean isProcessingQueue() { return processingQueue; } /** * Return true if the system running this supports VBO * * @return boolean true if VBO supported */ public boolean supportsVBO() { return GLContext.OpenGL15; } public int getWidth() { return width; } public int getHeight() { return height; } private void postdrawMesh() { GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glPopMatrix(); } /** * @param t */ private void predrawMesh(TriMesh t) { // set world matrix Quaternion rotation = t.getWorldRotation(); Vector3f translation = t.getWorldTranslation(); Vector3f scale = t.getWorldScale(); float rot = rotation.toAngleAxis(vRot); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glPushMatrix(); GL11.glTranslatef(translation.x, translation.y, translation.z); GL11.glRotatef(rot, vRot.x, vRot.y, vRot.z); GL11.glScalef(scale.x, scale.y, scale.z); if (!(scale.x == 1 && scale.y == 1 && scale.z == 1)) GL11.glEnable(GL11.GL_NORMALIZE); // since we are using // glScalef, we should enable // this to keep normals // working. prepVBO(t); // render the object FloatBuffer verticies = t.getVerticeAsFloatBuffer(); if (prevVerts != verticies) { GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY); if (t.isVBOVertexEnabled() && GLContext.OpenGL15) { usingVBO = true; GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, t.getVBOVertexID()); GL11.glVertexPointer(3, GL11.GL_FLOAT, 0, 0); } else { if (usingVBO) GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); GL11.glVertexPointer(3, 0, t.getVerticeAsFloatBuffer()); } } prevVerts = verticies; FloatBuffer normals = t.getNormalAsFloatBuffer(); if (prevNorms != normals) { if (normals != null || t.getVBONormalID() > 0) { GL11.glEnableClientState(GL11.GL_NORMAL_ARRAY); if (t.isVBONormalEnabled() && GLContext.OpenGL15) { usingVBO = true; GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, t.getVBONormalID()); GL11.glNormalPointer(GL11.GL_FLOAT, 0, 0); } else { if (usingVBO) GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); GL11.glNormalPointer(0, normals); } } else { GL11.glDisableClientState(GL11.GL_NORMAL_ARRAY); } } prevNorms = normals; FloatBuffer colors = t.getColorAsFloatBuffer(); if (colors == null || prevColor != colors) { if (colors != null || t.getVBOColorID() > 0) { GL11.glEnableClientState(GL11.GL_COLOR_ARRAY); if (t.isVBOColorEnabled() && GLContext.OpenGL15) { usingVBO = true; GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, t.getVBOColorID()); GL11.glColorPointer(4, GL11.GL_FLOAT, 0, 0); } else { if (usingVBO) GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); GL11.glColorPointer(4, 0, colors); } prevColor = colors; } else { GL11.glDisableClientState(GL11.GL_COLOR_ARRAY); } } for (int i = 0; i < t.getNumberOfUnits(); i++) { FloatBuffer textures = t.getTextureAsFloatBuffer(i); if (prevTex[i] != textures && textures != null) { if (GLContext.GL_ARB_multitexture && GLContext.OpenGL13) { GL13.glClientActiveTexture(GL13.GL_TEXTURE0 + i); } if (textures != null || t.getVBOTextureID(i) > 0) { GL11.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY); if (t.isVBOTextureEnabled() && GLContext.OpenGL15) { usingVBO = true; GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, t .getVBOTextureID(i)); GL11.glTexCoordPointer(2, GL11.GL_FLOAT, 0, 0); } else { if (usingVBO) GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); GL11.glTexCoordPointer(2, 0, textures); } } else { GL11.glDisableClientState(GL11.GL_TEXTURE_COORD_ARRAY); } } prevTex[i] = textures; } } /** * * <code>setBoundsStates</code> sets the rendering states for bounding * volumes, this includes wireframe and zbuffer. * * @param enabled * true if these states are to be enabled, false otherwise. */ private void setBoundsStates(boolean enabled) { boundsTextState.apply(); // not enabled -- no texture boundsWireState.setEnabled(enabled); boundsWireState.apply(); boundsZState.setEnabled(enabled); boundsZState.apply(); } }
package liquibase.database.core; import liquibase.CatalogAndSchema; import liquibase.database.AbstractJdbcDatabase; import liquibase.database.DatabaseConnection; import liquibase.database.OfflineConnection; import liquibase.database.jvm.JdbcConnection; import liquibase.exception.DatabaseException; import liquibase.executor.ExecutorService; import liquibase.logging.LogService; import liquibase.logging.LogType; import liquibase.logging.Logger; import liquibase.statement.core.RawSqlStatement; import liquibase.structure.DatabaseObject; import java.sql.Driver; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Arrays; import java.util.Enumeration; import java.util.Locale; public class DerbyDatabase extends AbstractJdbcDatabase { protected int driverVersionMajor; protected int driverVersionMinor; private Logger log = LogService.getLog(getClass()); private boolean shutdownEmbeddedDerby = true; public DerbyDatabase() { super.setCurrentDateTimeFunction("CURRENT_TIMESTAMP"); super.sequenceNextValueFunction = "NEXT VALUE FOR %s"; super.sequenceCurrentValueFunction = "(SELECT currentvalue FROM sys.syssequences WHERE sequencename = upper('%s'))"; determineDriverVersion(); this.addReservedWords(Arrays.asList("ABSOLUTE", "ACTION", "ADD", "AFTER", "ALL", "ALLOCATE", "ALTER", "AND", "ANY", "ARE", "ARRAY", "AS", "ASC", "ASENSITIVE", "ASSERTION", "ASYMMETRIC", "AT", "ATOMIC", "AUTHORIZATION", "AVG", "BEFORE", "BEGIN", "BETWEEN", "BIGINT", "BINARY", "BIT", "BIT_LENGTH", "BLOB", "BOOLEAN", "BOTH", "BREADTH", "BY", "CALL", "CALLED", "CASCADE", "CASCADED", "CASE", "CAST", "CATALOG", "CHAR", "CHARACTER", "CHARACTER_LENGTH", "CHAR_LENGTH", "CHECK", "CLOB", "CLOSE", "COALESCE", "COLLATE", "COLLATION", "COLUMN", "COMMIT", "CONDITION", "CONNECT", "CONNECTION", "CONSTRAINT", "CONSTRAINTS", "CONSTRUCTOR", "CONTAINS", "CONTINUE", "CONVERT", "CORRESPONDING", "COUNT", "CREATE", "CROSS", "CUBE", "CURRENT", "CURRENT_DATE", "CURRENT_DEFAULT_TRANSFORM_GROUP", "CURRENT_PATH", "CURRENT_ROLE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_TRANSFORM_GROUP_FOR_TYPE", "CURRENT_USER", "CURSOR", "CYCLE", "DATA", "DATE", "DAY", "DEALLOCATE", "DEC", "DECIMAL", "DECLARE", "DEFAULT", "DEFERRABLE", "DEFERRED", "DELETE", "DEPTH", "DEREF", "DESC", "DESCRIBE", "DESCRIPTOR", "DETERMINISTIC", "DIAGNOSTICS", "DISCONNECT", "DISTINCT", "DO", "DOMAIN", "DOUBLE", "DROP", "DYNAMIC", "EACH", "ELEMENT", "ELSE", "ELSEIF", "END", "EQUALS", "ESCAPE", "EXCEPT", "EXCEPTION", "EXEC", "EXECUTE", "EXISTS", "EXIT", "EXTERNAL", "EXTRACT", "FALSE", "FETCH", "FILTER", "FIRST", "FLOAT", "FOR", "FOREIGN", "FOUND", "FREE", "FROM", "FULL", "FUNCTION", "GENERAL", "GET", "GLOBAL", "GO", "GOTO", "GRANT", "GROUP", "GROUPING", "HANDLER", "HAVING", "HOLD", "HOUR", "IDENTITY", "IF", "IMMEDIATE", "IN", "INDICATOR", "INITIALLY", "INNER", "INOUT", "INPUT", "INSENSITIVE", "INSERT", "INT", "INTEGER", "INTERSECT", "INTERVAL", "INTO", "IS", "ISOLATION", "ITERATE", "JOIN", "KEY", "LANGUAGE", "LARGE", "LAST", "LATERAL", "LEADING", "LEAVE", "LEFT", "LEVEL", "LIKE", "LOCAL", "LOCALTIME", "LOCALTIMESTAMP", "LOCATOR", "LOOP", "LOWER", "MAP", "MATCH", "MAX", "MEMBER", "MERGE", "METHOD", "MIN", "MINUTE", "MODIFIES", "MODULE", "MONTH", "MULTISET", "NAMES", "NATIONAL", "NATURAL", "NCHAR", "NCLOB", "NEW", "NEXT", "NO", "NONE", "NOT", "NULL", "NULLIF", "NUMERIC", "OBJECT", "OCTET_LENGTH", "OF", "OLD", "ON", "ONLY", "OPEN", "OPTION", "OR", "ORDER", "ORDINALITY", "OUT", "OUTER", "OUTPUT", "OVER", "OVERLAPS", "PAD", "PARAMETER", "PARTIAL", "PARTITION", "PATH", "POSITION", "PRECISION", "PREPARE", "PRESERVE", "PRIMARY", "PRIOR", "PRIVILEGES", "PROCEDURE", "PUBLIC", "RANGE", "READ", "READS", "REAL", "RECURSIVE", "REF", "REFERENCES", "REFERENCING", "RELATIVE", "RELEASE", "REPEAT", "RESIGNAL", "RESTRICT", "RESULT", "RETURN", "RETURNS", "REVOKE", "RIGHT", "ROLE", "ROLLBACK", "ROLLUP", "ROUTINE", "ROW", "ROWS", "SAVEPOINT", "SCHEMA", "SCOPE", "SCROLL", "SEARCH", "SECOND", "SECTION", "SELECT", "SENSITIVE", "SESSION", "SESSION_USER", "SET", "SETS", "SIGNAL", "SIMILAR", "SIZE", "SMALLINT", "SOME", "SPACE", "SPECIFIC", "SPECIFICTYPE", "SQL", "SQLCODE", "SQLERROR", "SQLEXCEPTION", "SQLSTATE", "SQLWARNING", "START", "STATE", "STATIC", "SUBMULTISET", "SUBSTRING", "SUM", "SYMMETRIC", "SYSTEM", "SYSTEM_USER", "TABLE", "TABLESAMPLE", "TEMPORARY", "THEN", "TIME", "TIMESTAMP", "TIMEZONE_HOUR", "TIMEZONE_MINUTE", "TO", "TRAILING", "TRANSACTION", "TRANSLATE", "TRANSLATION", "TREAT", "TRIGGER", "TRIM", "TRUE", "UNDER", "UNDO", "UNION", "UNIQUE", "UNKNOWN", "UNNEST", "UNTIL", "UPDATE", "UPPER", "USAGE", "USER", "USING", "VALUE", "VALUES", "VARCHAR", "VARYING", "VIEW", "WHEN", "WHENEVER", "WHERE", "WHILE", "WINDOW", "WITH", "WITHIN", "WITHOUT", "WORK", "WRITE", "YEAR", "ZONE")); } @Override public boolean isCorrectDatabaseImplementation(DatabaseConnection conn) throws DatabaseException { return "Apache Derby".equalsIgnoreCase(conn.getDatabaseProductName()); } @Override public String getDefaultDriver(String url) { // CORE-1230 - don't shutdown derby network server if (url.startsWith("jdbc:derby: return "org.apache.derby.jdbc.ClientDriver"; } else if (url.startsWith("jdbc:derby") || url.startsWith("java:derby")) { return "org.apache.derby.jdbc.EmbeddedDriver"; } return null; } @Override public int getPriority() { return PRIORITY_DEFAULT; } @Override public boolean supportsSchemas() { return false; } @Override public boolean jdbcCallsCatalogsSchemas() { return true; } @Override public Integer getDefaultPort() { return 1527; } @Override protected String getDefaultDatabaseProductName() { return "Derby"; } @Override public String correctObjectName(String objectName, Class<? extends DatabaseObject> objectType) { if (objectName == null) { return null; } return objectName.toUpperCase(Locale.US); } @Override public String getShortName() { return "derby"; } public boolean getShutdownEmbeddedDerby() { return shutdownEmbeddedDerby; } public void setShutdownEmbeddedDerby(boolean shutdown) { this.shutdownEmbeddedDerby = shutdown; } @Override public boolean supportsSequences() { return ((driverVersionMajor == 10) && (driverVersionMinor >= 6)) || (driverVersionMajor >= 11); } @Override public boolean supportsInitiallyDeferrableColumns() { return false; } @Override public String getDateLiteral(String isoDate) { if (isDateOnly(isoDate)) { return "DATE(" + super.getDateLiteral(isoDate) + ")"; } else if (isTimeOnly(isoDate)) { return "TIME(" + super.getDateLiteral(isoDate) + ")"; } else { String dateString = super.getDateLiteral(isoDate); int decimalDigits = dateString.length() - dateString.indexOf('.') - 2; String padding = ""; for (int i=6; i> decimalDigits; i padding += "0"; } return "TIMESTAMP(" + dateString.replaceFirst("'$", padding+"'") + ")"; } } @Override public boolean supportsTablespaces() { return false; } @Override public String getViewDefinition(CatalogAndSchema schema, String name) throws DatabaseException { return super.getViewDefinition(schema, name).replaceFirst("CREATE VIEW \\w+ AS ", ""); } @Override public void close() throws DatabaseException { String url = getConnection().getURL(); String driverName = getDefaultDriver(url); super.close(); if (getShutdownEmbeddedDerby() && (driverName != null) && driverName.toLowerCase().contains("embedded")) { shutdownDerby(url, driverName); } } protected void shutdownDerby(String url, String driverName) throws DatabaseException { try { if (url.contains(";")) { url = url.substring(0, url.indexOf(";")) + ";shutdown=true"; } else { url += ";shutdown=true"; } LogService.getLog(getClass()).info(LogType.LOG, "Shutting down derby connection: " + url); // this cleans up the lock files in the embedded derby database folder JdbcConnection connection = (JdbcConnection) getConnection(); ClassLoader classLoader = connection.getWrappedConnection().getClass().getClassLoader(); Driver driver = (Driver) classLoader.loadClass(driverName).getConstructor().newInstance(); // this cleans up the lock files in the embedded derby database folder driver.connect(url, null); } catch (Exception e) { if (e instanceof SQLException) { String state = ((SQLException) e).getSQLState(); if ("XJ015".equals(state) || "08006".equals(state)) { // "The XJ015 error (successful shutdown of the Derby engine) and the 08006 // error (successful shutdown of a single database) are the only exceptions // thrown by Derby that might indicate that an operation succeeded. All other // exceptions indicate that an operation failed." return; } } throw new DatabaseException("Error closing derby cleanly", e); } } /** * Determine Apache Derby driver major/minor version. */ @SuppressWarnings({ "static-access", "unchecked" }) protected void determineDriverVersion() { try { // Locate the Derby sysinfo class and query its version info Enumeration<Driver> it = DriverManager.getDrivers(); while (it.hasMoreElements()) { Driver driver = it.nextElement(); if (driver.getClass().getName().contains("derby")) { driverVersionMajor = driver.getMajorVersion(); driverVersionMinor = driver.getMinorVersion(); return; } } // log.debug("Unable to load/access Apache Derby driver class " + "to check version"); driverVersionMajor = 10; driverVersionMinor = 6; } catch (Exception e) { driverVersionMajor = 10; driverVersionMinor = 6; } } @Override protected String getConnectionCatalogName() throws DatabaseException { if ((getConnection() == null) || (getConnection() instanceof OfflineConnection)) { return null; } try { return ExecutorService.getInstance().getExecutor("jdbc", this).queryForObject(new RawSqlStatement("select current schema from sysibm.sysdummy1"), String.class); } catch (Exception e) { LogService.getLog(getClass()).info(LogType.LOG, "Error getting default schema", e); } return null; } @Override public boolean supportsCatalogInObjectName(Class<? extends DatabaseObject> type) { return true; } public boolean supportsBooleanDataType() { if (getConnection() == null) { return false; ///assume not; } try { return (this.getDatabaseMajorVersion() > 10) || ((this.getDatabaseMajorVersion() == 10) && (this .getDatabaseMinorVersion() > 7)); } catch (DatabaseException e) { return false; //assume not } } @Override public int getMaxFractionalDigitsForTimestamp() { // According to return 9; } }
package com.kSaNa75.superkaburobo; import java.util.ArrayList; import jp.tradesc.superkaburobo.sdk.robot.AbstractRobot; import jp.tradesc.superkaburobo.sdk.trade.TradeAgent; // Screening import jp.tradesc.superkaburobo.sdk.trade.InformationManager; import jp.tradesc.superkaburobo.sdk.trade.data.Stock; // Asset import jp.tradesc.superkaburobo.sdk.trade.AssetManager; // Order import jp.tradesc.superkaburobo.sdk.trade.OrderManager; // log import com.kSaNa75.log.*; import com.kSaNa75.log.logger75.level; public class TradeRobot extends AbstractRobot { @Override public void order(TradeAgent arg0) { InformationManager im = InformationManager.getInstance(); ArrayList<Stock> stockList = im.getStockList(); Stock stock = stockList.get(0); OrderManager om = OrderManager.getInstance(); int quantity = stock.getUnit(); om.orderActualNowMarket(stock, quantity); } @Override public void screening(TradeAgent arg0) { // Asset AssetManager am = AssetManager.getInstance(); logger75.i(":" + am.getTotalAssetValue()); logger75.i(":" + am.getTotalStockValue()); logger75.i(":" + am.getTradableMoney()); // Screening InformationManager im = InformationManager.getInstance(); ArrayList<Stock> stockList = im.getStockList(); for (Stock stock:stockList) { logger75.i(stock.getStockName()); } } }
package swift.pubsub; import static sys.net.api.Networking.Networking; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import swift.crdt.core.CRDTIdentifier; import swift.dc.DCConstants; import swift.proto.MetadataStatsCollector; import swift.proto.PubSubHandshake; import swift.proto.SwiftProtocolHandler; import swift.proto.UnsubscribeUpdatesReply; import swift.proto.UnsubscribeUpdatesRequest; import sys.net.api.Endpoint; import sys.net.api.rpc.RpcEndpoint; import sys.net.api.rpc.RpcHandle; import sys.pubsub.PubSubNotification; import sys.pubsub.impl.AbstractPubSub; import sys.scheduler.Task; import sys.utils.FifoQueue; abstract public class ScoutPubSubService extends AbstractPubSub<CRDTIdentifier> implements SwiftSubscriber { private final static Object dummyVal = new Object(); final Endpoint suPubSub; final RpcEndpoint endpoint; final Map<CRDTIdentifier, Object> unsubscriptions = new ConcurrentHashMap<CRDTIdentifier, Object>(); final Task updater; private boolean disasterSafeSession; private MetadataStatsCollector statsCollector; final FifoQueue<PubSubNotification<CRDTIdentifier>> fifoQueue; public ScoutPubSubService(final String clientId, boolean disasterSafeSession, final Endpoint surrogate, final MetadataStatsCollector statsCollector) { super(clientId); this.disasterSafeSession = disasterSafeSession; this.statsCollector = statsCollector; // process incoming events observing source fifo order... this.fifoQueue = new FifoQueue<PubSubNotification<CRDTIdentifier>>() { public void process(PubSubNotification<CRDTIdentifier> event) { event.notifyTo(ScoutPubSubService.this); } }; this.suPubSub = Networking.resolve(surrogate.getHost(), surrogate.getPort() + 1); this.endpoint = Networking.rpcConnect().toService(0, new SwiftProtocolHandler() { @Override public void onReceive(BatchUpdatesNotification evt) { fifoQueue.offer(evt.seqN(), evt); } }); // FIXME: make sure this is reliable! this.endpoint.send(suPubSub, new PubSubHandshake(clientId, disasterSafeSession)); updater = new Task(5) { public void run() { updateSurrogatePubSub(); } }; } private void updateSurrogatePubSub() { final Set<CRDTIdentifier> uset = new HashSet<CRDTIdentifier>(unsubscriptions.keySet()); final UnsubscribeUpdatesRequest request = new UnsubscribeUpdatesRequest(-1L, super.id(), disasterSafeSession, uset); request.recordMetadataSample(statsCollector); endpoint.send(suPubSub, request, new SwiftProtocolHandler() { public void onReceive(RpcHandle conn, UnsubscribeUpdatesReply ack) { unsubscriptions.keySet().removeAll(uset); ack.recordMetadataSample(statsCollector); } }, 0); } public void subscribe(CRDTIdentifier key) { unsubscriptions.remove(key); super.subscribe(key, this); } public void unsubscribe(CRDTIdentifier key) { if (super.unsubscribe(key, this)) { unsubscriptions.put(key, dummyVal); if (!updater.isScheduled()) updater.reSchedule(0.1); } } public SortedSet<CRDTIdentifier> keys() { return new TreeSet<CRDTIdentifier>(super.subscribers.keySet()); } @Override public void onNotification(BatchUpdatesNotification evt) { Thread.dumpStack(); } @Override public void onNotification(PubSubNotification<CRDTIdentifier> evt) { Thread.dumpStack(); } @Override public void onNotification(UpdateNotification evt) { Thread.dumpStack(); } }
package com.martin.kantidroid; import java.util.List; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.widget.RemoteViews; import com.martin.noten.Fach; import com.martin.noten.PromoCheck; import com.martin.noten.PromoRes; public class WidgetProvider extends AppWidgetProvider { double schn = 0; Fach entry; Resources res; @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { super.onUpdate(context, appWidgetManager, appWidgetIds); res = context.getResources(); final int wcount = appWidgetIds.length; // Iterate through all instances of the widget for (int y = 0; y < wcount; y++) { // Get the intent for a click-event Intent notIntent = new Intent(context, com.martin.noten.Main.class); Intent kontIntent = new Intent(context, com.martin.kontingent.Overview.class); Intent kissIntent = new Intent(context, com.martin.kiss.MainActivity.class); Intent acnotIntent = new Intent(context, com.martin.noten.AddSelect.class); Intent ackontIntent = new Intent(context, com.martin.kontingent.AddSelect.class); PendingIntent penNotIntent = PendingIntent.getActivity(context, 0, notIntent, 0); PendingIntent penKontIntent = PendingIntent.getActivity(context, 0, kontIntent, 0); PendingIntent penKissIntent = PendingIntent.getActivity(context, 0, kissIntent, 0); PendingIntent penacNotIntent = PendingIntent.getActivity(context, 0, acnotIntent, 0); PendingIntent penacKontIntent = PendingIntent.getActivity(context, 0, ackontIntent, 0); // Get the views for the widget RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout); // set the intent for the click-event views.setOnClickPendingIntent(R.id.llCardNoten, penNotIntent); views.setOnClickPendingIntent(R.id.llCardKontingent, penKontIntent); views.setOnClickPendingIntent(R.id.llCardKISS, penKissIntent); views.setOnClickPendingIntent(R.id.ibNotenAdd, penacNotIntent); views.setOnClickPendingIntent(R.id.ibKontAdd, penacKontIntent); // Noten SharedPreferences spNoten = context.getSharedPreferences("MarkSettings", Context.MODE_PRIVATE); String sAbteilung = spNoten.getString("Abteilung", "Gym"); PromoCheck prCheck = new PromoCheck(context); PromoRes prResult = null; if (sAbteilung.contentEquals("Gym")) { prResult = prCheck.getGym(3); } else if (sAbteilung.contentEquals("HMS")) { prResult = prCheck.getHMS(3); } else { prResult = prCheck.getFMS(3); } views.setTextViewText(R.id.tvNotBig, "+ " + prResult.sPP.split("/")[0]); /* * if (prResult.iColor == R.color.holo_green_light) { * pluspunkte.setTextColor(res.getColor(R.color.holo_orange_light)); * } else { pluspunkte.setTextColor(res.getColor(prResult.iColor)); * } */ views.setTextViewText(R.id.tvNotSmall, " " + prResult.sSchnitt); // Kontingent com.martin.kontingent.DatabaseHandler dbK = new com.martin.kontingent.DatabaseHandler(context); int countK = dbK.getFachCount(); int totalK = 0; int used = 0; double dPercentage = 0; List<com.martin.kontingent.Fach> faecherK = dbK.getAllFaecher(context); com.martin.kontingent.Fach entry = null; for (int i = 0; i < countK; i++) { entry = faecherK.get(i); if (!entry.getKont_av().contentEquals("-")) { totalK = totalK + Integer.parseInt(entry.getKont_av()); } if (!entry.getKont_us().contentEquals("-")) { used = used + Integer.parseInt(entry.getKont_us()); } } if (!(totalK == 0)) { dPercentage = (double) Math.round((double) used * 100 / totalK * 100) / 100; } views.setTextViewText(R.id.tvKontSmall, dPercentage + "%"); views.setTextViewText(R.id.tvKontBig, used + "/" + totalK); // KISS SharedPreferences spKISS = context.getSharedPreferences("KISS", Context.MODE_PRIVATE); String sLehrer = spKISS.getString("lehrer", ""); if (!sLehrer.contentEquals("")) { String[] entries = sLehrer.split("-"); String[] imKISS = { "", "" }; int c = 0; for (int i = 0; i < entries.length; i++) { String current_kiss = spKISS.getString("KISS", ""); if (current_kiss.contains(entries[i]) && c < 2) { imKISS[c] = entries[i]; c++; // ftw :D } } switch (c) { case 0: views.setTextColor(R.id.tvKISS_1_name, res.getColor(R.color.primary_text_holo_light)); views.setTextColor(R.id.tvKISS_1_message, res.getColor(R.color.primary_text_holo_light)); views.setTextViewText(R.id.tvKISS_1_name, "-"); views.setTextViewText(R.id.tvKISS_1_message, ""); views.setTextViewText(R.id.tvKISS_2, ""); break; case 1: views.setTextColor(R.id.tvKISS_1_name, res.getColor(R.color.holo_red_light)); views.setTextColor(R.id.tvKISS_1_message, res.getColor(R.color.holo_red_light)); views.setTextViewText(R.id.tvKISS_1_name, imKISS[0]); views.setTextViewText(R.id.tvKISS_1_message, " ist im KISS gelistet"); views.setTextViewText(R.id.tvKISS_2, ""); break; case 2: views.setTextColor(R.id.tvKISS_1_name, res.getColor(R.color.holo_red_light)); views.setTextColor(R.id.tvKISS_1_message, res.getColor(R.color.holo_red_light)); views.setTextColor(R.id.tvKISS_2, res.getColor(R.color.holo_red_light)); views.setTextViewText(R.id.tvKISS_1_message, " ist im KISS gelistet"); views.setTextViewText(R.id.tvKISS_2, ""); views.setTextViewText(R.id.tvKISS_2, "Weitere sind ebenfalls im KISS gelistet"); break; } } appWidgetManager.updateAppWidget(appWidgetIds[y], views); } } }
package uk.ac.ebi.spot.goci.repository; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.data.rest.core.annotation.RestResource; import uk.ac.ebi.spot.goci.model.Association; import java.util.Collection; import java.util.List; @RepositoryRestResource public interface AssociationRepository extends JpaRepository<Association, Long> { Collection<Association> findByStudyId(long studyId); @RestResource(exported = false) Page<Association> findByStudyId(long studyId, Pageable pageable); @RestResource(exported = false) Collection<Association> findByStudyId(long studyId, Sort sort); List<Association> findByStudyIdAndLastUpdateDateIsNotNullOrderByLastUpdateDateDesc(Long studyId); Collection<Association> findByLociStrongestRiskAllelesSnpId(long snpId); @RestResource(exported = false) List<Association> findByStudyHousekeepingCatalogPublishDateIsNotNullAndStudyHousekeepingCatalogUnpublishDateIsNull(); @RestResource(exported = false) List<Association> findByStudyHousekeepingCatalogPublishDateIsNotNullAndStudyHousekeepingCatalogUnpublishDateIsNull( Sort sort); Page<Association> findByStudyHousekeepingCatalogPublishDateIsNotNullAndStudyHousekeepingCatalogUnpublishDateIsNull( Pageable pageable); @RestResource(exported = false) List<Association> findByLociStrongestRiskAllelesSnpIdAndStudyHousekeepingCatalogPublishDateIsNotNullAndStudyHousekeepingCatalogUnpublishDateIsNull( Long snpId); @RestResource(exported = false) List<Association> findByLociStrongestRiskAllelesSnpIdAndStudyHousekeepingCatalogPublishDateIsNotNullAndStudyHousekeepingCatalogUnpublishDateIsNull( Sort sort, Long snpId); Page<Association> findByLociStrongestRiskAllelesSnpIdAndStudyHousekeepingCatalogPublishDateIsNotNullAndStudyHousekeepingCatalogUnpublishDateIsNull( Pageable pageable, Long snpId); @RestResource(exported = false) List<Association> findByStudyDiseaseTraitIdAndStudyHousekeepingCatalogPublishDateIsNotNullAndStudyHousekeepingCatalogUnpublishDateIsNull( Long diseaseTraitId); @RestResource(exported = false) List<Association> findByStudyDiseaseTraitIdAndStudyHousekeepingCatalogPublishDateIsNotNullAndStudyHousekeepingCatalogUnpublishDateIsNull( Sort sort, Long diseaseTraitId); Page<Association> findByStudyDiseaseTraitIdAndStudyHousekeepingCatalogPublishDateIsNotNullAndStudyHousekeepingCatalogUnpublishDateIsNull( Pageable pageable, Long diseaseTraitId); @RestResource(exported = false) List<Association> findByEfoTraitsIdAndStudyHousekeepingCatalogPublishDateIsNotNullAndStudyHousekeepingCatalogUnpublishDateIsNull( Long efoTraitId); @RestResource(exported = false) List<Association> findByEfoTraitsIdAndStudyHousekeepingCatalogPublishDateIsNotNullAndStudyHousekeepingCatalogUnpublishDateIsNull( Sort sort, Long efoTraitId); Page<Association> findByEfoTraitsIdAndStudyHousekeepingCatalogPublishDateIsNotNullAndStudyHousekeepingCatalogUnpublishDateIsNull( Pageable pageable, Long efoTraitId); @Query(value = "select * from "+ "(select a.*, rownum rnum from (select * from association order by id) a where rownum <= :maxRow) "+ " where rnum >= :minRow ", nativeQuery = true) Collection<Association> findAllLSF(@Param("minRow") Integer minRow, @Param("maxRow") Integer maxRow); Collection<Association> findBylastMappingDateIsNull(); }
package com.mendeley.api.network; import android.os.AsyncTask; import com.mendeley.api.callbacks.RequestHandle; import com.mendeley.api.exceptions.MendeleyException; import com.mendeley.api.params.Page; import com.mendeley.api.util.Utils; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Map; import javax.net.ssl.HttpsURLConnection; public abstract class NetworkTask extends AsyncTask<String, Integer, MendeleyException> implements RequestHandle { Page next; String location; Date serverDate; InputStream is = null; OutputStream os = null; HttpsURLConnection con = null; protected abstract int getExpectedResponse(); /** * Extracts the headers from the given HttpsURLConnection object. */ protected void getResponseHeaders() throws IOException { Map<String, List<String>> headersMap = con.getHeaderFields(); if (headersMap == null) { // No headers implies an error, which should be handled based on the HTTP status code; // no need to throw another error here. return; } for (String key : headersMap.keySet()) { if (key != null) { switch (key) { case "Date": SimpleDateFormat simpledateformat = new SimpleDateFormat("EEE, dd MMM yyyy kk:mm:ss 'GMT'"); try { serverDate = simpledateformat.parse(headersMap.get(key).get(0)); } catch (ParseException e) { e.printStackTrace(); } break; case "Vary": case "Content-Type": case "X-Mendeley-Trace-Id": case "Connection": case "Content-Length": case "Content-Encoding": case "Mendeley-Count": // Unused break; case "Location": location = headersMap.get(key).get(0); case "Link": List<String> links = headersMap.get(key); String linkString = null; for (String link : links) { try { linkString = link.substring(link.indexOf("<")+1, link.indexOf(">")); } catch (IndexOutOfBoundsException e) {} if (link.indexOf("next") != -1) { next = new Page(linkString); } // "last" and "prev" links are not used } break; } } } } protected void closeConnection() { if (con != null) { con.disconnect(); } Utils.closeQuietly(is); Utils.closeQuietly(os); } @Override protected void onPostExecute(MendeleyException exception) { if (exception == null) { onSuccess(); } else { onFailure(exception); } } protected void onProgressUpdate(Integer[] progress) { super.onProgressUpdate(); } protected abstract void onSuccess(); protected abstract void onFailure(MendeleyException exception); public void cancel() { // If the request is cancelled, we simply cancel the AsyncTask. cancel(true); } }
package it.cnr.istc.stlab.lizard.core; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.io.FileUtils; import org.apache.jena.datatypes.RDFDatatype; import org.apache.jena.datatypes.TypeMapper; import org.apache.jena.ontology.BooleanClassDescription; import org.apache.jena.ontology.OntClass; import org.apache.jena.ontology.OntModel; import org.apache.jena.ontology.OntModelSpec; import org.apache.jena.ontology.OntProperty; import org.apache.jena.ontology.OntResource; import org.apache.jena.ontology.OntTools; import org.apache.jena.ontology.Ontology; import org.apache.jena.ontology.Restriction; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.Resource; import org.apache.jena.reasoner.ValidityReport; import org.apache.jena.reasoner.ValidityReport.Report; import org.apache.jena.util.iterator.ExtendedIterator; import org.apache.jena.vocabulary.OWL2; import org.apache.jena.vocabulary.RDFS; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sun.codemodel.CodeWriter; import com.sun.codemodel.JDefinedClass; import com.sun.codemodel.JMethod; import com.sun.codemodel.JMod; import com.sun.codemodel.writer.FileCodeWriter; import it.cnr.istc.stlab.lizard.commons.MavenUtils; import it.cnr.istc.stlab.lizard.commons.OntologyCodeProject; import it.cnr.istc.stlab.lizard.commons.exception.NotAvailableOntologyCodeEntityException; import it.cnr.istc.stlab.lizard.commons.exception.OntologyNotValidException; import it.cnr.istc.stlab.lizard.commons.inmemory.RestInterface; import it.cnr.istc.stlab.lizard.commons.model.AbstractOntologyCodeClass; import it.cnr.istc.stlab.lizard.commons.model.AbstractOntologyCodeClassImpl; import it.cnr.istc.stlab.lizard.commons.model.OntologyCodeClass; import it.cnr.istc.stlab.lizard.commons.model.OntologyCodeInterface; import it.cnr.istc.stlab.lizard.commons.model.OntologyCodeModel; import it.cnr.istc.stlab.lizard.commons.model.anon.BooleanAnonClass; import it.cnr.istc.stlab.lizard.commons.model.datatype.DatatypeCodeInterface; import it.cnr.istc.stlab.lizard.commons.model.types.OntologyCodeMethodType; import it.cnr.istc.stlab.lizard.commons.recipe.OntologyCodeGenerationRecipe; import it.cnr.istc.stlab.lizard.core.model.BeanOntologyCodeClass; import it.cnr.istc.stlab.lizard.core.model.BeanOntologyCodeInterface; import it.cnr.istc.stlab.lizard.core.model.JenaOntologyCodeClass; import it.cnr.istc.stlab.lizard.core.model.RestOntologyCodeClass; import it.cnr.istc.stlab.lizard.core.model.RestOntologyCodeModel; public class LizardCore implements OntologyCodeGenerationRecipe { private static Logger logger = LoggerFactory.getLogger(LizardCore.class); private URI ontologyURIBase; private RestOntologyCodeModel restOntologyModel; private OntologyCodeModel ontologyModel; public LizardCore(URI ontologyURI, URI[] others) { this.ontologyURIBase = ontologyURI; OntModel ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM); ontModel.read(ontologyURI.toString()); for (URI uri : others) { ontModel.read(uri.toString()); } validateOntology(ontModel); this.ontologyModel = new RestOntologyCodeModel(ontModel); } public LizardCore(URI ontologyURI) { this.ontologyURIBase = ontologyURI; // OntModel ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM_RDFS_INF); OntModel ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM); ontModel.read(ontologyURI.toString()); validateOntology(ontModel); this.ontologyModel = new RestOntologyCodeModel(ontModel); } private void validateOntology(OntModel ontModel) { logger.trace("Validating inf model"); ValidityReport validity = ontModel.validate(); if (validity != null) { if (!validity.isValid()) { for (Iterator<Report> in = validity.getReports(); in.hasNext();) { logger.error(" - " + in.next()); } throw new OntologyNotValidException("Ontology not valid!"); } else { logger.trace("Ontology valid!"); } } else { logger.warn("Validation of the ontology not performed!"); } } @Override public OntologyCodeProject generate() { OntologyCodeProject project = null; try { project = generateBeans(); } catch (NotAvailableOntologyCodeEntityException e) { e.printStackTrace(); } if (project != null) { OntologyCodeModel beansModel = project.getOntologyCodeModel(); project = generateRestProject(beansModel); } return project; } private OntologyCodeProject generateBeans() throws NotAvailableOntologyCodeEntityException { OntologyCodeModel ontologyCodeModel = new RestOntologyCodeModel(this.ontologyModel.asOntModel()); OntModel ontModel = ontologyCodeModel.asOntModel(); String baseURI = ontModel.getNsPrefixURI(""); if (baseURI == null) { ExtendedIterator<Ontology> ontologyIt = ontModel.listOntologies(); while (ontologyIt.hasNext()) baseURI = ontologyIt.next().getURI(); if (baseURI == null) ontModel.setNsPrefix("", ontologyURIBase.toString()); else ontModel.setNsPrefix("", baseURI); } URI ontologyBaseURI; try { ontologyBaseURI = new URI(baseURI); } catch (URISyntaxException e) { ontologyBaseURI = ontologyURIBase; } OntClass owlThing = ontModel.getOntClass(OWL2.Thing.getURI()); /* * Create interface for owl:Thing */ OntologyCodeInterface ontologyThingInterface = ontologyCodeModel.createOntologyClass(owlThing, BeanOntologyCodeInterface.class); createBeanMethods(ontologyThingInterface, ontologyCodeModel); ((JDefinedClass) ontologyThingInterface.asJDefinedClass()).method(JMod.PUBLIC, ontologyCodeModel.asJCodeModel().VOID, "setId").param(String.class, "id"); ((JDefinedClass) ontologyThingInterface.asJDefinedClass()).method(JMod.PUBLIC, String.class, "getId"); ((JDefinedClass) ontologyThingInterface.asJDefinedClass()).method(JMod.PUBLIC, ontologyCodeModel.asJCodeModel().VOID, "setIsCompleted").param(Boolean.class, "isCompleted"); ((JDefinedClass) ontologyThingInterface.asJDefinedClass()).method(JMod.PUBLIC, Boolean.class, "getIsCompleted"); /* * Create bean for owl:Thing */ /* * Create java bean and Jena-based class. */ ontologyCodeModel.createOntologyClass(owlThing, BeanOntologyCodeClass.class); ontologyCodeModel.createOntologyClass(owlThing, JenaOntologyCodeClass.class); List<OntClass> roots = OntTools.namedHierarchyRoots(ontModel); for (OntClass root : roots) { visitHierarchyTreeForBeans(root, ontologyCodeModel); } /* * Create class implementations for java beans */ Map<OntResource, BeanOntologyCodeClass> beanClassMap = ontologyCodeModel.getOntologyClasses(BeanOntologyCodeClass.class); Set<OntResource> ontResources = beanClassMap.keySet(); final Set<AbstractOntologyCodeClassImpl> ontologyClasses = new HashSet<AbstractOntologyCodeClassImpl>(); ontResources.forEach(ontResource -> { if (ontResource.isURIResource()) { BeanOntologyCodeClass ontologyClass = beanClassMap.get(ontResource); ontologyClasses.add(ontologyClass); } }); ontologyClasses.forEach(ontologyClass -> { OntClass ontClass = (OntClass) ontologyClass.getOntResource(); OntologyCodeInterface ontologyInterface = ontologyCodeModel.getOntologyClass(ontClass, BeanOntologyCodeInterface.class); ExtendedIterator<OntClass> superClassIt = ontClass.listSuperClasses(false); List<OntologyCodeInterface> ontologySuperInterfaces = new ArrayList<OntologyCodeInterface>(); ontologySuperInterfaces.add(ontologyCodeModel.getOntologyClass(ModelFactory.createOntologyModel().createOntResource(OWL2.Thing.getURI()), BeanOntologyCodeInterface.class)); if (ontologyInterface != null) ontologySuperInterfaces.add(ontologyInterface); while (superClassIt.hasNext()) { OntClass superClass = superClassIt.next(); if (superClass.isURIResource()) { OntologyCodeInterface ontologySuperInterface = ontologyCodeModel.getOntologyClass(superClass, BeanOntologyCodeInterface.class); if (ontologySuperInterface != null) ontologySuperInterfaces.add(ontologySuperInterface); } } OntologyCodeInterface[] classArray = new OntologyCodeInterface[ontologySuperInterfaces.size()]; ontologyCodeModel.createClassImplements(ontologyClass, ontologySuperInterfaces.toArray(classArray)); }); /* * Create class implementations for Jena-based classes */ Map<OntResource, JenaOntologyCodeClass> jenaClassMap = ontologyCodeModel.getOntologyClasses(JenaOntologyCodeClass.class); ontResources = jenaClassMap.keySet(); final Set<AbstractOntologyCodeClassImpl> jenaClasses = new HashSet<AbstractOntologyCodeClassImpl>(); for (OntResource ontResource : ontResources) { OntologyCodeClass ontologyClass = jenaClassMap.get(ontResource); jenaClasses.add(ontologyClass); } jenaClasses.forEach(ontologyClass -> { OntClass ontClass = (OntClass) ontologyClass.getOntResource(); OntologyCodeInterface ontologyInterface = ontologyCodeModel.getOntologyClass(ontClass, BeanOntologyCodeInterface.class); ExtendedIterator<OntClass> superClassIt = ontClass.listSuperClasses(false); List<OntologyCodeInterface> ontologySuperInterfaces = new ArrayList<OntologyCodeInterface>(); ontologySuperInterfaces.add(ontologyCodeModel.getOntologyClass(ModelFactory.createOntologyModel().createOntResource(OWL2.Thing.getURI()), BeanOntologyCodeInterface.class)); if (ontologyInterface != null) ontologySuperInterfaces.add(ontologyInterface); while (superClassIt.hasNext()) { OntClass superClass = superClassIt.next(); if (superClass.isURIResource()) { OntologyCodeInterface ontologySuperInterface = ontologyCodeModel.getOntologyClass(superClass, BeanOntologyCodeInterface.class); if (ontologySuperInterface != null) ontologySuperInterfaces.add(ontologySuperInterface); } } OntologyCodeInterface[] classArray = new OntologyCodeInterface[ontologySuperInterfaces.size()]; ontologyCodeModel.createClassImplements(ontologyClass, ontologySuperInterfaces.toArray(classArray)); }); return new OntologyCodeProject(ontologyBaseURI, ontologyCodeModel); } private OntologyCodeProject generateRestProject(OntologyCodeModel model) { this.restOntologyModel = new RestOntologyCodeModel(model); OntModel ontModel = restOntologyModel.asOntModel(); String baseURI = ontModel.getNsPrefixURI(""); if (baseURI == null) { ExtendedIterator<Ontology> ontologyIt = ontModel.listOntologies(); while (ontologyIt.hasNext()) baseURI = ontologyIt.next().getURI(); if (baseURI == null) ontModel.setNsPrefix("", ontologyURIBase.toString()); else ontModel.setNsPrefix("", baseURI); } URI ontologyBaseURI; try { ontologyBaseURI = new URI(baseURI); } catch (URISyntaxException e) { ontologyBaseURI = ontologyURIBase; } List<OntClass> roots = OntTools.namedHierarchyRoots(ontModel); for (OntClass root : roots) { visitHierarchyTreeForRest(root, restOntologyModel); } /* * CodeWriter writer = new SingleStreamCodeWriter(System.out); try { codeModel.build(writer); } catch (IOException e) { e.printStackTrace(); } */ return new OntologyCodeProject(ontologyBaseURI, restOntologyModel); } private BooleanAnonClass manageAnonClasses(OntClass ontClass, OntologyCodeModel ontologyModel) { return ontologyModel.createAnonClass(ontClass); } private void visitHierarchyTreeForRest(OntClass ontClass, OntologyCodeModel ontologyModel) { logger.debug("Visit hierarchy for rest " + ontClass.getURI()); OntologyCodeClass ontologyClass; try { if (ontologyModel.getOntologyClass(ontClass, BeanOntologyCodeClass.class) != null) { ontologyClass = ontologyModel.createOntologyClass(ontClass, RestOntologyCodeClass.class); createMethods(ontologyClass, ontologyModel); } } catch (NotAvailableOntologyCodeEntityException e) { e.printStackTrace(); } ExtendedIterator<OntClass> subClasses = ontClass.listSubClasses(); while (subClasses.hasNext()) { OntClass subClass = subClasses.next(); if (subClass.isURIResource()) visitHierarchyTreeForRest(subClass, ontologyModel); else manageAnonClasses(subClass, ontologyModel); } } private static boolean hasMethod(JDefinedClass jdefClass, String methodName) { for (JMethod m : jdefClass.methods()) { if (m.name().equals(methodName)) { return true; } } return false; } private void visitHierarchyTreeForBeans(OntClass ontClass, OntologyCodeModel ontologyModel) { OntologyCodeInterface ontologyInterface = null; try { ontologyInterface = ontologyModel.createOntologyClass(ontClass, BeanOntologyCodeInterface.class); } catch (NotAvailableOntologyCodeEntityException e) { e.printStackTrace(); } if (ontologyInterface != null) { createBeanMethods(ontologyInterface, ontologyModel); // TODO if (!hasMethod(((JDefinedClass) ontologyInterface.asJDefinedClass()), "setId")) { ((JDefinedClass) ontologyInterface.asJDefinedClass()).method(JMod.PUBLIC, ontologyInterface.getJCodeModel().VOID, "setId").param(String.class, "id"); ((JDefinedClass) ontologyInterface.asJDefinedClass()).method(JMod.PUBLIC, String.class, "getId"); ((JDefinedClass) ontologyInterface.asJDefinedClass()).method(JMod.PUBLIC, ontologyInterface.getJCodeModel().VOID, "setIsCompleted").param(Boolean.class, "isCompleted"); ((JDefinedClass) ontologyInterface.asJDefinedClass()).method(JMod.PUBLIC, Boolean.class, "getIsCompleted"); } try { ontologyModel.createOntologyClass(ontClass, BeanOntologyCodeClass.class); ontologyModel.createOntologyClass(ontClass, JenaOntologyCodeClass.class); } catch (NotAvailableOntologyCodeEntityException e) { e.printStackTrace(); } ExtendedIterator<OntClass> subClasses = ontClass.listSubClasses(); while (subClasses.hasNext()) { OntClass subClass = subClasses.next(); if (subClass.isURIResource()) visitHierarchyTreeForBeans(subClass, ontologyModel); else manageAnonClasses(subClass, ontologyModel); } } } public void createServiceAnnotations(File root, OntologyCodeModel ontologyCodeModel) { Map<OntResource, RestOntologyCodeClass> restClassMap = ontologyCodeModel.getOntologyClasses(RestOntologyCodeClass.class); Collection<RestOntologyCodeClass> restCalasses = restClassMap.values(); File metaInfFolder = new File(root, "src/main/resources/META-INF/services"); if (!metaInfFolder.exists()) metaInfFolder.mkdirs(); File restInterfaceAnnotation = new File(metaInfFolder, RestInterface.class.getCanonicalName()); System.out.println(getClass() + " created file " + restInterfaceAnnotation.getAbsolutePath()); BufferedWriter bw; try { bw = new BufferedWriter(new FileWriter(restInterfaceAnnotation)); restCalasses.forEach(restClass -> { try { bw.write(restClass.asJDefinedClass().fullName()); bw.newLine(); } catch (Exception e) { e.printStackTrace(); } }); bw.close(); } catch (IOException e) { e.printStackTrace(); } } private void createMethods(AbstractOntologyCodeClass owner, OntologyCodeModel ontologyModel) { OntClass ontClass = ontologyModel.asOntModel().getOntClass(owner.getOntResource().getURI()); Set<OntProperty> props = ontClass.listDeclaredProperties().toSet(); props.addAll(getRestrictionsPropertyDomain(ontClass)); Iterator<OntProperty> propIt = props.iterator(); while (propIt.hasNext()) { OntProperty ontProperty = propIt.next(); OntResource range = ontProperty.getRange(); if (range != null) { if (range.isURIResource()) { if (range.isClass()) { OntologyCodeInterface rangeClass = null; /* * The property is a datatype property. In this case we use Jena to map the range to the appropriate Java type. E.g. xsd:string -> java.lang.String */ OntClass rangeOntClass = ModelFactory.createOntologyModel().createClass(range.getURI()); if (ontProperty.isDatatypeProperty()) { try { rangeClass = ontologyModel.createOntologyClass(rangeOntClass, DatatypeCodeInterface.class); } catch (NotAvailableOntologyCodeEntityException e) { e.printStackTrace(); } } else { try { rangeClass = ontologyModel.createOntologyClass(rangeOntClass, BeanOntologyCodeInterface.class); } catch (NotAvailableOntologyCodeEntityException e) { e.printStackTrace(); } } if (rangeClass == null) { System.out.println(getClass() + " ATTENTION "); } Collection<AbstractOntologyCodeClass> domain = new ArrayList<AbstractOntologyCodeClass>(); domain.add(rangeClass); ontologyModel.createMethod(OntologyCodeMethodType.GET, ontProperty, owner, domain, rangeClass); ontologyModel.createMethod(OntologyCodeMethodType.SET, ontProperty, owner, domain, rangeClass); ontologyModel.createMethod(OntologyCodeMethodType.ADD_ALL, ontProperty, owner, domain, rangeClass); ontologyModel.createMethod(OntologyCodeMethodType.REMOVE_ALL, ontProperty, owner, domain, rangeClass); } } else { BooleanAnonClass anonClass = manageAnonClasses(range.asClass(), ontologyModel); Collection<AbstractOntologyCodeClass> domain = new ArrayList<AbstractOntologyCodeClass>(); domain.add(anonClass); ontologyModel.createMethod(OntologyCodeMethodType.GET, ontProperty, owner, domain, anonClass); ontologyModel.createMethod(OntologyCodeMethodType.SET, ontProperty, owner, domain, anonClass); ontologyModel.createMethod(OntologyCodeMethodType.ADD_ALL, ontProperty, owner, domain, anonClass); ontologyModel.createMethod(OntologyCodeMethodType.REMOVE_ALL, ontProperty, owner, domain, anonClass); } } else { OntResource thing = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM).createOntResource(OWL2.Thing.getURI()); Collection<AbstractOntologyCodeClass> domain = new ArrayList<AbstractOntologyCodeClass>(); domain.add(ontologyModel.getOntologyClass(thing, BeanOntologyCodeInterface.class)); ontologyModel.createMethod(OntologyCodeMethodType.GET, ontProperty, owner, domain, ontologyModel.getOntologyClass(thing, RestOntologyCodeClass.class)); ontologyModel.createMethod(OntologyCodeMethodType.SET, ontProperty, owner, domain, ontologyModel.getOntologyClass(thing, RestOntologyCodeClass.class)); ontologyModel.createMethod(OntologyCodeMethodType.ADD_ALL, ontProperty, owner, domain, ontologyModel.getOntologyClass(thing, RestOntologyCodeClass.class)); ontologyModel.createMethod(OntologyCodeMethodType.REMOVE_ALL, ontProperty, owner, domain, ontologyModel.getOntologyClass(thing, RestOntologyCodeClass.class)); } } ExtendedIterator<OntClass> superClassesIt = ontClass.listSuperClasses(); while (superClassesIt.hasNext()) { OntClass superClass = superClassesIt.next(); if (superClass.isRestriction()) { Restriction restriction = superClass.asRestriction(); OntProperty onProperty = restriction.getOnProperty(); Resource onClass = null; if (restriction.isSomeValuesFromRestriction()) { onClass = restriction.asSomeValuesFromRestriction().getSomeValuesFrom(); } else if (restriction.isAllValuesFromRestriction()) { onClass = restriction.asAllValuesFromRestriction().getAllValuesFrom(); } if (onClass != null && !onProperty.isDatatypeProperty()) { try { OntologyCodeClass rangeClass = ontologyModel.createOntologyClass(ontologyModel.asOntModel().getOntResource(onClass), RestOntologyCodeClass.class); Collection<AbstractOntologyCodeClass> domain = new ArrayList<AbstractOntologyCodeClass>(); domain.add(rangeClass); ontologyModel.createMethod(OntologyCodeMethodType.GET, onProperty, owner, null, rangeClass); ontologyModel.createMethod(OntologyCodeMethodType.SET, onProperty, owner, null, rangeClass); ontologyModel.createMethod(OntologyCodeMethodType.ADD_ALL, onProperty, owner, null, rangeClass); ontologyModel.createMethod(OntologyCodeMethodType.REMOVE_ALL, onProperty, owner, null, rangeClass); } catch (NotAvailableOntologyCodeEntityException e) { e.printStackTrace(); } } } } } private Set<OntProperty> getRestrictionsPropertyDomain(OntClass c) { Set<OntProperty> r = new HashSet<OntProperty>(); this.ontologyModel.asOntModel().listAllOntProperties().forEachRemaining(op -> { if (op.getDomain() != null && op.getDomain().isClass()) { OntClass ac = op.getDomain().asClass(); if (ac.isUnionClass()) { BooleanClassDescription booleanClassDescription = ac.asUnionClass(); ExtendedIterator<? extends OntClass> members = booleanClassDescription.listOperands(); while (members.hasNext()) { OntClass member = members.next(); if (member.getURI().equals(c.getURI())) { r.add(op); } } } } }); return r; } private void createBeanMethods(AbstractOntologyCodeClass owner, OntologyCodeModel ontologyModel) { OntClass ontClass = ontologyModel.asOntModel().getOntClass(owner.getOntResource().getURI()); Set<OntProperty> props = ontClass.listDeclaredProperties().toSet(); props.addAll(getRestrictionsPropertyDomain(ontClass)); Iterator<OntProperty> propIt = props.iterator(); while (propIt.hasNext()) { OntProperty ontProperty = propIt.next(); OntResource range = ontProperty.getRange(); if (range != null) { if (range.isURIResource()) { if (range.isClass()) { /* * Range of the property is a class */ OntologyCodeInterface rangeClass = null; OntClass rangeOntClass = ModelFactory.createOntologyModel().createClass(range.getURI()); if (ontProperty.isDatatypeProperty()) { // if (!hasTypeMapper(range.getURI())) { try { rangeClass = ontologyModel.createOntologyClass(rangeOntClass, DatatypeCodeInterface.class); } catch (NotAvailableOntologyCodeEntityException e) { e.printStackTrace(); } } else { try { rangeClass = ontologyModel.createOntologyClass(rangeOntClass, BeanOntologyCodeInterface.class); } catch (NotAvailableOntologyCodeEntityException e) { e.printStackTrace(); } } Collection<AbstractOntologyCodeClass> domain = new ArrayList<AbstractOntologyCodeClass>(); if (rangeClass != null) domain.add(rangeClass); ontologyModel.createMethod(OntologyCodeMethodType.GET, ontProperty, owner, null, rangeClass); ontologyModel.createMethod(OntologyCodeMethodType.SET, ontProperty, owner, domain, null); ontologyModel.createMethod(OntologyCodeMethodType.ADD_ALL, ontProperty, owner, domain, null); ontologyModel.createMethod(OntologyCodeMethodType.REMOVE_ALL, ontProperty, owner, domain, null); } } else { BooleanAnonClass anonClass = manageAnonClasses(range.asClass(), ontologyModel); Collection<AbstractOntologyCodeClass> domain = new ArrayList<AbstractOntologyCodeClass>(); domain.add(anonClass); ontologyModel.createMethod(OntologyCodeMethodType.GET, ontProperty, owner, null, anonClass); ontologyModel.createMethod(OntologyCodeMethodType.SET, ontProperty, owner, domain, null); ontologyModel.createMethod(OntologyCodeMethodType.ADD_ALL, ontProperty, owner, domain, null); ontologyModel.createMethod(OntologyCodeMethodType.REMOVE_ALL, ontProperty, owner, domain, null); } } else { /* * Range null */ OntologyCodeInterface rangeClass = null; OntResource rangeOntClass = null; if (ontProperty.isDatatypeProperty()) { try { rangeOntClass = ModelFactory.createOntologyModel().createOntResource(RDFS.Literal.getURI()); rangeClass = ontologyModel.createOntologyClass(rangeOntClass, DatatypeCodeInterface.class); } catch (NotAvailableOntologyCodeEntityException e) { e.printStackTrace(); } } else { try { rangeOntClass = ModelFactory.createOntologyModel().createOntResource(OWL2.Thing.getURI()); rangeClass = ontologyModel.createOntologyClass(rangeOntClass, BeanOntologyCodeInterface.class); } catch (NotAvailableOntologyCodeEntityException e) { e.printStackTrace(); } } Collection<AbstractOntologyCodeClass> domain = new ArrayList<AbstractOntologyCodeClass>(); domain.add(rangeClass); ontologyModel.createMethod(OntologyCodeMethodType.GET, ontProperty, owner, null, rangeClass); ontologyModel.createMethod(OntologyCodeMethodType.SET, ontProperty, owner, domain, null); ontologyModel.createMethod(OntologyCodeMethodType.ADD_ALL, ontProperty, owner, domain, null); ontologyModel.createMethod(OntologyCodeMethodType.REMOVE_ALL, ontProperty, owner, domain, null); } } ExtendedIterator<OntClass> superClassesIt = ontClass.listSuperClasses(); while (superClassesIt.hasNext()) { OntClass superClass = superClassesIt.next(); if (superClass.isRestriction()) { Restriction restriction = superClass.asRestriction(); OntProperty onProperty = restriction.getOnProperty(); Resource onClass = null; if (restriction.isSomeValuesFromRestriction()) { onClass = restriction.asSomeValuesFromRestriction().getSomeValuesFrom(); } else if (restriction.isAllValuesFromRestriction()) { onClass = restriction.asAllValuesFromRestriction().getAllValuesFrom(); } if (onClass != null) { if (!onProperty.isDatatypeProperty()) { try { AbstractOntologyCodeClass rangeClass = ontologyModel.createOntologyClass(ontologyModel.asOntModel().getOntResource(onClass), BeanOntologyCodeInterface.class); Collection<AbstractOntologyCodeClass> domain = new ArrayList<AbstractOntologyCodeClass>(); domain.add(rangeClass); ontologyModel.createMethod(OntologyCodeMethodType.GET, onProperty, owner, null, rangeClass); ontologyModel.createMethod(OntologyCodeMethodType.SET, onProperty, owner, null, rangeClass); ontologyModel.createMethod(OntologyCodeMethodType.ADD_ALL, onProperty, owner, null, rangeClass); ontologyModel.createMethod(OntologyCodeMethodType.REMOVE_ALL, onProperty, owner, null, rangeClass); } catch (NotAvailableOntologyCodeEntityException e) { e.printStackTrace(); } } } } } } public static void main(String[] args) { System.setProperty("M2_HOME", "/Users/lgu/Programs/apache-maven"); System.setProperty("JAVA_HOME", "/Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home"); registerDatatypes(); URI uri = null; try { // uri = new URI("/Users/lgu/Dropbox/stlab/ontologies/paraphrase/ppdb.owl"); uri = new URI("http: // uri = new URI("/Users/lgu/Desktop/prova.owl"); // uri = new URI("/Users/lgu/Desktop/cga.owl"); // uri = new URI("vocabs/foaf.rdf"); OntologyCodeGenerationRecipe codegen = new LizardCore(uri, new URI[] { new URI("http: OntologyCodeProject ontologyCodeProject = codegen.generate(); try { File testFolder = new File("test_out"); if (testFolder.exists()) { System.out.println("esists " + testFolder.getClass()); FileUtils.deleteDirectory(testFolder); } else { System.out.println("not esists"); } File src = new File("test_out/src/main/java"); File resources = new File("test_out/src/main/resources"); File test = new File("test_out/src/test/java"); if (!src.exists()) src.mkdirs(); if (!resources.exists()) resources.mkdirs(); if (!test.exists()) test.mkdirs(); CodeWriter writer = new FileCodeWriter(src, "UTF-8"); ontologyCodeProject.getOntologyCodeModel().asJCodeModel().build(writer); ((LizardCore) codegen).createServiceAnnotations(new File("test_out"), ontologyCodeProject.getOntologyCodeModel()); /* * Generate the POM descriptor file and build the project as a Maven project. */ File pom = new File("test_out/pom.xml"); Writer pomWriter = new FileWriter(new File("test_out/pom.xml")); Map<String, String> dataModel = new HashMap<String, String>(); dataModel.put("artifactId", ontologyCodeProject.getArtifactId()); dataModel.put("groupId", ontologyCodeProject.getGroupId()); MavenUtils.generatePOM(pomWriter, dataModel); MavenUtils.buildProject(pom); } catch (IOException e) { e.printStackTrace(); } } catch (URISyntaxException e) { e.printStackTrace(); } } public static boolean hasTypeMapper(String uri) { Iterator<RDFDatatype> it = TypeMapper.getInstance().listTypes(); while (it.hasNext()) { RDFDatatype rdfDatatype = (RDFDatatype) it.next(); if (rdfDatatype.getURI().equals(uri)) { return true; } } return false; } private static void registerDatatypes() { // TODO let register custom datatype // TypeMapper.getInstance().registerDatatype(new XSDNonNegativeIntegerType()); } }
package io.lnk.lookup.zookeeper; import java.nio.charset.Charset; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.apache.zookeeper.AsyncCallback.StatCallback; import org.apache.zookeeper.AsyncCallback.StringCallback; import org.apache.zookeeper.AsyncCallback.VoidCallback; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.ZooDefs.Ids; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Charsets; import io.lnk.api.URI; import io.lnk.api.utils.LnkThreadFactory; import io.lnk.lookup.zookeeper.ZooKeeperClient.Credentials; import io.lnk.lookup.zookeeper.notify.NotifyHandler; import io.lnk.lookup.zookeeper.notify.NotifyMessage; import io.lnk.lookup.zookeeper.utils.ZooKeeperUtils; /** * @author E-mail:liufei_it@126.com * * @version 1.0.0 * @since 2017613 6:06:52 */ public class ZooKeeperProvider implements Command { protected final Logger log = LoggerFactory.getLogger(getClass().getSimpleName()); static { System.setProperty("zookeeper.disableAutoWatchReset", String.valueOf(false)); } private static final String NODE_PATH_SPL = "/"; private static final String CHARSET = "charset"; private static final String SESSION_TIMEOUT_MILLIS = "sessionTimeoutMillis"; private static final String CONNECT_TIMEOUT_MILLIS = "connectTimeoutMillis"; protected final URI uri; private final ZooKeeperClient client; private final int connectTimeoutMillis; private final int sessionTimeoutMillis; private final String connectString; private final Charset charset; private final byte[] defaultData; private final ExecutorService executor; private final Map<String, NotifyHandler> notifyHandlers = new HashMap<String, NotifyHandler>(); public ZooKeeperProvider(URI uri) { this(uri, uri.getInt(CONNECT_TIMEOUT_MILLIS, 30000), uri.getInt(SESSION_TIMEOUT_MILLIS, 30000), uri.getAddress()); } public ZooKeeperProvider(URI uri, int connectionTimeoutMillis, int sessionTimeoutMillis, String connectString) { this(uri, connectionTimeoutMillis, sessionTimeoutMillis, connectString, uri.getCharset(CHARSET, Charsets.UTF_8)); } public ZooKeeperProvider(URI uri, int connectTimeoutMillis, int sessionTimeoutMillis, String connectString, Charset charset) { super(); this.uri = uri; this.connectTimeoutMillis = connectTimeoutMillis; this.sessionTimeoutMillis = sessionTimeoutMillis; this.connectString = connectString; this.charset = charset; this.defaultData = StringUtils.EMPTY.getBytes(charset); this.executor = Executors.newFixedThreadPool(2, LnkThreadFactory.newThreadFactory("ZooKeeperProvider-%d", false)); this.client = this.buildClient(); } private final ZooKeeperClient buildClient() { ZooKeeperClient zkClient = new ZooKeeperClient(sessionTimeoutMillis, Credentials.NONE, connectString); zkClient.registerExpirationHandler(this); zkClient.registerCloseEventExpirationHandler(this); log.info("build ZooKeeperClient connection to connect uri : {}", connectString); return zkClient; } @Override public void execute() throws RuntimeException { executor.submit(new Runnable() { public void run() { if (notifyHandlers.isEmpty()) { return; } for (int i = 0; i < 30; i++) { for (Map.Entry<String, NotifyHandler> e : notifyHandlers.entrySet()) { registerHandler(e.getKey(), e.getValue()); } } } }); } public void create(String path, CreateMode createMode) { try { this.client.get(connectTimeoutMillis).create(path, defaultData, Ids.OPEN_ACL_UNSAFE, createMode, new StringCallback() { public void processResult(int rc, String path, Object ctx, String name) { log.info("call create path callback rc:{}, path:{}, ctx:{}, name:{}", new Object[] {rc, path, ctx, name}); } }, this); } catch (Throwable e) { log.error("create path : " + path + " Error.", e); } } public void delete(String path) { try { this.client.get(connectTimeoutMillis).delete(path, ZooKeeperUtils.ANY_VERSION, new VoidCallback() { public void processResult(int rc, String path, Object ctx) { log.info("call delete callback rc:{}, path:{}, ctx:{}", new Object[] {rc, path, ctx}); } }, this); } catch (Throwable e) { log.error("remove path : " + path + " Error.", e); } } public boolean exists(String path) { try { return (this.client.get(connectTimeoutMillis).exists(path, true) != null); } catch (Throwable e) { log.error("exists path : " + path + " Error.", e); } return false; } public String pull(String path) { try { byte[] data = this.client.get(connectTimeoutMillis).getData(path, true, null); if (ArrayUtils.isEmpty(data)) { return null; } return new String(data, charset); } catch (Throwable e) { log.error("pull NotifyMessage Error.", e); } return null; } public List<String> getChildren(String path) { try { return this.client.get(connectTimeoutMillis).getChildren(path, true); } catch (Throwable e) { log.error("get children path Error.", e); } return null; } public void push(NotifyMessage message) { try { String path = message.getPath(); String data = message.getData(); CreateMode createMode = CreateMode.PERSISTENT; if (NotifyMessage.MessageMode.EPHEMERAL.equals(message.getMessageMode())) { createMode = CreateMode.EPHEMERAL; } byte[] dataBytes = data.getBytes(charset); ZooKeeper zooKeeper = this.client.get(connectTimeoutMillis); if (zooKeeper.exists(path, true) == null) { String[] nodes = StringUtils.split(path, NODE_PATH_SPL); String nodeTmp = StringUtils.EMPTY; for (String n : nodes) { nodeTmp += (NODE_PATH_SPL.concat(n)); if (zooKeeper.exists(nodeTmp, true) == null) { zooKeeper.create(nodeTmp, dataBytes, Ids.OPEN_ACL_UNSAFE, createMode, new StringCallback() { public void processResult(int rc, String path, Object ctx, String name) { log.info("call create path callback rc:{}, path:{}, ctx:{}, name:{}", new Object[] {rc, path, ctx, name}); } }, this); } } } zooKeeper.setData(path, dataBytes, ZooKeeperUtils.ANY_VERSION, new StatCallback() { public void processResult(int rc, String path, Object ctx, Stat stat) { log.info("call set data callback rc:{}, path:{}, ctx:{}, stat:{}", new Object[] {rc, path, ctx, stat}); } }, this); } catch (Throwable e) { log.error("push NotifyMessage Error.", e); } } public void registerHandler(String listenNode, NotifyHandler handler) { try { NotifyWatcher watcher = new NotifyWatcher(listenNode, handler, this); this.client.register(watcher); ZooKeeper zooKeeper = this.client.get(connectTimeoutMillis); Stat stat = zooKeeper.exists(listenNode, watcher); if (stat != null) { registerChildrenHandler(listenNode, zooKeeper, watcher); } log.info("register Watcher Handler : {}", listenNode); } catch (Throwable e) { log.error("register Watcher Handler : " + listenNode + " Error.", e); } finally { notifyHandlers.put(listenNode, handler); } } protected void registerChildrenHandler(String listenNode, ZooKeeper zooKeeper, NotifyWatcher watcher) { try { List<String> childPathList = zooKeeper.getChildren(listenNode, watcher); if (childPathList == null || childPathList.isEmpty()) { return; } for (String childPath : childPathList) { String childAbsPath = listenNode.concat(NODE_PATH_SPL).concat(childPath); zooKeeper.exists(childAbsPath, watcher, new StatCallback() { public void processResult(int rc, String path, Object ctx, Stat stat) { log.info("call exists callback rc:{}, path:{}, ctx:{}, stat:{}", new Object[] {rc, path, ctx, stat}); } }, this); log.info("register Children Watcher Handler : {}", childAbsPath); registerChildrenHandler(childAbsPath, zooKeeper, watcher); } log.info("register Children Watcher Handler : {}", listenNode); } catch (Throwable e) { log.error("register Watcher Handler : " + listenNode + " Error.", e); } } public void unregister(String listenNode, NotifyHandler handler) { this.client.unregister(new NotifyWatcher(listenNode, handler, this)); } }
package com.pilot51.voicenotify; import java.util.Timer; import java.util.TimerTask; import android.app.AlertDialog; import android.app.Dialog; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.TimePickerDialog; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; import android.widget.TimePicker; import android.widget.Toast; public class MainActivity extends PreferenceActivity implements OnPreferenceClickListener, OnSharedPreferenceChangeListener { private Common common; private Preference pScreen, pQuietStart, pQuietEnd, pTest, pSupport; private static final int DLG_SCREEN = 0, DLG_QUIET_START = 1, DLG_QUIET_END = 2, DLG_SUPPORT = 3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); common = new Common(this); addPreferencesFromResource(R.xml.preferences); pScreen = findPreference("screen"); pScreen.setOnPreferenceClickListener(this); pQuietStart = findPreference("quietStart"); pQuietStart.setOnPreferenceClickListener(this); pQuietEnd = findPreference("quietEnd"); pQuietEnd.setOnPreferenceClickListener(this); pTest = findPreference("test"); pTest.setOnPreferenceClickListener(this); pSupport = findPreference("support"); pSupport.setOnPreferenceClickListener(this); findPreference("appList").setIntent(new Intent(this, AppList.class)); Preference pAccess = findPreference("accessibility"), pTTS = findPreference("ttsSettings"); int sdkVer = android.os.Build.VERSION.SDK_INT; if (sdkVer > 4) pAccess.setIntent(new Intent(android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS)); else if (sdkVer == 4) { Intent intent = new Intent(Intent.ACTION_MAIN); intent.setClassName("com.android.settings", "com.android.settings.AccessibilitySettings"); pAccess.setIntent(intent); } Intent intent = new Intent(Intent.ACTION_MAIN); intent.setClassName("com.android.settings", "com.android.settings.TextToSpeechSettings"); if (!isCallable(intent)) intent.setClassName("com.android.settings", "com.android.settings.Settings$TextToSpeechSettingsActivity"); if (!isCallable(intent)) intent.setClassName("com.google.tv.settings", "com.google.tv.settings.TextToSpeechSettingsTop"); if (isCallable(intent)) pTTS.setIntent(intent); else { pTTS.setEnabled(false); pTTS.setSummary(R.string.tts_settings_summary_fail); } } private boolean isCallable(Intent intent) { return getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null; } @Override public boolean onPreferenceClick(Preference preference) { if (preference == pScreen) { showDialog(DLG_SCREEN); return true; } else if (preference == pQuietStart) { showDialog(DLG_QUIET_START); return true; } else if (preference == pQuietEnd) { showDialog(DLG_QUIET_END); return true; } else if (preference == pTest) { new Timer().schedule(new TimerTask() { @Override public void run() { Notification notification = new Notification(R.drawable.icon, getString(R.string.test_notify_msg), System.currentTimeMillis()); notification.defaults |= Notification.DEFAULT_SOUND; notification.flags |= Notification.FLAG_AUTO_CANCEL; notification.setLatestEventInfo(MainActivity.this, Common.TAG, getString(R.string.test), PendingIntent.getActivity(MainActivity.this, 0, getIntent(), 0)); ((NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE)).notify(0, notification); } }, 5000); return true; } else if (preference == pSupport) { showDialog(DLG_SUPPORT); return true; } return false; } @Override protected Dialog onCreateDialog(int id) { int i; switch (id) { case DLG_SCREEN: final CharSequence[] items = {MainActivity.this.getString(R.string.screen_off), MainActivity.this.getString(R.string.screen_on), MainActivity.this.getString(R.string.headset_off), MainActivity.this.getString(R.string.headset_on)}; final String speakScreenOff = "speakScreenOff", speakScreenOn = "speakScreenOn", speakHeadsetOff = "speakHeadsetOff", speakHeadsetOn = "speakHeadsetOn"; return new AlertDialog.Builder(this) .setTitle(R.string.device_state_dialog_title) .setMultiChoiceItems(items, new boolean[] {Common.prefs.getBoolean(speakScreenOff, true), Common.prefs.getBoolean(speakScreenOn, true), Common.prefs.getBoolean(speakHeadsetOff, true), Common.prefs.getBoolean(speakHeadsetOn, true)}, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { if (which == 0) // Screen off Common.prefs.edit().putBoolean(speakScreenOff, isChecked).commit(); else if (which == 1) // Screen on Common.prefs.edit().putBoolean(speakScreenOn, isChecked).commit(); else if (which == 2) // Headset off Common.prefs.edit().putBoolean(speakHeadsetOff, isChecked).commit(); else if (which == 3) // Headset on Common.prefs.edit().putBoolean(speakHeadsetOn, isChecked).commit(); } }).create(); case DLG_QUIET_START: i = Common.prefs.getInt("quietStart", 0); return new TimePickerDialog(MainActivity.this, sTimeSetListener, i/60, i%60, false); case DLG_QUIET_END: i = Common.prefs.getInt("quietEnd", 0); return new TimePickerDialog(MainActivity.this, eTimeSetListener, i/60, i%60, false); case DLG_SUPPORT: return new AlertDialog.Builder(this) .setTitle(R.string.support) .setItems(R.array.support_items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { switch (item) { case 0: // Donate startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://paypal.com/cgi-bin/webscr?cmd=_donations&business=pilota51%40gmail%2ecom&lc=US&item_name=Voice%20Notify&no_note=0&no_shipping=1&currency_code=USD"))); break; case 1: // Rate/Comment Intent iMarket = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.pilot51.voicenotify")); iMarket.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { startActivity(iMarket); } catch (ActivityNotFoundException e) { e.printStackTrace(); Toast.makeText(getBaseContext(), R.string.error_market, Toast.LENGTH_LONG).show(); } break; case 2: // Contact developer Intent iEmail = new Intent(Intent.ACTION_SEND); iEmail.setType("plain/text"); iEmail.putExtra(Intent.EXTRA_EMAIL, new String[] {getString(R.string.dev_email)}); iEmail.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.email_subject)); try { startActivity(iEmail); } catch (ActivityNotFoundException e) { e.printStackTrace(); Toast.makeText(getBaseContext(), R.string.error_email, Toast.LENGTH_LONG).show(); } break; } } }).create(); } return null; } private TimePickerDialog.OnTimeSetListener sTimeSetListener = new TimePickerDialog.OnTimeSetListener() { public void onTimeSet(TimePicker view, int hourOfDay, int minute) { Common.prefs.edit().putInt("quietStart", hourOfDay * 60 + minute).commit(); } }; private TimePickerDialog.OnTimeSetListener eTimeSetListener = new TimePickerDialog.OnTimeSetListener() { public void onTimeSet(TimePicker view, int hourOfDay, int minute) { Common.prefs.edit().putInt("quietEnd", hourOfDay * 60 + minute).commit(); } }; @Override protected void onResume() { super.onResume(); Common.prefs.registerOnSharedPreferenceChangeListener(this); } @Override protected void onPause() { super.onPause(); Common.prefs.unregisterOnSharedPreferenceChangeListener(this); } public void onSharedPreferenceChanged(SharedPreferences sp, String key) { if (key.equals("ttsStream")) common.setVolumeStream(); } }
package AttitudeTracker; import java.awt.Dimension; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import javax.swing.JDialog; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.ejml.data.DenseMatrix64F; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.XYPlot; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; public class AttitudeTrackerTests { public static final int NUM_DATAPOINTS = 10000; public static final double DT = 0.1; // seconds public static final double PROCESS_NOISE_MAGNITUDE = 10; public static final double X_MEASUREMENT_NOISE_MAGNITUDE = 2; public static final double V_MEASUREMENT_NOISE_MAGNITUDE = 0.000001; public static final double A_MEASUREMENT_NOISE_MAGNITUDE = 0.000001; public static final double PROCESS_RATE = 1-10.0/NUM_DATAPOINTS; // the only parameter of this fictional process public static void main(String[] args) { // testSimpleKfWithSyntheticData(false); // testSpeedKfWithSyntheticData(false); // testAccelKfWithSyntheticData(false); // testUnmeasuredAccelKfWithSyntheticData(true); // testTankSteerWithControl(true); testKfWithRecordedData(true); } /** * Run a test on the KF class, using synthetic data, * modeling a trivially simple movement process, and only * tracking a single variable ("Position"). */ public static void testSimpleKfWithSyntheticData(boolean terminateAfter) { // Generate synthetic data for a simple fictional movement process double[] time = new double[NUM_DATAPOINTS]; double[] x_ideal = new double[NUM_DATAPOINTS]; double[] x_actual = new double[NUM_DATAPOINTS]; double[] x_measured = new double[NUM_DATAPOINTS]; double[] x_estimated = new double[NUM_DATAPOINTS]; double x_cum_error = 0; // cumulative positional error = estimated - actual double x_cum_pred_error = 0; // cumulative positional error = estimated - actual time [0] = 0.0; x_ideal [0] = 100.0; x_actual [0] = 100.0; x_measured [0] = 100.0; x_estimated[0] = 0.0; for(int i = 1; i < NUM_DATAPOINTS; ++i) { time[i] = i * DT; x_ideal[i] = x_ideal [i-1] * PROCESS_RATE; x_actual[i] = x_ideal [i] + PROCESS_NOISE_MAGNITUDE * (Math.random() * 2 - 1); x_measured[i] = x_actual[i] + X_MEASUREMENT_NOISE_MAGNITUDE * (Math.random() * 2 - 1); } // Configure filter KalmanFilterSimple kf = new KalmanFilterSimple(); DenseMatrix64F F = new DenseMatrix64F(new double[][]{ {0.9}, }); // S. Levy's tutorial calls this A DenseMatrix64F Q = new DenseMatrix64F(new double[][]{ {0.0}, }); // S. Levy's tutorial lacks this term DenseMatrix64F H = new DenseMatrix64F(new double[][]{ {1.0}, }); // S. Levy's tutorial calls this C DenseMatrix64F R = new DenseMatrix64F(new double[][]{ {0.75}, }); // Expected magnitude of sensor noise kf.configure(F, Q, H); // Run filter DenseMatrix64F x_init = new DenseMatrix64F(new double [][]{ {x_measured[0]} }); // Cheating a little here with an accurate initial estimate DenseMatrix64F p_init = new DenseMatrix64F(new double [][]{ {1} }); // Arbitrary, cannot be 0 kf.setState(x_init, p_init); for(int i = 1; i < NUM_DATAPOINTS; ++i) { DenseMatrix64F z = new DenseMatrix64F(new double [][]{ {x_measured[i]} }); kf.predict(); double x_prediction = kf.getState().data[0]; kf.update(z, R); x_estimated[i] = kf.getState().data[0]; double x_err = x_actual[i] - x_estimated[i]; x_cum_error += x_err * x_err; double x_pred_err = x_actual[i] - x_prediction; x_cum_pred_error += x_pred_err * x_pred_err; } double x_stddev = Math.sqrt(x_cum_error / NUM_DATAPOINTS); // not actually the standard deviation but a similar computation double x_pred_stddev = Math.sqrt(x_cum_pred_error / NUM_DATAPOINTS); // not actually the standard deviation but a similar computation System.out.println("Positional KF: Typical error: " + x_stddev + " typical deviation from prediction: " + x_pred_stddev); // Graph results XYSeries x_i_s = new XYSeries("Movement model"); XYSeries x_a_s = new XYSeries("Actual position"); XYSeries x_m_s = new XYSeries("Measured position"); XYSeries x_e_s = new XYSeries("Estimated position"); for(int i = 1; i < NUM_DATAPOINTS; ++i) { x_i_s.add(time[i], x_ideal[i]); x_a_s.add(time[i], x_actual[i]); x_m_s.add(time[i], x_measured[i]); x_e_s.add(time[i], x_estimated[i]); } XYSeriesCollection sc = new XYSeriesCollection(); sc.addSeries(x_e_s); sc.addSeries(x_m_s); sc.addSeries(x_a_s); sc.addSeries(x_i_s); JFreeChart chart = ChartFactory.createXYLineChart("Simple KF test", "Time (s)", "Value", sc); showChart(chart, terminateAfter); } /** * Run a test on the KF class, using synthetic data, * modeling a trivially simple movement process, tracking * both position and velocity. */ public static void testSpeedKfWithSyntheticData(boolean terminateAfter) { // Generate synthetic data for a simple fictional movement process double[] time = new double[NUM_DATAPOINTS]; // X represents the position double[] x_ideal = new double[NUM_DATAPOINTS]; double[] x_actual = new double[NUM_DATAPOINTS]; double[] x_measured = new double[NUM_DATAPOINTS]; double[] x_estimated = new double[NUM_DATAPOINTS]; double x_cum_error = 0; // cumulative error = estimated - actual double x_cum_pred_error = 0; // cumulative predicted error = predicted - actual // V represents the velocity (derivative of position) double[] v_ideal = new double[NUM_DATAPOINTS]; double[] v_actual = new double[NUM_DATAPOINTS]; double[] v_measured = new double[NUM_DATAPOINTS]; double[] v_estimated = new double[NUM_DATAPOINTS]; double v_cum_error = 0; // cumulative error = estimated - actual double v_cum_pred_error = 0; // cumulative prediction error = predicted - actual time [0] = 0.0; x_ideal [0] = 100.0; x_actual [0] = 100.0; x_measured [0] = 100.0; x_estimated[0] = 0.0; v_ideal [0] = 0.0; v_actual [0] = -50.0; v_measured [0] = -50.0; v_estimated[0] = 0.0; for(int i = 1; i < NUM_DATAPOINTS; ++i) { time[i] = i * DT; x_ideal[i] = x_ideal [i-1] * PROCESS_RATE; x_actual[i] = x_ideal [i] + PROCESS_NOISE_MAGNITUDE * (Math.random() * 2 - 1); x_measured[i] = x_actual[i] + X_MEASUREMENT_NOISE_MAGNITUDE * (Math.random() * 2 - 1); v_ideal[i] = (x_ideal [i] - x_ideal [i-1]) / DT; v_actual[i] = (x_actual[i] - x_actual[i-1]) / DT; v_measured[i] = v_actual[i] + V_MEASUREMENT_NOISE_MAGNITUDE * (Math.random() * 2 - 1); } // Configure filter KalmanFilterSimple kf = new KalmanFilterSimple(); DenseMatrix64F F = new DenseMatrix64F(new double[][]{ {1.0, DT}, {0.0, PROCESS_RATE}, }); // The system dynamics model, S. Levy's tutorial calls this A DenseMatrix64F Q = new DenseMatrix64F(new double[][]{ {PROCESS_NOISE_MAGNITUDE * 0.25, 0.0}, {0.0, 0.0}, }); // Noise covariance, must be estimated or ignored. S. Levy's tutorial lacks this term, but it's added to the system dynamics model each predict step DenseMatrix64F H = new DenseMatrix64F(new double[][]{ {1.0, 0.0}, {0.0, 1.0}, }); // Maps observations to state variables - S. Levy's tutorial calls this C DenseMatrix64F R = new DenseMatrix64F(new double[][]{ {X_MEASUREMENT_NOISE_MAGNITUDE * 0.5, 0.0}, {0.0, V_MEASUREMENT_NOISE_MAGNITUDE * 0.5}, }); // Sensor value variance/covariance. This is a fake estimate for now. kf.configure(F, Q, H); // Run filter DenseMatrix64F x_init = new DenseMatrix64F(new double [][]{ {x_measured[0]}, {v_measured[0]}, }); // Cheating a little here with an accurate initial estimate DenseMatrix64F p_init = new DenseMatrix64F(new double [][]{ {1, 0}, {0, 1}, }); // Arbitrary at the moment kf.setState(x_init, p_init); for(int i = 1; i < NUM_DATAPOINTS; ++i) { DenseMatrix64F z = new DenseMatrix64F(new double [][]{ {x_measured[i]}, {v_measured[i]}, }); kf.predict(); double x_prediction = kf.getState().data[0]; double v_prediction = kf.getState().data[1]; kf.update(z, R); x_estimated[i] = kf.getState().data[0]; v_estimated[i] = kf.getState().data[1]; double x_err = x_actual[i] - x_estimated[i]; x_cum_error += x_err * x_err; double x_pred_err = x_actual[i] - x_prediction; x_cum_pred_error += x_pred_err * x_pred_err; double v_err = v_actual[i] - v_estimated[i]; v_cum_error += v_err * v_err; double v_pred_err = v_actual[i] - v_prediction; v_cum_pred_error += v_pred_err * v_pred_err; } double x_stddev = Math.sqrt(x_cum_error / NUM_DATAPOINTS); // not actually the standard deviation but a similar computation double x_pred_stddev = Math.sqrt(x_cum_pred_error / NUM_DATAPOINTS); // not actually the standard deviation but a similar computation double v_stddev = Math.sqrt(v_cum_error / NUM_DATAPOINTS); // not actually the standard deviation but a similar computation double v_pred_stddev = Math.sqrt(v_cum_pred_error / NUM_DATAPOINTS); // not actually the standard deviation but a similar computation System.out.println("Speed KF: Typical X error: " + x_stddev + " typical X deviation from prediction: " + x_pred_stddev); System.out.println("Speed KF: Typical V error: " + v_stddev + " typical V deviation from prediction: " + v_pred_stddev); // Graph results XYSeries x_i_s = new XYSeries("Model position"); XYSeries x_a_s = new XYSeries("Actual position"); XYSeries x_m_s = new XYSeries("Measured position"); XYSeries x_e_s = new XYSeries("Estimated position"); XYSeries v_i_s = new XYSeries("Model speed"); XYSeries v_a_s = new XYSeries("Actual speed"); XYSeries v_m_s = new XYSeries("Measured speed"); XYSeries v_e_s = new XYSeries("Estimated speed"); for(int i = 1; i < NUM_DATAPOINTS; ++i) { x_i_s.add(time[i], x_ideal[i]); x_a_s.add(time[i], x_actual[i]); x_m_s.add(time[i], x_measured[i]); x_e_s.add(time[i], x_estimated[i]); v_i_s.add(time[i], v_ideal[i]); v_a_s.add(time[i], v_actual[i]); v_m_s.add(time[i], v_measured[i]); v_e_s.add(time[i], v_estimated[i]); } XYSeriesCollection sc = new XYSeriesCollection(); sc.addSeries(x_e_s); sc.addSeries(x_m_s); sc.addSeries(x_a_s); sc.addSeries(x_i_s); sc.addSeries(v_e_s); sc.addSeries(v_m_s); sc.addSeries(v_a_s); sc.addSeries(v_i_s); JFreeChart chart = ChartFactory.createXYLineChart("Speed KF test", "Time (s)", "Value", sc); showChart(chart, terminateAfter); } /** * Run a test on the KF class, using synthetic data, * modeling a trivially simple movement process, tracking * position, velocity, and acceleration. */ public static void testAccelKfWithSyntheticData(boolean terminateAfter) { // Generate synthetic data for a simple fictional movement process double[] time = new double[NUM_DATAPOINTS]; // X represents the position double[] x_ideal = new double[NUM_DATAPOINTS]; double[] x_actual = new double[NUM_DATAPOINTS]; double[] x_measured = new double[NUM_DATAPOINTS]; double[] x_estimated = new double[NUM_DATAPOINTS]; double x_cum_error = 0; // cumulative error = estimated - actual double x_cum_pred_error = 0; // cumulative predicted error = predicted - actual // V represents the velocity (derivative of position) double[] v_ideal = new double[NUM_DATAPOINTS]; double[] v_actual = new double[NUM_DATAPOINTS]; double[] v_measured = new double[NUM_DATAPOINTS]; double[] v_estimated = new double[NUM_DATAPOINTS]; double v_cum_error = 0; // cumulative error = estimated - actual double v_cum_pred_error = 0; // cumulative prediction error = predicted - actual // A represents the acceleration (derivative of velocity) double[] a_ideal = new double[NUM_DATAPOINTS]; double[] a_actual = new double[NUM_DATAPOINTS]; double[] a_measured = new double[NUM_DATAPOINTS]; double[] a_estimated = new double[NUM_DATAPOINTS]; double a_cum_error = 0; // cumulative error = estimated - actual double a_cum_pred_error = 0; // cumulative predicted error = predicted - actual time [0] = 0.0; x_ideal [0] = 100.0; x_actual [0] = 100.0; x_measured [0] = 100.0; x_estimated[0] = 0.0; v_ideal [0] = 0.0; v_actual [0] = -50.0; v_measured [0] = -50.0; v_estimated[0] = 0.0; a_ideal [0] = 0.0; a_actual [0] = 0.0; a_measured [0] = 0.0; a_estimated[0] = 0.0; for(int i = 1; i < NUM_DATAPOINTS; ++i) { time[i] = i * DT; x_ideal[i] = x_ideal [i-1] * PROCESS_RATE; x_actual[i] = x_ideal [i] + PROCESS_NOISE_MAGNITUDE * (Math.random() * 2 - 1); x_measured[i] = x_actual[i] + X_MEASUREMENT_NOISE_MAGNITUDE * (Math.random() * 2 - 1); v_ideal[i] = (x_ideal [i] - x_ideal [i-1]) / DT; v_actual[i] = (x_actual[i] - x_actual[i-1]) / DT; v_measured[i] = v_actual[i] + V_MEASUREMENT_NOISE_MAGNITUDE * (Math.random() * 2 - 1); a_ideal[i] = (v_ideal [i] - v_ideal [i-1]) / DT; a_actual[i] = (v_actual[i] - v_actual[i-1]) / DT; a_measured[i] = a_actual[i] + A_MEASUREMENT_NOISE_MAGNITUDE * (Math.random() * 2 - 1); } // Configure filter KalmanFilterSimple kf = new KalmanFilterSimple(); DenseMatrix64F F = new DenseMatrix64F(new double[][]{ {1.0, DT, 0.0}, {0.0, 1.0, DT}, {0.0, 0.0, 1.0}, }); // The system dynamics model, S. Levy's tutorial calls this A DenseMatrix64F Q = new DenseMatrix64F(new double[][]{ {PROCESS_NOISE_MAGNITUDE * 0.25, 0.0, 0.0}, {0.0, 0.0, 0.0}, {0.0, 0.0, 0.0}, }); // Noise covariance, must be estimated or ignored. S. Levy's tutorial lacks this term, but it's added to the system dynamics model each predict step DenseMatrix64F H = new DenseMatrix64F(new double[][]{ {1.0, 0.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 0.0, 1.0}, }); // Maps observations to state variables - S. Levy's tutorial calls this C DenseMatrix64F R = new DenseMatrix64F(new double[][]{ {X_MEASUREMENT_NOISE_MAGNITUDE * 0.5, 0.0, 0.0}, {0.0, V_MEASUREMENT_NOISE_MAGNITUDE * 0.5, 0.0}, {0.0, 0.0, A_MEASUREMENT_NOISE_MAGNITUDE * 0.5}, }); // Sensor value variance/covariance. This is a fake estimate for now. kf.configure(F, Q, H); // Run filter DenseMatrix64F x_init = new DenseMatrix64F(new double [][]{ {x_measured[0]}, {v_measured[0]}, {a_measured[0]}, }); // Cheating a little here with an accurate initial estimate DenseMatrix64F p_init = new DenseMatrix64F(new double [][]{ {1, 0, 0}, {0, 1, 0}, {0, 0, 1}, }); // Arbitrary at the moment kf.setState(x_init, p_init); for(int i = 1; i < NUM_DATAPOINTS; ++i) { DenseMatrix64F z = new DenseMatrix64F(new double [][]{ {x_measured[i]}, {v_measured[i]}, {a_measured[i]}, }); kf.predict(); double x_prediction = kf.getState().data[0]; double v_prediction = kf.getState().data[1]; double a_prediction = kf.getState().data[2]; kf.update(z, R); x_estimated[i] = kf.getState().data[0]; v_estimated[i] = kf.getState().data[1]; a_estimated[i] = kf.getState().data[2]; double x_err = x_actual[i] - x_estimated[i]; x_cum_error += x_err * x_err; double x_pred_err = x_actual[i] - x_prediction; x_cum_pred_error += x_pred_err * x_pred_err; double v_err = v_actual[i] - v_estimated[i]; v_cum_error += v_err * v_err; double v_pred_err = v_actual[i] - v_prediction; v_cum_pred_error += v_pred_err * v_pred_err; double a_err = a_actual[i] - a_estimated[i]; a_cum_error += a_err * a_err; double a_pred_err = a_actual[i] - a_prediction; a_cum_pred_error += a_pred_err * a_pred_err; } double x_stddev = Math.sqrt(x_cum_error / NUM_DATAPOINTS); // not actually the standard deviation but a similar computation double x_pred_stddev = Math.sqrt(x_cum_pred_error / NUM_DATAPOINTS); // not actually the standard deviation but a similar computation double v_stddev = Math.sqrt(v_cum_error / NUM_DATAPOINTS); // not actually the standard deviation but a similar computation double v_pred_stddev = Math.sqrt(v_cum_pred_error / NUM_DATAPOINTS); // not actually the standard deviation but a similar computation double a_stddev = Math.sqrt(a_cum_error / NUM_DATAPOINTS); // not actually the standard deaiation but a similar computation double a_pred_stddev = Math.sqrt(a_cum_pred_error / NUM_DATAPOINTS); // not actually the standard deaiation but a similar computation System.out.println("Accel KF: Typical X error: " + x_stddev + " typical X deviation from prediction: " + x_pred_stddev); System.out.println("Accel KF: Typical V error: " + v_stddev + " typical V deviation from prediction: " + v_pred_stddev); System.out.println("Accel KF: Typical A error: " + a_stddev + " typical A deviation from prediction: " + a_pred_stddev); // Graph results XYSeries x_i_s = new XYSeries("Model position"); XYSeries x_a_s = new XYSeries("Actual position"); XYSeries x_m_s = new XYSeries("Measured position"); XYSeries x_e_s = new XYSeries("Estimated position"); XYSeries v_i_s = new XYSeries("Model speed"); XYSeries v_a_s = new XYSeries("Actual speed"); XYSeries v_m_s = new XYSeries("Measured speed"); XYSeries v_e_s = new XYSeries("Estimated speed"); XYSeries a_i_s = new XYSeries("Model accel"); XYSeries a_a_s = new XYSeries("Actual accel"); XYSeries a_m_s = new XYSeries("Measured accel"); XYSeries a_e_s = new XYSeries("Estimated accel"); for(int i = 1; i < NUM_DATAPOINTS; ++i) { x_i_s.add(time[i], x_ideal[i]); x_a_s.add(time[i], x_actual[i]); x_m_s.add(time[i], x_measured[i]); x_e_s.add(time[i], x_estimated[i]); v_i_s.add(time[i], v_ideal[i]); v_a_s.add(time[i], v_actual[i]); v_m_s.add(time[i], v_measured[i]); v_e_s.add(time[i], v_estimated[i]); a_i_s.add(time[i], a_ideal[i]); a_a_s.add(time[i], a_actual[i]); a_m_s.add(time[i], a_measured[i]); a_e_s.add(time[i], a_estimated[i]); } XYSeriesCollection sc = new XYSeriesCollection(); sc.addSeries(x_e_s); sc.addSeries(x_m_s); sc.addSeries(x_a_s); sc.addSeries(x_i_s); sc.addSeries(v_e_s); sc.addSeries(v_m_s); sc.addSeries(v_a_s); sc.addSeries(v_i_s); sc.addSeries(a_e_s); sc.addSeries(a_m_s); sc.addSeries(a_a_s); sc.addSeries(a_i_s); JFreeChart chart = ChartFactory.createXYLineChart("Accel KF test", "Time (s)", "Value", sc); showChart(chart, terminateAfter); } /** * Run a test on the KF class, using synthetic data, * modeling a trivially simple movement process, tracking * position, velocity, and acceleration. * * However, this one tracks acceleration without any sensor input representing acceleration. */ public static void testUnmeasuredAccelKfWithSyntheticData(boolean terminateAfter) { // Generate synthetic data for a simple fictional movement process double[] time = new double[NUM_DATAPOINTS]; // X represents the position double[] x_ideal = new double[NUM_DATAPOINTS]; double[] x_actual = new double[NUM_DATAPOINTS]; double[] x_measured = new double[NUM_DATAPOINTS]; double[] x_estimated = new double[NUM_DATAPOINTS]; double x_cum_error = 0; // cumulative error = estimated - actual double x_cum_pred_error = 0; // cumulative predicted error = predicted - actual // V represents the velocity (derivative of position) double[] v_ideal = new double[NUM_DATAPOINTS]; double[] v_actual = new double[NUM_DATAPOINTS]; double[] v_measured = new double[NUM_DATAPOINTS]; double[] v_estimated = new double[NUM_DATAPOINTS]; double v_cum_error = 0; // cumulative error = estimated - actual double v_cum_pred_error = 0; // cumulative prediction error = predicted - actual // A represents the acceleration (derivative of velocity) double[] a_ideal = new double[NUM_DATAPOINTS]; double[] a_actual = new double[NUM_DATAPOINTS]; double[] a_estimated = new double[NUM_DATAPOINTS]; double a_cum_error = 0; // cumulative error = estimated - actual double a_cum_pred_error = 0; // cumulative predicted error = predicted - actual time [0] = 0.0; x_ideal [0] = 100.0; x_actual [0] = 100.0; x_measured [0] = 100.0; x_estimated[0] = 0.0; v_ideal [0] = 0.0; v_actual [0] = -50.0; v_measured [0] = -50.0; v_estimated[0] = 0.0; a_ideal [0] = 0.0; a_actual [0] = 0.0; a_estimated[0] = 0.0; for(int i = 1; i < NUM_DATAPOINTS; ++i) { time[i] = i * DT; x_ideal[i] = x_ideal [i-1] * PROCESS_RATE; x_actual[i] = x_ideal [i] + PROCESS_NOISE_MAGNITUDE * (Math.random() * 2 - 1); x_measured[i] = x_actual[i] + X_MEASUREMENT_NOISE_MAGNITUDE * (Math.random() * 2 - 1); v_ideal[i] = (x_ideal [i] - x_ideal [i-1]) / DT; v_actual[i] = (x_actual[i] - x_actual[i-1]) / DT; v_measured[i] = v_actual[i] + V_MEASUREMENT_NOISE_MAGNITUDE * (Math.random() * 2 - 1); a_ideal[i] = (v_ideal [i] - v_ideal [i-1]) / DT; a_actual[i] = (v_actual[i] - v_actual[i-1]) / DT; } // Configure filter KalmanFilterSimple kf = new KalmanFilterSimple(); DenseMatrix64F F = new DenseMatrix64F(new double[][]{ {1.0, DT, 0.0}, {0.0, 1.0, DT}, {0.0, 0.0, 1.0}, }); // The system dynamics model, S. Levy's tutorial calls this A DenseMatrix64F Q = new DenseMatrix64F(new double[][]{ {PROCESS_NOISE_MAGNITUDE * 0.25, 0.0, 0.0}, {0.0, 0.0, 0.0}, {0.0, 0.0, 0.0}, }); // Noise covariance, must be estimated or ignored. S. Levy's tutorial lacks this term, but it's added to the system dynamics model each predict step DenseMatrix64F H = new DenseMatrix64F(new double[][]{ {1.0, 0.0, 0.0}, {0.0, 1.0, 0.0}, }); // Maps observations to state variables - S. Levy's tutorial calls this C DenseMatrix64F R = new DenseMatrix64F(new double[][]{ {X_MEASUREMENT_NOISE_MAGNITUDE * 0.5, 0.0}, {0.0, V_MEASUREMENT_NOISE_MAGNITUDE * 0.5}, }); // Sensor value variance/covariance. This is a fake estimate for now. kf.configure(F, Q, H); // Run filter DenseMatrix64F x_init = new DenseMatrix64F(new double [][]{ {x_measured[0]}, {v_measured[0]}, {0.0}, }); // Cheating a little here with an accurate initial estimate DenseMatrix64F p_init = new DenseMatrix64F(new double [][]{ {1, 0, 0}, {0, 1, 0}, {0, 0, 1}, }); // Arbitrary at the moment kf.setState(x_init, p_init); for(int i = 1; i < NUM_DATAPOINTS; ++i) { DenseMatrix64F z = new DenseMatrix64F(new double [][]{ {x_measured[i]}, {v_measured[i]}, }); kf.predict(); double x_prediction = kf.getState().data[0]; double v_prediction = kf.getState().data[1]; double a_prediction = kf.getState().data[2]; kf.update(z, R); x_estimated[i] = kf.getState().data[0]; v_estimated[i] = kf.getState().data[1]; a_estimated[i] = kf.getState().data[2]; double x_err = x_actual[i] - x_estimated[i]; x_cum_error += x_err * x_err; double x_pred_err = x_actual[i] - x_prediction; x_cum_pred_error += x_pred_err * x_pred_err; double v_err = v_actual[i] - v_estimated[i]; v_cum_error += v_err * v_err; double v_pred_err = v_actual[i] - v_prediction; v_cum_pred_error += v_pred_err * v_pred_err; double a_err = a_actual[i] - a_estimated[i]; a_cum_error += a_err * a_err; double a_pred_err = a_actual[i] - a_prediction; a_cum_pred_error += a_pred_err * a_pred_err; } double x_stddev = Math.sqrt(x_cum_error / NUM_DATAPOINTS); // not actually the standard deviation but a similar computation double x_pred_stddev = Math.sqrt(x_cum_pred_error / NUM_DATAPOINTS); // not actually the standard deviation but a similar computation double v_stddev = Math.sqrt(v_cum_error / NUM_DATAPOINTS); // not actually the standard deviation but a similar computation double v_pred_stddev = Math.sqrt(v_cum_pred_error / NUM_DATAPOINTS); // not actually the standard deviation but a similar computation double a_stddev = Math.sqrt(a_cum_error / NUM_DATAPOINTS); // not actually the standard deaiation but a similar computation double a_pred_stddev = Math.sqrt(a_cum_pred_error / NUM_DATAPOINTS); // not actually the standard deaiation but a similar computation System.out.println("Unmeasured Accel KF: Typical X error: " + x_stddev + " typical X deviation from prediction: " + x_pred_stddev); System.out.println("Unmeasured Accel KF: Typical V error: " + v_stddev + " typical V deviation from prediction: " + v_pred_stddev); System.out.println("Unmeasured Accel KF: Typical A error: " + a_stddev + " typical A deviation from prediction: " + a_pred_stddev); // Graph results XYSeries x_i_s = new XYSeries("Model position"); XYSeries x_a_s = new XYSeries("Actual position"); XYSeries x_m_s = new XYSeries("Measured position"); XYSeries x_e_s = new XYSeries("Estimated position"); XYSeries v_i_s = new XYSeries("Model speed"); XYSeries v_a_s = new XYSeries("Actual speed"); XYSeries v_m_s = new XYSeries("Measured speed"); XYSeries v_e_s = new XYSeries("Estimated speed"); XYSeries a_i_s = new XYSeries("Model accel"); XYSeries a_a_s = new XYSeries("Actual accel"); XYSeries a_e_s = new XYSeries("Estimated accel"); for(int i = 1; i < NUM_DATAPOINTS; ++i) { x_i_s.add(time[i], x_ideal[i]); x_a_s.add(time[i], x_actual[i]); x_m_s.add(time[i], x_measured[i]); x_e_s.add(time[i], x_estimated[i]); v_i_s.add(time[i], v_ideal[i]); v_a_s.add(time[i], v_actual[i]); v_m_s.add(time[i], v_measured[i]); v_e_s.add(time[i], v_estimated[i]); a_i_s.add(time[i], a_ideal[i]); a_a_s.add(time[i], a_actual[i]); a_e_s.add(time[i], a_estimated[i]); } XYSeriesCollection sc = new XYSeriesCollection(); sc.addSeries(x_e_s); sc.addSeries(x_m_s); sc.addSeries(x_a_s); sc.addSeries(x_i_s); sc.addSeries(v_e_s); sc.addSeries(v_m_s); sc.addSeries(v_a_s); sc.addSeries(v_i_s); sc.addSeries(a_e_s); sc.addSeries(a_a_s); sc.addSeries(a_i_s); JFreeChart chart = ChartFactory.createXYLineChart("Accel KF test without measurement input", "Time (s)", "Value", sc); showChart(chart, terminateAfter); } /** * Simulate a tank-drive robot * */ public static void testTankSteerWithControl(boolean terminateAfter) { // Generate simulated sensor data for a robot that: /* - Sits still for 1s * - Pivots right for 2s * - Drives straight for 1s * - Curves left for 3s * - Drives straight back for 1s * - Tries to pivot for 2s but the robot is held fixed in place * - Drives straight forward for 5s */ // Shadow some of the default values final int NUM_DATAPOINTS = (int)((1+2+1+3+1+2+5) / DT); final double MAX_VEHICLE_PIVOT_RATE_RAD_PER_S = Math.PI; final double YAW_PROCESS_NOISE_MAGNITUDE_RAD = 5 * Math.PI / 180; final double YAW_RATE_PROCESS_NOISE_MAGNITUDE_RAD_S = 5 * Math.PI / 180; final double YAW_MEASUREMENT_NOISE_MAGNITUDE_RAD = 15 * Math.PI / 180; final double YAW_RATE_MEASUREMENT_NOISE_MAGNITUDE_RAD_PER_S = 10 * Math.PI / 180; double[] time = new double[NUM_DATAPOINTS]; // Control input double[] left_wheel_speed = new double[NUM_DATAPOINTS]; double[] right_wheel_speed = new double[NUM_DATAPOINTS]; // Position double[] yaw_ideal = new double[NUM_DATAPOINTS]; double[] yaw_actual = new double[NUM_DATAPOINTS]; double[] yaw_measured = new double[NUM_DATAPOINTS]; double[] yaw_estimated = new double[NUM_DATAPOINTS]; double yaw_cum_error = 0; // cumulative error = estimated - actual double yaw_cum_pred_error = 0; // cumulative predicted error = predicted - actual // Rate - d(yaw)/dt double[] yaw_rate_ideal = new double[NUM_DATAPOINTS]; double[] yaw_rate_actual = new double[NUM_DATAPOINTS]; double[] yaw_rate_measured = new double[NUM_DATAPOINTS]; double[] yaw_rate_estimated = new double[NUM_DATAPOINTS]; double yaw_rate_cum_error = 0; // cumulative error = estimated - actual double yaw_rate_cum_pred_error = 0; // cumulative predicted error = predicted - actual for(int i = 0; i < NUM_DATAPOINTS; ++i) { time[i] = i * DT; boolean moving = true; boolean wheels_slipping = false; if(time[i] < 1.0) { // Sit still to start out moving = false; left_wheel_speed [i] = 0.0; right_wheel_speed[i] = 0.0; } else if(time[i] < 3.0) { // Pivot right left_wheel_speed [i] = +1.0; right_wheel_speed[i] = -1.0; } else if(time[i] < 5.0) { // Go straight left_wheel_speed [i] = +1.0; right_wheel_speed[i] = +1.0; } else if(time[i] < 8.0) { // Curve left left_wheel_speed [i] = 0.0; right_wheel_speed[i] = +1.0; } else if(time[i] < 9.0) { // Straight back left_wheel_speed [i] = -1.0; right_wheel_speed[i] = -1.0; } else if(time[i] < 11.0) { // Get stuck trying to turn wheels_slipping = true; yaw_rate_ideal[i] = 0; left_wheel_speed [i] = -1.0; right_wheel_speed[i] = +1.0; } else if(time[i] < 16.0) { // Straight forward left_wheel_speed [i] = +1.0; right_wheel_speed[i] = +1.0; } // Compute turning equation if(!wheels_slipping) { yaw_rate_ideal[i] = MAX_VEHICLE_PIVOT_RATE_RAD_PER_S * (left_wheel_speed[i] - right_wheel_speed[i]) / 2; } double yaw = (i == 0)? 0 : yaw_ideal[i - 1]; yaw_ideal[i] = yaw + yaw_rate_ideal[i] * DT; // There's no wobbling when the vehicle's stationary yaw_actual[i] = yaw_ideal[i]; yaw_rate_actual[i] = yaw_rate_ideal[i]; if(moving) { yaw_actual[i] += (2 * Math.random() - 1) * YAW_PROCESS_NOISE_MAGNITUDE_RAD; yaw_rate_actual[i] += (2 * Math.random() - 1) * YAW_RATE_PROCESS_NOISE_MAGNITUDE_RAD_S; } // There's always sensor noise yaw_measured[i] = yaw_actual[i] + (2 * Math.random() - 1) * YAW_MEASUREMENT_NOISE_MAGNITUDE_RAD; yaw_rate_measured[i] = yaw_rate_actual[i] + (2 * Math.random() - 1) * YAW_RATE_MEASUREMENT_NOISE_MAGNITUDE_RAD_PER_S; } // Configure filter KalmanFilterWithControl kf = new KalmanFilterWithControl(); DenseMatrix64F F = new DenseMatrix64F(new double[][]{ {1.0, DT }, {0.0,0.9}, // base the yaw rate estimate entirely on the controls }); // The system dynamics model, S. Levy's tutorial calls this A DenseMatrix64F Q = new DenseMatrix64F(new double[][]{ {YAW_PROCESS_NOISE_MAGNITUDE_RAD * 0.25, 0.0}, {0.0, YAW_RATE_PROCESS_NOISE_MAGNITUDE_RAD_S * 0.25}, }); // Noise covariance, must be estimated or ignored. DenseMatrix64F H = new DenseMatrix64F(new double[][]{ {1.0, 0.0}, {0.0, 1.0}, }); // Maps observations to state variables - S. Levy's tutorial calls this C DenseMatrix64F B = new DenseMatrix64F(new double[][]{ {0.0, 0.0}, {0.1, -0.1}, // Effect on each state variable for each control input }); // Maps controls to state variables DenseMatrix64F R = new DenseMatrix64F(new double[][]{ {YAW_MEASUREMENT_NOISE_MAGNITUDE_RAD * 0.5, 0.0}, {0.0, YAW_RATE_MEASUREMENT_NOISE_MAGNITUDE_RAD_PER_S * 0.5}, }); // Sensor value variance/covariance. This is a fake estimate for now. kf.configure(F, Q, H, B); // Run filter DenseMatrix64F x_init = new DenseMatrix64F(new double [][]{ {0.0}, {0.0}, }); // Start stationary DenseMatrix64F p_init = new DenseMatrix64F(new double [][]{ {1, 0}, {0, 1}, }); // Arbitrary at the moment kf.setState(x_init, p_init); for(int i = 0; i < NUM_DATAPOINTS; ++i) { DenseMatrix64F z = new DenseMatrix64F(new double [][]{ {yaw_measured[i]}, {yaw_rate_measured[i]}, }); DenseMatrix64F u = new DenseMatrix64F(new double [][]{ {left_wheel_speed [i]}, {right_wheel_speed[i]}, }); kf.predict(u); double yaw_prediction = kf.getState().data[0]; double yaw_rate_prediction = kf.getState().data[1]; kf.update(z, R); yaw_estimated[i] = kf.getState().data[0]; yaw_rate_estimated[i] = kf.getState().data[1]; double yaw_err = yaw_actual[i] - yaw_estimated[i]; yaw_cum_error += yaw_err * yaw_err; double yaw_pred_err = yaw_actual[i] - yaw_prediction; yaw_cum_pred_error += yaw_pred_err * yaw_pred_err; double yaw_rate_err = yaw_rate_actual[i] - yaw_rate_estimated[i]; yaw_rate_cum_error += yaw_rate_err * yaw_rate_err; double yaw_rate_pred_err = yaw_rate_actual[i] - yaw_rate_prediction; yaw_rate_cum_pred_error += yaw_rate_pred_err * yaw_rate_pred_err; } double yaw_stddev = Math.sqrt(yaw_cum_error / NUM_DATAPOINTS); // not actually the standard deviation but a similar computation double yaw_pred_stddev = Math.sqrt(yaw_cum_pred_error / NUM_DATAPOINTS); // not actually the standard deviation but a similar computation double yaw_rate_stddev = Math.sqrt(yaw_rate_cum_error / NUM_DATAPOINTS); // not actually the standard deviation but a similar computation double yaw_rate_pred_stddev = Math.sqrt(yaw_rate_cum_pred_error / NUM_DATAPOINTS); // not actually the standard deviation but a similar computation System.out.println("Tank steer KF: Typical yaw error: " + yaw_stddev * 180 / Math.PI + "deg, typical yaw deviation from prediction: " + yaw_pred_stddev * 180 / Math.PI); System.out.println("Tank steer KF: Typical yaw rate error: " + yaw_rate_stddev * 180 / Math.PI + "deg, typical yaw rate deviation from prediction: " + yaw_rate_pred_stddev * 180 / Math.PI); // Graph results XYSeries x_i_s = new XYSeries("Model yaw"); XYSeries x_a_s = new XYSeries("Actual yaw"); XYSeries x_m_s = new XYSeries("Measured yaw"); XYSeries x_e_s = new XYSeries("Estimated yaw"); XYSeries v_i_s = new XYSeries("Model yaw rate"); XYSeries v_a_s = new XYSeries("Actual yaw rate"); XYSeries v_m_s = new XYSeries("Measured yaw rate"); XYSeries v_e_s = new XYSeries("Estimated yaw rate"); for(int i = 1; i < NUM_DATAPOINTS; ++i) { x_i_s.add(time[i], yaw_ideal[i]); x_a_s.add(time[i], yaw_actual[i]); x_m_s.add(time[i], yaw_measured[i]); x_e_s.add(time[i], yaw_estimated[i]); v_i_s.add(time[i], yaw_rate_ideal[i]); v_a_s.add(time[i], yaw_rate_actual[i]); v_m_s.add(time[i], yaw_rate_measured[i]); v_e_s.add(time[i], yaw_rate_estimated[i]); } XYSeriesCollection sc = new XYSeriesCollection(); sc.addSeries(x_e_s); sc.addSeries(x_m_s); sc.addSeries(x_a_s); sc.addSeries(x_i_s); sc.addSeries(v_e_s); sc.addSeries(v_m_s); sc.addSeries(v_a_s); sc.addSeries(v_i_s); JFreeChart chart = ChartFactory.createXYLineChart("Tank steer KF", "Time (s)", "Yaw (radians) or Yaw Rate (rad/s)", sc); showChart(chart, terminateAfter); } /** * Display a chart in a dialog window * @param chart * @param terminateAfter */ private static void showChart(JFreeChart chart, boolean terminateAfter) { ChartPanel panel = new ChartPanel(chart); panel.setFillZoomRectangle(true); panel.setMouseWheelEnabled(true); JDialog dialog = new JDialog(); if(terminateAfter) { dialog.addWindowListener(new WindowListener() { @Override public void windowOpened(WindowEvent e) {} @Override public void windowIconified(WindowEvent e) {} @Override public void windowDeiconified(WindowEvent e) {} @Override public void windowDeactivated(WindowEvent e) {} @Override public void windowClosing(WindowEvent e) { System.exit(0);} @Override public void windowClosed(WindowEvent e) {} @Override public void windowActivated(WindowEvent e) {} }); } dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dialog.add(panel); dialog.pack(); dialog.setVisible(true); } public static void testKfWithRecordedData(boolean terminateAfter) { CSVParser parser = null; try { parser = new CSVParser(new FileReader("2017-1-13 IMU sensor data with corrections - Kovaka.csv"), CSVFormat.DEFAULT); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } final int NUM_DATAPOINTS = 7162; // t for Theta, the heading to magnetic north // w for lowercase omega, angular velocity double[] time = new double[NUM_DATAPOINTS]; double[] t_measured = new double[NUM_DATAPOINTS]; double[] t_estimated = new double[NUM_DATAPOINTS]; double[] t_demod = new double[NUM_DATAPOINTS]; double t_cum_err = 0; double[] d_theta = new double[NUM_DATAPOINTS]; double[] w_measured = new double[NUM_DATAPOINTS]; double[] w_estimated = new double[NUM_DATAPOINTS]; // Configure filter. // State vector (n = 2): // [ position (theta, t) ] // [ angular speed (omega, w) ] // Sensor vector (m = 3): // [ magnetometer theta ] // [ d(magnetometer theta) ] // [ gyro angular speed ] KalmanFilterSimple kf = new KalmanFilterSimple(); DenseMatrix64F F = new DenseMatrix64F(new double[][]{ {1.0, DT / 45}, {0.0, 1.0}, }); DenseMatrix64F Q = new DenseMatrix64F(new double[][]{ {0.05, 0.0}, {0.0, 1.0}, }); DenseMatrix64F H = new DenseMatrix64F(new double[][]{ {1.0, 0.0}, {0.0, 1.0}, {0.0, 1.0}, }); DenseMatrix64F R = new DenseMatrix64F(new double[][]{ {10.0, 0.0, 0.0}, { 0.0, 1.0, 0.0}, { 0.0, 0.0, 0.0}, }); kf.configure(F, Q, H); // Run filter DenseMatrix64F x_init = new DenseMatrix64F(new double [][]{ {2.0}, {0}, }); DenseMatrix64F p_init = new DenseMatrix64F(new double [][]{ {1, 0}, {0, 1}, }); kf.setState(x_init, p_init); int i = 0; try { // I deep-sixed the column headers, they were: // X,Y,Z,gX,gY,gZ,Hard Fe Y a=-36,Hard Fe Z =-221.5 final int COL_CORR_MAG_Y = 6; final int COL_CORR_MAG_Z = 7; final int COL_GYRO_Z = 5; double heading_boost = 0.0; for(CSVRecord record : parser.getRecords()) { t_measured[i] = Math.atan2(Double.parseDouble(record.get(COL_CORR_MAG_Y)), Double.parseDouble(record.get(COL_CORR_MAG_Z))); w_measured[i] = Double.parseDouble(record.get(COL_GYRO_Z)) * Math.PI / 180.0; if((i > 0) && ( (t_measured[i] > Math.PI / 2.0 && t_measured[i - 1] < -Math.PI / 2.0) || (t_measured[i] < -Math.PI / 2.0 && t_measured[i - 1] > Math.PI / 2.0) )) { // Defunct the modulo heading_boost += 2 * Math.PI; } t_demod[i] = t_measured[i] + heading_boost; time[i] = i * DT; // In this case we've been sampling the magnetometer faster than it updates. // The estimate has an update every timepoint, so there aren't zeroes most of // the samples. The downfall is a 1-sample lag. d_theta[i] = i>1? t_estimated[i - 1] - t_estimated[i - 2] : 0; // d_theta[i] = i>0? t_demod[i] - t_demod[i - 1] : 0; // The above computes the change over one dt, while the units of w are in rad/s // We didn't measure the dt in the data capture. So here we approximate dividing by that dt. d_theta[i] *= 250; DenseMatrix64F z = new DenseMatrix64F(new double [][]{ {t_demod[i]}, {d_theta[i]}, {w_measured[i]}, }); kf.predict(); double x_prediction = kf.getState().data[0]; double v_prediction = kf.getState().data[1]; kf.update(z, R); t_estimated[i] = kf.getState().data[0]; w_estimated[i] = kf.getState().data[1]; // This should eventually add up to zero t_cum_err += (t_estimated[i] - t_demod[i]); ++i; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Cumulative error: " + t_cum_err); // Graph results XYSeries x_m_s = new XYSeries("Measured position"); XYSeries x_e_s = new XYSeries("Estimated position"); XYSeries d_m_s = new XYSeries("Change in position"); XYSeries v_m_s = new XYSeries("Measured speed"); XYSeries v_e_s = new XYSeries("Estimated speed"); for(i = 0; i < NUM_DATAPOINTS; ++i) { x_m_s.add(time[i], t_demod[i]); x_e_s.add(time[i], t_estimated[i]); d_m_s.add(time[i], d_theta[i]); v_m_s.add(time[i], w_measured[i]); v_e_s.add(time[i], w_estimated[i]); } XYSeriesCollection sc = new XYSeriesCollection(); sc.addSeries(x_e_s); sc.addSeries(x_m_s); sc.addSeries(d_m_s); sc.addSeries(v_e_s); sc.addSeries(v_m_s); JFreeChart chart = ChartFactory.createXYLineChart("KF test w/rec data", "Time (s)", "Value", sc); showChart(chart, terminateAfter); } public static void testScalarKfWithRecordedData(boolean terminateAfter) { CSVParser parser = null; try { parser = new CSVParser(new FileReader("2017-1-13 IMU sensor data with corrections - Kovaka.csv"), CSVFormat.DEFAULT); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } final int NUM_DATAPOINTS = 7162; // t for Theta, the heading to magnetic north // w for lowercase omega, angular velocity double[] time = new double[NUM_DATAPOINTS]; double[] t_measured = new double[NUM_DATAPOINTS]; double[] t_estimated = new double[NUM_DATAPOINTS]; double[] t_demod = new double[NUM_DATAPOINTS]; double[] w_measured = new double[NUM_DATAPOINTS]; double[] w_estimated = new double[NUM_DATAPOINTS]; double[] k = new double[NUM_DATAPOINTS]; double[] p = new double[NUM_DATAPOINTS]; // Configure filters ScalarKalmanFilter pos_kf = new ScalarKalmanFilter(); // ScalarKalmanFilter vel_kf = new ScalarKalmanFilter(); pos_kf.configure(1, 0.05, 1); pos_kf.setState(2); // vel_kf.setState(0); int i = 0; try { // I deep-sixed the column headers, they were: // X,Y,Z,gX,gY,gZ,Hard Fe Y a=-36,Hard Fe Z =-221.5 final int COL_CORR_MAG_Y = 6; final int COL_CORR_MAG_Z = 7; final int COL_GYRO_Z = 5; double heading_boost = 0.0; for(CSVRecord record : parser.getRecords()) { t_measured[i] = Math.atan2(Double.parseDouble(record.get(COL_CORR_MAG_Y)), Double.parseDouble(record.get(COL_CORR_MAG_Z))); w_measured[i] = Double.parseDouble(record.get(COL_GYRO_Z)) * Math.PI / 180.0; if((i > 0) && ( (t_measured[i] > Math.PI / 2.0 && t_measured[i - 1] < -Math.PI / 2.0) || (t_measured[i] < -Math.PI / 2.0 && t_measured[i - 1] > Math.PI / 2.0) )) { // Defunct the modulo heading_boost += 2 * Math.PI; } t_demod[i] = t_measured[i] + heading_boost; time[i] = i * DT; pos_kf.predict(); // vel_kf.predict(); pos_kf.update(t_demod[i], 10); // vel_kf.update(w_measured[i], 0.01); t_estimated[i] = pos_kf.getState(); // w_estimated[i] = vel_kf.getState(); k[i] = pos_kf.getK(); p[i] = pos_kf.getP(); ++i; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Graph results XYSeries x_m_s = new XYSeries("Measured position"); XYSeries x_e_s = new XYSeries("Estimated position"); XYSeries k_s = new XYSeries("k"); XYSeries p_s = new XYSeries("p"); // XYSeries v_m_s = new XYSeries("Measured speed"); // XYSeries v_e_s = new XYSeries("Estimated speed"); for(i = 0; i < NUM_DATAPOINTS; ++i) { x_m_s.add(time[i], t_demod[i]); x_e_s.add(time[i], t_estimated[i]); k_s.add(time[i], k[i] * 10); p_s.add(time[i], p[i] * 10); // v_m_s.add(time[i], w_measured[i]); // v_e_s.add(time[i], w_estimated[i]); } XYSeriesCollection sc = new XYSeriesCollection(); sc.addSeries(x_e_s); sc.addSeries(x_m_s); sc.addSeries(k_s); sc.addSeries(p_s); // sc.addSeries(v_e_s); // sc.addSeries(v_m_s); JFreeChart chart = ChartFactory.createXYLineChart("Scalar KF test", "Time (s)", "Value", sc); showChart(chart, terminateAfter); } public static void testAttitudeTrackerWithRecordedData(boolean terminateAfter) { CSVParser parser; try { parser = new CSVParser(new FileReader("test_data_spinning.csv"), CSVFormat.DEFAULT); for(CSVRecord record : parser.getRecords()) { System.out.println("Got a record"); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package bitronix.tm.resource.common; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import bitronix.tm.TransactionManagerServices; import bitronix.tm.BitronixTransaction; import bitronix.tm.BitronixXid; import bitronix.tm.recovery.IncrementalRecoverer; import bitronix.tm.recovery.RecoveryException; import bitronix.tm.utils.*; import bitronix.tm.utils.CryptoEngine; import bitronix.tm.internal.*; import javax.transaction.*; import javax.transaction.xa.XAResource; import java.util.*; public class XAPool implements StateChangeListener { private final static Logger log = LoggerFactory.getLogger(XAPool.class); private final static String PASSWORD_PROPERTY_NAME = "password"; private Map statefulHolderTransactionMap = new HashMap(); private List objects = new ArrayList(); private ResourceBean bean; private XAResourceProducer xaResourceProducer; private Object xaFactory; private boolean failed = false; public XAPool(XAResourceProducer xaResourceProducer, ResourceBean bean) throws Exception { this.xaResourceProducer = xaResourceProducer; this.bean = bean; if (bean.getMaxPoolSize() < 1 || bean.getMinPoolSize() > bean.getMaxPoolSize()) throw new IllegalArgumentException("cannot create a pool with min " + bean.getMinPoolSize() + " connection(s) and max " + bean.getMaxPoolSize() + " connection(s)"); if (bean.getAcquireIncrement() < 1) throw new IllegalArgumentException("cannot create a pool with a connection acquisition increment less than 1, configured value is " + bean.getAcquireIncrement()); xaFactory = createXAFactory(bean); init(); } private void init() throws Exception { for (int i=0; i < bean.getMinPoolSize() ;i++) { createPooledObject(xaFactory); } if (bean.getMaxIdleTime() > 0) { TransactionManagerServices.getTaskScheduler().schedulePoolShrinking(this); } } public Object getXAFactory() { return xaFactory; } public synchronized void setFailed(boolean failed) { this.failed = failed; } public synchronized Object getConnectionHandle() throws Exception { return getConnectionHandle(true); } public synchronized Object getConnectionHandle(boolean recycle) throws Exception { if (failed) { try { if (log.isDebugEnabled()) log.debug("resource '" + bean.getUniqueName() + "' is marked as failed, resetting and recovering it before trying connection acquisition"); close(); init(); IncrementalRecoverer.recover(xaResourceProducer); } catch (RecoveryException ex) { throw new BitronixRuntimeException("incremental recovery failed when trying to acquire a connection from failed resource '" + bean.getUniqueName() + "'", ex); } catch (Exception ex) { throw new BitronixRuntimeException("pool reset failed when trying to acquire a connection from failed resource '" + bean.getUniqueName() + "'", ex); } } long remainingTime = bean.getAcquisitionTimeout() * 1000L; long before = System.currentTimeMillis(); while (true) { XAStatefulHolder xaStatefulHolder = null; if (recycle) { if (bean.isShareTransactionConnections()) { xaStatefulHolder = getSharedXaStatefulHolder(); } else if (xaStatefulHolder == null) { xaStatefulHolder = getNotAccessible(); } } if (xaStatefulHolder == null) { xaStatefulHolder = getInPool(); } if (log.isDebugEnabled()) log.debug("found " + Decoder.decodeXAStatefulHolderState(xaStatefulHolder.getState()) + " connection " + xaStatefulHolder + " from " + this); try { Object connectionHandle = xaStatefulHolder.getConnectionHandle(); if (bean.isShareTransactionConnections()) { putSharedXaStatefulHolder(xaStatefulHolder); } return connectionHandle; } catch (Exception ex) { if (log.isDebugEnabled()) log.debug("connection is invalid, trying to close it", ex); try { xaStatefulHolder.close(); } catch (Exception ex2) { if (log.isDebugEnabled()) log.debug("exception while trying to close invalid connection, ignoring it", ex2); } objects.remove(xaStatefulHolder); if (log.isDebugEnabled()) log.debug("removed invalid connection " + xaStatefulHolder + " from " + this); if (log.isDebugEnabled()) log.debug("waiting " + bean.getAcquisitionInterval() + "s before trying to acquire a connection again from " + this); try { wait(bean.getAcquisitionInterval() * 1000L); } catch (InterruptedException ex2) { // ignore } // check for timeout long now = System.currentTimeMillis(); remainingTime -= (now - before); if (remainingTime <= 0) { throw new BitronixRuntimeException("cannot get valid connection from " + this + " after trying for " + bean.getAcquisitionTimeout() + "s", ex); } } } // while true } public synchronized void close() { if (log.isDebugEnabled()) log.debug("closing all connections of " + this); for (int i = 0; i < totalPoolSize(); i++) { XAStatefulHolder xaStatefulHolder = (XAStatefulHolder) objects.get(i); try { xaStatefulHolder.close(); } catch (Exception ex) { if (log.isDebugEnabled()) log.debug("ignoring catched exception while closing connection " + xaStatefulHolder, ex); } } if (TransactionManagerServices.isTaskSchedulerRunning()) TransactionManagerServices.getTaskScheduler().cancelPoolShrinking(this); objects.clear(); failed = false; } public synchronized long totalPoolSize() { return objects.size(); } public synchronized long inPoolSize() { int count = 0; for (int i = 0; i < totalPoolSize(); i++) { XAStatefulHolder xaStatefulHolder = (XAStatefulHolder) objects.get(i); if (xaStatefulHolder.getState() == XAStatefulHolder.STATE_IN_POOL) count++; } return count; } public void stateChanged(XAStatefulHolder source, int oldState, int newState) { if (newState == XAStatefulHolder.STATE_IN_POOL) { if (log.isDebugEnabled()) log.debug("a connection's state changed to IN_POOL, notifying a thread eventually waiting for a connection"); synchronized (this) { notify(); } } } public void stateChanging(XAStatefulHolder source, int currentState, int futureState) { } public synchronized XAResourceHolder findXAResourceHolder(XAResource xaResource) { for (int i = 0; i < totalPoolSize(); i++) { XAStatefulHolder xaStatefulHolder = (XAStatefulHolder) objects.get(i); List xaResourceHolders = xaStatefulHolder.getXAResourceHolders(); for (int j = 0; j < xaResourceHolders.size(); j++) { XAResourceHolder holder = (XAResourceHolder) xaResourceHolders.get(j); if (holder.getXAResource() == xaResource) return holder; } } return null; } public List getXAResourceHolders() { return objects; } public Date getNextShrinkDate() { return new Date(System.currentTimeMillis() + bean.getMaxIdleTime() * 1000); } public synchronized void shrink() throws Exception { if (log.isDebugEnabled()) log.debug("shrinking " + this); List toRemoveXaStatefulHolders = new ArrayList(); long now = System.currentTimeMillis(); for (int i = 0; i < totalPoolSize(); i++) { if (totalPoolSize() - toRemoveXaStatefulHolders.size() <= bean.getMinPoolSize()) { if (log.isDebugEnabled()) log.debug("pool reached min size"); break; } XAStatefulHolder xaStatefulHolder = (XAStatefulHolder) objects.get(i); if (xaStatefulHolder.getState() != XAStatefulHolder.STATE_IN_POOL) continue; if (xaStatefulHolder.getLastReleaseDate() == null) continue; long expirationTime = (xaStatefulHolder.getLastReleaseDate().getTime() + (bean.getMaxIdleTime() * 1000)); if (log.isDebugEnabled()) log.debug("checking if connection can be closed: " + xaStatefulHolder + " - closing time: " + expirationTime + ", now time: " + now); if (expirationTime <= now) { xaStatefulHolder.close(); toRemoveXaStatefulHolders.add(xaStatefulHolder); } } // for if (log.isDebugEnabled()) log.debug("closed " + toRemoveXaStatefulHolders.size() + " idle connection(s)"); objects.removeAll(toRemoveXaStatefulHolders); } public String toString() { return "an XAPool of resource " + bean.getUniqueName() + " with " + totalPoolSize() + " connection(s) (" + inPoolSize() + " still available)" + (failed ? " -failed-" : ""); } private void createPooledObject(Object xaFactory) throws Exception { XAStatefulHolder xaStatefulHolder = xaResourceProducer.createPooledConnection(xaFactory, bean); xaStatefulHolder.addStateChangeEventListener(this); objects.add(xaStatefulHolder); } private static Object createXAFactory(ResourceBean bean) throws Exception { String className = bean.getClassName(); if (className == null) throw new IllegalArgumentException("className cannot be null"); Class xaFactoryClass = ClassLoaderUtils.loadClass(className); Object xaFactory = xaFactoryClass.newInstance(); Iterator it = bean.getDriverProperties().entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); String name = (String) entry.getKey(); String value = (String) entry.getValue(); if (name.endsWith(PASSWORD_PROPERTY_NAME)) { value = decrypt(value); } if (log.isDebugEnabled()) log.debug("setting vendor property '" + name + "' to '" + value + "'"); PropertyUtils.setProperty(xaFactory, name, value); } return xaFactory; } private static String decrypt(String resourcePassword) throws Exception { int startIdx = resourcePassword.indexOf("{"); int endIdx = resourcePassword.indexOf("}"); if (startIdx != 0 || endIdx == -1) return resourcePassword; String cipher = resourcePassword.substring(1, endIdx); if (log.isDebugEnabled()) log.debug("resource password is encrypted, decrypting " + resourcePassword); return CryptoEngine.decrypt(cipher, resourcePassword.substring(endIdx + 1)); } private XAStatefulHolder getNotAccessible() { if (log.isDebugEnabled()) log.debug("trying to recycle a NOT_ACCESSIBLE connection of " + this); BitronixTransaction transaction = TransactionContextHelper.currentTransaction(); if (transaction == null) { if (log.isDebugEnabled()) log.debug("no current transaction, no connection can be in state NOT_ACCESSIBLE when there is no global transaction context"); return null; } Uid currentTxGtrid = transaction.getResourceManager().getGtrid(); if (log.isDebugEnabled()) log.debug("current transaction GTRID is [" + currentTxGtrid + "]"); for (int i = 0; i < totalPoolSize(); i++) { XAStatefulHolder xaStatefulHolder = (XAStatefulHolder) objects.get(i); if (xaStatefulHolder.getState() == XAStatefulHolder.STATE_NOT_ACCESSIBLE) { if (log.isDebugEnabled()) log.debug("found a connection in NOT_ACCESSIBLE state: " + xaStatefulHolder); if (containsXAResourceHolderMatchingGtrid(xaStatefulHolder, currentTxGtrid)) return xaStatefulHolder; } } // for if (log.isDebugEnabled()) log.debug("no NOT_ACCESSIBLE connection enlisted in this transaction"); return null; } private boolean containsXAResourceHolderMatchingGtrid(XAStatefulHolder xaStatefulHolder, Uid currentTxGtrid) { List xaResourceHolders = xaStatefulHolder.getXAResourceHolders(); if (log.isDebugEnabled()) log.debug(xaResourceHolders.size() + " xa resource(s) created by connection in NOT_ACCESSIBLE state: " + xaStatefulHolder); for (int i = 0; i < xaResourceHolders.size(); i++) { XAResourceHolder xaResourceHolder = (XAResourceHolder) xaResourceHolders.get(i); XAResourceHolderState xaResourceHolderState = xaResourceHolder.getXAResourceHolderState(); if (xaResourceHolderState != null && xaResourceHolderState.getXid() != null) { // compare GTRIDs BitronixXid bitronixXid = xaResourceHolderState.getXid(); Uid resourceGtrid = bitronixXid.getGlobalTransactionIdUid(); if (log.isDebugEnabled()) log.debug("NOT_ACCESSIBLE xa resource GTRID: " + resourceGtrid); if (currentTxGtrid.equals(resourceGtrid)) { if (log.isDebugEnabled()) log.debug("NOT_ACCESSIBLE xa resource's GTRID matched this transaction's GTRID, recycling it"); return true; } } } return false; } private XAStatefulHolder getInPool() throws Exception { if (log.isDebugEnabled()) log.debug("getting a IN_POOL connection from " + this); if (inPoolSize() == 0) { if (log.isDebugEnabled()) log.debug("no more free connection in " + this + ", trying to grow it"); grow(); } waitForConnectionInPool(); for (int i = 0; i < totalPoolSize(); i++) { XAStatefulHolder xaStatefulHolder = (XAStatefulHolder) objects.get(i); if (xaStatefulHolder.getState() == XAStatefulHolder.STATE_IN_POOL) return xaStatefulHolder; } throw new BitronixRuntimeException("pool does not contain IN_POOL connection while it should !"); } private synchronized void grow() throws Exception { if (totalPoolSize() < bean.getMaxPoolSize()) { long increment = bean.getAcquireIncrement(); if (totalPoolSize() + increment > bean.getMaxPoolSize()) { increment = bean.getMaxPoolSize() - totalPoolSize(); } if (log.isDebugEnabled()) log.debug("incrementing " + bean.getUniqueName() + " pool size by " + increment + " unit(s) to reach " + (totalPoolSize() + increment) + " connection(s)"); for (int i=0; i < increment ;i++) { createPooledObject(xaFactory); } } else { if (log.isDebugEnabled()) log.debug("pool " + bean.getUniqueName() + " already at max size of " + totalPoolSize() + " connection(s), not growing it"); } } private synchronized void waitForConnectionInPool() throws Exception { long remainingTime = bean.getAcquisitionTimeout() * 1000L; if (log.isDebugEnabled()) log.debug("waiting for IN_POOL connections count to be > 0, currently is " + inPoolSize()); while (inPoolSize() == 0) { long before = System.currentTimeMillis(); try { if (log.isDebugEnabled()) log.debug("waiting " + remainingTime + "ms"); wait(remainingTime); if (log.isDebugEnabled()) log.debug("waiting over, IN_POOL connections count is now " + inPoolSize()); } catch (InterruptedException ex) { // ignore } long now = System.currentTimeMillis(); remainingTime -= (now - before); if (remainingTime <= 0 && inPoolSize() == 0) { if (log.isDebugEnabled()) log.debug("connection pool dequeue timed out"); if (TransactionManagerServices.isTransactionManagerRunning()) TransactionManagerServices.getTransactionManager().dumpTransactionContexts(); throw new Exception("XA pool of resource " + bean.getUniqueName() + " still empty after " + bean.getAcquisitionTimeout() + "s wait time"); } } // while } /**************************************************************** * Shared Connection Handling */ private XAStatefulHolder getSharedXaStatefulHolder() { BitronixTransaction transaction = TransactionContextHelper.currentTransaction(); if (transaction == null) { if (log.isDebugEnabled()) log.debug("no current transaction, shared connection map will not be used"); return null; } Uid currentTxGtrid = transaction.getResourceManager().getGtrid(); ThreadLocal threadLocal = (ThreadLocal) statefulHolderTransactionMap.get(currentTxGtrid); if (threadLocal != null) { XAStatefulHolder xaStatefulHolder = (XAStatefulHolder) threadLocal.get(); if (xaStatefulHolder != null && xaStatefulHolder.getState() != XAStatefulHolder.STATE_IN_POOL && xaStatefulHolder.getState() != XAStatefulHolder.STATE_CLOSED) { if (log.isDebugEnabled()) log.debug("sharing connection " + xaStatefulHolder + " in transaction " + currentTxGtrid); return xaStatefulHolder; } } return null; } private void putSharedXaStatefulHolder(final XAStatefulHolder xaStatefulHolder) { BitronixTransaction transaction = TransactionContextHelper.currentTransaction(); if (transaction == null) { if (log.isDebugEnabled()) log.debug("no current transaction, not adding " + xaStatefulHolder + " to shared connection map"); return; } final Uid currentTxGtrid = transaction.getResourceManager().getGtrid(); ThreadLocal threadLocal = (ThreadLocal) statefulHolderTransactionMap.get(currentTxGtrid); if (threadLocal == null) { // This is the first time this TxGtrid/ThreadLocal is going into the map, // register interest in synchronization so we can remove it at commit/rollback try { transaction.registerSynchronization(new Synchronization() { public void beforeCompletion() { // Do nothing } public void afterCompletion(int status) { synchronized (XAPool.this) { statefulHolderTransactionMap.remove(currentTxGtrid); if (log.isDebugEnabled()) log.debug("deleted shared connection mapping for " + currentTxGtrid); } } }); } catch (Exception e) { // OK, forget it. The transaction is either rollback only or already finished. return; } threadLocal = new ThreadLocal(); threadLocal.set(xaStatefulHolder); statefulHolderTransactionMap.put(currentTxGtrid, threadLocal); if (log.isDebugEnabled()) log.debug("added shared connection mapping for " + currentTxGtrid + " holder " + xaStatefulHolder); } else { threadLocal.set(xaStatefulHolder); } } }
package com.facebook.imagepipeline.producers; import android.content.ContentResolver; import android.database.Cursor; import android.graphics.Bitmap; import android.media.MediaMetadataRetriever; import android.media.ThumbnailUtils; import android.net.Uri; import android.os.Build; import android.os.ParcelFileDescriptor; import android.provider.DocumentsContract; import android.provider.MediaStore; import androidx.annotation.VisibleForTesting; import com.facebook.common.internal.ImmutableMap; import com.facebook.common.internal.Preconditions; import com.facebook.common.references.CloseableReference; import com.facebook.common.util.UriUtil; import com.facebook.imagepipeline.bitmaps.SimpleBitmapReleaser; import com.facebook.imagepipeline.image.CloseableImage; import com.facebook.imagepipeline.image.CloseableStaticBitmap; import com.facebook.imagepipeline.image.ImmutableQualityInfo; import com.facebook.imagepipeline.request.ImageRequest; import com.facebook.infer.annotation.Nullsafe; import java.io.FileNotFoundException; import java.util.Map; import java.util.concurrent.Executor; import javax.annotation.Nullable; @Nullsafe(Nullsafe.Mode.LOCAL) public class LocalVideoThumbnailProducer implements Producer<CloseableReference<CloseableImage>> { public static final String PRODUCER_NAME = "VideoThumbnailProducer"; @VisibleForTesting static final String CREATED_THUMBNAIL = "createdThumbnail"; private final Executor mExecutor; private final ContentResolver mContentResolver; public LocalVideoThumbnailProducer(Executor executor, ContentResolver contentResolver) { mExecutor = executor; mContentResolver = contentResolver; } @Override public void produceResults( final Consumer<CloseableReference<CloseableImage>> consumer, final ProducerContext producerContext) { final ProducerListener2 listener = producerContext.getProducerListener(); final ImageRequest imageRequest = producerContext.getImageRequest(); producerContext.putOriginExtra("local", "video"); final StatefulProducerRunnable cancellableProducerRunnable = new StatefulProducerRunnable<CloseableReference<CloseableImage>>( consumer, listener, producerContext, PRODUCER_NAME) { @Override protected void onSuccess(@Nullable CloseableReference<CloseableImage> result) { super.onSuccess(result); listener.onUltimateProducerReached(producerContext, PRODUCER_NAME, result != null); producerContext.putOriginExtra("local"); } @Override protected void onFailure(Exception e) { super.onFailure(e); listener.onUltimateProducerReached(producerContext, PRODUCER_NAME, false); producerContext.putOriginExtra("local"); } @Override protected @Nullable CloseableReference<CloseableImage> getResult() throws Exception { Bitmap thumbnailBitmap = null; String path; try { path = getLocalFilePath(imageRequest); } catch (IllegalArgumentException e) { path = null; } if (path != null) { thumbnailBitmap = ThumbnailUtils.createVideoThumbnail(path, calculateKind(imageRequest)); } if (thumbnailBitmap == null) { thumbnailBitmap = createThumbnailFromContentProvider(mContentResolver, imageRequest.getSourceUri()); } if (thumbnailBitmap == null) { return null; } CloseableStaticBitmap closeableStaticBitmap = new CloseableStaticBitmap( thumbnailBitmap, SimpleBitmapReleaser.getInstance(), ImmutableQualityInfo.FULL_QUALITY, 0); producerContext.setExtra(ProducerContext.ExtraKeys.IMAGE_FORMAT, "thumbnail"); closeableStaticBitmap.setImageExtras(producerContext.getExtras()); return CloseableReference.<CloseableImage>of(closeableStaticBitmap); } @Override protected Map<String, String> getExtraMapOnSuccess( final @Nullable CloseableReference<CloseableImage> result) { return ImmutableMap.of(CREATED_THUMBNAIL, String.valueOf(result != null)); } @Override protected void disposeResult(CloseableReference<CloseableImage> result) { CloseableReference.closeSafely(result); } }; producerContext.addCallbacks( new BaseProducerContextCallbacks() { @Override public void onCancellationRequested() { cancellableProducerRunnable.cancel(); } }); mExecutor.execute(cancellableProducerRunnable); } private static int calculateKind(ImageRequest imageRequest) { if (imageRequest.getPreferredWidth() > 96 || imageRequest.getPreferredHeight() > 96) { return MediaStore.Images.Thumbnails.MINI_KIND; } return MediaStore.Images.Thumbnails.MICRO_KIND; } @Nullable private String getLocalFilePath(ImageRequest imageRequest) { Uri uri = imageRequest.getSourceUri(); if (UriUtil.isLocalFileUri(uri)) { return imageRequest.getSourceFile().getPath(); } else if (UriUtil.isLocalContentUri(uri)) { String selection = null; String[] selectionArgs = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && "com.android.providers.media.documents".equals(uri.getAuthority())) { String documentId = DocumentsContract.getDocumentId(uri); Preconditions.checkNotNull(documentId); uri = Preconditions.checkNotNull(MediaStore.Video.Media.EXTERNAL_CONTENT_URI); selection = MediaStore.Video.Media._ID + "=?"; selectionArgs = new String[] {documentId.split(":")[1]}; } Cursor cursor = mContentResolver.query( uri, new String[] {MediaStore.Video.Media.DATA}, selection, selectionArgs, null); try { if (cursor != null && cursor.moveToFirst()) { return cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA)); } } finally { if (cursor != null) { cursor.close(); } } } return null; } @Nullable private static Bitmap createThumbnailFromContentProvider( ContentResolver contentResolver, Uri uri) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1) { try { ParcelFileDescriptor videoFile = contentResolver.openFileDescriptor(uri, "r"); Preconditions.checkNotNull(videoFile); MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever(); mediaMetadataRetriever.setDataSource(videoFile.getFileDescriptor()); return mediaMetadataRetriever.getFrameAtTime(-1); } catch (FileNotFoundException e) { return null; } } else { return null; } } }
package de.geeksfactory.opacclient.apis; import java.io.IOException; import java.net.URI; import java.net.URLDecoder; import java.net.URLEncoder; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.CookieStore; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.Node; import org.jsoup.nodes.TextNode; import org.jsoup.select.Elements; import de.geeksfactory.opacclient.NotReachableException; import de.geeksfactory.opacclient.i18n.StringProvider; import de.geeksfactory.opacclient.objects.Account; import de.geeksfactory.opacclient.objects.AccountData; import de.geeksfactory.opacclient.objects.Detail; import de.geeksfactory.opacclient.objects.DetailledItem; import de.geeksfactory.opacclient.objects.Filter; import de.geeksfactory.opacclient.objects.Filter.Option; import de.geeksfactory.opacclient.objects.Library; import de.geeksfactory.opacclient.objects.SearchRequestResult; import de.geeksfactory.opacclient.objects.SearchResult; import de.geeksfactory.opacclient.objects.SearchResult.MediaType; import de.geeksfactory.opacclient.searchfields.CheckboxSearchField; import de.geeksfactory.opacclient.searchfields.DropdownSearchField; import de.geeksfactory.opacclient.searchfields.SearchField; import de.geeksfactory.opacclient.searchfields.SearchQuery; import de.geeksfactory.opacclient.searchfields.TextSearchField; import de.geeksfactory.opacclient.utils.ISBNTools; /** * @author Johan von Forstner, 16.09.2013 * */ public class Pica extends BaseApi implements OpacApi { protected String opac_url = ""; protected String https_url = ""; protected JSONObject data; protected boolean initialised = false; protected Library library; protected int resultcount = 10; protected String reusehtml; protected Integer searchSet; protected String db; protected String pwEncoded; protected String languageCode; protected CookieStore cookieStore = new BasicCookieStore(); protected String lor_reservations; protected static HashMap<String, MediaType> defaulttypes = new HashMap<String, MediaType>(); protected static HashMap<String, String> languageCodes = new HashMap<String, String>(); static { defaulttypes.put("book", MediaType.BOOK); defaulttypes.put("article", MediaType.BOOK); defaulttypes.put("binary", MediaType.EBOOK); defaulttypes.put("periodical", MediaType.MAGAZINE); defaulttypes.put("onlineper", MediaType.EBOOK); defaulttypes.put("letter", MediaType.UNKNOWN); defaulttypes.put("handwriting", MediaType.UNKNOWN); defaulttypes.put("map", MediaType.MAP); defaulttypes.put("picture", MediaType.ART); defaulttypes.put("audiovisual", MediaType.MOVIE); defaulttypes.put("score", MediaType.SCORE_MUSIC); defaulttypes.put("sound", MediaType.CD_MUSIC); defaulttypes.put("software", MediaType.CD_SOFTWARE); defaulttypes.put("microfilm", MediaType.UNKNOWN); defaulttypes.put("empty", MediaType.UNKNOWN); languageCodes.put("de", "DU"); languageCodes.put("en", "EN"); languageCodes.put("nl", "NE"); languageCodes.put("fr", "FR"); } @Override public void init(Library lib) { super.init(lib); this.library = lib; this.data = lib.getData(); try { this.opac_url = data.getString("baseurl"); this.db = data.getString("db"); if (isAccountSupported(library)) { if (data.has("httpsbaseurl")) { this.https_url = data.getString("httpsbaseurl"); } else { this.https_url = this.opac_url; } } } catch (JSONException e) { throw new RuntimeException(e); } } protected int addParameters(SearchQuery query, List<NameValuePair> params, int index) throws JSONException { if (query.getValue().equals("") || query.getValue().equals("false")) return index; if (query.getSearchField() instanceof TextSearchField) { if (query.getSearchField().getData().getBoolean("ADI")) { params.add(new BasicNameValuePair(query.getKey(), query .getValue())); } else { if (index == 0) { params.add(new BasicNameValuePair("ACT" + index, "SRCH")); } else { params.add(new BasicNameValuePair("ACT" + index, "*")); } params.add(new BasicNameValuePair("IKT" + index, query.getKey())); params.add(new BasicNameValuePair("TRM" + index, query .getValue())); return index + 1; } } else if (query.getSearchField() instanceof CheckboxSearchField) { boolean checked = Boolean.valueOf(query.getValue()); if (checked) { params.add(new BasicNameValuePair(query.getKey(), "Y")); } } else if (query.getSearchField() instanceof DropdownSearchField) { params.add(new BasicNameValuePair(query.getKey(), query.getValue())); } return index; } @Override public SearchRequestResult search(List<SearchQuery> query) throws IOException, NotReachableException, OpacErrorException, JSONException { if (!initialised) start(); List<NameValuePair> params = new ArrayList<NameValuePair>(); int index = 0; start(); params.add(new BasicNameValuePair("ACT", "SRCHM")); params.add(new BasicNameValuePair("MATCFILTER", "Y")); params.add(new BasicNameValuePair("MATCSET", "Y")); params.add(new BasicNameValuePair("NOSCAN", "Y")); params.add(new BasicNameValuePair("PARSE_MNEMONICS", "N")); params.add(new BasicNameValuePair("PARSE_OPWORDS", "N")); params.add(new BasicNameValuePair("PARSE_OLDSETS", "N")); for (SearchQuery singleQuery : query) { index = addParameters(singleQuery, params, index); } if (index == 0) { throw new OpacErrorException( stringProvider.getString(StringProvider.NO_CRITERIA_INPUT)); } if (index > 4) { throw new OpacErrorException(stringProvider.getFormattedString( StringProvider.LIMITED_NUM_OF_CRITERIA, 4)); } String html = httpGet(opac_url + "/DB=" + db + "/SET=1/TTL=1/CMD?" + URLEncodedUtils.format(params, getDefaultEncoding()), getDefaultEncoding(), false, cookieStore); return parse_search(html, 1); } protected SearchRequestResult parse_search(String html, int page) throws OpacErrorException { Document doc = Jsoup.parse(html); updateSearchSetValue(doc); if (doc.select(".error").size() > 0) { if (doc.select(".error").text().trim() .equals("Es wurde nichts gefunden.")) { // nothing found return new SearchRequestResult(new ArrayList<SearchResult>(), 0, 1, 1); } else { // error throw new OpacErrorException(doc.select(".error").first() .text().trim()); } } reusehtml = html; int results_total = -1; String resultnumstr = doc.select(".pages").first().text(); Pattern p = Pattern.compile("[0-9]+$"); Matcher m = p.matcher(resultnumstr); if (m.find()) { resultnumstr = m.group(); } if (resultnumstr.contains("(")) { results_total = Integer.parseInt(resultnumstr.replaceAll( ".*\\(([0-9]+)\\).*", "$1")); } else if (resultnumstr.contains(": ")) { results_total = Integer.parseInt(resultnumstr.replaceAll( ".*: ([0-9]+)$", "$1")); } else { results_total = Integer.parseInt(resultnumstr); } List<SearchResult> results = new ArrayList<SearchResult>(); if (results_total == 1) { // Only one result try { DetailledItem singleResult = parse_result(html); SearchResult sr = new SearchResult(); sr.setType(getMediaTypeInSingleResult(html)); sr.setInnerhtml("<b>" + singleResult.getTitle() + "</b><br>" + singleResult.getDetails().get(0).getContent()); results.add(sr); } catch (IOException e) { e.printStackTrace(); } } Elements table = doc .select("table[summary=hitlist] tbody tr[valign=top]"); // identifier = null; Elements links = doc.select("table[summary=hitlist] a"); boolean haslink = false; for (int i = 0; i < links.size(); i++) { Element node = links.get(i); if (node.hasAttr("href") & node.attr("href").contains("SHW?") && !haslink) { haslink = true; try { List<NameValuePair> anyurl = URLEncodedUtils.parse(new URI( node.attr("href")), getDefaultEncoding()); for (NameValuePair nv : anyurl) { if (nv.getName().equals("identifier")) { // identifier = nv.getValue(); break; } } } catch (Exception e) { e.printStackTrace(); } } } for (int i = 0; i < table.size(); i++) { Element tr = table.get(i); SearchResult sr = new SearchResult(); if (tr.select("td.hit img").size() > 0) { String[] fparts = tr.select("td img").get(0).attr("src") .split("/"); String fname = fparts[fparts.length - 1]; if (data.has("mediatypes")) { try { sr.setType(MediaType.valueOf(data.getJSONObject( "mediatypes").getString(fname))); } catch (JSONException e) { sr.setType(defaulttypes.get(fname .toLowerCase(Locale.GERMAN).replace(".jpg", "") .replace(".gif", "").replace(".png", ""))); } catch (IllegalArgumentException e) { sr.setType(defaulttypes.get(fname .toLowerCase(Locale.GERMAN).replace(".jpg", "") .replace(".gif", "").replace(".png", ""))); } } else { sr.setType(defaulttypes.get(fname .toLowerCase(Locale.GERMAN).replace(".jpg", "") .replace(".gif", "").replace(".png", ""))); } } Element middlething = tr.child(2); List<Node> children = middlething.childNodes(); int childrennum = children.size(); List<String[]> strings = new ArrayList<String[]>(); for (int ch = 0; ch < childrennum; ch++) { Node node = children.get(ch); if (node instanceof TextNode) { String text = ((TextNode) node).text().trim(); if (text.length() > 3) strings.add(new String[] { "text", "", text }); } else if (node instanceof Element) { List<Node> subchildren = node.childNodes(); for (int j = 0; j < subchildren.size(); j++) { Node subnode = subchildren.get(j); if (subnode instanceof TextNode) { String text = ((TextNode) subnode).text().trim(); if (text.length() > 3) strings.add(new String[] { ((Element) node).tag().getName(), "text", text, ((Element) node).className(), ((Element) node).attr("style") }); } else if (subnode instanceof Element) { String text = ((Element) subnode).text().trim(); if (text.length() > 3) strings.add(new String[] { ((Element) node).tag().getName(), ((Element) subnode).tag().getName(), text, ((Element) node).className(), ((Element) node).attr("style") }); } } } } StringBuilder description = new StringBuilder(); int k = 0; for (String[] part : strings) { if (part[0] == "a" && k == 0) { description.append("<b>" + part[2] + "</b>"); } else if (k < 3) { description.append("<br />" + part[2]); } k++; } sr.setInnerhtml(description.toString()); sr.setNr(10 * (page - 1) + i); sr.setId(null); results.add(sr); } resultcount = results.size(); return new SearchRequestResult(results, results_total, page); } @Override public SearchRequestResult searchGetPage(int page) throws IOException, NotReachableException, OpacErrorException { if (!initialised) start(); String html = httpGet(opac_url + "/DB=" + db + "/SET=" + searchSet + "/TTL=1/NXT?FRST=" + (((page - 1) * resultcount) + 1), getDefaultEncoding(), false, cookieStore); return parse_search(html, page); } @Override public SearchRequestResult filterResults(Filter filter, Option option) throws IOException, NotReachableException { return null; } @Override public DetailledItem getResultById(String id, String homebranch) throws IOException, NotReachableException { if (id == null && reusehtml != null) { return parse_result(reusehtml); } if (!initialised) start(); String html = httpGet(id, getDefaultEncoding()); return parse_result(html); } @Override public DetailledItem getResult(int position) throws IOException { if (!initialised) start(); String html = httpGet(opac_url + "/DB=" + db + "/LNG=" + getLang() + "/SET=" + searchSet + "/TTL=1/SHW?FRST=" + (position + 1), getDefaultEncoding(), false, cookieStore); return parse_result(html); } protected DetailledItem parse_result(String html) throws IOException { Document doc = Jsoup.parse(html); doc.setBaseUri(opac_url); DetailledItem result = new DetailledItem(); if (doc.select("img[src*=permalink], img[src*=zitierlink]").size() > 0) { String id = opac_url + doc.select("img[src*=permalink], img[src*=zitierlink]") .get(0).parent().absUrl("href"); result.setId(id); } else { for (Element a : doc.select("a")) { if (a.attr("href").contains("PPN=")) { Map<String, String> hrefq = getQueryParamsFirst(a .absUrl("href")); String ppn = hrefq.get("PPN"); try { result.setId(opac_url + "/DB=" + data.getString("db") + "/PPNSET?PPN=" + ppn); } catch (JSONException e1) { e1.printStackTrace(); } break; } } } // GET COVER if (doc.select("td.preslabel:contains(ISBN) + td.presvalue").size() > 0) { Element isbnElement = doc.select( "td.preslabel:contains(ISBN) + td.presvalue").first(); String isbn = ""; for (Node child : isbnElement.childNodes()) { if (child instanceof TextNode) { isbn = ((TextNode) child).text().trim(); break; } } result.setCover(ISBNTools.getAmazonCoverURL(isbn, true)); } // GET TITLE AND SUBTITLE String titleAndSubtitle = ""; String selector = "td.preslabel:matches(.*(Titel|Aufsatz|Zeitschrift" + "|Title|Article|Periodical" + "|Titre|Article|P.riodique).*) + td.presvalue"; if (doc.select(selector).size() > 0) { titleAndSubtitle = doc.select(selector).first().text().trim(); int slashPosition = titleAndSubtitle.indexOf("/"); String title; String subtitle; if (slashPosition > 0) { title = titleAndSubtitle.substring(0, slashPosition).trim(); subtitle = titleAndSubtitle.substring(slashPosition + 1).trim(); result.addDetail(new Detail(stringProvider .getString(StringProvider.SUBTITLE), subtitle)); } else { title = titleAndSubtitle; subtitle = ""; } result.setTitle(title); } else { result.setTitle(""); } // GET OTHER INFORMATION Map<String, String> e = new HashMap<String, String>(); String location = ""; // reservation info will be stored as JSON, because it can get // complicated JSONArray reservationInfo = new JSONArray(); for (Element element : doc.select("td.preslabel + td.presvalue")) { Element titleElem = element.firstElementSibling(); String detail = element.text().trim(); String title = titleElem.text().replace("\u00a0", " ").trim(); if (element.select("hr").size() == 0) { // no separator if (title.indexOf(":") != -1) { title = title.substring(0, title.indexOf(":")); // remove // colon } if (title.contains("Standort") || title.contains("Vorhanden in") || title.contains("Location")) { location += detail; } else if (title.contains("Sonderstandort")) { location += " - " + detail; } else if (title.contains("Fachnummer") || title.contains("locationnumber")) { e.put(DetailledItem.KEY_COPY_LOCATION, detail); } else if (title.contains("Signatur") || title.contains("Shelf mark")) { e.put(DetailledItem.KEY_COPY_SHELFMARK, detail); } else if (title.contains("Anmerkung")) { location += " (" + detail + ")"; } else if (title.contains("Status") || title.contains("Ausleihinfo") || title.contains("Request info")) { if (element.select("div").size() > 0) detail = element.select("div").first().ownText(); else detail = element.ownText(); e.put(DetailledItem.KEY_COPY_STATUS, detail); // Get reservation info if (element.select("a:has(img[src*=inline_arrow])").size() > 0) { Element a = element.select("a:has(img[src*=inline_arrow])").first(); boolean multipleCopies = a.text().matches( ".*(Exemplare|Volume list).*"); JSONObject reservation = new JSONObject(); try { reservation.put("multi", multipleCopies); reservation.put("link", opac_url + a.attr("href")); reservation.put("desc", location); reservationInfo.put(reservation); } catch (JSONException e1) { e1.printStackTrace(); } result.setReservable(true); } } else if (!title.matches("(Titel|Titre|Title)")) { result.addDetail(new Detail(title, detail)); } } else if (e.size() > 0) { e.put(DetailledItem.KEY_COPY_BRANCH, location); result.addCopy(e); location = ""; e = new HashMap<String, String>(); } } e.put(DetailledItem.KEY_COPY_BRANCH, location); result.addCopy(e); result.setReservation_info(reservationInfo.toString()); return result; } @Override public ReservationResult reservation(DetailledItem item, Account account, int useraction, String selection) throws IOException { try { if (selection == null || !selection.startsWith("{")) { JSONArray json = new JSONArray(item.getReservation_info()); int selectedPos; if (selection != null) { selectedPos = Integer.parseInt(selection); } else if (json.length() == 1) { selectedPos = 0; } else { // a location must be selected ReservationResult res = new ReservationResult( MultiStepResult.Status.SELECTION_NEEDED); res.setActionIdentifier(ReservationResult.ACTION_BRANCH); Map<String, String> selections = new HashMap<String, String>(); for (int i = 0; i < json.length(); i++) { selections.put(String.valueOf(i), json.getJSONObject(i) .getString("desc")); } res.setSelection(selections); return res; } if (json.getJSONObject(selectedPos).getBoolean("multi")) { // A copy must be selected String html1 = httpGet(json.getJSONObject(selectedPos) .getString("link"), getDefaultEncoding()); Document doc1 = Jsoup.parse(html1); Elements trs = doc1 .select("table[summary=list of volumes header] tr:has(input[type=radio])"); if (trs.size() > 0) { Map<String, String> selections = new HashMap<String, String>(); for (Element tr : trs) { JSONObject values = new JSONObject(); for (Element input : doc1 .select("input[type=hidden]")) { values.put(input.attr("name"), input.attr("value")); } values.put(tr.select("input").attr("name"), tr .select("input").attr("value")); selections.put(values.toString(), tr.text()); } ReservationResult res = new ReservationResult( MultiStepResult.Status.SELECTION_NEEDED); res.setActionIdentifier(ReservationResult.ACTION_USER); res.setMessage(stringProvider .getString(StringProvider.PICA_WHICH_COPY)); res.setSelection(selections); return res; } else { ReservationResult res = new ReservationResult( MultiStepResult.Status.ERROR); res.setMessage(stringProvider .getString(StringProvider.NO_COPY_RESERVABLE)); return res; } } else { String html1 = httpGet(json.getJSONObject(selectedPos) .getString("link"), getDefaultEncoding()); Document doc1 = Jsoup.parse(html1); List<NameValuePair> params = new ArrayList<NameValuePair>(); for (Element input : doc1.select("input[type=hidden]")) { params.add(new BasicNameValuePair(input.attr("name"), input.attr("value"))); } params.add(new BasicNameValuePair("BOR_U", account .getName())); params.add(new BasicNameValuePair("BOR_PW", account .getPassword())); return reservation_result(params, false); } } else { // A copy has been selected JSONObject values = new JSONObject(selection); List<NameValuePair> params = new ArrayList<NameValuePair>(); Iterator<String> keys = values.keys(); while (keys.hasNext()) { String key = (String) keys.next(); String value = values.getString(key); params.add(new BasicNameValuePair(key, value)); } params.add(new BasicNameValuePair("BOR_U", account.getName())); params.add(new BasicNameValuePair("BOR_PW", account .getPassword())); return reservation_result(params, true); } } catch (JSONException e) { e.printStackTrace(); ReservationResult res = new ReservationResult( MultiStepResult.Status.ERROR); res.setMessage(stringProvider .getString(StringProvider.INTERNAL_ERROR)); return res; } } public ReservationResult reservation_result(List<NameValuePair> params, boolean multi) throws IOException { String html2 = httpPost(https_url + "/loan/DB=" + db + "/SET=" + searchSet + "/TTL=1/" + (multi ? "REQCONT" : "RESCONT"), new UrlEncodedFormEntity(params, getDefaultEncoding()), getDefaultEncoding()); Document doc2 = Jsoup.parse(html2); if (doc2.select(".alert").text().contains("ist fuer Sie vorgemerkt")) { return new ReservationResult(MultiStepResult.Status.OK); } else { ReservationResult res = new ReservationResult( MultiStepResult.Status.ERROR); res.setMessage(doc2.select(".cnt .alert").text()); return res; } } @Override public ProlongResult prolong(String media, Account account, int useraction, String Selection) throws IOException { if (pwEncoded == null) try { account(account); } catch (JSONException e1) { return new ProlongResult(MultiStepResult.Status.ERROR); } catch (OpacErrorException e1) { return new ProlongResult(MultiStepResult.Status.ERROR, e1.getMessage()); } List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("ACT", "UI_RENEWLOAN")); params.add(new BasicNameValuePair("BOR_U", account.getName())); params.add(new BasicNameValuePair("BOR_PW_ENC", URLDecoder.decode( pwEncoded, "UTF-8"))); params.add(new BasicNameValuePair("VB", media)); String html = httpPost(https_url + "/loan/DB=" + db + "/USERINFO", new UrlEncodedFormEntity(params, getDefaultEncoding()), getDefaultEncoding()); Document doc = Jsoup.parse(html); if (doc.select("td.regular-text") .text() .contains( "Die Leihfrist Ihrer ausgeliehenen Publikationen ist ") || doc.select("td.regular-text").text() .contains("Ihre ausgeliehenen Publikationen sind verl")) { return new ProlongResult(MultiStepResult.Status.OK); } else if (doc.select(".cnt").text().contains("identify")) { try { account(account); return prolong(media, account, useraction, Selection); } catch (JSONException e) { return new ProlongResult(MultiStepResult.Status.ERROR); } catch (OpacErrorException e) { return new ProlongResult(MultiStepResult.Status.ERROR, e.getMessage()); } } else { ProlongResult res = new ProlongResult(MultiStepResult.Status.ERROR); res.setMessage(doc.select(".cnt").text()); return res; } } @Override public ProlongAllResult prolongAll(Account account, int useraction, String selection) throws IOException { return null; } @Override public CancelResult cancel(String media, Account account, int useraction, String selection) throws IOException, OpacErrorException { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("ACT", "UI_CANCELRES")); params.add(new BasicNameValuePair("BOR_U", account.getName())); params.add(new BasicNameValuePair("BOR_PW_ENC", URLDecoder.decode( pwEncoded, "UTF-8"))); if (lor_reservations != null) params.add(new BasicNameValuePair("LOR_RESERVATIONS", lor_reservations)); params.add(new BasicNameValuePair("VB", media)); String html = httpPost(https_url + "/loan/DB=" + db + "/SET=" + searchSet + "/TTL=1/USERINFO", new UrlEncodedFormEntity( params, getDefaultEncoding()), getDefaultEncoding()); Document doc = Jsoup.parse(html); if (doc.select("td.regular-text").text() .contains("Ihre Vormerkungen sind ")) { return new CancelResult(MultiStepResult.Status.OK); } else if (doc.select(".cnt .alert").text() .contains("identify yourself")) { try { account(account); return cancel(media, account, useraction, selection); } catch (JSONException e) { throw new OpacErrorException( stringProvider.getString(StringProvider.INTERNAL_ERROR)); } } else { CancelResult res = new CancelResult(MultiStepResult.Status.ERROR); res.setMessage(doc.select(".cnt").text()); return res; } } @Override public AccountData account(Account account) throws IOException, JSONException, OpacErrorException { if (!initialised) start(); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("ACT", "UI_DATA")); params.add(new BasicNameValuePair("HOST_NAME", "")); params.add(new BasicNameValuePair("HOST_PORT", "")); params.add(new BasicNameValuePair("HOST_SCRIPT", "")); params.add(new BasicNameValuePair("LOGIN", "KNOWNUSER")); params.add(new BasicNameValuePair("STATUS", "HML_OK")); params.add(new BasicNameValuePair("BOR_U", account.getName())); params.add(new BasicNameValuePair("BOR_PW", account.getPassword())); String html = httpPost(https_url + "/loan/DB=" + db + "/USERINFO", new UrlEncodedFormEntity(params, getDefaultEncoding()), getDefaultEncoding()); Document doc = Jsoup.parse(html); if (doc.select(".cnt .alert, .cnt .error").size() > 0) { throw new OpacErrorException(doc.select(".cnt .alert, .cnt .error") .text()); } if (doc.select("input[name=BOR_PW_ENC]").size() > 0) { pwEncoded = URLEncoder.encode(doc.select("input[name=BOR_PW_ENC]") .attr("value"), "UTF-8"); } else { // TODO: do something here to help fix bug #229 } html = httpGet(https_url + "/loan/DB=" + db + "/USERINFO?ACT=UI_LOL&BOR_U=" + account.getName() + "&BOR_PW_ENC=" + pwEncoded, getDefaultEncoding()); doc = Jsoup.parse(html); html = httpGet(https_url + "/loan/DB=" + db + "/USERINFO?ACT=UI_LOR&BOR_U=" + account.getName() + "&BOR_PW_ENC=" + pwEncoded, getDefaultEncoding()); Document doc2 = Jsoup.parse(html); AccountData res = new AccountData(account.getId()); List<Map<String, String>> medien = new ArrayList<Map<String, String>>(); List<Map<String, String>> reserved = new ArrayList<Map<String, String>>(); if (doc.select("table[summary^=list]").size() > 0) { parse_medialist(medien, doc, 1, account.getName()); } if (doc2.select("table[summary^=list]").size() > 0) { parse_reslist(reserved, doc2, 1); } res.setLent(medien); res.setReservations(reserved); if (medien == null || reserved == null) { throw new OpacErrorException( stringProvider .getString(StringProvider.UNKNOWN_ERROR_ACCOUNT)); // Log.d("OPACCLIENT", html); } return res; } protected void parse_medialist(List<Map<String, String>> medien, Document doc, int offset, String accountName) throws ClientProtocolException, IOException { Elements copytrs = doc .select("table[summary^=list] > tbody > tr[valign=top]"); SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy", Locale.GERMAN); int trs = copytrs.size(); if (trs < 1) { medien = null; return; } assert (trs > 0); for (int i = 0; i < trs; i++) { Element tr = copytrs.get(i); if (tr.select("table[summary=title data]").size() > 0) { // According to HTML code from Bug reports (Server TU Darmstadt, // Berlin Ibero-Amerikanisches Institut) Map<String, String> e = new HashMap<String, String>(); // Check if there is a checkbox to prolong this item if (tr.select("input").size() > 0) e.put(AccountData.KEY_LENT_LINK, tr.select("input").attr("value")); else e.put(AccountData.KEY_LENT_RENEWABLE, "N"); Elements datatrs = tr.select("table[summary=title data] tr"); e.put(AccountData.KEY_LENT_TITLE, datatrs.get(0).text()); List<TextNode> textNodes = datatrs.get(1).select("td").first() .textNodes(); List<TextNode> nodes = new ArrayList<TextNode>(); Elements titles = datatrs.get(1).select("span.label-small"); for (TextNode node : textNodes) { if (!node.text().equals(" ")) nodes.add(node); } assert (nodes.size() == titles.size()); for (int j = 0; j < nodes.size(); j++) { String title = titles.get(j).text(); String value = nodes.get(j).text().trim().replace(";", ""); if (title.contains("Signatur")) { // not supported } else if (title.contains("Status")) { e.put(AccountData.KEY_LENT_STATUS, value); } else if (title.contains("Leihfristende")) { e.put(AccountData.KEY_LENT_DEADLINE, value); try { e.put(AccountData.KEY_LENT_DEADLINE_TIMESTAMP, String.valueOf(sdf.parse(value).getTime())); } catch (ParseException e1) { e1.printStackTrace(); } } else if (title.contains("Vormerkungen")) { // not supported } } medien.add(e); } else { // like in Kiel String prolongCount = ""; if (tr.select("iframe[name=nr_renewals_in_a_box]").size() > 0) { try { String html = httpGet(tr.select("iframe[name=nr_renewals_in_a_box]").attr("src"), getDefaultEncoding()); prolongCount = Jsoup.parse(html).text(); } catch (IOException e) { } } String reminderCount = tr.child(13).text().trim(); if (reminderCount.indexOf(" Mahn") >= 0 && reminderCount.indexOf("(") >= 0 && reminderCount.indexOf("(") < reminderCount .indexOf(" Mahn")) reminderCount = reminderCount.substring( reminderCount.indexOf("(") + 1, reminderCount.indexOf(" Mahn")); else reminderCount = ""; Map<String, String> e = new HashMap<String, String>(); if (tr.child(4).text().trim().length() < 5 && tr.child(5).text().trim().length() > 4) { e.put(AccountData.KEY_LENT_TITLE, tr.child(5).text().trim()); } else { e.put(AccountData.KEY_LENT_TITLE, tr.child(4).text().trim()); } String status = ""; if (!reminderCount.equals("0") && !reminderCount.equals("")) { status += reminderCount + " " + stringProvider .getString(StringProvider.REMINDERS) + ", "; } status += prolongCount + "x " + stringProvider .getString(StringProvider.PROLONGED_ABBR); // tr.child(25).text().trim() // + " Vormerkungen"); e.put(AccountData.KEY_LENT_STATUS, status); e.put(AccountData.KEY_LENT_DEADLINE, tr.child(21).text().trim()); try { e.put(AccountData.KEY_LENT_DEADLINE_TIMESTAMP, String .valueOf(sdf.parse( e.get(AccountData.KEY_LENT_DEADLINE)) .getTime())); } catch (ParseException e1) { e1.printStackTrace(); } e.put(AccountData.KEY_LENT_LINK, tr.child(1).select("input") .attr("value")); medien.add(e); } } assert (medien.size() == trs - 1); } protected void parse_reslist(List<Map<String, String>> medien, Document doc, int offset) throws ClientProtocolException, IOException { if (doc.select("input[name=LOR_RESERVATIONS]").size() > 0) { lor_reservations = doc.select("input[name=LOR_RESERVATIONS]").attr( "value"); } Elements copytrs = doc.select("table[summary^=list] tr[valign=top]"); int trs = copytrs.size(); if (trs < 1) { medien = null; return; } assert (trs > 0); for (int i = 0; i < trs; i++) { Element tr = copytrs.get(i); Map<String, String> e = new HashMap<String, String>(); e.put(AccountData.KEY_RESERVATION_TITLE, tr.child(5).text().trim()); e.put(AccountData.KEY_RESERVATION_READY, tr.child(17).text().trim()); e.put(AccountData.KEY_RESERVATION_CANCEL, tr.child(1).select("input").attr("value")); medien.add(e); } assert (medien.size() == trs - 1); } @Override public List<SearchField> getSearchFields() throws ClientProtocolException, IOException, JSONException { if (!initialised) start(); String html = httpGet(opac_url + "/LNG=" + getLang() + "/ADVANCED_SEARCHFILTER", getDefaultEncoding()); Document doc = Jsoup.parse(html); List<SearchField> fields = new ArrayList<SearchField>(); Elements options = doc.select("select[name=IKT0] option"); for (Element option : options) { TextSearchField field = new TextSearchField(); field.setDisplayName(option.text()); field.setId(option.attr("value")); field.setHint(""); field.setData(new JSONObject("{\"ADI\": false}")); Pattern pattern = Pattern.compile("\\[X?[A-Za-z]{2,3}:?\\]|\\(X?[A-Za-z]{2,3}:?\\)"); Matcher matcher = pattern.matcher(field.getDisplayName()); if (matcher.find()) { field.getData() .put("meaning", matcher.group().replace(":", "").toUpperCase()); field.setDisplayName(matcher.replaceFirst("").trim()); } fields.add(field); } Elements sort = doc.select("select[name=SRT]"); if (sort.size() > 0) { DropdownSearchField field = new DropdownSearchField(); field.setDisplayName(sort.first().parent().parent() .select(".longval").first().text()); field.setId("SRT"); List<Map<String, String>> sortOptions = new ArrayList<Map<String, String>>(); for (Element option : sort.select("option")) { Map<String, String> sortOption = new HashMap<String, String>(); sortOption.put("key", option.attr("value")); sortOption.put("value", option.text()); sortOptions.add(sortOption); } field.setDropdownValues(sortOptions); fields.add(field); } for (Element input : doc.select("input[type=text][name^=ADI]")) { TextSearchField field = new TextSearchField(); field.setDisplayName(input.parent().parent().select(".longkey") .text()); field.setId(input.attr("name")); field.setHint(input.parent().select("span").text()); field.setData(new JSONObject("{\"ADI\": true}")); fields.add(field); } for (Element dropdown : doc.select("select[name^=ADI]")) { DropdownSearchField field = new DropdownSearchField(); field.setDisplayName(dropdown.parent().parent().select(".longkey") .text()); field.setId(dropdown.attr("name")); List<Map<String, String>> dropdownOptions = new ArrayList<Map<String, String>>(); for (Element option : dropdown.select("option")) { Map<String, String> dropdownOption = new HashMap<String, String>(); dropdownOption.put("key", option.attr("value")); dropdownOption.put("value", option.text()); dropdownOptions.add(dropdownOption); } field.setDropdownValues(dropdownOptions); fields.add(field); } Elements fuzzy = doc.select("input[name=FUZZY]"); if (fuzzy.size() > 0) { CheckboxSearchField field = new CheckboxSearchField(); field.setDisplayName(fuzzy.first().parent().parent() .select(".longkey").first().text()); field.setId("FUZZY"); fields.add(field); } Elements mediatypes = doc.select("input[name=ADI_MAT]"); if (mediatypes.size() > 0) { DropdownSearchField field = new DropdownSearchField(); field.setDisplayName("Materialart"); field.setId("ADI_MAT"); List<Map<String, String>> values = new ArrayList<Map<String, String>>(); Map<String, String> all = new HashMap<String, String>(); all.put("key", ""); all.put("value", "Alle"); values.add(all); for (Element mt : mediatypes) { Map<String, String> value = new HashMap<String, String>(); value.put("key", mt.attr("value")); value.put("value", mt.parent().nextElementSibling().text() .replace("\u00a0", "")); values.add(value); } field.setDropdownValues(values); fields.add(field); } return fields; } @Override public boolean isAccountSupported(Library library) { return library.isAccountSupported(); } @Override public boolean isAccountExtendable() { return false; } @Override public String getAccountExtendableInfo(Account account) throws IOException, NotReachableException { return null; } @Override public String getShareUrl(String id, String title) { return id; } @Override public int getSupportFlags() { return SUPPORT_FLAG_ENDLESS_SCROLLING | SUPPORT_FLAG_CHANGE_ACCOUNT; } public void updateSearchSetValue(Document doc) { String url = doc.select("base").first().attr("href"); Integer setPosition = url.indexOf("SET=") + 4; String searchSetString = url.substring(setPosition, url.indexOf("/", setPosition)); searchSet = Integer.parseInt(searchSetString); } public MediaType getMediaTypeInSingleResult(String html) { Document doc = Jsoup.parse(html); MediaType mediatype = MediaType.UNKNOWN; if (doc.select("table[summary=presentation switch] img").size() > 0) { String[] fparts = doc .select("table[summary=presentation switch] img").get(0) .attr("src").split("/"); String fname = fparts[fparts.length - 1]; if (data.has("mediatypes")) { try { mediatype = MediaType.valueOf(data.getJSONObject( "mediatypes").getString(fname)); } catch (JSONException e) { mediatype = defaulttypes.get(fname .toLowerCase(Locale.GERMAN).replace(".jpg", "") .replace(".gif", "").replace(".png", "")); } catch (IllegalArgumentException e) { mediatype = defaulttypes.get(fname .toLowerCase(Locale.GERMAN).replace(".jpg", "") .replace(".gif", "").replace(".png", "")); } } else { mediatype = defaulttypes.get(fname.toLowerCase(Locale.GERMAN) .replace(".jpg", "").replace(".gif", "") .replace(".png", "")); } } return mediatype; } @Override protected String getDefaultEncoding() { try { if (data.has("charset")) return data.getString("charset"); } catch (JSONException e) { e.printStackTrace(); } return "UTF-8"; } @Override public void checkAccountData(Account account) throws IOException, JSONException, OpacErrorException { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("ACT", "UI_DATA")); params.add(new BasicNameValuePair("HOST_NAME", "")); params.add(new BasicNameValuePair("HOST_PORT", "")); params.add(new BasicNameValuePair("HOST_SCRIPT", "")); params.add(new BasicNameValuePair("LOGIN", "KNOWNUSER")); params.add(new BasicNameValuePair("STATUS", "HML_OK")); params.add(new BasicNameValuePair("BOR_U", account.getName())); params.add(new BasicNameValuePair("BOR_PW", account.getPassword())); String html = httpPost(https_url + "/loan/DB=" + db + "/USERINFO", new UrlEncodedFormEntity(params, getDefaultEncoding()), getDefaultEncoding()); Document doc = Jsoup.parse(html); if (doc.select(".cnt .alert, .cnt .error").size() > 0) { throw new OpacErrorException(doc.select(".cnt .alert, .cnt .error") .text()); } } @Override public void setLanguage(String language) { this.languageCode = language; } private String getLang() { if (supportedLanguages.contains(languageCode)) return languageCodes.get(languageCode); else if (supportedLanguages.contains("en")) // Fall back to English if language not available return languageCodes.get("en"); else if (supportedLanguages.contains("de")) // Fall back to German if English not available return languageCodes.get("de"); else return null; } @Override public Set<String> getSupportedLanguages() throws IOException { Set<String> langs = new HashSet<String>(); for (String lang : languageCodes.keySet()) { String html = httpGet(opac_url + "/DB=" + db + "/LNG=" + languageCodes.get(lang) + "/START_WELCOME", getDefaultEncoding()); if (!html.contains("MODE_START")) langs.add(lang); } return langs; } }
package org.jboss.as.jpa.hibernate4; import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Configuration; import org.jboss.as.jpa.spi.JtaManager; import org.jboss.as.jpa.spi.PersistenceProviderAdaptor; import org.jboss.as.jpa.spi.PersistenceUnitMetadata; import org.jboss.as.naming.deployment.ContextNames; import org.jboss.as.naming.deployment.JndiName; import org.jboss.msc.service.ServiceName; import java.util.ArrayList; import java.util.Map; /** * Implements the PersistenceProviderAdaptor for Hibernate * * @author Scott Marlow */ public class HibernatePersistenceProviderAdaptor implements PersistenceProviderAdaptor { private JBossAppServerJtaPlatform appServerJtaPlatform; @Override public void injectJtaManager(JtaManager jtaManager) { appServerJtaPlatform = new JBossAppServerJtaPlatform(jtaManager); } @Override public void addProviderProperties(Map properties, PersistenceUnitMetadata pu) { properties.put(Configuration.USE_NEW_ID_GENERATOR_MAPPINGS, "true"); properties.put(org.hibernate.ejb.AvailableSettings.SCANNER, "org.jboss.as.jpa.hibernate4.HibernateAnnotationScanner"); properties.put(AvailableSettings.APP_CLASSLOADER, pu.getClassLoader()); properties.put(AvailableSettings.JTA_PLATFORM, appServerJtaPlatform); properties.remove(AvailableSettings.TRANSACTION_MANAGER_STRATEGY); // remove legacy way of specifying TX manager (conflicts with JTA_PLATFORM) } @Override public Iterable<ServiceName> getProviderDependencies(PersistenceUnitMetadata pu) { String cacheManager = pu.getProperties().getProperty("hibernate.cache.infinispan.cachemanager"); String useCache = pu.getProperties().getProperty("hibernate.cache.use_second_level_cache"); String regionFactoryClass = pu.getProperties().getProperty("hibernate.cache.region.factory_class"); if ((useCache != null && useCache.equalsIgnoreCase("true")) || cacheManager != null) { if (regionFactoryClass == null) { regionFactoryClass = "org.hibernate.cache.infinispan.JndiInfinispanRegionFactory"; pu.getProperties().put("hibernate.cache.region.factory_class", regionFactoryClass); } if (cacheManager == null) { cacheManager = "java:jboss/infinispan/hibernate"; pu.getProperties().put("hibernate.cache.infinispan.cachemanager", cacheManager); } ArrayList<ServiceName> result = new ArrayList<ServiceName>(); result.add(adjustJndiName(cacheManager)); return result; } return null; } private ServiceName adjustJndiName(String jndiName) { jndiName = toJndiName(jndiName).toString(); int index = jndiName.indexOf("/"); String namespace = (index > 5) ? jndiName.substring(5, index) : null; String binding = (index > 5) ? jndiName.substring(index + 1) : jndiName.substring(5); ServiceName naming = (namespace != null) ? ContextNames.JAVA_CONTEXT_SERVICE_NAME.append(namespace) : ContextNames.JAVA_CONTEXT_SERVICE_NAME; return naming.append(binding); } private static JndiName toJndiName(String value) { return value.startsWith("java:") ? JndiName.of(value) : JndiName.of("java:jboss").append(value.startsWith("/") ? value.substring(1) : value); } @Override public void beforeCreateContainerEntityManagerFactory(PersistenceUnitMetadata pu) { // set backdoor annotation scanner access to pu HibernateAnnotationScanner.setThreadLocalPersistenceUnitMetadata(pu); } @Override public void afterCreateContainerEntityManagerFactory(PersistenceUnitMetadata pu) { // clear backdoor annotation scanner access to pu HibernateAnnotationScanner.clearThreadLocalPersistenceUnitMetadata(); } }
package org.kurento.test.browser; import java.awt.Color; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.commons.codec.binary.Base64; import org.junit.After; import org.kurento.client.EventListener; import org.kurento.client.IceCandidate; import org.kurento.client.MediaStateChangedEvent; import org.kurento.client.OnIceCandidateEvent; import org.kurento.client.WebRtcEndpoint; import org.kurento.commons.exception.KurentoException; import org.kurento.jsonrpc.JsonUtils; import org.kurento.test.base.KurentoTest; import org.kurento.test.grid.GridHandler; import org.kurento.test.latency.VideoTagType; import org.kurento.test.utils.Ffmpeg; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; import com.google.gson.JsonObject; import com.google.gson.JsonParser; /** * Specific client for tests within kurento-test project. This logic is linked to client page logic * (e.g. webrtc.html). * * @author Boni Garcia (bgarcia@gsyc.es) * @since 5.1.0 */ public class WebRtcTestPage extends WebPage { public interface WebRtcConfigurer { public void addIceCandidate(IceCandidate candidate); public String processOffer(String sdpOffer); } protected static final String LOCAL_VIDEO = "local"; protected static final String REMOTE_VIDEO = "video"; private List<Thread> callbackThreads = new ArrayList<>(); private Map<String, CountDownLatch> countDownLatchEvents = new HashMap<>(); @After @SuppressWarnings("deprecation") public void teardownKurentoServices() throws Exception { for (Thread t : callbackThreads) { t.stop(); } } public WebRtcTestPage() { } @Override public void setBrowser(Browser browserClient) { super.setBrowser(browserClient); // By default all tests are going to track color in both video tags checkColor(LOCAL_VIDEO, REMOTE_VIDEO); VideoTagType.setLocalId(LOCAL_VIDEO); VideoTagType.setRemoteId(REMOTE_VIDEO); } /* * setColorCoordinates */ @Override public void setColorCoordinates(int x, int y) { browser.getWebDriver().findElement(By.id("x")).clear(); browser.getWebDriver().findElement(By.id("y")).clear(); browser.getWebDriver().findElement(By.id("x")).sendKeys(String.valueOf(x)); browser.getWebDriver().findElement(By.id("y")).sendKeys(String.valueOf(y)); super.setColorCoordinates(x, y); } /* * similarColor */ public boolean similarColor(Color expectedColor) { return similarColor(REMOTE_VIDEO, expectedColor); } /* * similarColorAt */ public boolean similarColorAt(Color expectedColor, int x, int y) { return similarColorAt(REMOTE_VIDEO, expectedColor, x, y); } /* * close */ public void close() { browser.close(); } /* * subscribeEvents */ public void subscribeEvents(String eventType) { subscribeEventsToVideoTag("video", eventType); } /* * subscribeLocalEvents */ public void subscribeLocalEvents(String eventType) { subscribeEventsToVideoTag("local", eventType); } /* * subscribeEventsToVideoTag */ public void subscribeEventsToVideoTag(final String videoTag, final String eventType) { CountDownLatch latch = new CountDownLatch(1); final String browserName = browser.getId(); log.info("Subscribe event '{}' in video tag '{}' in browser '{}'", eventType, videoTag, browserName); countDownLatchEvents.put(browserName + eventType, latch); addEventListener(videoTag, eventType, new BrowserEventListener() { @Override public void onEvent(String event) { consoleLog(ConsoleLogLevel.INFO, "Event in " + videoTag + " tag: " + event); countDownLatchEvents.get(browserName + eventType).countDown(); } }); } /* * waitForEvent */ public boolean waitForEvent(final String eventType) throws InterruptedException { String browserName = browser.getId(); log.info("Waiting for event '{}' in browser '{}'", eventType, browserName); if (!countDownLatchEvents.containsKey(browserName + eventType)) { log.error("We cannot wait for an event without previous subscription"); return false; } boolean result = countDownLatchEvents.get(browserName + eventType).await(browser.getTimeout(), TimeUnit.SECONDS); // Record local audio when playing event reaches the browser if (eventType.equalsIgnoreCase("playing") && browser.getRecordAudio() > 0) { if (browser.isRemote()) { Ffmpeg.recordRemote(GridHandler.getInstance().getNode(browser.getId()), browser.getRecordAudio(), browser.getAudioSampleRate(), browser.getAudioChannel()); } else { Ffmpeg.record(browser.getRecordAudio(), browser.getAudioSampleRate(), browser.getAudioChannel()); } } countDownLatchEvents.remove(browserName + eventType); return result; } /* * addEventListener */ @SuppressWarnings("deprecation") public void addEventListener(final String videoTag, final String eventType, final BrowserEventListener eventListener) { Thread t = new Thread() { @Override public void run() { browser.executeScript(videoTag + ".addEventListener('" + eventType + "', videoEvent, false);"); try { new WebDriverWait(browser.getWebDriver(), browser.getTimeout()) .until(new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver d) { return d.findElement(By.id("status")).getAttribute("value") .equalsIgnoreCase(eventType); } }); eventListener.onEvent(eventType); } catch (Throwable t) { log.error("~~~ Exception in addEventListener {}", t.getMessage()); t.printStackTrace(); this.interrupt(); this.stop(); } } }; callbackThreads.add(t); t.setDaemon(true); t.start(); } /* * start */ public void start(String videoUrl) { browser.executeScript("play('" + videoUrl + "', false);"); } /* * stop */ public void stopPlay() { browser.executeScript("terminate();"); } /* * consoleLog */ public void consoleLog(ConsoleLogLevel level, String message) { log.info(message); browser.executeScript("console." + level.toString() + "('" + message + "');"); } /* * getCurrentTime */ public double getCurrentTime() { log.debug("getCurrentTime() called"); double currentTime = Double.parseDouble(browser.getWebDriver().findElement(By.id("currentTime")) .getAttribute("value")); log.debug("getCurrentTime() result: {}", currentTime); return currentTime; } /* * readConsole */ public String readConsole() { return browser.getWebDriver().findElement(By.id("console")).getText(); } /* * compare */ public boolean compare(double i, double j) { return Math.abs(j - i) <= browser.getThresholdTime(); } protected void addIceCandidate(JsonObject candidate) { browser.executeScript("addIceCandidate('" + candidate + "');"); } /* * Decide if one candidate has to be added or not according with two parameters */ protected Boolean filterCandidate(String candidate, WebRtcIpvMode webRtcIpvMode, WebRtcCandidateType webRtcCandidateType) { Boolean hasIpv = false; Boolean hasCandidateIpv6 = false; if (candidate.split("candidate:")[1].contains(":")) { hasCandidateIpv6 = true; } switch (webRtcIpvMode) { case IPV4: if (!hasCandidateIpv6) { hasIpv = true; } break; case IPV6: if (hasCandidateIpv6) { hasIpv = true; } break; case BOTH: default: hasIpv = true; break; } String candidateType = candidate.split("typ")[1].split(" ")[1]; Boolean hasCandidate = false; switch (webRtcCandidateType) { case HOST: case RELAY: case SRFLX: hasCandidate = webRtcCandidateType.toString().equals(candidateType); break; case ALL: default: hasCandidate = true; break; } return hasIpv && hasCandidate; } /* * initWebRtc with IPVMode */ public void initWebRtc(final WebRtcEndpoint webRtcEndpoint, final WebRtcChannel channel, final WebRtcMode mode, final WebRtcIpvMode webRtcIpvMode, final WebRtcCandidateType webRtcCandidateType) throws InterruptedException { webRtcEndpoint.addOnIceCandidateListener(new EventListener<OnIceCandidateEvent>() { @Override public void onEvent(OnIceCandidateEvent event) { JsonObject candidate = JsonUtils.toJsonObject(event.getCandidate()); log.debug("OnIceCandidateEvent on {}: {}", webRtcEndpoint.getId(), candidate); if (filterCandidate(candidate.get("candidate").getAsString(), webRtcIpvMode, webRtcCandidateType)) { addIceCandidate(candidate); } } }); webRtcEndpoint.addMediaStateChangedListener(new EventListener<MediaStateChangedEvent>() { @Override public void onEvent(MediaStateChangedEvent event) { log.debug("MediaStateChangedEvent from {} to {} on {} at {}", event.getOldState(), event.getNewState(), webRtcEndpoint.getId(), event.getTimestamp()); } }); WebRtcConfigurer webRtcConfigurer = new WebRtcConfigurer() { @Override public void addIceCandidate(IceCandidate candidate) { if (filterCandidate(candidate.getCandidate(), webRtcIpvMode, webRtcCandidateType)) { webRtcEndpoint.addIceCandidate(candidate); } } @Override public String processOffer(String sdpOffer) { String sdpAnswer = webRtcEndpoint.processOffer(sdpOffer); webRtcEndpoint.gatherCandidates(); return sdpAnswer; } }; initWebRtc(webRtcConfigurer, channel, mode); } /* * initWebRtc with IPVMode */ public void initWebRtc(final WebRtcEndpoint webRtcEndpoint, final WebRtcChannel channel, final WebRtcMode mode, final WebRtcIpvMode webRtcIpvMode) throws InterruptedException { initWebRtc(webRtcEndpoint, channel, mode, webRtcIpvMode, WebRtcCandidateType.ALL); } /* * initWebRtc without IPVMode */ public void initWebRtc(final WebRtcEndpoint webRtcEndpoint, final WebRtcChannel channel, final WebRtcMode mode) throws InterruptedException { initWebRtc(webRtcEndpoint, channel, mode, WebRtcIpvMode.BOTH, WebRtcCandidateType.ALL); } @SuppressWarnings({ "unchecked", "deprecation" }) protected void initWebRtc(final WebRtcConfigurer webRtcConfigurer, final WebRtcChannel channel, final WebRtcMode mode) throws InterruptedException { // ICE candidates Thread t1 = new Thread() { @Override public void run() { JsonParser parser = new JsonParser(); int numCandidate = 0; while (true) { try { ArrayList<Object> iceCandidates = (ArrayList<Object>) browser.executeScript("return iceCandidates;"); for (int i = numCandidate; i < iceCandidates.size(); i++) { JsonObject jsonCandidate = (JsonObject) parser.parse(iceCandidates.get(i).toString()); IceCandidate candidate = new IceCandidate(jsonCandidate.get("candidate").getAsString(), jsonCandidate.get( "sdpMid").getAsString(), jsonCandidate.get("sdpMLineIndex").getAsInt()); log.debug("Adding candidate {}: {}", i, jsonCandidate); webRtcConfigurer.addIceCandidate(candidate); numCandidate++; } // Poll 300 ms Thread.sleep(300); } catch (Throwable e) { log.debug("Exiting gather candidates thread"); break; } } } }; t1.start(); // Append WebRTC mode (send/receive and audio/video) to identify test addTestName(KurentoTest.getTestClassName() + "." + KurentoTest.getTestMethodName()); appendStringToTitle(mode.toString()); appendStringToTitle(channel.toString()); // Setting custom audio stream (if necessary) String audio = browser.getAudio(); if (audio != null) { browser.executeScript("setCustomAudio('" + audio + "');"); } // Setting MediaConstraints (if necessary) String channelJsFunction = channel.getJsFunction(); if (channelJsFunction != null) { browser.executeScript(channelJsFunction); } // Execute JavaScript kurentoUtils.WebRtcPeer browser.executeScript(mode.getJsFunction()); // SDP offer/answer final CountDownLatch latch = new CountDownLatch(1); Thread t2 = new Thread() { @Override public void run() { // Wait to valid sdpOffer String sdpOffer = (String) browser.executeScriptAndWaitOutput("return sdpOffer;"); log.debug("SDP offer: {}", sdpOffer); String sdpAnswer = webRtcConfigurer.processOffer(sdpOffer); log.debug("SDP answer: {}", sdpAnswer); // Encoding in Base64 to avoid parsing errors in JavaScript sdpAnswer = new String(Base64.encodeBase64(sdpAnswer.getBytes())); // Process sdpAnswer browser.executeScript("processSdpAnswer('" + sdpAnswer + "');"); latch.countDown(); } }; t2.start(); if (!latch.await(browser.getTimeout(), TimeUnit.SECONDS)) { t1.interrupt(); t1.stop(); t2.interrupt(); t2.stop(); throw new KurentoException("ICE negotiation not finished in " + browser.getTimeout() + " seconds"); } } /* * reload */ public void reload() { browser.reload(); browser.injectKurentoTestJs(); browser.executeScriptAndWaitOutput("return kurentoTest;"); setBrowser(browser); } /* * stopWebRtc */ public void stopWebRtc() { browser.executeScript("stop();"); browser.executeScript("var kurentoTest = new KurentoTest();"); countDownLatchEvents.clear(); } /* * addTestName */ public void addTestName(String testName) { try { browser.executeScript("addTestName('" + testName + "');"); } catch (WebDriverException we) { log.warn(we.getMessage()); } } /* * appendStringToTitle */ public void appendStringToTitle(String webRtcMode) { try { browser.executeScript("appendStringToTitle('" + webRtcMode + "');"); } catch (WebDriverException we) { log.warn(we.getMessage()); } } }
package com.abdallaadelessa.rtl; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.JFileChooser; import java.awt.BorderLayout; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.File; import java.io.FilenameFilter; import java.awt.event.ActionEvent; import javax.swing.JToolBar; import java.awt.GridLayout; import java.awt.FlowLayout; import java.awt.GridBagLayout; import java.awt.GridBagConstraints; import java.awt.Insets; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.LayoutStyle.ComponentPlacement; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.SwingConstants; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.JTextField; import javax.swing.JComboBox; import javax.swing.JCheckBox; import java.awt.Dialog.ModalExclusionType; import javax.swing.DefaultComboBoxModel; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; public class HomeScreen { private JFrame frame; private JTextField txtSrc; private JTextField txtDest; private File srcFile, destFile; private JCheckBox cbReverse; private JButton btnStart; private JComboBox comboBoxMode; public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { HomeScreen window = new HomeScreen(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } public HomeScreen() { initialize(); } public void start() { if (validate(true)) { try { RTLConvertor.setMode(comboBoxMode.getSelectedIndex()==0? RTLConvertor.MODE_RTL:RTLConvertor.MODE_LTR); RTLConvertor.setReverseLinearLayout(cbReverse.isSelected()); // RTLConvertor.addTextViewClass("com.linkdev.soutalkhaleej.views.customWidgets.TextViewWithMovingMarquee"); // RTLConvertor.addTextViewClass("com.rengwuxian.materialedittext.MaterialEditText"); if (srcFile.isDirectory()) { RTLConvertor.convertXmlFiles(srcFile, destFile); } else { RTLConvertor.convertXmlFile(srcFile, destFile); } } catch (Exception e) { showErrorMessage("Error", e.getMessage(), JOptionPane.ERROR_MESSAGE); } } } public boolean validate(boolean showDialog) { boolean isValid = true; if (srcFile == null || !srcFile.exists()) { isValid = false; if (showDialog) showErrorMessage("Error", "Please Select a Valid Source Path", JOptionPane.ERROR_MESSAGE); } else if (destFile == null || !destFile.exists()) { isValid = false; if (showDialog) showErrorMessage("Error", "Please Select a Valid Destination Folder", JOptionPane.ERROR_MESSAGE); } else if (srcFile != null && srcFile.isDirectory()) { File[] files = srcFile.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".xml"); } }); if (files.length == 0) { isValid = false; if (showDialog) showErrorMessage("Error", "Folder doesn't contain any xml files", JOptionPane.ERROR_MESSAGE); } } return isValid; } private File openPicker(int fileMode, FileNameExtensionFilter extensionFilter) { File selectedFile = null; JFileChooser fc = new JFileChooser(); if (extensionFilter != null) fc.setFileFilter(extensionFilter); fc.setCurrentDirectory(new java.io.File(".")); fc.setFileSelectionMode(fileMode); int returnVal = fc.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { selectedFile = fc.getSelectedFile(); } return selectedFile; } public void showErrorMessage(String title, String message, int messageType) { JOptionPane.showMessageDialog(frame, message, "Dialog", messageType); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setResizable(false); frame.setModalExclusionType(ModalExclusionType.APPLICATION_EXCLUDE); frame.setBounds(100, 100, 724, 254); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel lblNewLabel = new JLabel( "<html>A Java tool created to save wasted time in converting any android layout from LTR to RTL and viceversa</html>"); lblNewLabel.setHorizontalAlignment(SwingConstants.TRAILING); JLabel lblSrc = new JLabel("Source Path (Folder or File)"); txtSrc = new JTextField(); txtSrc.setColumns(10); JLabel lblDestinationPath = new JLabel("Destination Folder"); btnStart = new JButton("Start"); btnStart.setEnabled(false); btnStart.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { start(); } }); JButton btnBrowse = new JButton("Browse"); btnBrowse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { srcFile = openPicker(JFileChooser.FILES_AND_DIRECTORIES, new FileNameExtensionFilter("xml files or folders (*.xml)", "xml")); if (srcFile != null) { txtSrc.setText(srcFile.getPath()); } btnStart.setEnabled(validate(false)); } }); txtDest = new JTextField(); txtSrc.getDocument().addDocumentListener(new DocumentListener() { @Override public void changedUpdate(DocumentEvent arg0) { srcFile = new File(txtSrc.getText()); btnStart.setEnabled(validate(false)); } @Override public void insertUpdate(DocumentEvent arg0) { srcFile = new File(txtSrc.getText()); btnStart.setEnabled(validate(false)); } @Override public void removeUpdate(DocumentEvent arg0) { srcFile = new File(txtSrc.getText()); btnStart.setEnabled(validate(false)); } }); txtDest.getDocument().addDocumentListener(new DocumentListener() { @Override public void changedUpdate(DocumentEvent arg0) { destFile = new File(txtDest.getText()); btnStart.setEnabled(validate(false)); } @Override public void insertUpdate(DocumentEvent arg0) { destFile = new File(txtDest.getText()); btnStart.setEnabled(validate(false)); } @Override public void removeUpdate(DocumentEvent arg0) { destFile = new File(txtDest.getText()); btnStart.setEnabled(validate(false)); } }); txtDest.setColumns(10); JButton button = new JButton("Browse"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { destFile = openPicker(JFileChooser.DIRECTORIES_ONLY, null); if (destFile != null) { txtDest.setText(destFile.getPath()); } btnStart.setEnabled(validate(false)); } }); cbReverse = new JCheckBox("Reverse LinearLayouts"); cbReverse.setSelected(true); comboBoxMode = new JComboBox(); comboBoxMode.setModel(new DefaultComboBoxModel(new String[] {"RTL", "LTR"})); GroupLayout groupLayout = new GroupLayout(frame.getContentPane()); groupLayout.setHorizontalGroup( groupLayout.createParallelGroup(Alignment.TRAILING) .addGroup(groupLayout.createSequentialGroup() .addGap(26) .addGroup(groupLayout.createParallelGroup(Alignment.TRAILING) .addComponent(lblNewLabel, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 526, Short.MAX_VALUE) .addGroup(groupLayout.createSequentialGroup() .addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false) .addComponent(lblSrc, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lblDestinationPath, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(ComponentPlacement.UNRELATED) .addGroup(groupLayout.createParallelGroup(Alignment.LEADING) .addComponent(txtDest, GroupLayout.DEFAULT_SIZE, 319, Short.MAX_VALUE) .addGroup(groupLayout.createSequentialGroup() .addComponent(cbReverse, GroupLayout.DEFAULT_SIZE, 159, Short.MAX_VALUE) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(comboBoxMode, GroupLayout.PREFERRED_SIZE, 67, GroupLayout.PREFERRED_SIZE) .addGap(34) .addComponent(btnStart, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(txtSrc, GroupLayout.DEFAULT_SIZE, 435, Short.MAX_VALUE)) .addPreferredGap(ComponentPlacement.UNRELATED) .addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false) .addComponent(button, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnBrowse, GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)))) .addGap(50)) ); groupLayout.setVerticalGroup( groupLayout.createParallelGroup(Alignment.LEADING) .addGroup(groupLayout.createSequentialGroup() .addContainerGap() .addComponent(lblNewLabel, GroupLayout.PREFERRED_SIZE, 45, GroupLayout.PREFERRED_SIZE) .addGap(7) .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE) .addComponent(lblSrc) .addComponent(txtSrc, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(btnBrowse)) .addGap(18) .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE) .addComponent(lblDestinationPath) .addComponent(txtDest, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(button)) .addGap(13) .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE) .addComponent(cbReverse) .addComponent(btnStart, GroupLayout.PREFERRED_SIZE, 35, GroupLayout.PREFERRED_SIZE) .addComponent(comboBoxMode, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addContainerGap(50, Short.MAX_VALUE)) ); frame.getContentPane().setLayout(groupLayout); } }
import javax.swing.JFrame; public class AlphaBetaChess { //array for representation of the chess board /* * color=WHITE/black * pawn=P/p * knight=K/k * rook=R/r * bishop=B/b * queen=Q/q * king=A/a */ static String chessBoard[][]={ {"r","k","b","q","a","b","k","r"}, {"p","p","p","p","p","p","p","p"}, {" "," "," "," "," "," "," "," "}, {" "," "," "," "," "," "," "," "}, {" "," "," "," "," "," "," "," "}, {" "," "," "," "," "," "," "," "}, {"P","P","P","P","P","P","P","P"}, {"R","K","B","Q","A","B","K","R"}}; public static void main(String[] args) { JFrame f=new JFrame("Chess"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); UserInterface ui=new UserInterface(); f.add(ui); f.setSize(500, 500); f.setVisible(true); } //returns previous position(row1,column1), current position (row2,column2) and the captured piece if any else space public static String possibleMoves(){ String moveList=""; /* checks for each square on the chess board the further possible moves of the chess pieces returns the possible move for each piece and adds it to the moveList */ for (int i=0; i<64; i++) { switch (chessBoard[i/8][i%8]) { case "P": moveList+=possibleP(i); break; case "R": moveList+=possibleR(i); break; case "K": moveList+=possibleK(i); break; case "B": moveList+=possibleB(i); break; case "Q": moveList+=possibleQ(i); break; case "A": moveList+=possibleA(i); break; } } return moveList; } public static String possibleP(int i){ String moveList=""; return moveList; } public static String possibleR(int i){ String moveList=""; return moveList; } public static String possibleK(int i){ String moveList=""; return moveList; } public static String possibleB(int i){ String moveList=""; return moveList; } public static String possibleQ(int i){ String moveList=""; return moveList; } public static String possibleA(int i){ String moveList=""; return moveList; } }
package com.esotericsoftware.kryo.io; import com.esotericsoftware.kryo.KryoException; import java.io.IOException; import java.io.InputStream; /** An InputStream that reads data from a byte array and optionally fills the byte array from another OutputStream as needed. * Utility methods are provided for efficiently reading primitive types and strings. * @author Nathan Sweet <misc@n4te.com> */ public class Input extends InputStream { private byte[] buffer; private int capacity, position, limit, total; private char[] chars = new char[32]; private InputStream inputStream; /** Creates an uninitialized Input. {@link #setBuffer(byte[])} must be called before the Input is used. */ public Input () { } /** Creates a new Input for reading from a byte array. * @param bufferSize The size of the buffer. An exception is thrown if more bytes than this are read. */ public Input (int bufferSize) { this.capacity = bufferSize; buffer = new byte[bufferSize]; } /** Creates a new Input for reading from a byte array. * @param buffer An exception is thrown if more bytes than this are read. */ public Input (byte[] buffer) { setBuffer(buffer, 0, buffer.length); } /** Creates a new Input for reading from a byte array. * @param buffer An exception is thrown if more bytes than this are read. */ public Input (byte[] buffer, int offset, int count) { setBuffer(buffer, offset, count); } /** Creates a new Input for reading from an InputStream with a buffer size of 4096. */ public Input (InputStream inputStream) { this(4096); if (inputStream == null) throw new IllegalArgumentException("inputStream cannot be null."); this.inputStream = inputStream; } /** Creates a new Input for reading from an InputStream. */ public Input (InputStream inputStream, int bufferSize) { this(bufferSize); if (inputStream == null) throw new IllegalArgumentException("inputStream cannot be null."); this.inputStream = inputStream; } /** Sets a new buffer. The position and total are reset, discarding any buffered bytes. */ public void setBuffer (byte[] bytes) { setBuffer(bytes, 0, bytes.length); } /** Sets a new buffer. The position and total are reset, discarding any buffered bytes. */ public void setBuffer (byte[] bytes, int offset, int count) { if (bytes == null) throw new IllegalArgumentException("bytes cannot be null."); buffer = bytes; position = offset; limit = count; capacity = bytes.length; total = 0; inputStream = null; } public byte[] getBuffer () { return buffer; } public InputStream getInputStream () { return inputStream; } /** Sets a new InputStream. The position and total are reset, discarding any buffered bytes. * @param inputStream May be null. */ public void setInputStream (InputStream inputStream) { this.inputStream = inputStream; limit = 0; rewind(); } /** Returns the number of bytes read. */ public int total () { return total + position; } /** Sets the number of bytes read. */ public void setTotal (int total) { this.total = total; } /** Returns the current position in the buffer. */ public int position () { return position; } /** Sets the current position in the buffer. */ public void setPosition (int position) { this.position = position; } /** Returns the limit for the buffer. */ public int limit () { return limit; } /** Sets the limit in the buffer. */ public void setLimit (int limit) { this.limit = limit; } /** Sets the position and total to zero. */ public void rewind () { position = 0; total = 0; } /** Discards the specified number of bytes. */ public void skip (int count) throws KryoException { int skipCount = Math.min(limit - position, count); while (true) { position += skipCount; count -= skipCount; if (count == 0) break; skipCount = Math.min(count, capacity); require(skipCount); } } /** Fills the buffer with more bytes. Can be overridden to fill the bytes from a source other than the InputStream. * @return -1 if there are no more bytes. */ protected int fill (byte[] buffer, int offset, int count) throws KryoException { if (inputStream == null) return -1; try { return inputStream.read(buffer, offset, count); } catch (IOException ex) { throw new KryoException(ex); } } /** @param required Must be > 0. The buffer is filled until it has at least this many bytes. * @return the number of bytes remaining. * @throws KryoException if EOS is reached before required bytes are read (buffer underflow). */ private int require (int required) throws KryoException { int remaining = limit - position; if (remaining >= required) return remaining; if (required > capacity) throw new KryoException("Buffer too small: capacity: " + capacity + ", required: " + required); // Try to fill the buffer. int count = fill(buffer, limit, capacity - limit); if (count == -1) throw new KryoException("Buffer underflow."); remaining += count; if (remaining >= required) { limit += count; return remaining; } // Was not enough, compact and try again. System.arraycopy(buffer, position, buffer, 0, remaining); total += position; position = 0; while (true) { count = fill(buffer, remaining, capacity - remaining); if (count == -1) { if (remaining >= required) break; throw new KryoException("Buffer underflow."); } remaining += count; if (remaining >= required) break; // Enough has been read. } limit = remaining; return remaining; } /** @param optional Try to fill the buffer with this many bytes. * @return the number of bytes remaining, but not more than optional, or -1 if the EOS was reached and the buffer is empty. */ private int optional (int optional) throws KryoException { int remaining = limit - position; if (remaining >= optional) return optional; optional = Math.min(optional, capacity); // Try to fill the buffer. int count = fill(buffer, limit, capacity - limit); if (count == -1) return remaining == 0 ? -1 : Math.min(remaining, optional); remaining += count; if (remaining >= optional) { limit += count; return optional; } // Was not enough, compact and try again. System.arraycopy(buffer, position, buffer, 0, remaining); total += position; position = 0; while (true) { count = fill(buffer, remaining, capacity - remaining); if (count == -1) break; remaining += count; if (remaining >= optional) break; // Enough has been read. } limit = remaining; return remaining == 0 ? -1 : Math.min(remaining, optional); } public boolean eof () { return optional(1) == 0; } // InputStream public int available () throws IOException { return limit - position + ((null != inputStream) ? inputStream.available() : 0); } /** Reads a single byte as an int from 0 to 255, or -1 if there are no more bytes are available. */ public int read () throws KryoException { if (optional(1) == 0) return -1; return buffer[position++] & 0xFF; } /** Reads bytes.length bytes or less and writes them to the specified byte[], starting at 0, and returns the number of bytes * read. */ public int read (byte[] bytes) throws KryoException { return read(bytes, 0, bytes.length); } /** Reads count bytes or less and writes them to the specified byte[], starting at offset, and returns the number of bytes read * or -1 if no more bytes are available. */ public int read (byte[] bytes, int offset, int count) throws KryoException { if (bytes == null) throw new IllegalArgumentException("bytes cannot be null."); int startingCount = count; int copyCount = Math.min(limit - position, count); while (true) { System.arraycopy(buffer, position, bytes, offset, copyCount); position += copyCount; count -= copyCount; if (count == 0) break; offset += copyCount; copyCount = optional(count); if (copyCount == -1) { // End of data. if (startingCount == count) return -1; break; } if (position == limit) break; } return startingCount - count; } /** Discards the specified number of bytes. */ public long skip (long count) throws KryoException { long remaining = count; while (remaining > 0) { int skip = Math.max(Integer.MAX_VALUE, (int)remaining); skip(skip); remaining -= skip; } return count; } /** Closes the underlying InputStream, if any. */ public void close () throws KryoException { if (inputStream != null) { try { inputStream.close(); } catch (IOException ignored) { } } } // byte /** Reads a single byte. */ public byte readByte () throws KryoException { require(1); return buffer[position++]; } /** Reads a byte as an int from 0 to 255. */ public int readByteUnsigned () throws KryoException { require(1); return buffer[position++] & 0xFF; } /** Reads the specified number of bytes into a new byte[]. */ public byte[] readBytes (int length) throws KryoException { byte[] bytes = new byte[length]; readBytes(bytes, 0, length); return bytes; } /** Reads bytes.length bytes and writes them to the specified byte[], starting at index 0. */ public void readBytes (byte[] bytes) throws KryoException { readBytes(bytes, 0, bytes.length); } /** Reads count bytes and writes them to the specified byte[], starting at offset. */ public void readBytes (byte[] bytes, int offset, int count) throws KryoException { if (bytes == null) throw new IllegalArgumentException("bytes cannot be null."); int copyCount = Math.min(limit - position, count); while (true) { System.arraycopy(buffer, position, bytes, offset, copyCount); position += copyCount; count -= copyCount; if (count == 0) break; offset += copyCount; copyCount = Math.min(count, capacity); require(copyCount); } } // int /** Reads a 4 byte int. */ public int readInt () throws KryoException { require(4); byte[] buffer = this.buffer; int position = this.position; this.position = position + 4; return (buffer[position] & 0xFF) << 24 | (buffer[position + 1] & 0xFF) << 16 | (buffer[position + 2] & 0xFF) << 8 | buffer[position + 3] & 0xFF; } /** Reads a 1-5 byte int. */ public int readInt (boolean optimizePositive) throws KryoException { if (require(1) < 5) return readInt_slow(optimizePositive); int b = buffer[position++]; int result = b & 0x7F; if ((b & 0x80) != 0) { byte[] buffer = this.buffer; b = buffer[position++]; result |= (b & 0x7F) << 7; if ((b & 0x80) != 0) { b = buffer[position++]; result |= (b & 0x7F) << 14; if ((b & 0x80) != 0) { b = buffer[position++]; result |= (b & 0x7F) << 21; if ((b & 0x80) != 0) { b = buffer[position++]; result |= (b & 0x7F) << 28; } } } } return optimizePositive ? result : ((result >>> 1) ^ -(result & 1)); } private int readInt_slow (boolean optimizePositive) { // The buffer is guaranteed to have at least 1 byte. int b = buffer[position++]; int result = b & 0x7F; if ((b & 0x80) != 0) { require(1); byte[] buffer = this.buffer; b = buffer[position++]; result |= (b & 0x7F) << 7; if ((b & 0x80) != 0) { require(1); b = buffer[position++]; result |= (b & 0x7F) << 14; if ((b & 0x80) != 0) { require(1); b = buffer[position++]; result |= (b & 0x7F) << 21; if ((b & 0x80) != 0) { require(1); b = buffer[position++]; result |= (b & 0x7F) << 28; } } } } return optimizePositive ? result : ((result >>> 1) ^ -(result & 1)); } /** Returns true if enough bytes are available to read an int with {@link #readInt(boolean)}. */ public boolean canReadInt () throws KryoException { if (limit - position >= 5) return true; if (optional(5) <= 0) return false; int p = position; if ((buffer[p++] & 0x80) == 0) return true; if (p == limit) return false; if ((buffer[p++] & 0x80) == 0) return true; if (p == limit) return false; if ((buffer[p++] & 0x80) == 0) return true; if (p == limit) return false; if ((buffer[p++] & 0x80) == 0) return true; if (p == limit) return false; return true; } /** Returns true if enough bytes are available to read a long with {@link #readLong(boolean)}. */ public boolean canReadLong () throws KryoException { if (limit - position >= 9) return true; if (optional(5) <= 0) return false; int p = position; if ((buffer[p++] & 0x80) == 0) return true; if (p == limit) return false; if ((buffer[p++] & 0x80) == 0) return true; if (p == limit) return false; if ((buffer[p++] & 0x80) == 0) return true; if (p == limit) return false; if ((buffer[p++] & 0x80) == 0) return true; if (p == limit) return false; if ((buffer[p++] & 0x80) == 0) return true; if (p == limit) return false; if ((buffer[p++] & 0x80) == 0) return true; if (p == limit) return false; if ((buffer[p++] & 0x80) == 0) return true; if (p == limit) return false; if ((buffer[p++] & 0x80) == 0) return true; if (p == limit) return false; return true; } // string /** Reads the length and string of UTF8 characters, or null. This can read strings written by {@link Output#writeString(String)} * , {@link Output#writeString(CharSequence)}, and {@link Output#writeAscii(String)}. * @return May be null. */ public String readString () { int available = require(1); int b = buffer[position++]; if ((b & 0x80) == 0) return readAscii(); // ASCII. // Null, empty, or UTF8. int charCount = available >= 5 ? readUtf8Length(b) : readUtf8Length_slow(b); switch (charCount) { case 0: return null; case 1: return ""; } charCount if (chars.length < charCount) chars = new char[charCount]; readUtf8(charCount); return new String(chars, 0, charCount); } private int readUtf8Length (int b) { int result = b & 0x3F; // Mask all but first 6 bits. if ((b & 0x40) != 0) { // Bit 7 means another byte, bit 8 means UTF8. byte[] buffer = this.buffer; b = buffer[position++]; result |= (b & 0x7F) << 6; if ((b & 0x80) != 0) { b = buffer[position++]; result |= (b & 0x7F) << 13; if ((b & 0x80) != 0) { b = buffer[position++]; result |= (b & 0x7F) << 20; if ((b & 0x80) != 0) { b = buffer[position++]; result |= (b & 0x7F) << 27; } } } } return result; } private int readUtf8Length_slow (int b) { int result = b & 0x3F; // Mask all but first 6 bits. if ((b & 0x40) != 0) { // Bit 7 means another byte, bit 8 means UTF8. require(1); byte[] buffer = this.buffer; b = buffer[position++]; result |= (b & 0x7F) << 6; if ((b & 0x80) != 0) { require(1); b = buffer[position++]; result |= (b & 0x7F) << 13; if ((b & 0x80) != 0) { require(1); b = buffer[position++]; result |= (b & 0x7F) << 20; if ((b & 0x80) != 0) { require(1); b = buffer[position++]; result |= (b & 0x7F) << 27; } } } } return result; } private void readUtf8 (int charCount) { byte[] buffer = this.buffer; char[] chars = this.chars; // Try to read 7 bit ASCII chars. int charIndex = 0; int count = Math.min(require(1), charCount); int position = this.position; int b; while (charIndex < count) { b = buffer[position++]; if (b < 0) { position break; } chars[charIndex++] = (char)b; } this.position = position; // If buffer didn't hold all chars or any were not ASCII, use slow path for remainder. if (charIndex < charCount) readUtf8_slow(charCount, charIndex); } private void readUtf8_slow (int charCount, int charIndex) { char[] chars = this.chars; byte[] buffer = this.buffer; while (charIndex < charCount) { if (position == limit) require(1); int b = buffer[position++] & 0xFF; switch (b >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: chars[charIndex] = (char)b; break; case 12: case 13: if (position == limit) require(1); chars[charIndex] = (char)((b & 0x1F) << 6 | buffer[position++] & 0x3F); break; case 14: require(2); chars[charIndex] = (char)((b & 0x0F) << 12 | (buffer[position++] & 0x3F) << 6 | buffer[position++] & 0x3F); break; } charIndex++; } } private String readAscii () { byte[] buffer = this.buffer; int end = position; int start = end - 1; int limit = this.limit; int b; do { if (end == limit) return readAscii_slow(); b = buffer[end++]; } while ((b & 0x80) == 0); buffer[end - 1] &= 0x7F; // Mask end of ascii bit. String value = new String(buffer, 0, start, end - start); buffer[end - 1] |= 0x80; position = end; return value; } private String readAscii_slow () { position--; // Re-read the first byte. // Copy chars currently in buffer. int charCount = limit - position; if (charCount > chars.length) chars = new char[charCount * 2]; char[] chars = this.chars; byte[] buffer = this.buffer; for (int i = position, ii = 0, n = limit; i < n; i++, ii++) chars[ii] = (char)buffer[i]; position = limit; // Copy additional chars one by one. while (true) { require(1); int b = buffer[position++]; if (charCount == chars.length) { char[] newChars = new char[charCount * 2]; System.arraycopy(chars, 0, newChars, 0, charCount); chars = newChars; this.chars = newChars; } if ((b & 0x80) == 0x80) { chars[charCount++] = (char)(b & 0x7F); break; } chars[charCount++] = (char)b; } return new String(chars, 0, charCount); } /** Reads the length and string of UTF8 characters, or null. This can read strings written by {@link Output#writeString(String)} * , {@link Output#writeString(CharSequence)}, and {@link Output#writeAscii(String)}. * @return May be null. */ public StringBuilder readStringBuilder () { int available = require(1); int b = buffer[position++]; if ((b & 0x80) == 0) return new StringBuilder(readAscii()); // ASCII. // Null, empty, or UTF8. int charCount = available >= 5 ? readUtf8Length(b) : readUtf8Length_slow(b); switch (charCount) { case 0: return null; case 1: return new StringBuilder(""); } charCount if (chars.length < charCount) chars = new char[charCount]; readUtf8(charCount); StringBuilder builder = new StringBuilder(charCount); builder.append(chars, 0, charCount); return builder; } // float /** Reads a 4 byte float. */ public float readFloat () throws KryoException { return Float.intBitsToFloat(readInt()); } /** Reads a 1-5 byte float with reduced precision. */ public float readFloat (float precision, boolean optimizePositive) throws KryoException { return readInt(optimizePositive) / (float)precision; } // short /** Reads a 2 byte short. */ public short readShort () throws KryoException { require(2); return (short)(((buffer[position++] & 0xFF) << 8) | (buffer[position++] & 0xFF)); } /** Reads a 2 byte short as an int from 0 to 65535. */ public int readShortUnsigned () throws KryoException { require(2); return ((buffer[position++] & 0xFF) << 8) | (buffer[position++] & 0xFF); } // long /** Reads an 8 byte long. */ public long readLong () throws KryoException { require(8); byte[] buffer = this.buffer; return (long)buffer[position++] << 56 | (long)(buffer[position++] & 0xFF) << 48 | (long)(buffer[position++] & 0xFF) << 40 | (long)(buffer[position++] & 0xFF) << 32 | (long)(buffer[position++] & 0xFF) << 24 | (buffer[position++] & 0xFF) << 16 | (buffer[position++] & 0xFF) << 8 | buffer[position++] & 0xFF; } /** Reads a 1-9 byte long. */ public long readLong (boolean optimizePositive) throws KryoException { if (require(1) < 9) return readLong_slow(optimizePositive); int b = buffer[position++]; long result = b & 0x7F; if ((b & 0x80) != 0) { byte[] buffer = this.buffer; b = buffer[position++]; result |= (b & 0x7F) << 7; if ((b & 0x80) != 0) { b = buffer[position++]; result |= (b & 0x7F) << 14; if ((b & 0x80) != 0) { b = buffer[position++]; result |= (b & 0x7F) << 21; if ((b & 0x80) != 0) { b = buffer[position++]; result |= (long)(b & 0x7F) << 28; if ((b & 0x80) != 0) { b = buffer[position++]; result |= (long)(b & 0x7F) << 35; if ((b & 0x80) != 0) { b = buffer[position++]; result |= (long)(b & 0x7F) << 42; if ((b & 0x80) != 0) { b = buffer[position++]; result |= (long)(b & 0x7F) << 49; if ((b & 0x80) != 0) { b = buffer[position++]; result |= (long)b << 56; } } } } } } } } if (!optimizePositive) result = (result >>> 1) ^ -(result & 1); return result; } private long readLong_slow (boolean optimizePositive) { // The buffer is guaranteed to have at least 1 byte. int b = buffer[position++]; long result = b & 0x7F; if ((b & 0x80) != 0) { require(1); byte[] buffer = this.buffer; b = buffer[position++]; result |= (b & 0x7F) << 7; if ((b & 0x80) != 0) { require(1); b = buffer[position++]; result |= (b & 0x7F) << 14; if ((b & 0x80) != 0) { require(1); b = buffer[position++]; result |= (b & 0x7F) << 21; if ((b & 0x80) != 0) { require(1); b = buffer[position++]; result |= (long)(b & 0x7F) << 28; if ((b & 0x80) != 0) { require(1); b = buffer[position++]; result |= (long)(b & 0x7F) << 35; if ((b & 0x80) != 0) { require(1); b = buffer[position++]; result |= (long)(b & 0x7F) << 42; if ((b & 0x80) != 0) { require(1); b = buffer[position++]; result |= (long)(b & 0x7F) << 49; if ((b & 0x80) != 0) { require(1); b = buffer[position++]; result |= (long)b << 56; } } } } } } } } if (!optimizePositive) result = (result >>> 1) ^ -(result & 1); return result; } // boolean /** Reads a 1 byte boolean. */ public boolean readBoolean () throws KryoException { require(1); return buffer[position++] == 1; } // char /** Reads a 2 byte char. */ public char readChar () throws KryoException { require(2); return (char)(((buffer[position++] & 0xFF) << 8) | (buffer[position++] & 0xFF)); } // double /** Reads an 8 bytes double. */ public double readDouble () throws KryoException { return Double.longBitsToDouble(readLong()); } /** Reads a 1-9 byte double with reduced precision. */ public double readDouble (double precision, boolean optimizePositive) throws KryoException { return readLong(optimizePositive) / (double)precision; } }
package org.apache.maven.integrationtests; import junit.framework.TestCase; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.FileUtils; import org.apache.maven.it.util.ResourceExtractor; import java.io.File; public class MavenIT0080Test extends TestCase /*extends AbstractMavenIntegrationTest*/ { /** * Test that depending on a WAR doesn't also get its dependencies * transitively. */ public void testit0080() throws Exception { String basedir = System.getProperty( "maven.test.tmpdir", System.getProperty( "java.io.tmpdir" ) ); File testDir = new File( basedir, getName() ); FileUtils.deleteDirectory( testDir ); System.out.println( "Extracting it0080 to " + testDir.getAbsolutePath() ); ResourceExtractor.extractResourcePath( getClass(), "/it0080", testDir ); Verifier verifier = new Verifier( testDir.getAbsolutePath() ); verifier.executeGoal( "package" ); verifier.assertFilePresent( "test-component-a/target/test-component-a-0.1.jar" ); verifier.assertFilePresent( "test-component-b/target/test-component-b-0.1.war" ); verifier.assertFilePresent( "test-component-b/target/test-component-b-0.1.war!/WEB-INF/lib/test-component-a-0.1.jar" ); verifier.assertFilePresent( "test-component-c/target/test-component-c-0.1.ear" ); verifier.assertFilePresent( "test-component-c/target/test-component-c-0.1.ear!/test-component-b-0.1.war" ); verifier.assertFilePresent( "test-component-c/target/test-component-c-0.1/test-component-b-0.1.war" ); verifier.assertFileNotPresent( "test-component-c/target/test-component-c-0.1/test-component-a-0.1.jar" ); verifier.verifyErrorFreeLog(); verifier.resetStreams(); System.out.println( "PASS" ); } }
package com.example.librarytest; import java.util.ArrayList; import java.util.List; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMapOptions; import com.google.android.gms.maps.GoogleMap.OnMapClickListener; import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener; import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.model.BitmapDescriptor; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.Polygon; import com.google.android.gms.maps.model.PolygonOptions; import com.google.android.gms.maps.model.Polyline; import com.google.android.gms.maps.model.PolylineOptions; import android.app.Activity; import android.app.FragmentTransaction; import android.content.res.Resources; import android.graphics.Color; import android.graphics.Point; import android.support.v4.app.FragmentActivity; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.RelativeLayout; // This class isn't used yet public class AtkPolygon extends FragmentActivity implements OnMapClickListener, OnMarkerDragListener, OnMarkerClickListener { private GoogleMap map = null; private RelativeLayout rel = null; private int inc = 0; private int selmkr = 0; private boolean hideT = true; private Polygon poly; private List<Marker> mkr = new ArrayList<Marker>(); private Polyline line; private int endm = 1; private float dens; private Button trackpad, pls, mns, del, dis; private Activity active; private RelativeLayout rel2, rel3; private MapFragment mapf; private int shift = 0; public AtkPolygon(GoogleMap map, RelativeLayout rel, Activity active) { this.map = map; this.rel = rel; this.active = active; } public void startDrawing() { if (map != null && rel != null) { map.setOnMapClickListener(this); map.setOnMarkerDragListener(this); map.setOnMarkerClickListener(this); dens = Resources.getSystem().getDisplayMetrics().density; if (poly == null) poly = map.addPolygon(new PolygonOptions() .add(new LatLng(0, 0)).strokeWidth(2) .strokeColor(Color.BLACK).fillColor(0x7FB5B1E0)); if (line == null) line = map.addPolyline(new PolylineOptions() .add(new LatLng(0, 0)).color(Color.WHITE).width(2)); setButtons(); } } public void redraw(Polygon poly){ if(poly !=null){ if(poly.getPoints().size() > 1){ this.poly = poly; poly.setFillColor(0x7FB5B1E0); inc = poly.getPoints().size()-1; selmkr = inc; mkr.clear(); for(int i = 0; i < inc ; i++) { mkr.add(i,map.addMarker(new MarkerOptions().position(poly.getPoints().get(i)) .anchor((float) 0.5, (float) 0.5).draggable(true) .visible(hideT))); flagRed(mkr.get(i)); } flagGreen(mkr.get(inc-1)); line = map.addPolyline(new PolylineOptions() .add(mkr.get(0).getPosition(), mkr.get(inc-1).getPosition()).color(Color.WHITE).width(2)); startDrawing(); } } } public void stopDrawing() { map.setOnMapClickListener(null); if(active instanceof OnMapClickListener) map.setOnMapClickListener((OnMapClickListener) active); map.setOnMarkerDragListener(null); if(active instanceof OnMarkerDragListener) map.setOnMarkerDragListener((OnMarkerDragListener)active); map.setOnMarkerClickListener(null); if(active instanceof OnMarkerClickListener) map.setOnMarkerClickListener((OnMarkerClickListener)active); rel.removeView(trackpad); rel.removeView(del); rel.removeView(pls); rel.removeView(mns); rel.removeView(dis); rel.removeView(rel2); rel.removeView(rel3); for (int i = 0;i <inc; i++) mkr.get(i).remove(); //mkr.clear(); inc = 0; selmkr = 0; line.remove(); poly = null; //poly.setFillColor(0xF1B5B1E0); } public Polygon getPolygon() { return poly; } public void clear(){ map.clear(); } public void shiftUp(int shift){ this.shift = shift; } @Override public void onMapClick(LatLng point) { if (inc > 0) flagRed(mkr.get(selmkr - 1)); mkr.add(selmkr, map.addMarker(new MarkerOptions().position(point) .anchor((float) 0.5, (float) 0.5).draggable(true) .visible(hideT))); selmkr++; inc++; flagGreen(mkr.get(selmkr - 1)); } private void flagRed(Marker arg0) { BitmapDescriptor unsel = BitmapDescriptorFactory .fromResource(R.drawable.unselected_vertex); arg0.setIcon(unsel); } private void flagGreen(Marker arg0) { BitmapDescriptor sel = BitmapDescriptorFactory .fromResource(R.drawable.selected_vertex); arg0.setIcon(sel); if (inc > 0) { if (selmkr == inc) endm = 1; if (selmkr != inc) endm = selmkr + 1; } doOption(); } private void doOption() { PolygonOptions options = new PolygonOptions(); PolylineOptions lineOptions = new PolylineOptions(); for (int i = 0; i < inc; i++) { options.add(mkr.get(i).getPosition()); } lineOptions.add(mkr.get(selmkr - 1).getPosition(), mkr.get(endm - 1) .getPosition()); poly.setPoints(options.getPoints()); line.setPoints(lineOptions.getPoints()); } @Override public boolean onMarkerClick(Marker arg0) { flagRed(mkr.get(selmkr - 1)); for (int i = 0; i < inc; i++) { if (arg0.equals(mkr.get(i))) { selmkr = i + 1; flagGreen(arg0); break; } } return false; } @Override public void onMarkerDrag(Marker arg0) { if (arg0.equals(mkr.get(selmkr - 1))) mvScreen(); doOption(); } @Override public void onMarkerDragEnd(Marker arg0) { resetrl(); doOption(); } @Override public void onMarkerDragStart(Marker arg0) { if (arg0.equals(mkr.get(selmkr - 1))) mvScreen(); doOption(); } private void Plus() { if (inc > 1) { flagRed(mkr.get(selmkr - 1)); if (selmkr == inc) selmkr = 1; else if (selmkr != inc) selmkr++; flagGreen(mkr.get(selmkr - 1)); } } private void Minus() { if (inc > 1) { flagRed(mkr.get(selmkr - 1)); if (selmkr == 1) selmkr = inc; else if (selmkr != 1) selmkr flagGreen(mkr.get(selmkr - 1)); } } private void doDelete() { if (inc > 0) { mkr.get(selmkr - 1).remove(); mkr.remove(selmkr - 1); inc selmkr if (selmkr == 0) selmkr = inc; if (selmkr > 0) flagGreen(mkr.get(selmkr - 1)); } } private void doDis() { for (int i = 0; i < inc; i++) { mkr.get(i).setVisible(!hideT); } line.setVisible(!hideT); hideT = !hideT; } private void setButtons() { float h, w; h = rel.getHeight() / dens; w = rel.getWidth() / dens; createRel(); del = addbutton(del,R.drawable.deletered, Math.round(50 * dens), Math.round(50 * dens), 60 * dens, (h - 60 - shift) * dens); dis = addbutton(dis, R.drawable.package_purge, Math.round(50 * dens), Math.round(50 * dens), (w - 125) * dens, (h - 60 - shift) * dens); pls = addbutton(pls, R.drawable.add, Math.round(50 * dens), Math.round(50 * dens), 0, (h - 60 - shift) * dens); mns = addbutton(mns, R.drawable.minus, Math.round(50 * dens), Math.round(50 * dens), (w - 65) * dens, (h - 60 - shift) * dens); trackpad = addbutton(trackpad, R.drawable.move_red, Math.round(75 * dens), Math.round(100 * dens), ((w / 2) - 50) * dens, (h - 75 - shift) * dens); del.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { doDelete(); } }); dis.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { doDis(); } }); pls.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Plus(); } }); mns.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Minus(); } }); trackpad.setOnTouchListener(new View.OnTouchListener() { Point pmkr = new Point(); Point pmkr2 = new Point(); float touchx; float touchy; @Override public boolean onTouch(View v, MotionEvent event) { if (inc > 0) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mvScreen(); pmkr.set( map.getProjection().toScreenLocation( mkr.get(selmkr - 1).getPosition()).x, map.getProjection().toScreenLocation( mkr.get(selmkr - 1).getPosition()).y); pmkr2.set((int) event.getX(), (int) event.getY()); break; case MotionEvent.ACTION_MOVE: touchx = (event.getX() - pmkr2.x) + pmkr.x; touchy = (event.getY() - pmkr2.y) + pmkr.y; mkr.get(selmkr - 1).setPosition( map.getProjection().fromScreenLocation( new Point(Math.round(touchx), Math .round(touchy)))); mvScreen(); doOption(); break; case MotionEvent.ACTION_UP: resetrl(); break; } } return false; } }); } private void mvScreen() { fixBearing(); mapf.getMap().moveCamera( CameraUpdateFactory.newLatLngZoom(mkr.get(selmkr - 1) .getPosition(), map.getCameraPosition().zoom + 2)); rel2.setX(map.getProjection().toScreenLocation( mkr.get(selmkr - 1).getPosition()).x - 78 * dens); rel2.setY(map.getProjection().toScreenLocation( mkr.get(selmkr - 1).getPosition()).y - 170 * dens); rel3.setX(rel2.getX()); rel3.setY(rel2.getY()); } private void resetrl() { rel2.setX(-200 * dens); rel2.setY(-200 * dens); rel3.setX(rel2.getX()); rel3.setY(rel2.getY()); } private Button addbutton(Button btn, int dr, int height, int width, float x, float y) { btn = new Button(active.getBaseContext()); btn.setBackgroundResource(dr); btn.setHeight(height); btn.setWidth(width); btn.setX(x); btn.setY(y); rel.addView(btn); return btn; } private void createRel() { rel2 = new RelativeLayout(active.getBaseContext()); RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams( (int) (150 * dens), (int) (150 * dens)); rel2.setLayoutParams(rlp); rel2.setPadding(2,2,2,2); rel2.setBackgroundColor(Color.WHITE); rel.addView(rel2); rel2.setId(100); //this need to be corrected GoogleMapOptions options = new GoogleMapOptions(); options.mapType(GoogleMap.MAP_TYPE_SATELLITE).compassEnabled(false) .rotateGesturesEnabled(false).tiltGesturesEnabled(false) .zoomControlsEnabled(false).camera(map.getCameraPosition()); MapFragment.newInstance(options); mapf = MapFragment.newInstance(options); FragmentTransaction fragmentTransaction = active.getFragmentManager() .beginTransaction(); fragmentTransaction.add(100, mapf); fragmentTransaction.commit(); rel3 = new RelativeLayout(active.getBaseContext()); RelativeLayout.LayoutParams rlp3 = new RelativeLayout.LayoutParams( (int) (150 * dens), (int) (150 * dens)); rel3.setLayoutParams(rlp3); rel.addView(rel3); ImageView img = new ImageView(active.getBaseContext()); img.setBackgroundResource(R.drawable.cross_vertex_5); img.setX(30 * dens); img.setY(30 * dens); rel3.addView(img, (int) (90 * dens), (int) (90 * dens)); resetrl(); } private void fixBearing(){ if (mapf.getMap().getCameraPosition().bearing != map .getCameraPosition().bearing) { mapf.getMap().moveCamera( CameraUpdateFactory.newCameraPosition(map.getCameraPosition())); } } }
package java.awt; import java.util.Arrays; import java.util.Timer; import java.util.TimerTask; import org.videolan.Libbluray; public class BDRootWindow extends Frame { public BDRootWindow () { super(); setUndecorated(true); setBackground(new Color(0, 0, 0, 0)); BDToolkit.setFocusedWindow(this); } public Rectangle getDirtyRect() { return dirty; } public void setBounds(int x, int y, int width, int height) { if (!isVisible()) { if ((width > 0) && (height > 0)) { if ((backBuffer == null) || (getWidth() * getHeight() < width * height)) { backBuffer = new int[width * height]; Arrays.fill(backBuffer, 0); } } super.setBounds(x, y, width, height); Libbluray.updateGraphic(width, height, null); dirty.setBounds(0, 0, width - 1, height - 1); } } public int[] getBdBackBuffer() { return backBuffer; } public Image getBackBuffer() { /* exists only in J2SE */ org.videolan.Logger.getLogger("BDRootWindow").unimplemented("getBackBuffer"); return null; } public void notifyChanged() { if (!isVisible()) { org.videolan.Logger.getLogger("BDRootWindow").error("sync(): not visible"); return; } synchronized (this) { changeCount++; if (timerTask == null) { timerTask = new RefreshTimerTask(this); timer.schedule(timerTask, 50, 50); } } } public void sync() { synchronized (this) { if (timerTask != null) { timerTask.cancel(); timerTask = null; } changeCount = 0; if ((dirty.width | dirty.height) >= 0) { Libbluray.updateGraphic(getWidth(), getHeight(), backBuffer, dirty.x, dirty.y, dirty.x + dirty.width - 1, dirty.y + dirty.height - 1); } dirty.setSize(-1, -1); } } private class RefreshTimerTask extends TimerTask { public RefreshTimerTask(BDRootWindow window) { this.window = window; this.changeCount = window.changeCount; } public void run() { synchronized (window) { if (this.changeCount == window.changeCount) window.sync(); else this.changeCount = window.changeCount; } } private BDRootWindow window; private int changeCount; } public void dispose() { if (isVisible()) { hide(); } if (timerTask != null) { timerTask.cancel(); timerTask = null; } if (timer != null) { timer.cancel(); timer = null; } BDToolkit.setFocusedWindow(null); super.dispose(); } private int[] backBuffer = null; private Rectangle dirty = new Rectangle(); private int changeCount = 0; private Timer timer = new Timer(); private TimerTask timerTask = null; private static final long serialVersionUID = -8325961861529007953L; }
package com.fullmetalgalaxy.client; import java.util.HashMap; import java.util.Map; import com.fullmetalgalaxy.model.RpcUtil; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.History; import com.google.gwt.user.client.HistoryListener; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.WindowResizeListener; import com.google.gwt.user.client.Event.NativePreviewEvent; import com.google.gwt.user.client.Event.NativePreviewHandler; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.PopupPanel; import com.google.gwt.user.client.ui.RootPanel; /** * @author Vincent Legendre * */ public class AppRoot implements EntryPoint, WindowResizeListener, ClickHandler, HistoryListener, SourcesPreviewEvents, NativePreviewHandler { protected PopupPanel m_loadingPanel = new PopupPanel( false, true ); protected int m_isLoading = 0; protected Map m_dialogMap = new HashMap(); private HistoryState m_historyState = new HistoryState(); private EventPreviewListenerCollection m_previewListenerCollection = new EventPreviewListenerCollection(); public AppRoot() { // TODO Auto-generated constructor stub } /* (non-Javadoc) * @see com.google.gwt.core.client.EntryPoint#onModuleLoad() */ public void onModuleLoad() { m_loadingPanel.setWidget( new Image( ClientUtil.getBaseUrl() + "images/loading.cache.gif" ) ); m_loadingPanel.setVisible( true ); m_loadingPanel.setStyleName( "gwt-DialogBox" ); // Hook the window resize event, so that we can adjust the UI. // onWindowResized( Window.getClientWidth(), Window.getClientHeight() ); Window.addWindowResizeListener( this ); // Hook the preview event. // no other element should hook this event as only one can receive it. Event.addNativePreviewHandler( this ); // Add history listener History.addHistoryListener( this ); // If the application starts with no history token, start it off in the // 'baz' state. String initToken = History.getToken(); // onHistoryChanged() is not called when the application first runs. Call // it now in order to reflect the initial state. onHistoryChanged( initToken ); } /* (non-Javadoc) * @see com.fullmetalgalaxy.client.SourcesPreviewEvents#addPreviewListener(com.google.gwt.user.client.EventPreview) */ public void addPreviewListener(NativePreviewHandler p_listener) { if( !m_previewListenerCollection.contains( p_listener ) ) { m_previewListenerCollection.add( p_listener ); } } /* (non-Javadoc) * @see com.fullmetalgalaxy.client.SourcesPreviewEvents#removePreviewListener(com.google.gwt.user.client.EventPreview) */ public void removePreviewListener(NativePreviewHandler p_listener) { m_previewListenerCollection.remove( p_listener ); } /* (non-Javadoc) * @see com.google.gwt.user.client.Event.NativePreviewHandler#onPreviewNativeEvent(com.google.gwt.user.client.Event.NativePreviewEvent) */ @Override public void onPreviewNativeEvent(NativePreviewEvent p_event) { m_previewListenerCollection.fireEventPreview( p_event ); } /** * * @return the current history state. */ public HistoryState getHistoryState() { return m_historyState; } /** * Called when the browser window is resized. */ public void onWindowResized(int p_width, int p_height) { if( m_isLoading > 0 ) { m_loadingPanel.center(); } // m_dockPanel.setHeight( "" + (p_height - 20) + "px" ); } public void onClick(ClickEvent p_event) { } /** * this method should return the list of all possible MiniApp this application can show. * key is a string which match the div id of the html source * value is the corresponding MiniApp. * @return */ protected MiniApp getMApp(String p_key) { return null; } /** * this method should return the default history token which contain the first MiniApp * which have to be displayed on module loading. * @return */ public HistoryState getDefaultHistoryState() { if( RootPanel.get( "app_history" ) != null ) { return new HistoryState( DOM.getElementAttribute( RootPanel.get( "app_history" ).getElement(), "content" ) ); } return new HistoryState(); } /** * display all MiniApp found in p_historyToken and hide the other one. * @see com.google.gwt.user.client.HistoryListener#onHistoryChanged(java.lang.String) */ public void onHistoryChanged(String p_historyToken) { HistoryState oldHistoryState = m_historyState; if( p_historyToken.length() == 0 ) { m_historyState = getDefaultHistoryState(); } else { m_historyState = new HistoryState( p_historyToken ); } for( String key : m_historyState.keySet() ) { if( getMApp( key ) != null ) { // this mini app is present in history: show it show( key, getMApp( key ) ); } } // hide useless mini app for( String key : oldHistoryState.keySet() ) { if( (!m_historyState.containsKey( key ) ) && (getMApp( key ) != null)) { hide( key, getMApp( key ) ); } } } protected void show(String p_id, MiniApp p_miniApp) { assert p_miniApp != null; RootPanel panel = RootPanel.get( p_id ); if( panel != null ) { panel.setVisible( true ); if( p_miniApp.getTopWidget() != null ) { if( panel.getWidgetCount() == 0 ) { panel.add( p_miniApp.getTopWidget() ); } } } else { RpcUtil.logDebug( "couldn't display mini app " + p_id ); } p_miniApp.show( getHistoryState() ); } private void hide(String p_id, MiniApp p_miniApp) { if( p_miniApp == null ) { return; } p_miniApp.hide(); RootPanel panel = RootPanel.get( p_id ); if( panel != null ) { if( p_miniApp.getTopWidget() != null ) { panel.remove( p_miniApp.getTopWidget() ); } panel.setVisible( false ); } } public void startLoading() { if( m_isLoading < 0 ) { m_isLoading = 0; } m_isLoading++; m_loadingPanel.show(); m_loadingPanel.center(); } public void stopLoading() { if( m_isLoading > 0 ) { m_isLoading } if( m_isLoading == 0 ) { m_loadingPanel.hide(); } } }
package com.polidea.rxandroidble.mockrxandroidble; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattDescriptor; import android.support.annotation.NonNull; import com.polidea.rxandroidble.RxBleConnection; import com.polidea.rxandroidble.RxBleDeviceServices; import com.polidea.rxandroidble.exceptions.BleConflictingNotificationAlreadySetException; import com.polidea.rxandroidble.internal.util.ObservableUtil; import java.util.HashMap; import java.util.Map; import java.util.UUID; import rx.Observable; import static android.bluetooth.BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE; import static android.bluetooth.BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE; import static android.bluetooth.BluetoothGattDescriptor.ENABLE_INDICATION_VALUE; class RxBleConnectionMock implements RxBleConnection { static final UUID CLIENT_CHARACTERISTIC_CONFIG_UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"); private HashMap<UUID, Observable<Observable<byte[]>>> notificationObservableMap = new HashMap<>(); private HashMap<UUID, Observable<Observable<byte[]>>> indicationObservableMap = new HashMap<>(); private RxBleDeviceServices rxBleDeviceServices; private int rssi; private Map<UUID, Observable<byte[]>> characteristicNotificationSources; public RxBleConnectionMock(RxBleDeviceServices rxBleDeviceServices, int rssi, Map<UUID, Observable<byte[]>> characteristicNotificationSources) { this.rxBleDeviceServices = rxBleDeviceServices; this.rssi = rssi; this.characteristicNotificationSources = characteristicNotificationSources; } @Override public Observable<RxBleDeviceServices> discoverServices() { return Observable.just(rxBleDeviceServices); } @Override public Observable<BluetoothGattCharacteristic> getCharacteristic(@NonNull UUID characteristicUuid) { return discoverServices() .flatMap(rxBleDeviceServices -> rxBleDeviceServices.getCharacteristic(characteristicUuid)); } @Override public Observable<byte[]> readCharacteristic(@NonNull UUID characteristicUuid) { return getCharacteristic(characteristicUuid).map(BluetoothGattCharacteristic::getValue); } @Override public Observable<byte[]> readCharacteristic(@NonNull BluetoothGattCharacteristic characteristic) { return Observable.just(characteristic.getValue()); } @Override public Observable<byte[]> readDescriptor(UUID serviceUuid, UUID characteristicUuid, UUID descriptorUuid) { return discoverServices() .flatMap(rxBleDeviceServices -> rxBleDeviceServices.getDescriptor(serviceUuid, characteristicUuid, descriptorUuid)) .map(BluetoothGattDescriptor::getValue); } @Override public Observable<byte[]> readDescriptor(BluetoothGattDescriptor descriptor) { return Observable.just(descriptor.getValue()); } @Override public Observable<Integer> readRssi() { return Observable.just(rssi); } @Override public Observable<Observable<byte[]>> setupNotification(@NonNull UUID characteristicUuid) { if (indicationObservableMap.containsKey(characteristicUuid)) { return Observable.error(new BleConflictingNotificationAlreadySetException(characteristicUuid, true)); } Observable<Observable<byte[]>> availableObservable = notificationObservableMap.get(characteristicUuid); if (availableObservable != null) { return availableObservable; } Observable<Observable<byte[]>> newObservable = createCharacteristicNotificationObservable(characteristicUuid, false) .doOnUnsubscribe(() -> dismissCharacteristicNotification(characteristicUuid, false)) .map(notificationDescriptorData -> observeOnCharacteristicChangeCallbacks(characteristicUuid)) .replay(1) .refCount(); notificationObservableMap.put(characteristicUuid, newObservable); return newObservable; } @Override public Observable<Observable<byte[]>> setupNotification(@NonNull BluetoothGattCharacteristic characteristic) { return setupNotification(characteristic.getUuid()); } @Override public Observable<Observable<byte[]>> setupIndication(@NonNull UUID characteristicUuid) { if (notificationObservableMap.containsKey(characteristicUuid)) { return Observable.error(new BleConflictingNotificationAlreadySetException(characteristicUuid, false)); } Observable<Observable<byte[]>> availableObservable = indicationObservableMap.get(characteristicUuid); if (availableObservable != null) { return availableObservable; } Observable<Observable<byte[]>> newObservable = createCharacteristicNotificationObservable(characteristicUuid, true) .doOnUnsubscribe(() -> dismissCharacteristicNotification(characteristicUuid, true)) .map(notificationDescriptorData -> observeOnCharacteristicChangeCallbacks(characteristicUuid)) .replay(1) .refCount(); indicationObservableMap.put(characteristicUuid, newObservable); return newObservable; } @Override public Observable<Observable<byte[]>> setupIndication(@NonNull BluetoothGattCharacteristic characteristic) { return setupIndication(characteristic.getUuid()); } @Override public Observable<BluetoothGattCharacteristic> writeCharacteristic(@NonNull BluetoothGattCharacteristic bluetoothGattCharacteristic) { return getCharacteristic(bluetoothGattCharacteristic.getUuid()) .map(characteristic -> characteristic.setValue(bluetoothGattCharacteristic.getValue())) .flatMap(ignored -> Observable.just(bluetoothGattCharacteristic)); } @Override public Observable<byte[]> writeCharacteristic(@NonNull BluetoothGattCharacteristic bluetoothGattCharacteristic, @NonNull byte[] data) { return Observable.just(data); } @Override public Observable<byte[]> writeCharacteristic(@NonNull UUID characteristicUuid, @NonNull byte[] data) { return getCharacteristic(characteristicUuid) .map(characteristic -> characteristic.setValue(data)) .flatMap(ignored -> Observable.just(data)); } @Override public Observable<byte[]> writeDescriptor(UUID serviceUuid, UUID characteristicUuid, UUID descriptorUuid, byte[] data) { return discoverServices() .flatMap(rxBleDeviceServices -> rxBleDeviceServices.getDescriptor(serviceUuid, characteristicUuid, descriptorUuid)) .map(bluetoothGattDescriptor -> bluetoothGattDescriptor.setValue(data)).flatMap(ignored -> Observable.just(data)); } @Override public Observable<byte[]> writeDescriptor(BluetoothGattDescriptor descriptor, byte[] data) { return Observable.just(data); } private Observable<Observable<byte[]>> createCharacteristicNotificationObservable(UUID characteristicUuid, boolean isIndication) { return getClientConfigurationDescriptor(characteristicUuid) .flatMap(bluetoothGattDescriptor -> setupCharacteristicNotification(bluetoothGattDescriptor, true, isIndication)) .flatMap(ObservableUtil::justOnNext) .flatMap(bluetoothGattDescriptorPair -> { if (!characteristicNotificationSources.containsKey(characteristicUuid)) { return Observable.error(new IllegalStateException("Lack of notification source for given characteristic")); } return Observable.just(characteristicNotificationSources.get(characteristicUuid)); }); } private void dismissCharacteristicNotification(UUID characteristicUuid, boolean isIndication) { notificationObservableMap.remove(characteristicUuid); getClientConfigurationDescriptor(characteristicUuid) .flatMap(descriptor -> setupCharacteristicNotification(descriptor, false, isIndication)) .subscribe( ignored -> { }, ignored -> { }); } @NonNull private Observable<BluetoothGattDescriptor> getClientConfigurationDescriptor(UUID characteristicUuid) { return getCharacteristic(characteristicUuid) .map(bluetoothGattCharacteristic -> { BluetoothGattDescriptor bluetoothGattDescriptor = bluetoothGattCharacteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_UUID); if (bluetoothGattDescriptor == null) { //adding notification descriptor if not present bluetoothGattDescriptor = new BluetoothGattDescriptor(CLIENT_CHARACTERISTIC_CONFIG_UUID, 0); bluetoothGattCharacteristic.addDescriptor(bluetoothGattDescriptor); } return bluetoothGattDescriptor; }); } @NonNull private Observable<byte[]> observeOnCharacteristicChangeCallbacks(UUID characteristicUuid) { return characteristicNotificationSources.get(characteristicUuid); } private void setCharacteristicNotification(UUID notificationCharacteristicUUID, boolean enable) { writeCharacteristic(notificationCharacteristicUUID, new byte[]{(byte) (enable ? 1 : 0)}).subscribe(); } @NonNull private Observable<byte[]> setupCharacteristicNotification( BluetoothGattDescriptor bluetoothGattDescriptor, boolean enabled, boolean isIndication ) { BluetoothGattCharacteristic bluetoothGattCharacteristic = bluetoothGattDescriptor.getCharacteristic(); setCharacteristicNotification(bluetoothGattCharacteristic.getUuid(), enabled); final byte[] enableValue = isIndication ? ENABLE_INDICATION_VALUE : ENABLE_NOTIFICATION_VALUE; return writeDescriptor(bluetoothGattDescriptor, enabled ? enableValue : DISABLE_NOTIFICATION_VALUE); } }
package dpm.lejos.project; import lejos.nxt.comm.RConsole; import java.util.Arrays; /** * Corrects the position reported by the odometer * based on readings from the light sensors * * @author David Lavoie-Boutin * @version v1.3 */ public class OdometryCorrection extends Thread{ private Odometer odo; private Robot robot; private Navigation navigation; private double [] last; private double[] now; private enum Side {LEFT, RIGHT} /** * constructor * @param odo odometer reference * @param robot robot reference * @param navigation reference to the navigation object */ public OdometryCorrection(Odometer odo, Robot robot, Navigation navigation){ this.odo = odo; this.robot = robot; this.navigation = navigation; } /** * get the angle offset form the line perpendicular to the black lines * @param side which sensor crossed the line first * @return the angle offset */ public double calculate(Side side){ double xDist = now[0] - last[0]; double yDist = now[1] - last[1]; double position = Math.sqrt(xDist * xDist +yDist * yDist); switch (side) { case LEFT: return (-Math.atan2(position, Robot.lsDistance)); case RIGHT: return (Math.atan2(position, Robot.lsDistance)); default: return -1; } } /** * compute the global heading based on the measured angle * @param theta the angle offset from the the black line * @return the global heading */ public double getNewTheta(double theta){ double oldTheta = odo.getThetaInDegrees(); double newTheta = 0; if (oldTheta >= -45 && oldTheta <= 45) newTheta = theta; else if (oldTheta >= 45 && oldTheta <= 135) newTheta = Math.PI/2.0 + theta; else if (oldTheta >= -135 && oldTheta <= -45) newTheta = - Math.PI/2.0 + theta; else if (oldTheta >= 135 || oldTheta <= -135) { newTheta = Math.PI + theta; if (newTheta > Math.PI) { newTheta -= 2 * Math.PI; } } return newTheta; } /** * method to stop the motors forcing navigation to recompute the motion */ private void stopMotors(){ robot.motorLeft.stop(); robot.motorRight.stop(); } /** * main runnable method * * this method compares the status of the two light * sensors and computed the current angle based on * the measured time difference between two lines detected * * it then adjusts the odometer values to match those measured */ public void run(){ double newTheta; while(true) { if (navigation.isMovingForward()) { //Right sensor passes first if (odo.isRightLine()) { RConsole.println("--\nCorrecting Odometry\tRight sensor first\n--"); last = odo.getPosition(); RConsole.println(Arrays.toString(last)); //Wait for left Sensor while (true) { if (odo.isLeftLine()) { now = odo.getPosition(); RConsole.println(Arrays.toString(now)); double intermediateTheta = calculate(Side.RIGHT); newTheta = getNewTheta(intermediateTheta); RConsole.println("New Theta: " + String.valueOf(Math.toDegrees(newTheta))); sleep(20); odo.setTheta(newTheta); while (odo.isLeftLine()) { sleep(20); } if (Math.abs(now[2] - newTheta) > Math.toRadians(Robot.CORRECTION_THRESHOLD)) { stopMotors(); } last = now = null; break; } } } //Left Sensor passes first if (odo.isLeftLine()) { RConsole.println("--\nCorrecting Odometry\tLeft sensor first\n--"); last = odo.getPosition(); RConsole.println(Arrays.toString(last)); //Wait for right Sensor while (true) { if (odo.isRightLine()) { now = odo.getPosition(); RConsole.println(Arrays.toString(now)); newTheta = calculate(Side.LEFT); RConsole.println("Computed Theta: " + String.valueOf(Math.toDegrees(newTheta))); newTheta = getNewTheta(newTheta); RConsole.println("New Theta: " + String.valueOf(Math.toDegrees(newTheta))); sleep(20); while (odo.isRightLine()) { sleep(20); } odo.setTheta(newTheta); if (Math.abs(now[2] - newTheta) > Math.toRadians(Robot.CORRECTION_THRESHOLD)) { stopMotors(); RConsole.println("Stop Motors, closeEnough should do the rest"); } last = now = null; break; } } } sleep(10); } else { sleep(1000); } } } /** * set the navigation object used to determine * when to enable odometry correction * * needed to avoid circular dependencies in the constructors * * @param navigation reference to the navigation class */ public void setNavigation(Navigation navigation){ this.navigation = navigation; } private void sleep(int time){ try { Thread.sleep(time); } catch (InterruptedException e) { e.printStackTrace(); } } }
package org.eclipse.birt.report.model.simpleapi; import java.io.IOException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map.Entry; import org.eclipse.birt.core.script.JavascriptEvalUtil; import org.eclipse.birt.report.model.api.ReportDesignHandle; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.model.api.core.IModuleModel; import org.eclipse.birt.report.model.api.simpleapi.IAction; import org.eclipse.birt.report.model.api.simpleapi.IDataBinding; import org.eclipse.birt.report.model.api.simpleapi.IDataItem; import org.eclipse.birt.report.model.api.simpleapi.IDataSet; import org.eclipse.birt.report.model.api.simpleapi.IDataSource; import org.eclipse.birt.report.model.api.simpleapi.IDesignElement; import org.eclipse.birt.report.model.api.simpleapi.IDynamicText; import org.eclipse.birt.report.model.api.simpleapi.IFilterCondition; import org.eclipse.birt.report.model.api.simpleapi.IGrid; import org.eclipse.birt.report.model.api.simpleapi.IHideRule; import org.eclipse.birt.report.model.api.simpleapi.IHighlightRule; import org.eclipse.birt.report.model.api.simpleapi.IImage; import org.eclipse.birt.report.model.api.simpleapi.ILabel; import org.eclipse.birt.report.model.api.simpleapi.IList; import org.eclipse.birt.report.model.api.simpleapi.IMasterPage; import org.eclipse.birt.report.model.api.simpleapi.IReportDesign; import org.eclipse.birt.report.model.api.simpleapi.IReportElement; import org.eclipse.birt.report.model.api.simpleapi.ISortCondition; import org.eclipse.birt.report.model.api.simpleapi.IStyle; import org.eclipse.birt.report.model.api.simpleapi.ITable; import org.eclipse.birt.report.model.api.simpleapi.ITextItem; import org.eclipse.birt.report.model.elements.interfaces.IDesignElementModel; import org.mozilla.javascript.BaseFunction; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextFactory; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject; import org.mozilla.javascript.WrappedException; /** * ReportDesign */ public class ReportDesign extends ScriptableObject implements IReportDesign { private static final long serialVersionUID = 5768246404361271845L; /** * The class name in JavaScript. */ public static final String CLASS_NAME = "ReportDesign"; //$NON-NLS-1$ final private InternalReportDesign report; /** * Constructor. * * @param report */ public ReportDesign( ReportDesignHandle report ) { this.report = new InternalReportDesign( report ); initFunctions( ); } /** * Gets master page script instance. * * @param name * @return master page script instance */ public IMasterPage getMasterPage( String name ) { return report.getMasterPage( name ); } public IDataSet getDataSet( String name ) { return report.getDataSet( name ); } public IDataSource getDataSource( String name ) { return report.getDataSource( name ); } public IReportElement getReportElement( String name ) { return report.getReportElement( name ); } /* * (non-Javadoc) * * @seeorg.eclipse.birt.report.model.api.simpleapi.IReportDesign# * getReportElementByID(long) */ public IReportElement getReportElementByID( long id ) { return report.getReportElementByID( id ); } public IDataItem getDataItem( String name ) { return report.getDataItem( name ); } public IGrid getGrid( String name ) { return report.getGrid( name ); } public IImage getImage( String name ) { return report.getImage( name ); } public ILabel getLabel( String name ) { return report.getLabel( name ); } public IList getList( String name ) { return report.getList( name ); } public ITable getTable( String name ) { return report.getTable( name ); } public IDynamicText getDynamicText( String name ) { return report.getDynamicText( name ); } public ITextItem getTextItem( String name ) { return report.getTextItem( name ); } public void setDisplayNameKey( String displayNameKey ) throws SemanticException { report.setProperty( IDesignElementModel.DISPLAY_NAME_ID_PROP, displayNameKey ); } public String getDisplayNameKey( ) { return report.getDisplayNameKey( ); } public void setDisplayName( String displayName ) throws SemanticException { report.setProperty( IDesignElementModel.DISPLAY_NAME_PROP, displayName ); } public String getDisplayName( ) { return report.getDisplayName( ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.model.api.simpleapi.IReportDesign#save() */ public void save( ) throws IOException { report.save( ); } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.api.simpleapi.IReportDesign#saveAs(java * .lang.String) */ public void saveAs( String newName ) throws IOException { report.saveAs( newName ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.model.api.simpleapi.IReportDesign#getTheme() */ public String getTheme( ) { return report.getTheme( ); } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.api.simpleapi.IReportDesign#setTheme(java * .lang.String) */ public void setTheme( String theme ) throws SemanticException { report.setProperty( IModuleModel.THEME_PROP, theme ); } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.api.simpleapi.IDesignElement#getParent() */ public IDesignElement getParent( ) { return report.getParent( ); } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.api.simpleapi.IDesignElement#getNamedExpression * (java.lang.String) */ public String getNamedExpression( String name ) { return report.getNamedExpression( name ); } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.api.simpleapi.IDesignElement#getQualifiedName * () */ public String getQualifiedName( ) { return report.getQualifiedName( ); } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.api.simpleapi.IDesignElement#getReport() */ public IReportDesign getReport( ) { return report; } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.api.simpleapi.IDesignElement#getStyle() */ public IStyle getStyle( ) { return report.getStyle( ); } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.api.simpleapi.IDesignElement#getUserProperty * (java.lang.String) */ public Object getUserProperty( String name ) { return report.getUserProperty( name ); } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.api.simpleapi.IDesignElement#setNamedExpression * (java.lang.String, java.lang.String) */ public void setNamedExpression( String name, String exp ) throws SemanticException { report.setNamedExpression( name, exp ); } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.api.simpleapi.IDesignElement#setUserProperty * (java.lang.String, java.lang.Object, java.lang.String) */ public void setUserProperty( String name, Object value, String type ) throws SemanticException { report.setUserProperty( name, value, type ); } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.api.simpleapi.IDesignElement#setUserProperty * (java.lang.String, java.lang.String) */ public void setUserProperty( String name, String value ) throws SemanticException { report.setUserProperty( name, value ); } /* * (non-Javadoc) * * @see org.mozilla.javascript.ScriptableObject#getClassName() */ public String getClassName( ) { return CLASS_NAME; } private void initFunctions( ) { Method[] tmpMethods = this.getClass( ).getDeclaredMethods( ); HashMap<String, Method> methods = new LinkedHashMap<String, Method>( ); for ( int i = 0; i < tmpMethods.length; i++ ) { Method tmpMethod = tmpMethods[i]; String methodName = tmpMethod.getName( ); // must handle special case with long parameter or polymiorphism if ( "getReportElementByID".equals( methodName ) //$NON-NLS-1$ || "setUserProperty".equals( methodName ) ) //$NON-NLS-1$ continue; if ( ( tmpMethod.getModifiers( ) & Modifier.PUBLIC ) != 0 ) methods.put( methodName, tmpMethod ); } ContextFactory.getGlobal( ).enterContext( ); try { for ( final Entry<String, Method> entry : methods.entrySet( ) ) { this.defineProperty( entry.getKey( ), new BaseFunction( ) { public Object call( Context cx, Scriptable scope, Scriptable thisObj, Object[] args ) { Object[] convertedArgs = JavascriptEvalUtil .convertToJavaObjects( args ); try { Method method = entry.getValue( ); return method.invoke( ReportDesign.this, convertedArgs ); } catch ( Exception e ) { throw new WrappedException( e ); } } }, DONTENUM ); } } finally { Context.exit( ); } this.defineProperty( "getReportElementByID", //$NON-NLS-1$ new Function_getReportElementByID( ), DONTENUM ); this.defineProperty( "setUserProperty", //$NON-NLS-1$ new Function_setUserProperty( ), DONTENUM ); } private class Function_getReportElementByID extends BaseFunction { private static final long serialVersionUID = 1L; public Object call( Context cx, Scriptable scope, Scriptable thisObj, java.lang.Object[] args ) { Object[] convertedArgs = JavascriptEvalUtil .convertToJavaObjects( args ); return report.getReportElementByID( (Integer) convertedArgs[0] ); } } private class Function_setUserProperty extends BaseFunction { private static final long serialVersionUID = 1L; public Object call( Context cx, Scriptable scope, Scriptable thisObj, java.lang.Object[] args ) { Object[] convertedArgs = JavascriptEvalUtil .convertToJavaObjects( args ); try { if ( convertedArgs.length == 2 ) report.setUserProperty( (String) convertedArgs[0], (String) convertedArgs[1] ); else if ( convertedArgs.length == 3 ) report.setUserProperty( (String) convertedArgs[0], convertedArgs[1], (String) convertedArgs[2] ); } catch ( SemanticException e ) { throw new WrappedException( e ); } return null; } } /* * (non-Javadoc) * * @seeorg.eclipse.birt.report.model.api.simpleapi.IDesignElement# * getUserPropertyExpression(java.lang.String) */ public Object getUserPropertyExpression( String name ) { return report.getUserPropertyExpression( name ); } /* * (non-Javadoc) * * @seeorg.eclipse.birt.report.model.api.simpleapi.IReportDesign# * createFilterCondition() */ public IFilterCondition createFilterCondition( ) { return report.createFilterCondition( ); } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.api.simpleapi.IReportDesign#createHideRule * () */ public IHideRule createHideRule( ) { return report.createHideRule( ); } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.api.simpleapi.IReportDesign#createHighLightRule * () */ public IHighlightRule createHighLightRule( ) { return report.createHighLightRule( ); } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.api.simpleapi.IReportDesign#createSortCondition * () */ public ISortCondition createSortCondition( ) { return report.createSortCondition( ); } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.api.simpleapi.IReportDesign#createAction() */ public IAction createAction( ) { return report.createAction( ); } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.api.simpleapi.IReportDesign#createDataBinding * () */ public IDataBinding createDataBinding( ) { return report.createDataBinding( ); } }
package com.humbughq.mobile; import java.sql.SQLException; import java.util.HashMap; import java.util.concurrent.Callable; import android.annotation.TargetApi; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.PorterDuff.Mode; import android.os.Build; import android.os.Bundle; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.SimpleCursorAdapter; import android.util.Log; import android.view.Gravity; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.TextView; import com.crashlytics.android.Crashlytics; import com.j256.ormlite.android.AndroidDatabaseResults; public class HumbugActivity extends FragmentActivity implements MessageListFragment.Listener { ZulipApp app; // Intent Extra constants public enum Flag { RESET_DATABASE, } boolean suspended = false; boolean logged_in = false; HumbugActivity that = this; // self-ref SharedPreferences settings; String client_id; private DrawerLayout drawerLayout; private ActionBarDrawerToggle drawerToggle; private Menu menu; public Person you; protected HashMap<String, Bitmap> gravatars = new HashMap<String, Bitmap>(); private AsyncGetEvents event_poll; MessageListFragment currentList; MessageListFragment narrowedList; MessageListFragment homeList; private SimpleCursorAdapter.ViewBinder streamBinder = new SimpleCursorAdapter.ViewBinder() { @Override public boolean setViewValue(View arg0, Cursor arg1, int arg2) { switch (arg0.getId()) { case R.id.name: TextView name = (TextView) arg0; name.setText(arg1.getString(arg2)); return true; case R.id.stream_dot: // Set the color of the (currently white) dot arg0.setVisibility(View.VISIBLE); arg0.getBackground().setColorFilter(arg1.getInt(arg2), Mode.MULTIPLY); return true; } return false; } }; protected RefreshableCursorAdapter streamsAdapter; protected RefreshableCursorAdapter peopleAdapter; /** Called when the activity is first created. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Build.HARDWARE.contains("goldfish")) { Log.i("hardware", "running in emulator"); } else { Crashlytics.start(this); } app = (ZulipApp) getApplicationContext(); settings = app.settings; processParams(); if (!app.isLoggedIn()) { openLogin(); return; } this.onPrepareOptionsMenu(menu); this.logged_in = true; setContentView(R.layout.main); drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.streams_open, R.string.streams_close) { /** Called when a drawer has settled in a completely closed state. */ public void onDrawerClosed(View view) { // pass } /** Called when a drawer has settled in a completely open state. */ public void onDrawerOpened(View drawerView) { // pass } }; // Set the drawer toggle as the DrawerListener drawerLayout.setDrawerListener(drawerToggle); ListView streamsDrawer = (ListView) findViewById(R.id.streams_drawer); ListView peopleDrawer = (ListView) findViewById(R.id.people_drawer); Callable<Cursor> streamsGenerator = new Callable<Cursor>() { @Override public Cursor call() throws Exception { return ((AndroidDatabaseResults) app.getDao(Stream.class) .queryBuilder().selectRaw("rowid _id", "*") .orderByRaw(Stream.NAME_FIELD + " COLLATE NOCASE") .queryRaw().closeableIterator().getRawResults()) .getRawCursor(); } }; Callable<Cursor> peopleGenerator = new Callable<Cursor>() { @Override public Cursor call() throws Exception { // TODO Auto-generated method stub return ((AndroidDatabaseResults) app.getDao(Person.class) .queryBuilder().selectRaw("rowid _id", "*") .orderByRaw(Person.NAME_FIELD + " COLLATE NOCASE") .where().eq(Person.ISBOT_FIELD, false).queryRaw() .closeableIterator().getRawResults()).getRawCursor(); } }; try { this.streamsAdapter = new RefreshableCursorAdapter( this.getApplicationContext(), R.layout.stream_tile, streamsGenerator.call(), streamsGenerator, new String[] { Stream.NAME_FIELD, Stream.COLOR_FIELD }, new int[] { R.id.name, R.id.stream_dot }, 0); streamsAdapter.setViewBinder(streamBinder); streamsDrawer.setAdapter(streamsAdapter); this.peopleAdapter = new RefreshableCursorAdapter( this.getApplicationContext(), R.layout.stream_tile, peopleGenerator.call(), peopleGenerator, new String[] { Person.NAME_FIELD }, new int[] { R.id.name }, 0); peopleDrawer.setAdapter(peopleAdapter); } catch (SQLException e) { throw new RuntimeException(e); } catch (Exception e) { ZLog.logException(e); } streamsDrawer.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO: is there a way to get the Stream from the adapter // without re-querying it? narrow(Stream.getById(app, (int) id)); } }); peopleDrawer.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { narrow_pm_with(Person.getById(app, (int) id)); } }); if (getActionBar() != null) { // the AB is unavailable when invoked from JUnit getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setHomeButtonEnabled(true); } homeList = MessageListFragment.newInstance(null); pushListFragment(homeList, false); } private void pushListFragment(MessageListFragment list, boolean back) { currentList = list; FragmentTransaction transaction = getSupportFragmentManager() .beginTransaction(); transaction.replace(R.id.list_fragment_container, list); if (back) { transaction.addToBackStack(null); } transaction.commit(); getSupportFragmentManager().executePendingTransactions(); } private void processParams() { Bundle params = getIntent().getExtras(); if (params == null) return; for (String unprocessedParam : params.keySet()) { Flag param; if (unprocessedParam.contains(getBaseContext().getPackageName())) { try { param = Flag.valueOf(unprocessedParam .substring(getBaseContext().getPackageName() .length() + 1)); } catch (IllegalArgumentException e) { Log.e("params", "Invalid app-specific intent specified.", e); continue; } } else { continue; } switch (param) { case RESET_DATABASE: Log.i("params", "Resetting the database..."); boolean result = app.resetDatabase(); Log.i("params", "Database deleted successfully."); this.finish(); break; } } } protected void narrow(final Stream stream) { doNarrow(new NarrowFilterStream(stream)); } protected void narrow_pm_with(final Person person) { doNarrow(new NarrowFilterPM(person)); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public void onListResume(MessageListFragment list) { currentList = list; NarrowFilter filter = list.filter; if (filter == null) { getActionBar().setTitle("Zulip"); getActionBar().setSubtitle(null); this.drawerToggle.setDrawerIndicatorEnabled(true); } else { String title = list.filter.getTitle(); if (title != null) { getActionBar().setTitle(title); } getActionBar().setSubtitle(list.filter.getSubtitle()); this.drawerToggle.setDrawerIndicatorEnabled(false); } this.drawerLayout.closeDrawers(); } protected void doNarrow(NarrowFilter filter) { narrowedList = MessageListFragment.newInstance(filter); // Push to the back stack if we are not already narrowed pushListFragment(narrowedList, currentList == homeList); narrowedList.onReadyToDisplay(true); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. drawerToggle.syncState(); } public boolean onPrepareOptionsMenu(Menu menu) { /* * We want to show a menu only when we're logged in, so this function is * called by both Android and our own app when we encounter state * changes where we might want to update the menu. */ if (menu == null) { // We were called by a function before the menu had been // initialised, so we should bail. return false; } this.menu = menu; menu.clear(); if (this.logged_in) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.options, menu); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Pass the event to ActionBarDrawerToggle, if it returns // true, then it has handled the app icon touch event if (drawerToggle.onOptionsItemSelected(item)) { // Close the right drawer if we opened the left one drawerLayout.closeDrawer(Gravity.RIGHT); return true; } // Handle item selection switch (item.getItemId()) { case android.R.id.home: getSupportFragmentManager().popBackStack(); break; case R.id.compose_stream: String stream = null; if (currentList.filter != null && currentList.filter.getComposeStream() != null) { stream = currentList.filter.getComposeStream().getName(); } openCompose(MessageType.STREAM_MESSAGE, stream, null, null); break; case R.id.compose_pm: String recipient = null; if (currentList.filter != null) { recipient = currentList.filter.getComposePMRecipient(); } openCompose(MessageType.PRIVATE_MESSAGE, null, null, recipient); break; case R.id.refresh: Log.w("menu", "Refreshed manually by user. We shouldn't need this."); onRefresh(); ((RefreshableCursorAdapter) ((ListView) findViewById(R.id.streams_drawer)) .getAdapter()).refresh(); break; case R.id.logout: logout(); break; case R.id.legal: openLegal(); break; default: return super.onOptionsItemSelected(item); } return true; } public void openCompose(MessageType type) { openCompose(type, null, null, null); } public void openCompose(Stream stream, String topic) { openCompose(MessageType.STREAM_MESSAGE, stream.getName(), topic, null); } public void openCompose(String pmRecipients) { openCompose(MessageType.PRIVATE_MESSAGE, null, null, pmRecipients); } public void openCompose(final MessageType type, String stream, String topic, String pmRecipients) { FragmentManager fm = getSupportFragmentManager(); ComposeDialog dialog = ComposeDialog.newInstance(type, stream, topic, pmRecipients); dialog.show(fm, "fragment_compose"); } /** * Log the user out of the app, clearing our cache of their credentials. */ private void logout() { this.logged_in = false; app.logOut(); this.openLogin(); } /** * Switch to the login view. */ protected void openLogin() { Intent i = new Intent(this, LoginActivity.class); startActivity(i); finish(); } protected void openLegal() { Intent i = new Intent(this, LegalActivity.class); startActivityForResult(i, 0); } public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // our display has changed, lets recalculate the spacer // this.size_bottom_spacer(); drawerToggle.onConfigurationChanged(newConfig); } protected void onPause() { super.onPause(); Log.i("status", "suspend"); this.suspended = true; if (event_poll != null) { event_poll.abort(); event_poll = null; } } protected void onResume() { super.onResume(); Log.i("status", "resume"); this.suspended = false; homeList.onActivityResume(); if (narrowedList != null) { narrowedList.onActivityResume(); } startRequests(); } protected void onRefresh() { super.onResume(); if (event_poll != null) { event_poll.abort(); event_poll = null; } app.clearConnectionState(); app.resetDatabase(); app.setEmail(app.you.getEmail()); startRequests(); } protected void startRequests() { Log.i("zulip", "Starting requests"); if (event_poll != null) { event_poll.abort(); } event_poll = new AsyncGetEvents(this); event_poll.start(); } public void onReadyToDisplay(boolean registered) { homeList.onReadyToDisplay(registered); if (narrowedList != null) { narrowedList.onReadyToDisplay(registered); } } public void onNewMessages(Message[] messages) { homeList.onNewMessages(messages); if (narrowedList != null) { narrowedList.onNewMessages(messages); } } }
package dr.app.beauti.options; import dr.evolution.datatype.DataType; import java.util.ArrayList; import java.util.List; /** * @author Alexei Drummond * @author Andrew Rambaut */ public class PartitionModel extends ModelOptions { public static final String[] GTR_RATE_NAMES = {"ac", "ag", "at", "cg", "gt"}; static final String[] GTR_TRANSITIONS = {"A-C", "A-G", "A-T", "C-G", "G-T"}; public PartitionModel(BeautiOptions options, DataPartition partition) { this(options, partition.getName(), partition.getAlignment().getDataType()); } /** * A copy constructor * * @param options the beauti options * @param name the name of the new model * @param source the source model */ public PartitionModel(BeautiOptions options, String name, PartitionModel source) { this(options, name, source.dataType); nucSubstitutionModel = source.nucSubstitutionModel; aaSubstitutionModel = source.aaSubstitutionModel; binarySubstitutionModel = source.binarySubstitutionModel; frequencyPolicy = source.frequencyPolicy; gammaHetero = source.gammaHetero; gammaCategories = source.gammaCategories; invarHetero = source.invarHetero; codonHeteroPattern = source.codonHeteroPattern; unlinkedSubstitutionModel = source.unlinkedSubstitutionModel; unlinkedHeterogeneityModel = source.unlinkedHeterogeneityModel; unlinkedFrequencyModel = source.unlinkedFrequencyModel; } public PartitionModel(BeautiOptions options, String name, DataType dataType) { this.options = options; this.name = name; this.dataType = dataType; double substWeights = 1.0; //Substitution model parameters createParameter("frequencies", "base frequencies", UNITY_SCALE, 0.25, 0.0, 1.0); createParameter("CP1.frequencies", "base frequencies for codon position 1", UNITY_SCALE, 0.25, 0.0, 1.0); createParameter("CP2.frequencies", "base frequencies for codon position 2", UNITY_SCALE, 0.25, 0.0, 1.0); createParameter("CP1+2.frequencies", "base frequencies for codon positions 1 & 2", UNITY_SCALE, 0.25, 0.0, 1.0); createParameter("CP3.frequencies", "base frequencies for codon position 3", UNITY_SCALE, 0.25, 0.0, 1.0); createScaleParameter("kappa", "HKY transition-transversion parameter", SUBSTITUTION_PARAMETER_SCALE, 1.0, 1.0E-8, Double.POSITIVE_INFINITY); createScaleParameter("CP1.kappa", "HKY transition-transversion parameter for codon position 1", SUBSTITUTION_PARAMETER_SCALE, 1.0, 1.0E-8, Double.POSITIVE_INFINITY); createScaleParameter("CP2.kappa", "HKY transition-transversion parameter for codon position 2", SUBSTITUTION_PARAMETER_SCALE, 1.0, 1.0E-8, Double.POSITIVE_INFINITY); createScaleParameter("CP1+2.kappa", "HKY transition-transversion parameter for codon positions 1 & 2", SUBSTITUTION_PARAMETER_SCALE, 1.0, 1.0E-8, Double.POSITIVE_INFINITY); createScaleParameter("CP3.kappa", "HKY transition-transversion parameter for codon position 3", SUBSTITUTION_PARAMETER_SCALE, 1.0, 1.0E-8, Double.POSITIVE_INFINITY); // createParameter("frequencies", "GTR base frequencies", UNITY_SCALE, 0.25, 0.0, 1.0); // createParameter("CP1.frequencies", "GTR base frequencies for codon position 1", UNITY_SCALE, 0.25, 0.0, 1.0); // createParameter("CP2.frequencies", "GTR base frequencies for codon position 2", UNITY_SCALE, 0.25, 0.0, 1.0); // createParameter("CP1+2.frequencies", "GTR base frequencies for codon positions 1 & 2", UNITY_SCALE, 0.25, 0.0, 1.0); // createParameter("CP3.frequencies", "GTR base frequencies for codon position 3", UNITY_SCALE, 0.25, 0.0, 1.0); // create the relative rate parameters for the GTR rate matrix for (int j = 0; j < 5; j++) { createScaleParameter(GTR_RATE_NAMES[j], "GTR " + GTR_TRANSITIONS[j] + " substitution parameter", SUBSTITUTION_PARAMETER_SCALE, 1.0, 1.0E-8, Double.POSITIVE_INFINITY); for (int i = 1; i <= 3; i++) { createScaleParameter( "CP" + i + "." + GTR_RATE_NAMES[j], "GTR " + GTR_TRANSITIONS[j] + " substitution parameter for codon position " + i, SUBSTITUTION_PARAMETER_SCALE, 1.0, 1.0E-8, Double.POSITIVE_INFINITY); } createScaleParameter("CP1+2." + GTR_RATE_NAMES[j], "GTR " + GTR_TRANSITIONS[j] + " substitution parameter for codon positions 1 & 2", SUBSTITUTION_PARAMETER_SCALE, 1.0, 1.0E-8, Double.POSITIVE_INFINITY); } // createParameter("frequencies", "Binary Simple frequencies", UNITY_SCALE, 0.5, 0.0, 1.0); // createParameter("frequencies", "Binary Covarion frequencies of the visible states", UNITY_SCALE, 0.5, 0.0, 1.0); createParameter("hfrequencies", "Binary Covarion frequencies of the hidden rates", UNITY_SCALE, 0.5, 0.0, 1.0); createParameter("bcov.alpha", "Binary Covarion rate of evolution in slow mode", UNITY_SCALE, 0.5, 0.0, 1.0); createParameter("bcov.s", "Binary Covarion rate of flipping between slow and fast modes", SUBSTITUTION_PARAMETER_SCALE, 0.5, 0.0, 100.0); createParameter("alpha", "gamma shape parameter", SUBSTITUTION_PARAMETER_SCALE, 0.5, 0.0, 1000.0); createParameter("CP1.alpha", "gamma shape parameter for codon position 1", SUBSTITUTION_PARAMETER_SCALE, 0.5, 0.0, 1000.0); createParameter("CP2.alpha", "gamma shape parameter for codon position 2", SUBSTITUTION_PARAMETER_SCALE, 0.5, 0.0, 1000.0); createParameter("CP1+2.alpha", "gamma shape parameter for codon positions 1 & 2", SUBSTITUTION_PARAMETER_SCALE, 0.5, 0.0, 1000.0); createParameter("CP3.alpha", "gamma shape parameter for codon position 3", SUBSTITUTION_PARAMETER_SCALE, 0.5, 0.0, 1000.0); createParameter("pInv", "proportion of invariant sites parameter", NONE, 0.5, 0.0, 1.0); createParameter("CP1.pInv", "proportion of invariant sites parameter for codon position 1", NONE, 0.5, 0.0, 1.0); createParameter("CP2.pInv", "proportion of invariant sites parameter for codon position 2", NONE, 0.5, 0.0, 1.0); createParameter("CP1+2.pInv", "proportion of invariant sites parameter for codon positions 1 & 2", NONE, 0.5, 0.0, 1.0); createParameter("CP3.pInv", "proportion of invariant sites parameter for codon position 3", NONE, 0.5, 0.0, 1.0); createParameter("mu", "relative rate parameter", SUBSTITUTION_PARAMETER_SCALE, 1.0, 0.0, Double.POSITIVE_INFINITY); createParameter("CP1.mu", "relative rate parameter for codon position 1", SUBSTITUTION_PARAMETER_SCALE, 1.0, 0.0, Double.POSITIVE_INFINITY); createParameter("CP2.mu", "relative rate parameter for codon position 2", SUBSTITUTION_PARAMETER_SCALE, 1.0, 0.0, Double.POSITIVE_INFINITY); createParameter("CP1+2.mu", "relative rate parameter for codon positions 1 & 2", SUBSTITUTION_PARAMETER_SCALE, 1.0, 0.0, Double.POSITIVE_INFINITY); createParameter("CP3.mu", "relative rate parameter for codon position 3", SUBSTITUTION_PARAMETER_SCALE, 1.0, 0.0, Double.POSITIVE_INFINITY); createScaleOperator("kappa", substWeights); createScaleOperator("CP1.kappa", substWeights); createScaleOperator("CP2.kappa", substWeights); createScaleOperator("CP1+2.kappa", substWeights); createScaleOperator("CP3.kappa", substWeights); createOperator("frequencies", OperatorType.DELTA_EXCHANGE, 0.01, substWeights); createOperator("CP1.frequencies", OperatorType.DELTA_EXCHANGE, 0.01, substWeights); createOperator("CP2.frequencies", OperatorType.DELTA_EXCHANGE, 0.01, substWeights); createOperator("CP1+2.frequencies", OperatorType.DELTA_EXCHANGE, 0.01, substWeights); createOperator("CP3.frequencies", OperatorType.DELTA_EXCHANGE, 0.01, substWeights); for (String rateName : GTR_RATE_NAMES) { createScaleOperator(rateName, substWeights); for (int j = 1; j <= 3; j++) { createScaleOperator("CP" + j + "." + rateName, substWeights); } createScaleOperator("CP1+2." + rateName, substWeights); } createScaleOperator("alpha", substWeights); for (int i = 1; i <= 3; i++) { createScaleOperator("CP" + i + ".alpha", substWeights); } createScaleOperator("CP1+2.alpha", substWeights); createScaleOperator("pInv", substWeights); for (int i = 1; i <= 3; i++) { createScaleOperator("CP" + i + ".pInv", substWeights); } createScaleOperator("CP1+2.pInv", substWeights); createScaleOperator("bcov.alpha", substWeights); createScaleOperator("bcov.s", substWeights); //createOperator("frequencies", OperatorType.DELTA_EXCHANGE, 0.01, substWeights); createOperator("hfrequencies", OperatorType.DELTA_EXCHANGE, 0.01, substWeights); } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Operator> getOperators() { List<Operator> operators = new ArrayList<Operator>(); switch (dataType.getType()) { case DataType.NUCLEOTIDES: if (getCodonPartitionCount() > 1 && unlinkedSubstitutionModel) { if (codonHeteroPattern.equals("123")) { switch (nucSubstitutionModel) { case HKY: operators.add(getOperator("CP1.kappa")); operators.add(getOperator("CP2.kappa")); operators.add(getOperator("CP3.kappa")); break; case GTR: for (int i = 1; i <= 3; i++) { for (String rateName : GTR_RATE_NAMES) { operators.add(getOperator("CP" + i + "." + rateName)); } } break; default: throw new IllegalArgumentException("Unknown nucleotides substitution model"); } if (frequencyPolicy == FrequencyPolicy.ESTIMATED) { if (getCodonPartitionCount() > 1 && unlinkedSubstitutionModel) { operators.add(getOperator("CP1.frequencies")); operators.add(getOperator("CP2.frequencies")); operators.add(getOperator("CP3.frequencies")); } else { operators.add(getOperator("frequencies")); } } } else if (codonHeteroPattern.equals("112")) { switch (nucSubstitutionModel) { case HKY: operators.add(getOperator("CP1+2.kappa")); operators.add(getOperator("CP3.kappa")); break; case GTR: for (String rateName : GTR_RATE_NAMES) { operators.add(getOperator("CP1+2." + rateName)); } for (String rateName : GTR_RATE_NAMES) { operators.add(getOperator("CP3." + rateName)); } break; default: throw new IllegalArgumentException("Unknown nucleotides substitution model"); } if (frequencyPolicy == FrequencyPolicy.ESTIMATED) { if (getCodonPartitionCount() > 1 && unlinkedSubstitutionModel) { operators.add(getOperator("CP1+2.frequencies")); operators.add(getOperator("CP3.frequencies")); } else { operators.add(getOperator("frequencies")); } } } else { throw new IllegalArgumentException("codonHeteroPattern must be one of '111', '112' or '123'"); } } else { // no codon partitioning switch (nucSubstitutionModel) { case HKY: operators.add(getOperator("kappa")); break; case GTR: for (String rateName : GTR_RATE_NAMES) { operators.add(getOperator(rateName)); } break; default: throw new IllegalArgumentException("Unknown nucleotides substitution model"); } if (frequencyPolicy == FrequencyPolicy.ESTIMATED) { operators.add(getOperator("frequencies")); } } break; case DataType.AMINO_ACIDS: break; case DataType.TWO_STATES: case DataType.COVARION: switch (binarySubstitutionModel) { case BIN_SIMPLE: break; case BIN_COVARION: operators.add(getOperator("bcov.alpha")); operators.add(getOperator("bcov.s")); operators.add(getOperator("bcov.frequencies")); operators.add(getOperator("bcov.hfrequencies")); break; default: throw new IllegalArgumentException("Unknown binary substitution model"); } break; default: throw new IllegalArgumentException("Unknown data type"); } // if gamma do shape move if (gammaHetero) { if (getCodonPartitionCount() > 1 && unlinkedHeterogeneityModel) { if (codonHeteroPattern.equals("123")) { operators.add(getOperator("CP1.alpha")); operators.add(getOperator("CP2.alpha")); operators.add(getOperator("CP3.alpha")); } else if (codonHeteroPattern.equals("112")) { operators.add(getOperator("CP1+2.alpha")); operators.add(getOperator("CP3.alpha")); } else { throw new IllegalArgumentException("codonHeteroPattern must be one of '111', '112' or '123'"); } } else { operators.add(getOperator("alpha")); } } // if pinv do pinv move if (invarHetero) { if (getCodonPartitionCount() > 1 && unlinkedHeterogeneityModel) { if (codonHeteroPattern.equals("123")) { operators.add(getOperator("CP1.pInv")); operators.add(getOperator("CP2.alpha")); operators.add(getOperator("CP3.pInv")); } else if (codonHeteroPattern.equals("112")) { operators.add(getOperator("CP1+2.pInv")); operators.add(getOperator("CP3.pInv")); } else { throw new IllegalArgumentException("codonHeteroPattern must be one of '111', '112' or '123'"); } } else { operators.add(getOperator("pInv")); } } return operators; } /** * @param includeRelativeRates true if relative rate parameters should be added * @return a list of parameters that are required */ List<Parameter> getParameters(boolean includeRelativeRates) { List<Parameter> params = new ArrayList<Parameter>(); switch (dataType.getType()) { case DataType.NUCLEOTIDES: if (getCodonPartitionCount() > 1 && unlinkedSubstitutionModel) { if (codonHeteroPattern.equals("123")) { switch (nucSubstitutionModel) { case HKY: params.add(getParameter("CP1.kappa")); params.add(getParameter("CP2.kappa")); params.add(getParameter("CP3.kappa")); break; case GTR: for (int i = 1; i <= getCodonPartitionCount(); i++) { for (String rateName : GTR_RATE_NAMES) { params.add(getParameter("CP" + i + "." + rateName)); } } break; default: throw new IllegalArgumentException("Unknown nucleotides substitution model"); } params.add(getParameter("CP1.mu")); params.add(getParameter("CP2.mu")); params.add(getParameter("CP3.mu")); } else if (codonHeteroPattern.equals("112")) { switch (nucSubstitutionModel) { case HKY: params.add(getParameter("CP1+2.kappa")); params.add(getParameter("CP3.kappa")); break; case GTR: for (String rateName : GTR_RATE_NAMES) { params.add(getParameter("CP1+2." + rateName)); } for (String rateName : GTR_RATE_NAMES) { params.add(getParameter("CP3." + rateName)); } break; default: throw new IllegalArgumentException("Unknown nucleotides substitution model"); } params.add(getParameter("CP1+2.mu")); params.add(getParameter("CP3.mu")); } else { throw new IllegalArgumentException("codonHeteroPattern must be one of '111', '112' or '123'"); } } else { // no codon partitioning switch (nucSubstitutionModel) { case HKY: params.add(getParameter("kappa")); break; case GTR: for (String rateName : GTR_RATE_NAMES) { params.add(getParameter(rateName)); } break; default: throw new IllegalArgumentException("Unknown nucleotides substitution model"); } if (includeRelativeRates) { params.add(getParameter("mu")); } } break; case DataType.AMINO_ACIDS: if (includeRelativeRates) { params.add(getParameter("mu")); } break; case DataType.TWO_STATES: case DataType.COVARION: switch (binarySubstitutionModel) { case BIN_SIMPLE: break; case BIN_COVARION: params.add(getParameter("bcov.alpha")); params.add(getParameter("bcov.s")); break; default: throw new IllegalArgumentException("Unknown binary substitution model"); } if (includeRelativeRates) { params.add(getParameter("mu")); } break; default: throw new IllegalArgumentException("Unknown data type"); } // if gamma do shape move if (gammaHetero) { if (getCodonPartitionCount() > 1 && unlinkedHeterogeneityModel) { if (codonHeteroPattern.equals("123")) { params.add(getParameter("CP1.alpha")); params.add(getParameter("CP2.alpha")); params.add(getParameter("CP3.alpha")); } else if (codonHeteroPattern.equals("112")) { params.add(getParameter("CP1+2.alpha")); params.add(getParameter("CP3.alpha")); } else { throw new IllegalArgumentException("codonHeteroPattern must be one of '111', '112' or '123'"); } } else { params.add(getParameter("alpha")); } } // if pinv do pinv move if (invarHetero) { if (getCodonPartitionCount() > 1 && unlinkedHeterogeneityModel) { if (codonHeteroPattern.equals("123")) { params.add(getParameter("CP1.pInv")); params.add(getParameter("CP2.pInv")); params.add(getParameter("CP3.pInv")); } else if (codonHeteroPattern.equals("112")) { params.add(getParameter("CP1+2.pInv")); params.add(getParameter("CP3.pInv")); } else { throw new IllegalArgumentException("codonHeteroPattern must be one of '111', '112' or '123'"); } } else { params.add(getParameter("pInv")); } } if (frequencyPolicy == FrequencyPolicy.ESTIMATED) { if (getCodonPartitionCount() > 1 && unlinkedHeterogeneityModel) { if (codonHeteroPattern.equals("123")) { params.add(getParameter("CP1.frequencies")); params.add(getParameter("CP2.frequencies")); params.add(getParameter("CP3.frequencies")); } else if (codonHeteroPattern.equals("112")) { params.add(getParameter("CP1+2.frequencies")); params.add(getParameter("CP3.frequencies")); } else { throw new IllegalArgumentException("codonHeteroPattern must be one of '111', '112' or '123'"); } } else { params.add(getParameter("frequencies")); } } return params; } public Parameter getParameter(String name) { if (name.startsWith(getName())) { name = name.substring(getName().length() + 1); } Parameter parameter = parameters.get(name); if (parameter == null) { throw new IllegalArgumentException("Parameter with name, " + name + ", is unknown"); } parameter.setPrefix(getPrefix()); return parameter; } Operator getOperator(String name) { Operator operator = operators.get(name); if (operator == null) throw new IllegalArgumentException("Operator with name, " + name + ", is unknown"); operator.setPrefix(getName()); return operator; } public int getCodonPartitionCount() { if (codonHeteroPattern == null || codonHeteroPattern.equals("111")) { return 1; } if (codonHeteroPattern.equals("123")) { return 3; } if (codonHeteroPattern.equals("112")) { return 2; } throw new IllegalArgumentException("codonHeteroPattern must be one of '111', '112' or '123'"); } public void addWeightsForPartition(DataPartition partition, int[] weights, int offset) { int n = partition.getSiteCount(); int codonCount = n / 3; int remainder = n % 3; if (codonHeteroPattern == null || codonHeteroPattern.equals("111")) { weights[offset] += n; return; } if (codonHeteroPattern.equals("123")) { weights[offset] += codonCount + (remainder > 0 ? 1 : 0); weights[offset + 1] += codonCount + (remainder > 1 ? 1 : 0); weights[offset + 2] += codonCount; return; } if (codonHeteroPattern.equals("112")) { weights[offset] += codonCount * 2 + remainder; // positions 1 + 2 weights[offset + 1] += codonCount; // position 3 return; } throw new IllegalArgumentException("codonHeteroPattern must be one of '111', '112' or '123'"); } public String toString() { return getName(); } public NucModelType getNucSubstitutionModel() { return nucSubstitutionModel; } public void setNucSubstitutionModel(NucModelType nucSubstitutionModel) { this.nucSubstitutionModel = nucSubstitutionModel; } public AminoAcidModelType getAaSubstitutionModel() { return aaSubstitutionModel; } public void setAaSubstitutionModel(AminoAcidModelType aaSubstitutionModel) { this.aaSubstitutionModel = aaSubstitutionModel; } public int getBinarySubstitutionModel() { return binarySubstitutionModel; } public void setBinarySubstitutionModel(int binarySubstitutionModel) { this.binarySubstitutionModel = binarySubstitutionModel; } public FrequencyPolicy getFrequencyPolicy() { return frequencyPolicy; } public void setFrequencyPolicy(FrequencyPolicy frequencyPolicy) { this.frequencyPolicy = frequencyPolicy; } public boolean isGammaHetero() { return gammaHetero; } public void setGammaHetero(boolean gammaHetero) { this.gammaHetero = gammaHetero; } public int getGammaCategories() { return gammaCategories; } public void setGammaCategories(int gammaCategories) { this.gammaCategories = gammaCategories; } public boolean isInvarHetero() { return invarHetero; } public void setInvarHetero(boolean invarHetero) { this.invarHetero = invarHetero; } public String getCodonHeteroPattern() { return codonHeteroPattern; } public void setCodonHeteroPattern(String codonHeteroPattern) { this.codonHeteroPattern = codonHeteroPattern; } /** * @return true if the rate matrix parameters are unlinked across codon positions */ public boolean isUnlinkedSubstitutionModel() { return unlinkedSubstitutionModel; } public void setUnlinkedSubstitutionModel(boolean unlinkedSubstitutionModel) { this.unlinkedSubstitutionModel = unlinkedSubstitutionModel; } public boolean isUnlinkedHeterogeneityModel() { return unlinkedHeterogeneityModel; } public void setUnlinkedHeterogeneityModel(boolean unlinkedHeterogeneityModel) { this.unlinkedHeterogeneityModel = unlinkedHeterogeneityModel; } public boolean isUnlinkedFrequencyModel() { return unlinkedFrequencyModel; } public void setUnlinkedFrequencyModel(boolean unlinkedFrequencyModel) { this.unlinkedFrequencyModel = unlinkedFrequencyModel; } public DataType getDataType() { return dataType; } public void setDataType(DataType dataType) { this.dataType = dataType; } public boolean isDolloModel() { return dolloModel; } public void setDolloModel(boolean dolloModel) { this.dolloModel = dolloModel; } public String getPrefix() { String prefix = ""; if (options.getActiveModels().size() > 1) { // There is more than one active partition model prefix += getName() + "."; } return prefix; } public String getPrefix(int codonPartitionNumber) { String prefix = ""; if (options.getActiveModels().size() > 1) { // There is more than one active partition model prefix += getName() + "."; } if (getCodonPartitionCount() > 1 && codonPartitionNumber > 0) { if (getCodonHeteroPattern().equals("123")) { prefix += "CP" + codonPartitionNumber + "."; } else if (getCodonHeteroPattern().equals("112")) { if (codonPartitionNumber == 1) { prefix += "CP1+2."; } else { prefix += "CP3."; } } else { throw new IllegalArgumentException("unsupported codon hetero pattern"); } } return prefix; } // Instance variables private final BeautiOptions options; private NucModelType nucSubstitutionModel = NucModelType.HKY; private AminoAcidModelType aaSubstitutionModel = AminoAcidModelType.BLOSUM_62; private int binarySubstitutionModel = BeautiOptions.BIN_SIMPLE; private FrequencyPolicy frequencyPolicy = FrequencyPolicy.ESTIMATED; private boolean gammaHetero = false; private int gammaCategories = 4; private boolean invarHetero = false; private String codonHeteroPattern = null; private boolean unlinkedSubstitutionModel = false; private boolean unlinkedHeterogeneityModel = false; private boolean unlinkedFrequencyModel = false; private boolean dolloModel = false; public DataType dataType; public String name; }
package com.humbughq.mobile; import java.util.List; import com.humbughq.mobile.R; import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.TextView; /** * Adapter which stores Messages in a view, and generates LinearLayouts for * consumption by the ListView which displays the view. */ public class MessageAdapter extends ArrayAdapter<Message> { public MessageAdapter(Context context, List<Message> objects) { super(context, 0, objects); } /** * Creates a new (empty) message tile with all the relevant fillable Views * tagged. * * @return the constructed message tile */ private LinearLayout generateTile() { Context context = this.getContext(); LinearLayout tile = new LinearLayout(context); tile.setOrientation(LinearLayout.VERTICAL); LinearLayout envelopeTile = new LinearLayout(context); envelopeTile.setOrientation(LinearLayout.HORIZONTAL); envelopeTile.setTag("envelope"); tile.addView(envelopeTile); TextView displayRecipient = new TextView(context); displayRecipient.setTag("display_recipient"); displayRecipient.setTypeface(Typeface.DEFAULT_BOLD); displayRecipient.setGravity(Gravity.CENTER_HORIZONTAL); displayRecipient.setPadding(10, 5, 10, 5); envelopeTile.addView(displayRecipient); TextView sep = new TextView(context); sep.setText(" | "); sep.setTag("sep"); TextView instance = new TextView(context); instance.setPadding(10, 5, 10, 5); instance.setTag("instance"); envelopeTile.addView(sep); envelopeTile.addView(instance); TextView senderName = new TextView(context); senderName.setTag("senderName"); senderName.setPadding(10, 5, 10, 5); senderName.setTypeface(Typeface.DEFAULT_BOLD); tile.addView(senderName); TextView contentView = new TextView(context); contentView.setTag("contentView"); contentView.setPadding(10, 0, 10, 10); tile.addView(contentView); return tile; } public View getView(int position, View convertView, ViewGroup ignored) { Context context = this.getContext(); Message message = getItem(position); LinearLayout tile; if (convertView == null) { // We didn't get passed a tile, so construct a new one. // In the future, we should inflate from a layout here. tile = generateTile(); } else { tile = (LinearLayout) convertView; } LinearLayout envelopeTile = (LinearLayout) tile .findViewWithTag("envelope"); TextView display_recipient = (TextView) tile .findViewWithTag("display_recipient"); if (message.getType() == MessageType.STREAM_MESSAGE) { envelopeTile.setBackgroundResource(R.drawable.stream_header); } else { envelopeTile.setBackgroundResource(R.drawable.huddle_header); } if (message.getType() != MessageType.STREAM_MESSAGE) { display_recipient.setText(context.getString(R.string.huddle_text) + " " + message.getDisplayRecipient()); display_recipient.setTextColor(Color.WHITE); } else { display_recipient.setText(message.getDisplayRecipient()); display_recipient.setTextColor(Color.BLACK); } TextView sep = (TextView) tile.findViewWithTag("sep"); TextView instance = (TextView) tile.findViewWithTag("instance"); if (message.getType() == MessageType.STREAM_MESSAGE) { instance.setVisibility(View.VISIBLE); sep.setVisibility(View.VISIBLE); instance.setText(message.getSubject()); } else { instance.setVisibility(View.GONE); sep.setVisibility(View.GONE); } TextView senderName = (TextView) tile.findViewWithTag("senderName"); senderName.setText(message.getSender().getName()); TextView contentView = (TextView) tile.findViewWithTag("contentView"); contentView.setText(message.getContent()); int color; if (message.getType() != MessageType.STREAM_MESSAGE) { color = context.getResources().getColor(R.color.huddle_body); } else { color = context.getResources().getColor(R.color.stream_body); } senderName.setBackgroundColor(color); contentView.setBackgroundColor(color); tile.setTag(R.id.messageID, message.getID()); return tile; } public long getItemId(int position) { return this.getItem(position).getID(); } }
// vim: et sw=4 sts=4 tabstop=4 package com.issc.ui; import com.issc.Bluebit; import com.issc.data.BLEDevice; import com.issc.impl.FunctionAdapter; import com.issc.impl.GattProxy; import com.issc.R; import com.issc.util.Log; import com.issc.util.Util; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.app.ListActivity; import android.bluetooth.BluetoothClass; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothProfile; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.ParcelUuid; import android.view.View; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import com.samsung.android.sdk.bt.gatt.BluetoothGatt; import com.samsung.android.sdk.bt.gatt.BluetoothGattAdapter; import com.samsung.android.sdk.bt.gatt.BluetoothGattCallback; import com.samsung.android.sdk.bt.gatt.BluetoothGattCharacteristic; import com.samsung.android.sdk.bt.gatt.BluetoothGattService; public class ActivityFunctionPicker extends ListActivity { private BluetoothDevice mDevice; private FunctionAdapter mAdapter; private BluetoothGatt mGatt; private GattProxy.Listener mListener; private final static int DISCOVERY_DIALOG = 1; private ProgressDialog mDiscoveringDialog; private boolean mDiscovered = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_function_picker); Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (!extras.containsKey(Bluebit.CHOSEN_DEVICE)) { finish(); } mListener = new GattListener(); initAdapter(); BLEDevice device = intent.getParcelableExtra(Bluebit.CHOSEN_DEVICE); mDevice = device.getDevice(); TextView tv = (TextView) findViewById(R.id.picker_dev_name); tv.setText(mDevice.getName()); } @Override protected void onResume() { super.onResume(); GattProxy proxy = GattProxy.get(this); proxy.addListener(mListener); proxy.retrieveGatt(mListener); } @Override protected void onPause() { super.onPause(); GattProxy proxy = GattProxy.get(this); proxy.rmListener(mListener); } @Override protected Dialog onCreateDialog(int id, Bundle args) { if (id == DISCOVERY_DIALOG) { mDiscoveringDialog = new ProgressDialog(this); mDiscoveringDialog.setMessage(this.getString(R.string.discovering)); mDiscoveringDialog.setOnCancelListener(new Dialog.OnCancelListener() { public void onCancel(DialogInterface dialog) { stopDiscovery(); } }); return mDiscoveringDialog; } return null; } private void connectToDevice() { runOnUiThread(new Runnable() { public void run() { showDialog(DISCOVERY_DIALOG); } }); if (mGatt != null) { if (mGatt.getConnectionState(mDevice) == BluetoothProfile.STATE_CONNECTED) { Log.d("connected"); List<BluetoothGattService> list = mGatt.getServices(mDevice); if ((list == null) || (list.size() == 0)) { Log.d("start discovery"); mGatt.discoverServices(mDevice); } else { onDiscovered(mDevice); } } else { Log.d("connecting to device"); mGatt.connect(mDevice, false); } } else { Log.e("mGatt is null!!"); } } private void stopDiscovery() { runOnUiThread(new Runnable() { public void run() { dismissDialog(DISCOVERY_DIALOG); } }); } private void initAdapter() { mAdapter = new FunctionAdapter(this); setListAdapter(mAdapter); } private void onDiscovered(BluetoothDevice device) { Log.d("on discovered:"); mDiscovered = true; if (mGatt != null) { List<BluetoothGattService> srvs = mGatt.getServices(device); Iterator<BluetoothGattService> it = srvs.iterator(); while (it.hasNext()) { appendServices(it.next()); } } } private void appendServices(final BluetoothGattService srv) { runOnUiThread(new Runnable() { public void run() { mAdapter.addUuidInUiThread(srv.getUuid()); } }); } @Override protected void onListItemClick(ListView l, View v, int pos, long id) { Intent i = mAdapter.createIntent(pos); BLEDevice device = new BLEDevice(mDevice); i.putExtra(Bluebit.CHOSEN_DEVICE, device); startActivity(i); } class GattListener extends GattProxy.ListenerHelper { GattListener() { super("ActivityFunctionPicker"); } @Override public void onRetrievedGatt(BluetoothGatt gatt) { Log.d(String.format("onRetrievedGatt")); mGatt = gatt; connectToDevice(); } @Override public void onServicesDiscovered(BluetoothDevice device, int status) { stopDiscovery(); onDiscovered(device); } @Override public void onConnectionStateChange(BluetoothDevice device, int status, int newState) { if (mGatt == null) { Log.d("There is no Gatt to be used, skip"); return; } if (newState == BluetoothProfile.STATE_CONNECTED) { Log.d("connected to device, start discovery"); mGatt.discoverServices(mDevice); } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { } } } }
package edu.oakland.OUSoft.database; import edu.oakland.OUSoft.items.Course; import edu.oakland.OUSoft.items.Instructor; import edu.oakland.OUSoft.items.Person; import edu.oakland.OUSoft.items.Student; import java.util.ArrayList; import java.util.List; public class OUPeople { private ArrayList<Student> students; private ArrayList<Instructor> instructors; private ArrayList<Person> others; private ArrayList<Course> courses; private ArrayList<Enrollment> enrollments; public OUPeople() { this.students = new ArrayList<>(); this.instructors = new ArrayList<>(); this.others = new ArrayList<>(); } public void addCourse(Course course) throws IllegalArgumentException { if (course.getInstructor() == null) { throw new IllegalArgumentException("Course did not have an instructor assigned."); } this.courses.add(course); } /** * Add a course to the database, with the given Instructor assigned. * * @param course The Course to add * @param instructor The Instructor to assign */ public void addCourse(Course course, Instructor instructor) { course.setInstructor(instructor); this.courses.add(course); } /** * Enroll a Student in a Course. * * @param student The Student to enroll * @param course The Course to enroll the Student in */ public void enroll(Student student, Course course) { this.enrollments.add(new Enrollment(course, student)); } /** * Withdraw a Student from a Course. * * @param student The Student to withdraw * @param course The Course to withdraw the Student from */ public void withdraw(Student student, Course course) { this.enrollments.remove(getEnrollment(student, course)); } /** * Get the {@link Enrollment} of this Student and Course, if one exists. * * @param student The student to get Enrollment of * @param course The course to get Enrollment of * @return The Enrollment, or null if none exists */ public Enrollment getEnrollment(Student student, Course course) { for (Enrollment e : this.enrollments) { if (e.getCourse() == course && e.getStudent() == student) { return e; } } return null; } /** * Get any Enrollments that contain the given Course * * @param course The Course to get Enrollments of * @return Any Enrollments with this Course */ public List<Enrollment> getEnrollments(Course course) { List<Enrollment> enrollmentList = new ArrayList<>(); for (Enrollment e : this.enrollments) { if (e.getCourse() == course) { enrollmentList.add(e); } } return enrollmentList; } /** * Get any Enrollments that contain the given Student * * @param student The Student to get Enrollments of * @return Any Enrollments with this Student */ public List<Enrollment> getEnrollments(Student student) { List<Enrollment> enrollmentList = new ArrayList<>(); for (Enrollment e : this.enrollments) { if (e.getStudent() == student) { enrollmentList.add(e); } } return enrollmentList; } /** * Check whether a student is enrolled in a Course * * @param student The Student to check * @param course The Course to check * @return If the student is enrolled */ public boolean studentIsEnrolled(Student student, Course course) { return getEnrollment(student, course) != null; } /** * Get the number of students enrolled in a course. * * @param course the Course to check * @return The number of Students enrolled */ public int numberStudentsEnrolled(Course course) { return getEnrollments(course).size(); } /** * Get the number of courses a student is enrolled in. * * @param student The student to check * @return The number of courses the student is enrolled in */ public int numberCoursesEnrolled(Student student) { return getEnrollments(student).size(); } /** * Print all the students who are enrolled in a course to standard output. * * @param course The Course to print students of */ public void printEnrolled(Course course) { for (Enrollment enrollment : getEnrollments(course)) { System.out.println(enrollment.getStudent().toString()); } } /** * Print all the courses a student is enrolled in to standard output. * * @param student The Student to print courses of */ public void printCourses(Student student) { for (Enrollment enrollment : getEnrollments(student)) { System.out.println(enrollment.getCourse().toString()); } } /** * Retrieve a person using their ID * * @param ID The persons ID * @return The Person, or null if not found */ public Person retrieveByID(String ID) { Person s = retrieveStudentByID(ID); if (s != null) { return s; } Person i = retrieveInstructorByID(ID); if (i != null) { return i; } return retrieveOtherByID(ID); } /** * Retrieve a student using their ID * * @param ID The students ID * @return The student, or null if not found */ public Student retrieveStudentByID(String ID) { for (Student student : students) { if (student.getID().equals(ID)) { return student; } } return null; } /** * Retrieve an instructor using their ID * * @param ID The instructors ID * @return The instructor, or null if not found */ public Instructor retrieveInstructorByID(String ID) { for (Instructor instructor : instructors) { if (instructor.getID().equals(ID)) { return instructor; } } return null; } /** * Retrieve someone uncategorized using their ID * * @param ID The persons ID * @return The person, or null if not found */ public Person retrieveOtherByID(String ID) { for (Person person : this.others) { if (person.getID().equals(ID)) { return person; } } return null; } /** * Add a person to the database, automatically determining type * * @param person The Person to add */ public void add(Person person) { if (person instanceof Student) { this.students.add((Student) person); } else if (person instanceof Instructor) { this.instructors.add((Instructor) person); } else { this.others.add(person); } } /** * Remove a student by reference * * @param student The Student to remove */ public void removeStudent(Student student) { this.students.remove(student); } /** * Remove an instructor by reference * * @param instructor The Instructor to remove */ public void removeInstructor(Instructor instructor) { this.instructors.remove(instructor); } /** * Remove an other by reference * * @param other The other to remove */ public void removeInstructor(Person other) { this.others.remove(other); } /** * Remove someone from the database by reference * * @param person The Person to remove */ public void remove(Person person) { this.students.remove(person); this.instructors.remove(person); this.others.remove(person); } /** * Remove a student by ID * * @param ID The ID of the Student to remove */ public void removeStudentByID(String ID) { this.students.remove(retrieveStudentByID(ID)); } /** * Remove an instructor by ID * * @param ID The ID of the Instructor to remove */ public void removeInstructorByID(String ID) { this.instructors.remove(retrieveInstructorByID(ID)); } /** * Remove an other by ID * * @param ID The ID of the other to remove */ public void removeOtherByID(String ID) { this.others.remove(retrieveOtherByID(ID)); } /** * Remove someone from the database based on ID * Note they are removed from all sub-databases. This will not be a problem if IDs are unique. * * @param ID The persons ID */ public void removeByID(String ID) { this.removeInstructorByID(ID); this.removeStudentByID(ID); this.removeOtherByID(ID); } /** * Print every student to standard output */ public void printAllStudents(boolean doHeader) { if (doHeader) { System.out.println("Students in the database: " + this.students.size()); } for (Student student : this.students) { System.out.println(student); } } /** * Print every instructor to standard output */ public void printAllInstructors(boolean doHeader) { if (doHeader) { System.out.println("Instructors in the database: " + this.instructors.size()); } for (Instructor instructor : this.instructors) { System.out.println(instructor); } } /** * Print every uncategorized person to standard output */ public void printAllOthers(boolean doHeader) { if (doHeader) { System.out.println("There are " + this.others.size() + " others in the database"); } for (Person person : this.others) { System.out.println(person); } } /** * Print every person to standard output */ public void printAll(boolean doHeader) { if (doHeader) { int count = this.students.size() + this.instructors.size() + this.others.size(); System.out.println("People in the database: " + count); } this.printAllInstructors(false); this.printAllStudents(false); this.printAllOthers(false); } }
/* * Class to handle all inputs, states, and transitions of the shooter/intake assembly. * 2014 FRC Team 1736 Robot Casserole */ package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.Solenoid; import edu.wpi.first.wpilibj.Talon; public class Jaws { Solenoid bottomJawLeftSolenoid, bottomJawRightSolenoid, topJawSolenoid; Talon rollerTalon; public Jaws(int bottomJawLeftSolenoidId, int bottomJawRightSolenoidId, int topJawSolenoidId, int rollerTalonId) { bottomJawLeftSolenoid = new Solenoid(bottomJawLeftSolenoidId); bottomJawRightSolenoid = new Solenoid(bottomJawRightSolenoidId); topJawSolenoid = new Solenoid(topJawSolenoidId); rollerTalon = new Talon(rollerTalonId); } }
/* @java.file.header */ package org.gridgain.grid.kernal.visor.cmd.dto; import org.gridgain.grid.util.typedef.internal.*; import java.io.*; /** * Portable object metadata field information. */ public class VisorPortableMetadataField implements Serializable { private static final long serialVersionUID = 0L; /** Field name. */ private String fieldName; /** Field type name. */ private String fieldTypeName; /** Field id. */ private Integer fieldId; /** Field name. */ public String fieldName() { return fieldName; } public void fieldName(String fieldName) { this.fieldName = fieldName; } /** Field type name. */ public String fieldTypeName() { return fieldTypeName; } public void fieldTypeName(String fieldTypeName) { this.fieldTypeName = fieldTypeName; } /** Field id. */ public Integer fieldId() { return fieldId; } public void fieldId(Integer fieldId) { this.fieldId = fieldId; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(VisorPortableMetadataField.class, this); } }
package com.mapotempo.fleet.core.model; import com.couchbase.lite.Database; import com.couchbase.lite.Document; import com.mapotempo.fleet.core.base.MapotempoModelBase; import com.mapotempo.fleet.core.base.DocumentBase; import java.util.ArrayList; import java.util.List; /** * Company. */ @DocumentBase(type = "user") public class User extends MapotempoModelBase { // MAPOTEMPO KEY public static final String USER = "user"; public static final String COMPANY_ID = "company_id"; public static final String ROLES = "roles"; public User(Database database) { super(database); } public User(Document doc) { super(doc); } public String getUser() { return (String)getProperty(USER, "Unknow"); } public String getCompanyId() { return (String)getProperty(COMPANY_ID, "No company id found"); } public List<String> getRoles() { return (ArrayList<String>)getProperty(ROLES, new ArrayList<String>()); } }
package eu.kairat.tools.logfileMerger; import com.beust.jcommander.Parameter; import java.io.*; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Merger { private static final Pattern LOG_LINE_DATE_PATTERN = Pattern.compile("^(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3}) (.*)$"); private static final SimpleDateFormat LOG_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss,SSS"); @Parameter(names = "-logfileSourcePath", description = "The path where the tool can find the logfiles to merge.") String logfileSourcePath; @Parameter(names = "-logfileSourceFileExtension", description = "The file extension of the logfiles to merge. (default = \"log\")") String logfileSourceFileExtension = "log"; @Parameter(names = "-logfileTargetPath", description = "The path where the tool creates the logfile containing the merging result. (default = \".\\\")") String logfileTargetPath = ".\\"; @Parameter(names = "-logfileTargetName", description = "The name of the logfile containing the merging result. (default = \"mergedLogfile.log\")") String logfileTargetName = "mergedLogfile.log"; private void checkArguments() { // check source file extension if(null == logfileSourceFileExtension) throw new RuntimeException("logfileSourceFileExtension is null"); Pattern p = Pattern.compile("^\\w+$"); Matcher m = p.matcher(logfileSourceFileExtension); if(!m.matches()) throw new RuntimeException("logfileSourceFileExtension is invalid"); // check source path if(null == logfileSourcePath) throw new RuntimeException("logfileSourcePath is null"); if(!Files.isDirectory(Paths.get(logfileSourcePath))) throw new RuntimeException("logfileSourcePath is not a directory"); // check logfile target name if(null == logfileTargetName) throw new RuntimeException("logfileTargetName is null"); p = Pattern.compile("^[\\w,\\s-]+\\.[A-Za-z]+$"); m = p.matcher(logfileTargetName); if(!m.matches()) throw new RuntimeException("logfileTargetName is invalid"); // check source path if(null == logfileTargetPath) throw new RuntimeException("logfileTargetPath is null"); if(!Files.isDirectory(Paths.get(logfileTargetPath))) throw new RuntimeException("logfileSourcePath is not a directory"); } void merge() throws Exception { System.out.println("CHECKING ARGUMENTS..."); checkArguments(); final List<Line> lineObjects = new LinkedList<Line>(); int maxSourceChars = 0; int processedFiles = 0; int processedMessages = 0; int processedLines = 0; final Path dir = Paths.get(logfileSourcePath); Line lastItem = null; System.out.println("READING FILES..."); final DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.{" + logfileSourceFileExtension + "}"); for (Path entry : stream) { final String source = entry.getFileName().toString().replaceFirst("[.][^.]+$", ""); maxSourceChars = Math.max(maxSourceChars, source.length()); try (BufferedReader br = new BufferedReader(new FileReader(entry.toString()))) { for (String line; (line = br.readLine()) != null; ) { boolean newItemGenerated = false; final Matcher m = LOG_LINE_DATE_PATTERN.matcher(line); while (m.find()) { final String dateString = m.group(1); final String message = m.group(2); //System.out.println(dateString + source + message); final Date date = LOG_DATE_FORMAT.parse(dateString); lastItem = new Line(source, date, message); lineObjects.add(lastItem); newItemGenerated = true; processedMessages++; break; } if (!newItemGenerated) { lastItem.message += "\n\t" + line; } processedLines++; } } processedFiles++; System.out.println("FILES:" + processedFiles + "|MESSAGES:" + processedMessages + "|LINES:" + processedLines); } System.out.println("SORTING..."); Collections.sort(lineObjects); System.out.println("CREATING FILE..."); Date date = new Date() ; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS") ; final File file = new File(logfileTargetPath + dateFormat.format(date) + "_" + logfileTargetName); // if file doesnt exists, then create it if (file.exists()) { System.out.println("DELETING EXISTENT TARGET FILE..."); file.delete(); } else { file.createNewFile(); } FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); final int finalMaxSourceChars = maxSourceChars; System.out.println("WRITING FILE..."); lineObjects.stream().forEach( l -> { try { bw.write(LOG_DATE_FORMAT.format(l.date)); bw.write(" "); bw.write(String.format("%" + finalMaxSourceChars + "s", l.source)); bw.write(" "); bw.write(l.message); bw.newLine(); } catch (IOException e) { throw new RuntimeException(e); } } ); bw.close(); System.out.println("SYSTEM READY_"); } }
package org.synyx.minos.core.security; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.security.access.AccessDecisionManager; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.SecurityConfig; import org.springframework.security.authentication.InsufficientAuthenticationException; import org.springframework.security.authentication.dao.SaltSource; import org.springframework.security.authentication.encoding.PasswordEncoder; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.synyx.hades.domain.auditing.AuditorAware; import org.synyx.minos.core.domain.Password; import org.synyx.minos.core.domain.User; import org.synyx.minos.umt.dao.UserDao; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Implementation of the {@code AuthenticationService} to use Spring Security. * * @author Oliver Gierke - gierke@synyx.de */ public class SpringSecurityAuthenticationService extends AbstractAuthenticationService implements AuditorAware<User> { private static final Log LOG = LogFactory.getLog(SpringSecurityAuthenticationService.class); private final UserDao userDao; private final AccessDecisionManager accessDecisionManager; private final SaltSource saltSource; private final PasswordEncoder passwordEncoder; public SpringSecurityAuthenticationService(UserDao userDao, AccessDecisionManager accessDecisionManager, SaltSource saltSource, PasswordEncoder passwordEncoder) { super(); this.userDao = userDao; this.accessDecisionManager = accessDecisionManager; this.saltSource = saltSource; this.passwordEncoder = passwordEncoder; } @Override public User getCurrentAuditor() { return getCurrentUser(); } @Override public User getCurrentUser() { UserDetails userDetails = getAuthenticatedUser(); if (userDetails == null) { return null; } else if (userDetails instanceof MinosUserDetails) { return userDao.readByPrimaryKey(((MinosUserDetails) userDetails).getId()); } else { return userDao.findByUsername(userDetails.getUsername()); } } @Override public Password getEncryptedPasswordFor(User user) { if (passwordEncoder == null) { return user.getPassword(); } Object salt = saltSource == null ? null : saltSource.getSalt(new MinosUserDetails(user)); String plainPassword = user.getPassword().toString(); return new Password(passwordEncoder.encodePassword(plainPassword, salt), true); } @Override protected boolean hasPermissions(Collection<String> permissions) { if (null == permissions || permissions.isEmpty()) { return false; } Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null) { return false; } try { accessDecisionManager.decide(authentication, null, toAttributes(permissions)); return true; } catch (AccessDeniedException e) { LOG.debug("Access denied!", e); return false; } catch (InsufficientAuthenticationException e) { LOG.debug("Access denied!", e); return false; } } private List<ConfigAttribute> toAttributes(Collection<String> permissions) { List<ConfigAttribute> attributes = new ArrayList<ConfigAttribute>(); for (String permission : permissions) { attributes.add(new SecurityConfig(permission)); } return attributes; } private UserDetails getAuthenticatedUser() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (null == authentication) { return null; } // Principal may be "anonymous", which is a string if (!(authentication.getPrincipal() instanceof UserDetails)) { return null; } return (UserDetails) authentication.getPrincipal(); } }
package kalang.compiler; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Stack; import kalang.antlr.KalangLexer; import kalang.antlr.KalangParser; import kalang.antlr.KalangParser.ArgumentDeclContext; import kalang.antlr.KalangParser.ArgumentDeclListContext; import kalang.antlr.KalangParser.ArgumentsContext; import kalang.antlr.KalangParser.BreakStatContext; import kalang.antlr.KalangParser.CastExprContext; import kalang.antlr.KalangParser.ClassBodyContext; import kalang.antlr.KalangParser.CompiliantUnitContext; import kalang.antlr.KalangParser.ContinueStatContext; import kalang.antlr.KalangParser.DoWhileStatContext; import kalang.antlr.KalangParser.ExprAssignContext; import kalang.antlr.KalangParser.ExprGetArrayElementContext; import kalang.antlr.KalangParser.ExprGetFieldContext; import kalang.antlr.KalangParser.ExprInvocationContext; import kalang.antlr.KalangParser.ExprMemberInvocationContext; import kalang.antlr.KalangParser.ExprMidOpContext; import kalang.antlr.KalangParser.ExprPrimayContext; import kalang.antlr.KalangParser.ExprSelfOpContext; import kalang.antlr.KalangParser.ExprSelfOpPreContext; import kalang.antlr.KalangParser.ExprStatContext; import kalang.antlr.KalangParser.ExpressionContext; import kalang.antlr.KalangParser.ExpressionsContext; import kalang.antlr.KalangParser.FieldDeclContext; import kalang.antlr.KalangParser.FieldDeclListContext; import kalang.antlr.KalangParser.ForInitContext; import kalang.antlr.KalangParser.ForStatContext; import kalang.antlr.KalangParser.ForUpdateContext; import kalang.antlr.KalangParser.GetterContext; import kalang.antlr.KalangParser.IfStatContext; import kalang.antlr.KalangParser.IfStatSuffixContext; import kalang.antlr.KalangParser.ImportDeclContext; import kalang.antlr.KalangParser.ImportDeclListContext; import kalang.antlr.KalangParser.LiteralContext; import kalang.antlr.KalangParser.MethodDeclContext; import kalang.antlr.KalangParser.MethodDeclListContext; import kalang.antlr.KalangParser.NewExprContext; import kalang.antlr.KalangParser.PrimaryIdentifierContext; import kalang.antlr.KalangParser.PrimaryLiteralContext; import kalang.antlr.KalangParser.PrimayParenContext; import kalang.antlr.KalangParser.QualifiedNameContext; import kalang.antlr.KalangParser.ReturnStatContext; import kalang.antlr.KalangParser.SetterContext; import kalang.antlr.KalangParser.StatContext; import kalang.antlr.KalangParser.StatListContext; import kalang.antlr.KalangParser.TryStatContext; import kalang.antlr.KalangParser.TypeContext; import kalang.antlr.KalangParser.VarDeclContext; import kalang.antlr.KalangParser.VarDeclStatContext; import kalang.antlr.KalangParser.VarInitContext; import kalang.antlr.KalangParser.WhileStatContext; import kalang.antlr.KalangVisitor; import kalang.core.VarTable; import jast.ast.*; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.misc.Interval; import org.antlr.v4.runtime.tree.AbstractParseTreeVisitor; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.TerminalNode; public class SourceParser extends AbstractParseTreeVisitor<ExprNode> implements KalangVisitor<ExprNode> { private static final String MAP_CLASS = "java.util.HashMap"; private static final String ROOT_CLASS = "java.lang.Object"; private static final String FLOAT_CLASS = "float"; private static final String INT_CLASS = "int"; private static final String BOOLEAN_CLASS = "java.lang.Boolean"; private static final String CHAR_CLASS = "java.lang.Character"; private static final String STRING_CLASS = "java.lang.String"; private static final String NULL_CLASS = "java.lang.NullObject"; static String DEFAULT_METHOD_TYPE = "java.lang.Object"; static String DEFAULT_LIST_CLASS = "java.util.LinkedList"; static String DEFAULT_VAR_TYPE;// = "java.lang.Object"; //short name to full name private final Map<String,String> fullNames = new HashMap(); private final List<String> importPaths = new LinkedList(); Stack<VarTable> vtbs = new Stack(); int varCounter = 0; ClassNode cls = new ClassNode(); List<Statement> codes; List<ExprNode> arguments; MethodNode method; private final Map<AstNode,ParseTree> a2p = new HashMap(); private AstLoader astLoader; private final ParseTree context; private final CommonTokenStream tokens; private final String className; private String classPath; public static class Position{ int offset; int length; } public static class ParseError extends RuntimeException{ Position position; public ParseError(String msg,Position position){ super(msg); this.position = position; } public Position getPosition() { return position; } } public void compile(AstLoader astLoader){ this.astLoader = astLoader; visit(context); } public SourceParser(String className,String src){ KalangLexer lexer = new KalangLexer(new ANTLRInputStream(src)); tokens = new CommonTokenStream(lexer); KalangParser parser = new KalangParser(tokens); this.context = parser.compiliantUnit(); this.className = className; this.classPath = ""; if(className.contains(".")){ classPath = className.substring(0, className.lastIndexOf('.')); } cls = new ClassNode(); } public void importPackage(String packageName){ this.importPaths.add(packageName); } public Position getLocation(ParseTree tree){ Position loc = new Position(); Interval itv = tree.getSourceInterval(); Token t = tokens.get(itv.a); Token tt = tokens.get(itv.b); loc.offset = t.getStartIndex(); loc.length = tt.getStopIndex() - loc.offset + 1; return loc; } public Position getLocation(AstNode node){ ParseTree tree = this.a2p.get(node); if(tree!=null){ return getLocation(tree); } return null; } private VarTable getVarTable(){ return vtbs.peek(); } public Map<AstNode,ParseTree> getParseTreeMap(){ return this.a2p; } private void pushVarTable(){ VarTable vtb; if(vtbs.size()>0){ vtb = new VarTable(getVarTable()); }else{ vtb = new VarTable(); } vtbs.push(vtb); } private void popVarTable(){ vtbs.pop(); } public ClassNode getAst(){ return this.cls; } private void addCode(Statement node,ParseTree tree){ codes.add(node); a2p.put(node, tree); } @Override public ExprNode visitMapExpr(KalangParser.MapExprContext ctx) { return visit(ctx.map()); } @Override public ExprNode visitListOrArrayExpr(KalangParser.ListOrArrayExprContext ctx) { return visit(ctx.listOrArray()); } @Override public ExprNode visitMap(KalangParser.MapContext ctx) { int vid = this.varCounter++; VarDeclStmt vds = new VarDeclStmt(); vds.varId = vid; vds.type = MAP_CLASS; vds.initExpr = new NewExpr(vds.type); addCode(vds,ctx); VarExpr ve = new VarExpr(); ve.varId = vid; ve.declStmt = vds; List ids = ctx.Identifier(); for(int i=0;i<ids.size();i++){ ExpressionContext e = ctx.expression(i); ExprNode v = visit(e); List args = new LinkedList(); ConstExpr k = new ConstExpr(); k.type = STRING_CLASS; k.value = ctx.Identifier(i).getText(); args.add(k); args.add(v); InvocationExpr iv = new InvocationExpr(ve,"put",args); ExprStmt es = new ExprStmt(iv); addCode(es,ctx); } //TODO set generic type return ve; } @Override public ExprNode visitListOrArray(KalangParser.ListOrArrayContext ctx) { String type = ROOT_CLASS; String clsName = DEFAULT_LIST_CLASS; int vid = this.varCounter++; VarDeclStmt vds = new VarDeclStmt(); vds.varId = vid; vds.type = clsName; vds.initExpr = new NewExpr(vds.type); addCode(vds,ctx); VarExpr ve = new VarExpr(); ve.varId = vid; ve.declStmt = vds; for(ExpressionContext e:ctx.expression()){ List args = new LinkedList(); args.add(visit(e)); InvocationExpr iv = new InvocationExpr(ve,"add",args); addCode(new ExprStmt(iv),ctx); } //TODO set generic type return ve; } @Override public ExprNode visitExprNewArray(KalangParser.ExprNewArrayContext ctx) { NewArrayExpr nae = new NewArrayExpr(); nae.size = visit(ctx.expression()); nae.type = ctx.noArrayType().getText(); a2p.put(nae, ctx); return nae; } @Override public ExprNode visitNoArrayType(KalangParser.NoArrayTypeContext ctx) { //do nothing return null; } @Override public ExprNode visitExprQuestion(KalangParser.ExprQuestionContext ctx) { int vid = this.varCounter++; VarDeclStmt vds = new VarDeclStmt(); addCode(vds,ctx); vds.varId = vid; VarExpr ve = new VarExpr(); ve.varId = vid; ve.declStmt = vds; IfStmt is = new IfStmt(); is.conditionExpr = visit(ctx.expression(0)); is.trueBody =new ExprStmt(new AssignExpr(ve,visit(ctx.expression(1)))); is.falseBody = new ExprStmt(new AssignExpr(ve,visit(ctx.expression(2)))); addCode(is,ctx); a2p.put(ve, ctx); return ve; } @Override public ExprNode visitPostIfStmt(KalangParser.PostIfStmtContext ctx) { ExprNode leftExpr = visitExpression(ctx.expression(0)); if(!(leftExpr instanceof AssignExpr)){ this.reportError("AssignExpr required", ctx); } AssignExpr assignExpr = (AssignExpr) leftExpr; ExprNode to = assignExpr.to; ExprNode from = assignExpr.from; ExprNode cond = visitExpression(ctx.expression(1)); Token op = ctx.op; if(op!=null){ String opStr = op.getText(); BinaryExpr be = new BinaryExpr(to,cond,opStr); cond = be; } AssignExpr as = new AssignExpr(); as.from = from;as.to = to; IfStmt is = new IfStmt(); is.conditionExpr = cond; is.trueBody = new ExprStmt(as); addCode(is,ctx); return null; } @Override public ExprNode visitCompiliantUnit(CompiliantUnitContext ctx) { //List<ImportNode> imports = this.visitImportDeclList(ctx.importDeclList()); visitClassBody(ctx.classBody()); //cls.imports = imports; cls.name= this.className; cls.modifier=getModifier(ctx.BANG()!=null,ctx.QUESTION()!=null); String classType = ctx.classType.getText(); if(classType.equals("interface")) cls.isInterface = true; if(ctx.parentClass!=null) cls.parentName=(ctx.parentClass.getText()); cls.interfaces = new LinkedList(); if(ctx.interfaces!=null && ctx.interfaces.size()>0){ for(Token itf:ctx.interfaces){ cls.interfaces.add(itf.getText()); } } return null; } @Override public ExprNode visitClassBody(ClassBodyContext ctx) { this.pushVarTable(); this.visitFieldDeclList(ctx.fieldDeclList()); this.visitMethodDeclList(ctx.methodDeclList()); return null; } @Override public ExprNode visitFieldDeclList(FieldDeclListContext ctx) { cls.fields = new LinkedList(); for(FieldDeclContext fd:ctx.fieldDecl()){ this.visitFieldDecl(fd); } return null; } @Override public ExprNode visitFieldDecl(FieldDeclContext ctx) { String type = ctx.type()==null?DEFAULT_VAR_TYPE:ctx.type().getText(); FieldNode fo = new FieldNode(); fo.name=(ctx.Identifier().getText()); fo.type=(type); if(ctx.varInit()!=null){ fo.initExpr = (visitVarInit(ctx.varInit())); } fo.modifier = getModifier(ctx.BANG()!=null,ctx.QUESTION()!=null); //fields.add(fo.name); cls.fields.add(fo); //TODO visit setter and getter return null; } @Override public ExprNode visitSetter(SetterContext ctx) { // TODO setter imp return null; } @Override public ExprNode visitGetter(GetterContext ctx) { // TODO getter imp return null; } @Override public ExprNode visitMethodDeclList(MethodDeclListContext ctx) { cls.methods = new LinkedList(); for(MethodDeclContext md:ctx.methodDecl()){ visitMethodDecl(md); } return null; } @Override public ExprNode visitMethodDecl(MethodDeclContext ctx) { this.pushVarTable(); String name = ctx.name.getText(); String type = "void"; if(!ctx.prefix.getText().equals(type)){ type = ctx.type()==null ? DEFAULT_METHOD_TYPE :ctx.type().getText(); } int mdf = getModifier(ctx.BANG()!=null,ctx.QUESTION()!=null); boolean isStatic = false; if(ctx.STATIC()!=null){ isStatic = true; } method = new MethodNode(mdf,type,name,isStatic); if(ctx.argumentDeclList()!=null){ visitArgumentDeclList(ctx.argumentDeclList()); } if(ctx.statList()!=null){ BlockStmt body = new BlockStmt(); method.body = body; codes = body.statements = new LinkedList(); visitStatList(ctx.statList()); } method.exceptionTypes = new LinkedList(); if(ctx.exceptionTypes!=null){ for(Token et:ctx.exceptionTypes){ String eFullType = this.getFullClassName(et.getText()); method.exceptionTypes.add(eFullType); } } this.popVarTable(); cls.methods.add(method); return null; } @Override public ExprNode visitType(TypeContext ctx) { //do nothing return null; } @Override public ExprNode visitArgumentDeclList(ArgumentDeclListContext ctx) { method.parameters = new LinkedList(); for(ArgumentDeclContext ad:ctx.argumentDecl()){ visitArgumentDecl(ad); } return null; } @Override public ExprNode visitArgumentDecl(ArgumentDeclContext ctx) { String name = ctx.Identifier().getText(); String type = DEFAULT_VAR_TYPE; if(ctx.type()!=null){ type = ctx.type().getText(); } ParameterNode pn = new ParameterNode(); pn.name = name; pn.type = type; method.parameters.add(pn); return null; } @Override public ExprNode visitStatList(StatListContext ctx) { for(StatContext s:ctx.stat()){ visitStat(s); } return null; } @Override public ExprNode visitIfStat(IfStatContext ctx) { List oCodes = codes; IfStmt ifStmt = new IfStmt(); BlockStmt trueBody = new BlockStmt(); BlockStmt falseBody = new BlockStmt(); ifStmt.trueBody = trueBody; ifStmt.falseBody = falseBody; ExprNode expr = visitExpression(ctx.expression()); ifStmt.conditionExpr = expr; codes = trueBody.statements = new LinkedList(); visitStatList(ctx.statList()); codes = falseBody.statements = new LinkedList(); visitIfStatSuffix(ctx.ifStatSuffix()); codes = oCodes; addCode(ifStmt,ctx); return null; } private ExprNode visitExpression(ExpressionContext expression) { return (ExprNode) visit(expression); } @Override public ExprNode visitIfStatSuffix(IfStatSuffixContext ctx) { visitStatList(ctx.statList()); return null; } @Override public ExprNode visitStat(StatContext ctx) { visit(ctx.getChild(0)); return null; } @Override public ExprNode visitReturnStat(ReturnStatContext ctx) { ExprNode expr = visitExpression(ctx.expression()); ReturnStmt rs = new ReturnStmt(); rs.expr = expr; addCode(rs,ctx); return null; } @Override public ExprNode visitVarDeclStat(VarDeclStatContext ctx) { this.visitVarDecl(ctx.varDecl()); return null; } @Override public ExprNode visitVarDecl(VarDeclContext ctx) { String name = ctx.Identifier().getText(); String type = DEFAULT_VAR_TYPE; if(ctx.type()!=null){ type = ctx.type().getText(); } boolean isReadOnly = ctx.getChild(0).getText() == "val"; //TODO readonly VarTable vtb = this.getVarTable(); if(this.getNodeByName(name)!=null){ reportError("defined duplicatedly:" + name,ctx.Identifier()); } VarDeclStmt vds = new VarDeclStmt(); Integer vid = varCounter++; vtb.put(name, vds); vds.varName = name; vds.type = type; vds.varId = vid; if(ctx.varInit()!=null){ vds.initExpr = visit(ctx.varInit()); } addCode(vds,ctx); return null; } private void reportError(String string, ParseTree tree) { throw new ParseError(string,this.getLocation(tree)); } @Override public ExprNode visitVarInit(VarInitContext ctx) { ExprNode vo = visitExpression(ctx.expression()); return vo; } @Override public ExprNode visitBreakStat(BreakStatContext ctx) { BreakStmt bs = new BreakStmt(); addCode(bs,ctx); return null; } @Override public ExprNode visitContinueStat(ContinueStatContext ctx) { ContinueStmt cs = new ContinueStmt(); addCode(cs,ctx); return null; } @Override public ExprNode visitWhileStat(WhileStatContext ctx) { //WhileStmt ws = new WhileStmt(); List oCodes = codes; LoopStmt ws = new LoopStmt(); BlockStmt body = new BlockStmt(); ws.loopBody = body; AstNode expr = visitExpression(ctx.expression()); ws.preConditionExpr = (ExprNode) expr; codes = body.statements = new LinkedList(); visitStatList(ctx.statList()); codes = oCodes; addCode(ws,ctx); return null; } @Override public ExprNode visitDoWhileStat(DoWhileStatContext ctx) { BlockStmt bs = new BlockStmt(); List oCodes = codes; codes = bs.statements; visit(ctx.statList()); codes = oCodes; ExprNode cond = visit(ctx.expression()); LoopStmt ls =new LoopStmt(); ls.loopBody = bs; ls.postConditionExpr = cond; addCode(ls,ctx); return null; } @Override public ExprNode visitForStat(ForStatContext ctx) { List oCodes = codes; this.pushVarTable(); LoopStmt ls = new LoopStmt(); BlockStmt body = new BlockStmt(); ls.loopBody = body; codes = ls.initStmts =new LinkedList(); visitForInit(ctx.forInit()); AstNode texpr = visitExpression(ctx.expression()); ls.preConditionExpr = (ExprNode) texpr; codes = body.statements = new LinkedList(); visitStatList(ctx.statList()); visitForUpdate(ctx.forUpdate()); this.popVarTable(); codes = oCodes; return null; } @Override public ExprNode visitForInit(ForInitContext ctx) { visit(ctx.varDecl()); return null; } @Override public ExprNode visitForUpdate(ForUpdateContext ctx) { visitExpressions(ctx.expressions()); return null; } @Override public ExprNode visitExpressions(ExpressionsContext ctx) { for(ExpressionContext e:ctx.expression()){ ExprNode expr = visitExpression(e); addCode(new ExprStmt(expr),ctx); } return null; } @Override public ExprNode visitExprStat(ExprStatContext ctx) { AstNode expr = visitExpression(ctx.expression()); ExprStmt es = new ExprStmt(); es.expr = (ExprNode) expr; addCode(es,ctx); return null; } @Override public ExprNode visitExprPrimay(ExprPrimayContext ctx) { ExprNode expr = (ExprNode) visit(ctx.primary()); a2p.put(expr, ctx); return expr; } @Override public InvocationExpr visitExprMemberInvocation(ExprMemberInvocationContext ctx) { InvocationExpr ie = this.getInvocationExpr( null , ctx.Identifier().getText() ,ctx.arguments()); a2p.put(ie, ctx); return ie; } @Override public AssignExpr visitExprAssign(ExprAssignContext ctx) { String assignOp = ctx.getChild(1).getText(); ExprNode to = visitExpression(ctx.expression(0)); ExprNode from = visitExpression(ctx.expression(1)); if(assignOp.length()>1){ String op = assignOp.substring(0,assignOp.length()-1); from = new BinaryExpr(to,from,op); } AssignExpr aexpr = new AssignExpr(); aexpr.from = (ExprNode) from; aexpr.to = (ExprNode) to; a2p.put(aexpr, ctx); return aexpr; } @Override public ExprNode visitExprMidOp(ExprMidOpContext ctx) { String op = ctx.getChild(1).getText(); BinaryExpr be = new BinaryExpr(); be.expr1 = (ExprNode) visitExpression(ctx.expression(0)); be.expr2 = (ExprNode) visitExpression(ctx.expression(1)); be.operation = op; a2p.put(be, ctx); return be; } private InvocationExpr getInvocationExpr(AstNode expr,String methodName,ArgumentsContext argumentsCtx){ InvocationExpr is = new InvocationExpr(); is.methodName =methodName; is.target = (ExprNode) expr; arguments = is.arguments = new LinkedList(); visitArguments(argumentsCtx); return is; } @Override public ExprNode visitExprInvocation(ExprInvocationContext ctx) { InvocationExpr ei = this.getInvocationExpr( visitExpression(ctx.expression()) , ctx.Identifier().getText() , ctx.arguments()); a2p.put(ei, ctx); return ei; } @Override public ExprNode visitExprGetField(ExprGetFieldContext ctx) { AstNode expr = visitExpression(ctx.expression()); String name = ctx.Identifier().getText(); FieldExpr fe = new FieldExpr(); fe.target = (ExprNode) expr; fe.fieldName = name; a2p.put(fe, ctx); return fe; } @Override public ExprNode visitExprSelfOp(ExprSelfOpContext ctx) { UnaryExpr ue = new UnaryExpr(); ue.postOperation = ctx.getChild(1).getText(); ue.expr = (ExprNode) visitExpression(ctx.expression()); a2p.put(ue, ctx); return ue; } @Override public UnaryExpr visitExprSelfOpPre(ExprSelfOpPreContext ctx) { String op = ctx.getChild(0).getText(); UnaryExpr ue = new UnaryExpr(); ue.expr = (ExprNode) visitExpression(ctx.expression()); ue.preOperation = op; a2p.put(ue, ctx); return ue; } @Override public ElementExpr visitExprGetArrayElement(ExprGetArrayElementContext ctx) { ElementExpr ee = new ElementExpr(); ee.target = (ExprNode) visitExpression(ctx.expression(0)); ee.key = (ExprNode) visitExpression(ctx.expression(1)); a2p.put(ee, ctx); return ee; } @Override public ExprNode visitPrimayParen(PrimayParenContext ctx) { return visitExpression(ctx.expression()); } @Override public ConstExpr visitPrimaryLiteral(PrimaryLiteralContext ctx) { return visitLiteral(ctx.literal()); } @Override public ExprNode visitPrimaryIdentifier(PrimaryIdentifierContext ctx) { String name = ctx.Identifier().getText(); return getNodeByName(name); } private String checkFullClassName(String name,ParseTree tree){ String fn = getFullClassName(name); if(fn==null){ this.reportError("Unknown class:"+name,tree); } return fn; } private String getFullClassName(String name){ if(fullNames.containsKey(name)){ return fullNames.get(name); }else{ for(String p:this.importPaths){ String clsName = p + "." + name; ClassNode cls = astLoader.getAst(clsName); if(cls!=null){ return clsName; } } } return null; } private ExprNode getNodeByName(String name) { VarTable vtb = this.getVarTable(); if(vtb.exist(name)){ VarExpr ve = new VarExpr(); VarDeclStmt declStmt = (VarDeclStmt) vtb.get(name); //vars.indexOf(vo); ve.varId = declStmt.varId; ve.declStmt = declStmt; return ve; }else{ //find parameters if(method!=null && method.parameters!=null){ for(ParameterNode p:method.parameters){ if(p.name.equals(name)) return new ParameterExpr(p); } } if(cls.fields!=null){ for(FieldNode f:cls.fields){ if(f.name.equals(name)){ FieldExpr fe = new FieldExpr(); fe.fieldName = name; return fe; } } } String clsName = this.getFullClassName(name); if(clsName!=null){ return new ClassExpr(clsName); } } return null; } @Override public ConstExpr visitLiteral(LiteralContext ctx) { ConstExpr ce = new ConstExpr(); String t = ctx.getText(); if(ctx.IntegerLiteral()!=null){ ce.type = INT_CLASS; ce.value = Integer.parseInt(t); }else if(ctx.FloatingPointLiteral()!=null){ ce.type = FLOAT_CLASS; ce.value = Float.parseFloat(t); }else if(ctx.BooleanLiteral()!=null){ ce.type = BOOLEAN_CLASS; ce.value = Boolean.parseBoolean(t); }else if(ctx.CharacterLiteral()!=null){ ce.type = CHAR_CLASS; char[] chars = t.toCharArray(); ce.value = chars[1]; }else if(ctx.StringLiteral()!=null){ ce.type = STRING_CLASS; //TODO parse string ce.value = t.substring(1,t.length()-1); }else{ ce.type = NULL_CLASS; } return ce; } @Override public ExprNode visitArguments(ArgumentsContext ctx) { for(ExpressionContext e:ctx.expression()){ ExprNode expr = visitExpression(e); arguments.add(expr); } return null; } private List doVisitAll(List list){ List retList = new LinkedList(); for(Object i:list){ retList.add(visit((ParseTree) i)); } return retList; } @Override public ExprNode visitImportDeclList(ImportDeclListContext ctx) { doVisitAll(ctx.importDecl()); return null; } @Override public ExprNode visitImportDecl(ImportDeclContext ctx) { String name = ctx.name.getText(); String prefix = ""; boolean relative = ctx.root==null || ctx.root.getText().length()==0; if(relative && this.classPath.length()>0){ prefix = this.classPath + "."; } if(ctx.path!=null) for(Token p:ctx.path) prefix += p.getText()+"."; if(name.equals("*")){ this.importPaths.add(prefix.substring(0,prefix.length()-1)); }else{ String key = name; if(ctx.alias!=null) key = ctx.alias.getText(); this.fullNames.put(key, prefix + name); } return null; } @Override public ExprNode visitQualifiedName(QualifiedNameContext ctx) { //do nothing return null; } public Integer getModifier(boolean isPrivated,boolean isProtected) { if(isPrivated) return Modifier.PRIVATE; if(isProtected) return Modifier.PROTECTED; return Modifier.PUBLIC; } @Override public ExprNode visitNewExpr(NewExprContext ctx) { String type = ctx.Identifier().getText(); ClassExpr expr = new ClassExpr(); expr.name = checkFullClassName(type,ctx); return this.getInvocationExpr(expr, "<init>",ctx.arguments()); } @Override public ExprNode visitCastExpr(CastExprContext ctx) { CastExpr ce = new CastExpr(); ce.expr = visitExpression(ctx.expression()); ce.type = ctx.type().getText(); return ce; } @Override public ExprNode visitTryStat(TryStatContext ctx) { TryStmt tryStmt = new TryStmt(); BlockStmt execStmt = new BlockStmt(); tryStmt.execStmt = execStmt; List oCodes = codes; codes = execStmt.statements = new LinkedList(); visit(ctx.tryStmtList); if(ctx.catchTypes!=null){ tryStmt.catchStmts = new LinkedList(); for(int i=0;i<ctx.catchTypes.size();i++){ BlockStmt catchBody = new BlockStmt(); codes = catchBody.statements = new LinkedList(); String vName = ctx.catchVarNames.get(i).getText(); String vType = ctx.catchTypes.get(i).getText(); this.pushVarTable(); VarDeclStmt declStmt = this.getVarDecl(vName, vType); visit(ctx.catchStmts.get(i)); this.popVarTable(); CatchStmt catchStmt = new CatchStmt(); catchStmt.catchVarDecl = declStmt; catchStmt.execStmt = catchBody; tryStmt.catchStmts.add(catchStmt); } } if(ctx.finalStmtList!=null){ this.pushVarTable(); BlockStmt finalBody = new BlockStmt(); codes = finalBody.statements; visit(ctx.finalStmtList); this.popVarTable(); tryStmt.finallyStmt = finalBody; } codes = oCodes; this.addCode(tryStmt, ctx); return null; } /** * create var decl stmt and put to var table * @param name * @param type * @return */ private VarDeclStmt getVarDecl(String name,String type){ VarDeclStmt vds = new VarDeclStmt(); vds.type = this.getFullClassName(type); vds.varId = this.varCounter++; vds.varName = name; this.getVarTable().put(name, vds.varId); return vds; } }
package com.qozix.tileview.tiles; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.BitmapFactory; import android.support.v4.util.LruCache; import com.jakewharton.DiskLruCache; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class TileCache { private static final int DISK_CACHE_CAPACITY = 8 * 1024; private static final int IO_BUFFER_SIZE = 8 * 1024; private static final int COMPRESSION_QUALITY = 40; private static final BitmapFactory.Options BITMAPFACTORY_OPTIONS = new BitmapFactory.Options(); static { BITMAPFACTORY_OPTIONS.inPreferredConfig = Bitmap.Config.RGB_565; } private MessageDigest digest; private LruCache<String, Bitmap> memoryCache; private DiskLruCache diskCache; // TODO: register local broadcast receiver to destroy the cache during onDestroy of containing Activity public TileCache( final Context context ) { try { digest = MessageDigest.getInstance( "MD5" ); } catch ( NoSuchAlgorithmException e1 ) { } // in memory cache final int memory = (int) ( Runtime.getRuntime().maxMemory() / 1024 ); final int size = memory / 8; memoryCache = new LruCache<String, Bitmap>( size ) { @Override protected int sizeOf( String key, Bitmap bitmap ) { // The cache size will be measured in kilobytes rather than number of items. // emulate bitmap.getByteCount for APIs less than 12 int byteCount = bitmap.getRowBytes() * bitmap.getHeight(); return byteCount / 1024; } }; // disk cache new Thread(new Runnable(){ @Override public void run(){ File cacheDirectory = new File( context.getCacheDir().getPath() + File.separator + "com/qozix/mapview" ); try { diskCache = DiskLruCache.open( cacheDirectory, 1, 1, DISK_CACHE_CAPACITY ); } catch ( IOException e ) { } } }).start(); } public void addBitmap( String key, Bitmap bitmap ) { addBitmapToMemoryCache( key, bitmap ); addBitmapToDiskCache( key, bitmap ); } public Bitmap getBitmap( String key ) { Bitmap bitmap = getBitmapFromMemoryCache( key ); if ( bitmap == null ) { bitmap = getBitmapFromDiskCache( key ); } return bitmap; } public void destroy(){ memoryCache.evictAll(); memoryCache = null; new Thread(new Runnable(){ @Override public void run(){ try { diskCache.delete(); diskCache = null; } catch ( IOException e ) { } } }).start(); } public void clear() { memoryCache.evictAll(); new Thread(new Runnable(){ @Override public void run(){ try { diskCache.delete(); } catch ( IOException e ) { } } }).start(); } private void addBitmapToMemoryCache( String key, Bitmap bitmap ) { if ( key == null || bitmap == null ) { return; } if ( getBitmapFromMemoryCache( key ) == null ) { memoryCache.put( key, bitmap ); } } private Bitmap getBitmapFromMemoryCache( String key ) { return memoryCache.get( key ); } private void addBitmapToDiskCache( String key, Bitmap bitmap ) { if ( diskCache == null ) { return; } key = getMD5( key ); DiskLruCache.Editor editor = null; try { editor = diskCache.edit( key ); if ( editor == null ) { return; } OutputStream output = null; try { output = new BufferedOutputStream( editor.newOutputStream( 0 ), IO_BUFFER_SIZE ); boolean compressed = bitmap.compress( CompressFormat.JPEG, COMPRESSION_QUALITY, output ); if ( compressed ) { diskCache.flush(); editor.commit(); } else { editor.abort(); } } finally { if ( output != null ) { output.close(); } } } catch ( Exception e ) { try { if ( editor != null ) { editor.abort(); } } catch ( IOException io ) { } } } private Bitmap getBitmapFromDiskCache( String key ) { if ( diskCache == null ) { return null; } key = getMD5( key ); Bitmap bitmap = null; DiskLruCache.Snapshot snapshot = null; try { snapshot = diskCache.get( key ); if ( snapshot == null ) { return null; } final InputStream input = snapshot.getInputStream( 0 ); if ( input != null ) { BufferedInputStream buffered = new BufferedInputStream( input, IO_BUFFER_SIZE ); bitmap = BitmapFactory.decodeStream( buffered, null, BITMAPFACTORY_OPTIONS ); } } catch ( Exception e ) { } finally { if ( snapshot != null ) { snapshot.close(); } } return bitmap; } private String getMD5( String fileName ) { if ( digest != null ) { digest.update( fileName.getBytes(), 0, fileName.length() ); return new BigInteger( 1, digest.digest() ).toString( 16 ); } // if digest is unavailable, at least make some attempt at an acceptable filename return fileName.replace("[^a-z0-9_-]", "_"); } }
package kalang.compiler; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Stack; import kalang.antlr.KalangLexer; import kalang.antlr.KalangParser; import kalang.antlr.KalangParser.ArgumentsContext; import kalang.antlr.KalangParser.BlockStmtContext; import kalang.antlr.KalangParser.BreakStatContext; import kalang.antlr.KalangParser.CastExprContext; import kalang.antlr.KalangParser.ClassBodyContext; import kalang.antlr.KalangParser.CompiliantUnitContext; import kalang.antlr.KalangParser.ContinueStatContext; import kalang.antlr.KalangParser.DoWhileStatContext; import kalang.antlr.KalangParser.ExprAssignContext; import kalang.antlr.KalangParser.ExprGetArrayElementContext; import kalang.antlr.KalangParser.ExprGetFieldContext; import kalang.antlr.KalangParser.ExprIdentifierContext; import kalang.antlr.KalangParser.ExprInvocationContext; import kalang.antlr.KalangParser.ExprLiteralContext; import kalang.antlr.KalangParser.ExprMemberInvocationContext; import kalang.antlr.KalangParser.ExprMidOpContext; import kalang.antlr.KalangParser.ExprParenContext; import kalang.antlr.KalangParser.ExprSelfOpContext; import kalang.antlr.KalangParser.ExprSelfOpPreContext; import kalang.antlr.KalangParser.ExprSelfRefContext; import kalang.antlr.KalangParser.ExprStatContext; import kalang.antlr.KalangParser.ExpressionContext; import kalang.antlr.KalangParser.ExpressionsContext; import kalang.antlr.KalangParser.FieldDeclContext; import kalang.antlr.KalangParser.ForStatContext; import kalang.antlr.KalangParser.IfStatContext; import kalang.antlr.KalangParser.ImportDeclContext; import kalang.antlr.KalangParser.LiteralContext; import kalang.antlr.KalangParser.MethodDeclContext; import kalang.antlr.KalangParser.NewExprContext; import kalang.antlr.KalangParser.QualifiedNameContext; import kalang.antlr.KalangParser.ReturnStatContext; import kalang.antlr.KalangParser.StatContext; import kalang.antlr.KalangParser.TryStatContext; import kalang.antlr.KalangParser.TypeContext; import kalang.antlr.KalangParser.VarDeclContext; import kalang.antlr.KalangParser.VarDeclStatContext; import kalang.antlr.KalangParser.VarDeclsContext; import kalang.antlr.KalangParser.VarModifierContext; import kalang.antlr.KalangParser.WhileStatContext; import kalang.antlr.KalangVisitor; import kalang.core.VarTable; import jast.ast.*; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.DefaultErrorStrategy; import org.antlr.v4.runtime.FailedPredicateException; import org.antlr.v4.runtime.InputMismatchException; import org.antlr.v4.runtime.NoViableAltException; import org.antlr.v4.runtime.Parser; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.RecognitionException; import org.antlr.v4.runtime.RuleContext; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.misc.Interval; import org.antlr.v4.runtime.tree.AbstractParseTreeVisitor; import org.antlr.v4.runtime.tree.ErrorNode; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.ParseTreeListener; import org.antlr.v4.runtime.tree.TerminalNode; import org.apache.commons.collections4.BidiMap; import org.apache.commons.collections4.bidimap.DualHashBidiMap; import org.apache.commons.collections4.bidimap.TreeBidiMap; public class SourceParser extends AbstractParseTreeVisitor implements KalangVisitor { private static final String MAP_CLASS = "java.util.HashMap"; static String DEFAULT_METHOD_TYPE = "java.lang.Object"; static String DEFAULT_LIST_CLASS = "java.util.LinkedList"; static String DEFAULT_VAR_TYPE;// = "java.lang.Object"; //short name to full name private final Map<String, String> fullNames = new HashMap<>(); private final List<String> importPaths = new LinkedList<>(); ClassNode cls = new ClassNode(); MethodNode method; private final BidiMap<AstNode, ParseTree> a2p = new DualHashBidiMap<>(); private AstLoader astLoader; private ParseTree context; private TokenStream tokens; private final String className; private String classPath; TypeSystem typeSystem; private VarTable<String, VarDeclStmt> vtb; private KalangParser parser; private HashMap<Token,ParseTree> token2tree = new HashMap<>(); private SemanticErrorHandler semanticErrorHandler = new SemanticErrorHandler() { @Override public void handleSemanticError(SemanticErrorException see) { System.err.println(see); } }; private ParseTreeListener parseTreeListener = new ParseTreeListener() { Stack<Integer> treeStartToken = new Stack<Integer>(); @Override public void visitTerminal(TerminalNode tn) {} @Override public void visitErrorNode(ErrorNode en) {} @Override public void enterEveryRule(ParserRuleContext prc) { treeStartToken.push(parser.getCurrentToken().getTokenIndex()); } @Override public void exitEveryRule(ParserRuleContext prc) { int stopIndex = parser.getCurrentToken().getTokenIndex(); int startIndex = treeStartToken.pop(); for(int i=startIndex;i<=stopIndex;i++){ Token tk = tokens.get(i); if(!token2tree.containsKey(tk)) token2tree.put(tk, prc); } } }; public SemanticErrorHandler getSemanticErrorHandler() { return semanticErrorHandler; } public void setSemanticErrorHandler(SemanticErrorHandler semanticErrorHandler) { this.semanticErrorHandler = semanticErrorHandler; } public AstNode getAstNode(ParseTree tree){ AstNode node = null; while(node==null && tree!=null){ node = a2p.getKey(tree); tree = tree.getParent(); } return node; } public ParseTree getParseTree(AstNode node){ return a2p.get(node); } public ParseTree getParseTreeByTokenIndex(int tokenIndex){ Token t = tokens.get(tokenIndex); ParseTree tree = token2tree.get(t); return tree; } @Override public Object visitThrowStat(KalangParser.ThrowStatContext ctx) { ExprNode expr = (ExprNode) visit(ctx.expression()); ThrowStmt ts = new ThrowStmt(expr); map(ts, ctx); return ts; } String getClassName() { return className; } public static class Position { int offset; int length; } public static class ParseError extends RuntimeException { private static final long serialVersionUID = -4496606055942267965L; Position position; public ParseError(String msg, Position position) { super(msg); this.position = position; } public Position getPosition() { return position; } } public static SourceParser create(String clsName,String source){ KalangLexer lexer = new KalangLexer(new ANTLRInputStream(source)); TokenStream tokens = new CommonTokenStream(lexer); KalangParser p = new KalangParser(tokens); SourceParser sp = new SourceParser(clsName, p); p.setErrorHandler(new DefaultErrorStrategy() { @Override public void reportError(Parser recognizer, RecognitionException e) { String msg = AntlrErrorString.exceptionString(recognizer, e); RuleContext ctx = e.getCtx(); if (ctx == null) { Token tk = e.getOffendingToken(); sp.reportError(msg, tk); } else { sp.reportError(msg, ctx); } } }); return sp; } public void compile(AstLoader astLoader) { this.astLoader = astLoader; this.typeSystem = new TypeSystem(astLoader); parser.addParseListener(parseTreeListener); this.context = parser.compiliantUnit(); visit(context); parser.removeParseListener(parseTreeListener); } public SourceParser(String className, KalangParser parser) { this.className = className; this.classPath = ""; this.parser = parser; tokens = parser.getTokenStream(); if (className.contains(".")) { classPath = className.substring(0, className.lastIndexOf('.')); } cls = ClassNode.create(); } @Override public Object visit(ParseTree tree) { if (tree == null) { System.err.println("visit null"); return null; } return super.visit(tree); } public void importPackage(String packageName) { this.importPaths.add(packageName); } public Position getLocation(Token token) { return getLocation(token, token); } public Position getLocation(Token token, Token token2) { Position loc = new Position(); loc.offset = token.getStartIndex(); loc.length = token2.getStopIndex() - loc.offset + 1; return loc; } public Position getLocation(ParseTree tree) { Interval itv = tree.getSourceInterval(); int a = itv.a; int b = itv.b; if (a > b) { b = a; } Token t = tokens.get(a); Token tt = tokens.get(b); return getLocation(t, tt); } public Position getLocation(AstNode node) { ParseTree tree = this.a2p.get(node); if (tree != null) { return getLocation(tree); } return null; } void newVarStack() { if (vtb != null) { vtb = new VarTable<String, VarDeclStmt>(vtb); } else { vtb = new VarTable<String, VarDeclStmt>(); } } void popVarStack() { vtb = vtb.getParent(); } public Map<AstNode, ParseTree> getParseTreeMap() { return this.a2p; } public ClassNode getAst() { return this.cls; } private void map(AstNode node,ParseTree tree){ a2p.put(node,tree); } @Override public MultiStmtExpr visitMapExpr(KalangParser.MapExprContext ctx) { return visitMap(ctx.map()); } @Override public MultiStmtExpr visitListOrArrayExpr(KalangParser.ListOrArrayExprContext ctx) { return visitListOrArray(ctx.listOrArray()); } @Override public MultiStmtExpr visitMap(KalangParser.MapContext ctx) { MultiStmtExpr mse = MultiStmtExpr.create(); VarObject vo = new VarObject(); VarDeclStmt vds = new VarDeclStmt(vo); vo.type = MAP_CLASS; NewExpr initExpr = new NewExpr(); initExpr.type = vo.type; vo.initExpr = initExpr; mse.stmts.add(vds); VarExpr ve = new VarExpr(vo); List<TerminalNode> ids = ctx.Identifier(); for (int i = 0; i < ids.size(); i++) { ExpressionContext e = ctx.expression(i); ExprNode v = (ExprNode) visit(e); InvocationExpr iv = new InvocationExpr(); iv.target = ve; iv.methodName = "put"; ConstExpr k = new ConstExpr(); k.type = this.typeSystem.getStringClass();// STRING_CLASS; k.value = ctx.Identifier(i).getText(); iv.arguments.add(k); iv.arguments.add(v); ExprStmt es = new ExprStmt(iv); mse.stmts.add(es); } mse.reference = ve; map(mse,ctx); //TODO set generic type return mse; } @Override public MultiStmtExpr visitListOrArray(KalangParser.ListOrArrayContext ctx) { MultiStmtExpr mse = MultiStmtExpr.create(); String clsName = DEFAULT_LIST_CLASS; VarObject vo = new VarObject(); VarDeclStmt vds = new VarDeclStmt(vo); vo.type = clsName; NewExpr initExpr = new NewExpr(); initExpr.type = vo.type; vo.initExpr = initExpr; mse.stmts.add(vds); //addCode(vds, ctx); VarExpr ve = new VarExpr(vo); for (ExpressionContext e : ctx.expression()) { InvocationExpr iv = new InvocationExpr(); iv.target = ve; iv.methodName = "add"; iv.arguments.add((ExprNode) visit(e)); mse.stmts.add(new ExprStmt(iv)); } mse.reference = ve; //TODO set generic type map(mse,ctx); return mse; } @Override public AstNode visitExprNewArray(KalangParser.ExprNewArrayContext ctx) { NewArrayExpr nae = new NewArrayExpr(); nae.size = (ExprNode) visit(ctx.expression()); nae.type = checkFullType(ctx.noArrayType().getText(), ctx); a2p.put(nae, ctx); return nae; } @Override public AstNode visitNoArrayType(KalangParser.NoArrayTypeContext ctx) { //do nothing return null; } @Override public AstNode visitExprQuestion(KalangParser.ExprQuestionContext ctx) { MultiStmtExpr mse = MultiStmtExpr.create(); VarObject vo = new VarObject(); VarDeclStmt vds = new VarDeclStmt(vo); mse.stmts.add(vds); //addCode(vds, ctx); VarExpr ve = new VarExpr(vo); IfStmt is = new IfStmt(); is.conditionExpr = (ExprNode) visit(ctx.expression(0)); is.trueBody = new ExprStmt(new AssignExpr(ve, (ExprNode) visit(ctx.expression(1)))); is.falseBody = new ExprStmt(new AssignExpr(ve, (ExprNode) visit(ctx.expression(2)))); mse.reference = ve; //addCode(is, ctx); a2p.put(ve, ctx); return mse; } @Override public AstNode visitPostIfStmt(KalangParser.PostIfStmtContext ctx) { ExprNode leftExpr = visitExpression(ctx.expression(0)); if (!(leftExpr instanceof AssignExpr)) { this.reportError("AssignExpr required", ctx); } AssignExpr assignExpr = (AssignExpr) leftExpr; ExprNode to = assignExpr.to; ExprNode from = assignExpr.from; ExprNode cond = visitExpression(ctx.expression(1)); Token op = ctx.op; if (op != null) { String opStr = op.getText(); BinaryExpr be = new BinaryExpr(to, cond, opStr); cond = be; } AssignExpr as = new AssignExpr(); as.from = from; as.to = to; IfStmt is = new IfStmt(); is.conditionExpr = cond; is.trueBody = new ExprStmt(as); //addCode(is, ctx); map(is,ctx); return is; } @Override public AstNode visitCompiliantUnit(CompiliantUnitContext ctx) { this.visitAll(ctx.importDecl()); cls.name = this.className; cls.modifier = parseModifier(ctx.varModifier()); String classType = ctx.classType.getText(); if (classType.equals("interface")) { cls.isInterface = true; } if (ctx.parentClass != null) { cls.parentName = this.checkFullType(ctx.parentClass.getText(), ctx); } if (ctx.interfaces != null && ctx.interfaces.size() > 0) { for (Token itf : ctx.interfaces) { String iType = checkFullType(itf.getText(), ctx); if(iType!=null){ cls.interfaces.add(iType); } } } visitClassBody(ctx.classBody()); a2p.put(cls, ctx); return null; } @Override public AstNode visitClassBody(ClassBodyContext ctx) { this.newVarStack(); this.visitChildren(ctx); this.popVarStack(); a2p.put(cls, ctx); return null; } @Override public List<VarObject> visitFieldDecl(FieldDeclContext ctx) { List<VarObject> list = visitVarDecls(ctx.varDecls()); int mdf = this.parseModifier(ctx.varModifier()); if(cls.fields==null){ cls.fields = new LinkedList(); } for (VarObject v : list) { v.modifier = mdf; cls.fields.add(v); } return list; } @Override public AstNode visitMethodDecl(MethodDeclContext ctx) { method = MethodNode.create(); this.newVarStack(); String name; String type; int mdf = parseModifier(ctx.varModifier()); if (ctx.prefix != null && ctx.prefix.getText().equals("constructor")) { type = this.className; name = "<init>"; mdf = mdf | Modifier.STATIC; } else { if (ctx.type() == null) { type = "void"; } else { type = checkFullType(ctx.type().getText(), ctx); } name = ctx.name.getText(); } method.modifier = mdf; method.type = type; method.name = name; if (ctx.varDecls() != null) { List<VarObject> vars = visitVarDecls(ctx.varDecls()); method.parameters.addAll(vars); } if (ctx.stat() != null) { method.body = visitStat(ctx.stat()); } if (ctx.exceptionTypes != null) { for (Token et : ctx.exceptionTypes) { String eFullType = this.checkFullType(et.getText(), ctx); method.exceptionTypes.add(eFullType); } } this.popVarStack(); cls.methods.add(method); a2p.put(method, ctx); return method; } @Override public AstNode visitType(TypeContext ctx) { //do nothing return null; } public void visitAll(List<? extends ParseTree> list) { for (ParseTree i : list) { visit(i); } } @Override public AstNode visitIfStat(IfStatContext ctx) { IfStmt ifStmt = new IfStmt(); ExprNode expr = visitExpression(ctx.expression()); ifStmt.conditionExpr = expr; if (ctx.trueStmt != null) { ifStmt.trueBody = visitStat(ctx.trueStmt); } if (ctx.falseStmt != null) { ifStmt.falseBody = visitStat(ctx.falseStmt); } map(ifStmt,ctx); return ifStmt; } private ExprNode visitExpression(ExpressionContext expression) { return (ExprNode) visit(expression); } @Override public Statement visitStat(StatContext ctx) { //visitChildren(ctx); return (Statement) visit(ctx.getChild(0)); } @Override public AstNode visitReturnStat(ReturnStatContext ctx) { ReturnStmt rs = new ReturnStmt(); if (ctx.expression() != null) { rs.expr = visitExpression(ctx.expression()); } map(rs,ctx); return rs; } @Override public VarDeclStmt visitVarDeclStat(VarDeclStatContext ctx) { //List<VarDeclStmt> list = new LinkedList(); VarObject var = this.visitVarDecl(ctx.varDecl()); VarDeclStmt vds = new VarDeclStmt(var); vtb.put(var.name, vds); map(vds,ctx); return vds; } @Override public VarObject visitVarDecl(VarDeclContext ctx) { String name = ctx.name.getText(); String type = DEFAULT_VAR_TYPE; if (ctx.varType != null) { type = ctx.varType.getText(); } else if (ctx.type() != null) { type = ctx.type().getText(); } if (type != null) { type = checkFullType(type, ctx); } ExprNode namedNode = this.getNodeByName(name); if (namedNode != null) { String msg = null; if (namedNode instanceof ClassExpr) { msg = "Can't use class name as variable name:" + name; } else if (namedNode instanceof ParameterExpr) { msg = "Variable was definded in parameters:" + name; } else if (namedNode instanceof VarExpr) { msg = "Variable was definded already:" + name; } if (msg != null) { reportError(msg, ctx); } } VarObject vds = new VarObject(); vds.name = name; vds.type = type; if (ctx.expression() != null) { vds.initExpr = (ExprNode) visit(ctx.expression()); } map(vds,ctx); return vds; } private void reportError(String msg, Token token,ParseTree tree) { SemanticErrorException see = new SemanticErrorException(msg, token,tree,this); semanticErrorHandler.handleSemanticError(see); // ParseError error = new ParseError(msg, this.getLocation(token)); // System.err.println(error.getMessage()); } private void reportError(String string, ParseTree tree) { int a = tree.getSourceInterval().a; reportError(string, tokens.get(a),tree); } private void reportError(String string, Token token) { reportError(string, token,token2tree.get(token)); } @Override public AstNode visitBreakStat(BreakStatContext ctx) { BreakStmt bs = new BreakStmt(); map(bs,ctx); return bs; } @Override public AstNode visitContinueStat(ContinueStatContext ctx) { ContinueStmt cs = new ContinueStmt(); map(cs,ctx); return cs; } @Override public AstNode visitWhileStat(WhileStatContext ctx) { LoopStmt ws = new LoopStmt(); ws.preConditionExpr = visitExpression(ctx.expression()); if (ctx.stat() != null) { ws.loopBody = visitStat(ctx.stat()); } map(ws,ctx); return ws; } @Override public AstNode visitDoWhileStat(DoWhileStatContext ctx) { LoopStmt ls = new LoopStmt(); if (ctx.stat() != null) { this.newVarStack(); ls.loopBody = visitStat(ctx.stat()); this.popVarStack(); } ls.postConditionExpr = (ExprNode) visit(ctx.expression()); map(ls,ctx); return ls; } @Override public AstNode visitForStat(ForStatContext ctx) { this.newVarStack(); LoopStmt ls = LoopStmt.create(); List<VarObject> vars = visitVarDecls(ctx.varDecls()); for(VarObject v:vars){ VarDeclStmt vds = new VarDeclStmt(v); vtb.put(v.name, vds); ls.initStmts.add(vds); } ls.preConditionExpr = (ExprNode) visit(ctx.expression()); //TODO fixme BlockStmt bs = BlockStmt.create(); if (ctx.stat() != null) { Statement st = visitStat(ctx.stat()); if(st instanceof BlockStmt){ bs.statements.addAll(((BlockStmt)st).statements); } } if(ctx.expressions()!=null){ bs.statements.addAll(visitExpressions(ctx.expressions())); } ls.loopBody = bs; this.popVarStack(); map(ls,ctx); return ls; } @Override public List<Statement> visitExpressions(ExpressionsContext ctx) { List<Statement> list = new LinkedList(); for (ExpressionContext e : ctx.expression()) { ExprNode expr = visitExpression(e); //addCode(new ExprStmt(expr), ctx); list.add(new ExprStmt(expr)); } return list; } @Override public AstNode visitExprStat(ExprStatContext ctx) { AstNode expr = visitExpression(ctx.expression()); ExprStmt es = new ExprStmt(); es.expr = (ExprNode) expr; map(es,ctx); return es; } @Override public InvocationExpr visitExprMemberInvocation(ExprMemberInvocationContext ctx) { String methodName; ExprNode target; if (ctx.key != null) { target = new KeyExpr(ctx.key.getText()); methodName = "<init>"; } else { methodName = ctx.Identifier().getText(); target = null; } InvocationExpr ie = this.getInvocationExpr( target, methodName, ctx.arguments()); a2p.put(ie, ctx); return ie; } @Override public AssignExpr visitExprAssign(ExprAssignContext ctx) { String assignOp = ctx.getChild(1).getText(); ExprNode to = visitExpression(ctx.expression(0)); ExprNode from = visitExpression(ctx.expression(1)); if (assignOp.length() > 1) { String op = assignOp.substring(0, assignOp.length() - 1); from = new BinaryExpr(to, from, op); } AssignExpr aexpr = new AssignExpr(); aexpr.from = (ExprNode) from; aexpr.to = (ExprNode) to; a2p.put(aexpr, ctx); return aexpr; } @Override public AstNode visitExprMidOp(ExprMidOpContext ctx) { String op = ctx.getChild(1).getText(); BinaryExpr be = new BinaryExpr(); be.expr1 = (ExprNode) visitExpression(ctx.expression(0)); be.expr2 = (ExprNode) visitExpression(ctx.expression(1)); be.operation = op; a2p.put(be, ctx); return be; } private InvocationExpr getInvocationExpr(AstNode expr, String methodName, ArgumentsContext argumentsCtx) { InvocationExpr is = new InvocationExpr(); is.methodName = methodName; is.target = (ExprNode) expr; is.arguments = visitArguments(argumentsCtx); return is; } @Override public AstNode visitExprInvocation(ExprInvocationContext ctx) { InvocationExpr ei = this.getInvocationExpr( visitExpression(ctx.expression()), ctx.Identifier().getText(), ctx.arguments()); a2p.put(ei, ctx); return ei; } @Override public AstNode visitExprGetField(ExprGetFieldContext ctx) { AstNode expr = visitExpression(ctx.expression()); String name = ctx.Identifier().getText(); FieldExpr fe = new FieldExpr(); fe.target = (ExprNode) expr; fe.fieldName = name; a2p.put(fe, ctx); return fe; } @Override public AstNode visitExprSelfOp(ExprSelfOpContext ctx) { UnaryExpr ue = new UnaryExpr(); ue.postOperation = ctx.getChild(1).getText(); ue.expr = (ExprNode) visitExpression(ctx.expression()); a2p.put(ue, ctx); return ue; } @Override public UnaryExpr visitExprSelfOpPre(ExprSelfOpPreContext ctx) { String op = ctx.getChild(0).getText(); UnaryExpr ue = new UnaryExpr(); ue.expr = (ExprNode) visitExpression(ctx.expression()); ue.preOperation = op; a2p.put(ue, ctx); return ue; } @Override public ElementExpr visitExprGetArrayElement(ExprGetArrayElementContext ctx) { ElementExpr ee = new ElementExpr(); ee.target = (ExprNode) visitExpression(ctx.expression(0)); ee.key = (ExprNode) visitExpression(ctx.expression(1)); a2p.put(ee, ctx); return ee; } private String checkFullType(String name, ParseTree tree) { if (this.typeSystem.isPrimitiveType(name)) { return name; } String fn = getExistedClassName(name); if (fn == null) { this.reportError("Unknown class:" + name, tree); return DEFAULT_VAR_TYPE; } return fn; } private String getExistedClassName(String name) { String postfix = ""; if (name.endsWith("[]")) { name = name.substring(0, name.length() - 2); postfix = "[]"; } if (fullNames.containsKey(name)) { return fullNames.get(name) + postfix; } else { ClassNode cls = astLoader.getAst(name); if(cls!=null) return name + postfix; for (String p : this.importPaths) { String clsName = p + "." + name; cls = astLoader.getAst(clsName); if (cls != null) { return clsName + postfix; } } } return null; } private ExprNode getNodeByName(String name) { if (vtb.exist(name)) { VarExpr ve = new VarExpr(); VarDeclStmt declStmt = (VarDeclStmt) vtb.get(name); //vars.indexOf(vo); ve.var = declStmt.var; return ve; } else { //find parameters if (method != null && method.parameters != null) { for (VarObject p : method.parameters) { if (p.name.equals(name)) { return new VarExpr(p); } } } if (cls.fields != null) { for (VarObject f : cls.fields) { if (f.name.equals(name)) { FieldExpr fe = new FieldExpr(); fe.fieldName = name; return fe; } } } String clsName = this.getExistedClassName(name); if (clsName!=null) { return new ClassExpr(clsName); } } return null; } @Override public ConstExpr visitLiteral(LiteralContext ctx) { ConstExpr ce = new ConstExpr(); String t = ctx.getText(); if (ctx.IntegerLiteral() != null) { ce.type = typeSystem.getIntPrimitiveType(); ce.value = Integer.parseInt(t); } else if (ctx.FloatingPointLiteral() != null) { ce.type = typeSystem.getFloatPrimitiveType(); ce.value = Float.parseFloat(t); } else if (ctx.BooleanLiteral() != null) { ce.type = typeSystem.getBooleanPrimitiveType(); ce.value = Boolean.parseBoolean(t); } else if (ctx.CharacterLiteral() != null) { ce.type = typeSystem.getCharPrimitiveType(); char[] chars = t.toCharArray(); ce.value = chars[1]; } else if (ctx.StringLiteral() != null) { ce.type = typeSystem.getStringClass(); //TODO parse string ce.value = t.substring(1, t.length() - 1); } else { ce.type = typeSystem.getNullPrimitiveType(); } map(ce,ctx); return ce; } @Override public List<ExprNode> visitArguments(ArgumentsContext ctx) { LinkedList<ExprNode> arguments = new LinkedList(); for (ExpressionContext e : ctx.expression()) { ExprNode expr = visitExpression(e); arguments.add(expr); } return arguments; } @Override public AstNode visitImportDecl(ImportDeclContext ctx) { String name = ctx.name.getText(); String prefix = ""; boolean relative = ctx.root == null || ctx.root.getText().length() == 0; if (relative && this.classPath.length() > 0) { prefix = this.classPath + "."; } if (ctx.path != null) { for (Token p : ctx.path) { prefix += p.getText() + "."; } } if (name.equals("*")) { this.importPaths.add(prefix.substring(0, prefix.length() - 1)); } else { String key = name; if (ctx.alias != null) { key = ctx.alias.getText(); } this.fullNames.put(key, prefix + name); } return null; } @Override public AstNode visitQualifiedName(QualifiedNameContext ctx) { //do nothing return null; } public int parseModifier(VarModifierContext modifier) { //String[] mdfs = modifier.split(" "); if (modifier == null) { return Modifier.PUBLIC; } int m = 0; int access = 0; for (ParseTree c : modifier.children) { String s = c.getText(); if (s.equals("public")) { access = Modifier.PUBLIC; } else if (s.equals("protected")) { access = Modifier.PROTECTED; } else if (s.equals("private")) { access = Modifier.PRIVATE; } else if (s.equals("static")) { m += Modifier.STATIC; } else if (s.equals("final")) { m += Modifier.FINAL; } } if (access == 0) { access = Modifier.PUBLIC; } return m + access; } public Integer getModifier(boolean isPrivated, boolean isProtected) { if (isPrivated) { return Modifier.PRIVATE; } if (isProtected) { return Modifier.PROTECTED; } return Modifier.PUBLIC; } @Override public AstNode visitNewExpr(NewExprContext ctx) { String type = ctx.Identifier().getText(); ClassExpr expr = new ClassExpr(); expr.name = checkFullType(type, ctx); InvocationExpr inv = this.getInvocationExpr(expr, "<init>", ctx.arguments()); map(inv,ctx); return inv; } @Override public AstNode visitCastExpr(CastExprContext ctx) { CastExpr ce = new CastExpr(); ce.expr = visitExpression(ctx.expression()); ce.type = ctx.type().getText(); map(ce,ctx); return ce; } @Override public AstNode visitTryStat(TryStatContext ctx) { TryStmt tryStmt = new TryStmt(); this.newVarStack(); tryStmt.execStmt = visitStat(ctx.tryStmtList); this.popVarStack(); if (ctx.catchTypes != null) { for (int i = 0; i < ctx.catchTypes.size(); i++) { CatchStmt catchStmt =CatchStmt.create(); String vName = ctx.catchVarNames.get(i).getText(); String vType = ctx.catchTypes.get(i).getText(); this.newVarStack(); VarObject vo = new VarObject(); vo.name = vName; vo.type = vType; VarDeclStmt declStmt = new VarDeclStmt(vo); catchStmt.execStmt = visitStat(ctx.catchStmts.get(i)); this.popVarStack(); catchStmt.catchVarDecl = declStmt; tryStmt.catchStmts.add(catchStmt); } } if (ctx.finalStmtList != null) { this.newVarStack(); tryStmt.finallyStmt = visitStat(ctx.finalStmtList); this.popVarStack(); } map(tryStmt,ctx); return tryStmt; } @Override public List<VarObject> visitVarDecls(VarDeclsContext ctx) { List<VarObject> list = new LinkedList(); for (VarDeclContext v : ctx.varDecl()) { list.add(visitVarDecl(v)); } return list; } @Override public AstNode visitExprIdentifier(ExprIdentifierContext ctx) { String name = ctx.Identifier().getText(); ExprNode expr = this.getNodeByName(name); if (expr == null) { this.reportError(name + " is undefined!", ctx); } map(expr,ctx); return expr; } @Override public AstNode visitExprLiteral(ExprLiteralContext ctx) { return visitLiteral(ctx.literal()); } @Override public AstNode visitExprParen(ExprParenContext ctx) { return visitExpression(ctx.expression()); } @Override public AstNode visitBlockStmt(BlockStmtContext ctx) { BlockStmt bs = BlockStmt.create(); if (ctx.stat() == null) { return bs; } for (StatContext s : ctx.stat()) { bs.statements.add(visitStat(s)); } map(bs,ctx); return bs; } @Override public AstNode visitVarModifier(VarModifierContext ctx) { // do nothing return null; } @Override public AstNode visitExprSelfRef(ExprSelfRefContext ctx) { KeyExpr expr = new KeyExpr(ctx.ref.getText()); a2p.put(expr, ctx); return expr; } public String toString(){ return "SourceParser:" + className; } }
package be.viaa.fxp; import java.io.FileNotFoundException; import java.io.IOException; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import be.viaa.util.Strings; /** * FXP implementation of a file transporter * * @author Hannes Lowette * */ public class FxpFileTransporter implements FileTransporter { /** * The logger for this class */ private static final Logger logger = LogManager.getLogger(FxpFileTransporter.class); /** * The maximum amount of retry attempts */ private static final int MAX_RETRY_ATTEMPTS = 10; /** * The amount of times the file size equal check needs to verify */ private static final int FILESIZE_EQUAL_CHECKS = 10; /** * The interval in between 2 file size checks */ private static final long FILESIZE_COMPARE_INTERVAL = 10000L; /** * The executor service */ private final ExecutorService executor = Executors.newCachedThreadPool(); @Override public void transfer(File sourceFile, File destinationFile, Host source, Host destination, boolean move) throws IOException { FxpStatus status = FxpStatus.RUNNING; /* * Debug information */ logger.debug("Attempting file transfer"); logger.debug("Source Host: {}:{}", source.getHost(), source.getPort()); logger.debug("Target Host: {}:{}", source.getHost(), source.getPort()); logger.debug("Source file: {}/{}", sourceFile.getDirectory(), sourceFile.getName()); logger.debug("Target file: {}/{}", destinationFile.getDirectory(), destinationFile.getName()); /* * Attempt 10 times to transfer the file correctly */ for (int attempt = 0; attempt < MAX_RETRY_ATTEMPTS; attempt++) { if ((status = transferSingle(sourceFile, destinationFile, source, destination)) == FxpStatus.OK) { break; } else if (attempt + 1 >= MAX_RETRY_ATTEMPTS) { throw new IOException("file could not be transferred"); } else { logger.info("RETRY {}", attempt); } try { Thread.sleep(10000L); } catch (Exception ex) { ex.printStackTrace(); // This should never happen } } /* * If move is set to true, the source file needs to be deleted */ if (FxpStatus.OK.equals(status) && move) { delete(sourceFile, source); } } @Override public void move(File sourceFile, File destinationFile, Host host) throws IOException { FTPClient client = connect(host); try { logger.debug("attempting to move file"); logger.debug("Host: {}", host.getHost()); logger.debug("Directory: {}", sourceFile.getDirectory()); logger.debug("Source filename: {}", sourceFile.getName()); logger.debug("Target filename: {}", destinationFile.getName()); // /* // * Send the commands that indicate a transaction needs to happen // */ // client.sendCommand("TYPE I"); // /* // * Send the STOR and RETR commands to the corresponding FTP servers // * TODO: Find out why this needs to be on a different thread. // */ // executor.submit(new FxpCommandThread(client, "RNFR " + sourceFile.getDirectory() + "/" + sourceFile.getName())); // executor.submit(new FxpCommandThread(client, "RNTO " + destinationFile.getDirectory() + "/" + destinationFile.getName())); if (client.rename(sourceFile.getDirectory() + "/" + sourceFile.getName(), destinationFile.getDirectory() + "/" + destinationFile.getName())) { logger.info("SUCCESS: moved file from directory '{}' to '{}'", sourceFile.getDirectory(), destinationFile.getDirectory()); } else { throw new IOException("could not move file '" + sourceFile.getDirectory() + "/" + sourceFile.getName() + "' - " + client.getReplyString()); } } catch (IOException ex) { // TODO: Connection to the FTP server has gone wrong logger.catching(ex); } finally { client.disconnect(); } } @Override public void delete(File file, Host host) throws IOException { FTPClient client = connect(host); try { logger.debug("attempting to delete file"); logger.debug("Host: {}:{}", host.getHost(), host.getPort()); logger.debug("File: {}/{}", file.getDirectory(), file.getName()); /* * Check to see if the source file exists and whether it' a file or a directory */ client.changeWorkingDirectory(file.getDirectory()); boolean isDirectory = false; if (containsFile(Arrays.asList(client.listDirectories()), file.getName())) { // This is a directory isDirectory = true; } else { // This might be a file if (!Arrays.asList(client.listNames()).contains(file.getName())) { // No. Nothing exists throw new FileNotFoundException("could not find file " + file.getDirectory() + "/" + file.getName() + " on the FTP server"); } else { isDirectory = true; } } /* * Delete the file or directory from the remote FTP server and return the OK status when successful */ if (!isDirectory) { if (!client.deleteFile(file.getName())) { throw new IOException("could not delete " + file.getDirectory() + "/" + file.getName()); } else { logger.info("SUCCESS: file {}/{} successfully deleted", file.getDirectory(), file.getName()); } } else { // We must delete a directory. Recursively delete all files within it removeDirectory(client, file.getDirectory(), file.getName()); } } finally { client.disconnect(); } } public static boolean containsFile(List<FTPFile> files, String file) { for (FTPFile ftpFile : files) { if (ftpFile.getName().equals(file)) { return true; } } return false; } public static void removeDirectory(FTPClient ftpClient, String parentDir, String currentDir) throws IOException { String dirToList = parentDir; if (!currentDir.equals("")) { dirToList += "/" + currentDir; } FTPFile[] subFiles = ftpClient.listFiles(dirToList); if (subFiles != null && subFiles.length > 0) { for (FTPFile aFile : subFiles) { String currentFileName = aFile.getName(); if (currentFileName.equals(".") || currentFileName.equals("..")) { // skip parent directory and the directory itself continue; } String filePath = parentDir + "/" + currentDir + "/" + currentFileName; if (currentDir.equals("")) { filePath = parentDir + "/" + currentFileName; } if (aFile.isDirectory()) { // remove the sub directory removeDirectory(ftpClient, dirToList, currentFileName); } else { // delete the file boolean deleted = ftpClient.deleteFile(filePath); if (deleted) { logger.info("DELETED the file: " + filePath); } else { logger.info("CANNOT delete the file: " + filePath); throw new IOException("CANNOT delete the file: " + filePath); } } } // finally, remove the directory itself boolean removed = ftpClient.removeDirectory(dirToList); if (removed) { logger.info("REMOVED the directory: " + dirToList); } else { logger.info("CANNOT remove the directory: " + dirToList); throw new IOException("CANNOT remove the directory: " + dirToList); } } } @Override public void rename(File source, File destination, Host host) throws IOException { FTPClient client = connect(host); logger.info("attempting to rename file '{}/{}'", source.getDirectory(), source.getName()); logger.debug("Host: {}:{}", host.getHost(), host.getPort()); logger.debug("New: {}/{}", destination.getDirectory(), destination.getName()); try { client.changeWorkingDirectory(source.getDirectory()); client.rename(source.getName(), destination.getName()); logger.info("SUCCESS: renamed file '{}/{}'", source.getDirectory(), source.getName()); } finally { client.disconnect(); } } private FxpStatus transferSingle(File sourceFile, File destinationFile, Host source, Host destination) throws IOException { FTPClient sourceClient = connect(source); FTPClient targetClient = connect(destination); Future<?> future_source = null; Future<?> future_destination = null; File partFile = destinationFile.derive(destinationFile.getName() + ".part"); try { /* * Send the commands that indicate a transaction needs to happen * TODO: Rework to use short commands? */ targetClient.sendCommand("TYPE I"); sourceClient.sendCommand("TYPE I"); targetClient.sendCommand("PASV"); sourceClient.sendCommand("PORT " + filterPortNumber(targetClient.getReplyString())); /* * Transfer the file data */ createDirectoryTree(destinationFile, targetClient); createDirectoryTree(sourceFile, sourceClient); /* * Send the STOR and RETR commands to the corresponding FTP servers. */ logger.debug("sending store and retreive commands"); future_destination = executor.submit(new FxpCommandThread(targetClient, "STOR " + partFile.getName())); future_source = executor.submit(new FxpCommandThread(sourceClient, "RETR " + sourceFile.getName())); /* * Periodically check the size of the partfile and compare it to the size of the file that * is being transferred. */ AtomicInteger counter = new AtomicInteger(); AtomicLong currentSize = new AtomicLong(); AtomicLong expectedSize = new AtomicLong(get(sourceFile, source).getSize()); while (currentSize.get() != expectedSize.get() && counter.get() <= FILESIZE_EQUAL_CHECKS) { Thread.sleep(FILESIZE_COMPARE_INTERVAL); long filesize = get(partFile, destination).getSize(); if (filesize == currentSize.get()) { // If these are equal, the file hasn't progressed at all in 30 seconds counter.incrementAndGet(); } currentSize.set(filesize); logger.info("Transfer progress: {}", ((float) currentSize.get() * 100) / ((float) expectedSize.get())); } /* * Check to see if the file sizes are different */ if (expectedSize.get() != get(partFile, destination).getSize()) { // TODO: the files have not successfully transferred logger.warn("ERROR: could not transfer file {}/{}", sourceFile.getDirectory(), sourceFile.getName()); return FxpStatus.ERROR; } /* * If they aren't, we can assume the files are equal */ else { rename(partFile, destinationFile, destination); logger.info("SUCCESS: file {}/{} transferred", sourceFile.getDirectory(), sourceFile.getName()); return FxpStatus.OK; } } catch (Exception ex) { logger.catching(ex); return FxpStatus.ERROR; } finally { sourceClient.disconnect(); targetClient.disconnect(); future_source.cancel(true); future_destination.cancel(true); } } /** * Attempts to create the directory structure of the given file * * @param file * @param client * @return * @throws IOException */ private boolean createDirectoryTree(File file, FTPClient client) throws IOException { Deque<String> directoryStructure = new LinkedList<>(Arrays.asList(file.getDirectory().split("/"))); Deque<String> directoryUnexistant = new LinkedList<>(); logger.debug("creating directory tree for {}", file.getDirectory()); /* * Scans to see which directory is already present and which directories * need to be created. */ while (!directoryStructure.isEmpty()) { if (!client.changeWorkingDirectory(Strings.join("/", directoryStructure))) { directoryUnexistant.addFirst(directoryStructure.removeLast()); } else break; } logger.debug("folders to be created: {}", Strings.join("/", directoryUnexistant)); /* * Creates the directories that need to be created */ for (Iterator<String> iterator = directoryUnexistant.iterator(); iterator.hasNext();) { String directory = iterator.next(); if (!client.makeDirectory(directory) || !client.changeWorkingDirectory(directory)) { throw new IOException("could not create directory tree"); } } return true; } /** * * @param client * @param host * @return * @throws IOException */ private FTPClient connect(Host host) throws IOException { FTPClient client = new FTPClient(); client.setControlEncoding("UTF8"); try { logger.debug("connecting to {}:{}", host.getHost(), host.getPort()); /* * Attempt to establish a connection */ client.connect(host.getHost(), host.getPort()); client.enterLocalPassiveMode(); logger.debug("made connection with {}:{}", host.getHost(), host.getPort()); /* * Attempt to authenticate on the remote server */ if (!client.login(host.getUsername(), host.getPassword())) { throw new IOException("invalid credentials for the source FTP"); } logger.debug("successfully authenticated with {}:{}", host.getHost(), host.getPort()); /* * Send both of the FTP hosts to see if they are reachable */ if (!client.isConnected() || !client.isAvailable()) { throw new IOException("ftp connection not available"); } return client; } catch (Exception ex) { if (client.isConnected()) client.disconnect(); throw new IOException("could not connect to " + host.getHost() + ":" + host.getPort(), ex); } } /** * Gets a remote FTP file by its name * * @param file * @param client * @return */ private FTPFile get(File file, Host host) throws IOException { FTPClient client = connect(host); try { logger.debug("looking up file {}/{} on {}:{}", file.getDirectory(), file.getName(), host.getHost(), host.getPort()); client.changeWorkingDirectory(file.getDirectory()); FTPFile[] files = client.listFiles(file.getName()); if (files == null || files.length == 0) { throw new FileNotFoundException("file '" + file.getDirectory() + "/" + file.getName() + "' not found on '" + client.getRemoteAddress().getHostAddress() + "'"); } if (files.length == 1) { return files[0]; } throw new FileNotFoundException("ambiguous filename"); } finally { client.disconnect(); } } /** * Support method that is used to retrieve the port number that is received * in a string in between 2 parentheses * * @param input * @return */ private final String filterPortNumber(String input) { return input.substring(input.indexOf("(") + 1, input.indexOf(")")); } }
package com.trikke.writer; import com.trikke.data.*; import com.trikke.util.SqlUtil; import com.trikke.util.Util; import javax.lang.model.element.Modifier; import java.io.IOException; import java.util.ArrayList; import java.util.EnumSet; import java.util.Iterator; public class CRUDClientWriter extends Writer { private final Model mModel; public CRUDClientWriter( String directory, Model model ) throws IOException { super( directory, model, model.getCRUDClientName() ); this.mModel = model; } @Override public void compile() throws Exception { writer.emitPackage( mModel.getClassPackage() ); emitImports(); emitClass(); emitMethods(); writer.endType(); writer.close(); } private void emitImports() throws IOException { writer.emitImports( "android.content.*", "android.database.Cursor", "android.net.Uri", "java.util.ArrayList", "android.os.RemoteException" ); writer.emitEmptyLine(); } private void emitClass() throws IOException { writer.beginType( mModel.getClassPackage() + "." + mModel.getCRUDClientName(), "class", EnumSet.of( Modifier.PUBLIC, Modifier.FINAL ) ); } private void emitMethods() throws Exception { for ( Table table : mModel.getTables() ) { emitTableCRUD( table ); } writer.emitEmptyLine(); writer.emitJavadoc( "Simple get operations for Views" ); for ( View view : mModel.getViews() ) { emitViewCRUD( view ); } } private void emitViewCRUD( View view ) throws Exception { ArrayList<String> paramsWhere = new ArrayList<String>(); paramsWhere.add( "Context" ); paramsWhere.add( "c" ); paramsWhere.add( "String" ); paramsWhere.add( "rowname" ); paramsWhere.add( "Object" ); paramsWhere.add( "queryvalue" ); // Normal Get with UNIQUE writer.emitEmptyLine(); writer.beginMethod( "Cursor", "get" + Util.capitalize( view.name ) + "With", EnumSet.of( Modifier.PUBLIC, Modifier.STATIC ), paramsWhere.toArray( new String[paramsWhere.size()] ) ); writer.emitStatement( "ContentResolver cr = c.getContentResolver()" ); writer.emitStatement( "return cr.query(" + mModel.getContentProviderName() + "." + SqlUtil.URI( view ) + ", null, rowname + \"=?\", new String[]{String.valueOf(queryvalue)},null)" ); writer.endMethod(); } private void emitTableCRUD( Table table ) throws Exception { // Default array params for all rows ArrayList<String> params = new ArrayList<String>(); for ( Field row : table.fields ) { params.add( SqlUtil.getJavaTypeFor( row.type ) ); params.add( row.name ); } ArrayList<String> paramsJustContext = new ArrayList<String>(); paramsJustContext.add( "Context" ); paramsJustContext.add( "c" ); ArrayList<String> paramsWithContext = new ArrayList<String>(); paramsWithContext.addAll( paramsJustContext ); paramsWithContext.addAll( params ); ArrayList<String> updateParams = new ArrayList<String>(); updateParams.add( "Context" ); updateParams.add( "c" ); updateParams.add( SqlUtil.getJavaTypeFor( table.getPrimaryKey().type ) ); updateParams.add( table.getPrimaryKey().name ); updateParams.addAll( params ); writer.emitEmptyLine(); writer.emitJavadoc( table.name + " OPERATIONS" ); writer.emitEmptyLine(); Iterator<Constraint> constraintiter; // Gets writeGetWith( table, table.getPrimaryKey() ); constraintiter = table.constraints.iterator(); while ( constraintiter.hasNext() ) { Constraint constraint = constraintiter.next(); if ( constraint.type.equals( Constraint.Type.UNIQUE ) ) { final String[] fields = SqlUtil.getFieldsFromConstraint( constraint ); for ( int i = 0; i < fields.length; i++ ) { writeGetWith( table, table.getFieldByName( fields[i] ) ); } } } // Normal Add writer.emitEmptyLine(); writer.beginMethod( "Uri", "add" + Util.capitalize( table.name ), EnumSet.of( Modifier.PUBLIC, Modifier.STATIC ), paramsWithContext.toArray( new String[paramsWithContext.size()] ) ); writer.emitStatement( "ContentValues contentValues = new ContentValues()" ); for ( Field row : table.fields ) { writer.emitStatement( "contentValues.put(" + mModel.getDbClassName() + "." + SqlUtil.ROW_COLUMN( table, row ) + "," + row.name + ")" ); } writer.emitStatement( "ContentResolver cr = c.getContentResolver()" ); writer.emitStatement( "return cr.insert(" + mModel.getContentProviderName() + "." + SqlUtil.URI( table ) + ", contentValues)" ); writer.endMethod(); // Removes writeRemoveWith( table, table.getPrimaryKey() ); constraintiter = table.constraints.iterator(); while ( constraintiter.hasNext() ) { Constraint constraint = constraintiter.next(); if ( constraint.type.equals( Constraint.Type.UNIQUE ) ) { final String[] fields = SqlUtil.getFieldsFromConstraint( constraint ); for ( int i = 0; i < fields.length; i++ ) { writeRemoveWith( table, table.getFieldByName( fields[i] ) ); } } } // Remove All results writer.emitEmptyLine(); writer.beginMethod( "int", "removeAll" + Util.capitalize( table.name ), EnumSet.of( Modifier.PUBLIC, Modifier.STATIC ), "Context", "c" ); writer.emitStatement( "ContentResolver cr = c.getContentResolver()" ); writer.emitStatement( "return cr.delete(" + mModel.getContentProviderName() + "." + SqlUtil.URI( table ) + ", null, null)" ); writer.endMethod(); // Get All results writer.emitEmptyLine(); writer.beginMethod( "Cursor", "getAll" + Util.capitalize( table.name ), EnumSet.of( Modifier.PUBLIC, Modifier.STATIC ), "Context", "c" ); writer.emitStatement( "ContentResolver cr = c.getContentResolver()" ); String arrays = mModel.getDbClassName() + "." + SqlUtil.ROW_COLUMN( table, Table.getDefaultAndroidIdField() ) + ",\n"; for ( Field row : table.fields ) { arrays += mModel.getDbClassName() + "." + SqlUtil.ROW_COLUMN( table, row ) + ",\n"; } writer.emitStatement( "String[] result_columns = new String[]{\n" + arrays + "}" ); writer.emitStatement( "String where = null" ); writer.emitStatement( "String whereArgs[] = null" ); writer.emitStatement( "String order = null" ); writer.emitStatement( "Cursor resultCursor = cr.query(" + mModel.getContentProviderName() + "." + SqlUtil.URI( table ) + ", result_columns, where, whereArgs, order)" ); writer.emitStatement( "return resultCursor" ); writer.endMethod(); // Normal Update writer.emitEmptyLine(); writer.beginMethod( "int", "update" + Util.capitalize( table.name ), EnumSet.of( Modifier.PUBLIC, Modifier.STATIC ), updateParams.toArray( new String[updateParams.size()] ) ); writer.emitStatement( "ContentValues contentValues = new ContentValues()" ); for ( Field row : table.fields ) { writer.emitStatement( "contentValues.put(" + mModel.getDbClassName() + "." + SqlUtil.ROW_COLUMN( table, row ) + "," + row.name + ")" ); } writer.emitStatement( "Uri rowURI = ContentUris.withAppendedId(" + mModel.getContentProviderName() + "." + SqlUtil.URI( table ) + "," + table.getPrimaryKey().name + ")" ); writer.emitStatement( "String where = null" ); writer.emitStatement( "String whereArgs[] = null" ); writer.emitStatement( "ContentResolver cr = c.getContentResolver()" ); writer.emitStatement( "return cr.update(rowURI, contentValues, where, whereArgs)" ); writer.endMethod(); // Update where writeUpdateWhere( table, table.getPrimaryKey() ); constraintiter = table.constraints.iterator(); while ( constraintiter.hasNext() ) { Constraint constraint = constraintiter.next(); if ( constraint.type.equals( Constraint.Type.UNIQUE ) ) { final String[] fields = SqlUtil.getFieldsFromConstraint( constraint ); for ( int i = 0; i < fields.length; i++ ) { writeUpdateWhere( table, table.getFieldByName( fields[i] ) ); } } } } private void writeGetWith( Table table, Field field ) throws IOException { ArrayList<String> params = new ArrayList<String>(); params.add( "Context" ); params.add( "c" ); params.add( SqlUtil.getJavaTypeFor( field.type ) ); params.add( field.name ); writer.emitEmptyLine(); writer.beginMethod( "Cursor", "get" + Util.capitalize( table.name ) + "With" + Util.capitalize( field.name ), EnumSet.of( Modifier.PUBLIC, Modifier.STATIC ), params.toArray( new String[params.size()] ) ); writer.emitStatement( "ContentResolver cr = c.getContentResolver()" ); writer.emitStatement( "return cr.query(" + mModel.getContentProviderName() + "." + SqlUtil.URI( table ) + ", null, " + mModel.getDbClassName() + "." + SqlUtil.ROW_COLUMN( table, field ) + " + \"=?\", new String[]{String.valueOf(" + field.name + ")},null)" ); writer.endMethod(); } private void writeRemoveWith( Table table, Field field ) throws IOException { ArrayList<String> params = new ArrayList<String>(); params.add( "Context" ); params.add( "c" ); params.add( SqlUtil.getJavaTypeFor( field.type ) ); params.add( field.name ); // Normal remove with primary writer.emitEmptyLine(); writer.beginMethod( "int", "remove" + Util.capitalize( table.name ) + "With" + Util.capitalize( field.name ), EnumSet.of( Modifier.PUBLIC, Modifier.STATIC ), params.toArray( new String[params.size()] ) ); writer.emitStatement( "ContentResolver cr = c.getContentResolver()" ); writer.emitStatement( "return cr.delete(" + mModel.getContentProviderName() + "." + SqlUtil.URI( table ) + ", " + mModel.getDbClassName() + "." + SqlUtil.ROW_COLUMN( table, field ) + " + \"=?\", new String[]{String.valueOf(" + field.name + ")})" ); writer.endMethod(); } private void writeUpdateWhere( Table table, Field field ) throws IOException { ArrayList<String> params = new ArrayList<String>(); params.add( "Context" ); params.add( "c" ); params.add( SqlUtil.getJavaTypeFor( field.type ) ); params.add( field.name ); // Default array params for all rows for ( Field row : table.fields ) { if ( row.equals( field ) ) { continue; } params.add( SqlUtil.getJavaTypeFor( row.type ) ); params.add( row.name ); } // Update with where clause writer.emitEmptyLine(); writer.beginMethod( "int", "update" + Util.capitalize( table.name ) + "Where" + Util.capitalize( field.name ), EnumSet.of( Modifier.PUBLIC, Modifier.STATIC ), params.toArray( new String[params.size()] ) ); writer.emitStatement( "ContentValues contentValues = new ContentValues()" ); for ( Field row : table.fields ) { writer.emitStatement( "contentValues.put(" + mModel.getDbClassName() + "." + SqlUtil.ROW_COLUMN( table, row ) + "," + row.name + ")" ); } writer.emitStatement( "Uri rowURI = " + mModel.getContentProviderName() + "." + SqlUtil.URI( table ) ); writer.emitStatement( "String where = " + mModel.getDbClassName() + "." + SqlUtil.ROW_COLUMN( table, field ) + " + \"=?\"" ); writer.emitStatement( "String whereArgs[] = new String[]{String.valueOf(" + field.name + ")}" ); writer.emitStatement( "ContentResolver cr = c.getContentResolver()" ); writer.emitStatement( "return cr.update(rowURI, contentValues, where, whereArgs)" ); writer.endMethod(); } }
package ch.bind.philib.lang; import java.util.concurrent.atomic.AtomicLong; import ch.bind.philib.validation.SimpleValidation; public final class ThreadUtil { private static final PhiLog LOG = PhiLog.getLogger(ThreadUtil.class); public static final long DEFAULT_JOIN_TIMEOUT_MS = 1000L; private ThreadUtil() { } public static void sleepUntilMs(long time) throws InterruptedException { long diff = time - System.currentTimeMillis(); if (diff <= 0) { return; } else { Thread.sleep(diff); } } public static boolean interruptAndJoin(Thread t) { return interruptAndJoin(t, DEFAULT_JOIN_TIMEOUT_MS); } public static boolean interruptAndJoin(Thread t, long waitTime) { if (t == null) return true; if (!t.isAlive()) return true; t.interrupt(); try { t.join(waitTime); } catch (InterruptedException e) { LOG.warn("interrupted while waiting for a thread to finish: " + e.getMessage(), e); } if (t.isAlive()) { LOG.warn("thread is still alive: " + t.getName()); return false; } else { return true; } } private static final AtomicLong FOREVER_RUNNER_SEQ = new AtomicLong(1); private static final String FOREVER_RUNNER_NAME_FMT = "%s-for-%s-%d"; // TODO: documentation public static Thread runForever(Runnable runnable) { SimpleValidation.notNull(runnable); String threadName = String.format(FOREVER_RUNNER_NAME_FMT, ForeverRunner.class.getSimpleName(), runnable.getClass().getSimpleName(), FOREVER_RUNNER_SEQ.getAndIncrement()); return runForever(runnable, threadName); } // TODO: documentation public static Thread runForever(Runnable runnable, String threadName) { return runForever(null, runnable, threadName); } // TODO: documentation public static Thread runForever(ThreadGroup group, Runnable runnable, String threadName) { // stackSize of 0 stands for: ignore this parameter return runForever(null, runnable, threadName, 0); } // TODO: documentation public static Thread runForever(ThreadGroup group, Runnable runnable, String threadName, long stackSize) { SimpleValidation.notNull(runnable); SimpleValidation.notNull(threadName); ForeverRunner runner = new ForeverRunner(threadName, runnable); Thread t = new Thread(group, runner, threadName, stackSize); t.start(); return t; } private static final class ForeverRunner implements Runnable { private final String threadName; private final Runnable runnable; public ForeverRunner(String threadName, Runnable runnable) { this.threadName = threadName; this.runnable = runnable; } @Override public void run() { while (true) { try { runnable.run(); // regular shutdown return; } catch (Exception e) { if (e instanceof InterruptedException) { // externally requested shutdown return; } else { LOG.info("runnable crashed, restarting it. thread-name=" + threadName, e); } } } } } }
package com.valkryst.AsciiPanel; import com.valkryst.AsciiPanel.component.AsciiScreen; import com.valkryst.AsciiPanel.font.AsciiFont; import com.valkryst.radio.Radio; import com.valkryst.radio.Receiver; import lombok.Getter; import java.awt.*; public class AsciiPanel extends Canvas implements Receiver<String> { /** The width of the panel, in characters. */ @Getter private int widthInCharacters; /** The height of the panel, in characters. */ @Getter private int heightInCharacters; /** The asciiFont to draw with. */ @Getter private AsciiFont asciiFont; /** The cursor. */ @Getter private final AsciiCursor asciiCursor = new AsciiCursor(this); /** The screen being displayed on the panel. */ @Getter private AsciiScreen currentScreen; @Getter private Radio<String> radio = new Radio<>(); /** * Constructs a new AsciiPanel. * * @param widthInCharacters * The width of the panel, in characters. * * @param heightInCharacters * The height of the panel, in characters. * * @param asciiFont * The asciiFont to use. */ public AsciiPanel(int widthInCharacters, int heightInCharacters, final AsciiFont asciiFont) throws NullPointerException { if (asciiFont == null) { throw new NullPointerException("You must specify an asciiFont to use."); } if (widthInCharacters < 1) { widthInCharacters = 1; } if (heightInCharacters < 1) { heightInCharacters = 1; } this.asciiFont = asciiFont; this.widthInCharacters = widthInCharacters; this.heightInCharacters = heightInCharacters; this.setSize(widthInCharacters * asciiFont.getWidth(), heightInCharacters * asciiFont.getHeight()); currentScreen = new AsciiScreen(0, 0, widthInCharacters, heightInCharacters); radio.addReceiver("DRAW", this); } @Override public void receive(final String event, final String data) { if (event.equals("DRAW")) { draw(); } } /** Draws every character of every row onto the canvas. */ public void draw() { currentScreen.draw(this, asciiFont); } /** * Determines whether or not the specified position is within the bounds of the panel. * * @param columnIndex * The x-axis (column) coordinate. * * @param rowIndex * The y-axis (row) coordinate. * * @return * Whether or not the specified position is within the bounds of the panel. */ public boolean isPositionValid(final int columnIndex, final int rowIndex) { boolean isWithinBounds = rowIndex >= 0; isWithinBounds &= rowIndex < heightInCharacters; isWithinBounds &= columnIndex >= 0; isWithinBounds &= columnIndex < widthInCharacters; return isWithinBounds; } /** * Swaps-out the current screen for the new screen. * * @param newScreen * The new screen to swap-in. * * @return * The swapped-out screen. */ public AsciiScreen swapScreen(final AsciiScreen newScreen) { final AsciiScreen oldScreen = currentScreen; currentScreen = newScreen; draw(); return oldScreen; } }
package co.arcs.groove.thresher; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringReader; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.annotation.Nullable; import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicHeader; import org.apache.http.util.EntityUtils; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.base.Charsets; import com.google.common.collect.Lists; import com.google.common.io.CharStreams; public class Client { static final String DOMAIN = "grooveshark.com"; private static final int TIMEOUT = 10000; private boolean debugLogging = false; final HttpClient httpClient; final ObjectMapper jsonMapper; private Session session; public Client() { PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setDefaultMaxPerRoute(2); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT) .setSocketTimeout(TIMEOUT).setConnectionRequestTimeout(TIMEOUT).build(); List<BasicHeader> headers = Lists.newArrayList(new BasicHeader(HttpHeaders.CONNECTION, "close"), new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "gzip,deflate")); this.httpClient = HttpClients.custom().setConnectionManager(connectionManager) .setDefaultHeaders(headers).setDefaultRequestConfig(requestConfig).build(); this.jsonMapper = new ObjectMapper(); } /** * Sends a request, and keeps the connection open for re-use. * * @param requestBuilder * @return JSON node containing the response body. * @throws IOException * @throws GroovesharkException */ JsonNode sendRequest(RequestBuilder requestBuilder) throws IOException, GroovesharkException { createSessionIfRequired(); session.createCommsTokenAsRequired(); boolean sessionAlreadyRenewed = false; boolean commsTokenAlreadyRenewed = false; while (true) { // Renew out of date session/token if (!sessionAlreadyRenewed) { createSessionIfRequired(); } if (!commsTokenAlreadyRenewed) { session.createCommsTokenAsRequired(); } HttpPost httpRequest = requestBuilder.build(session); httpRequest.setHeader(HttpHeaders.CONNECTION, "keep-alive"); try { JsonNode jsonNode = executeRequest(httpRequest); // Handle fault codes from the API GroovesharkException exception = mapGroovesharkFaultCodeToException(jsonNode); if (exception != null) { if (exception instanceof GroovesharkException.InvalidSessionException) { // Attempt to renew session and retry if (sessionAlreadyRenewed) { throw new GroovesharkException.ServerErrorException( "Failed with invalid session. Renewed session still invalid."); } else { createSession(); sessionAlreadyRenewed = true; continue; } } else if (exception instanceof GroovesharkException.InvalidCommsTokenException) { // Attempt to renew token and retry if (commsTokenAlreadyRenewed) { throw new GroovesharkException.ServerErrorException( "Failed with invalid comms token. Renewed token also invalid."); } else { session.createCommsToken(); commsTokenAlreadyRenewed = true; continue; } } else { // The exception can't be handled internally throw exception; } } return jsonNode; } finally { // Finished with connection at this point, so make it reuseable httpRequest.reset(); } } } /** * Boilerplate to send the request and parse the response payload as JSON. */ private JsonNode executeRequest(HttpPost httpRequest) throws IOException, GroovesharkException { HttpResponse response = httpClient.execute(httpRequest); String payload = CharStreams.toString(new InputStreamReader(response.getEntity() .getContent(), Charsets.UTF_8)); if (debugLogging) { ObjectWriter writer = jsonMapper.writer().withDefaultPrettyPrinter(); JsonNode requestNode = jsonMapper.readTree(CharStreams.toString(new InputStreamReader( httpRequest.getEntity().getContent()))); JsonNode responseNode = jsonMapper.readTree(new StringReader(payload)); System.out.println(httpRequest.getURI().toString()); System.out.println(writer.writeValueAsString(requestNode)); System.out.println(writer.writeValueAsString(responseNode)); System.out.println(); } // Parse response JSON try { return jsonMapper.readTree(new StringReader(payload)); } catch (JsonProcessingException e) { throw new GroovesharkException.ServerErrorException( "Failed to parse response - received data was not valid JSON: " + payload); } } private static GroovesharkException mapGroovesharkFaultCodeToException(JsonNode jsonNode) { if (jsonNode.has("fault")) { JsonNode faultNode = jsonNode.get("fault"); int faultCode = faultNode.get("code").asInt(); switch (faultCode) { case FaultCodes.INVALID_SESSION: return new GroovesharkException.InvalidSessionException(faultNode); case FaultCodes.INVALID_TOKEN: return new GroovesharkException.InvalidCommsTokenException(faultNode); case FaultCodes.RATE_LIMITED: return new GroovesharkException.RateLimitedException(faultNode); case FaultCodes.INVALID_CLIENT: case FaultCodes.HTTP_ERROR: case FaultCodes.HTTP_TIMEOUT: case FaultCodes.MAINTENANCE: case FaultCodes.MUST_BE_LOGGED_IN: case FaultCodes.PARSE_ERROR: default: // Something has gone unrecoverably wrong, so just // return a generic exception with debugging info. return new GroovesharkException.ServerErrorException(faultNode); } } return null; } private void createSessionIfRequired() throws IOException, GroovesharkException { if ((session == null) || session.isExpired()) { createSession(); } } private void createSession() throws IOException, GroovesharkException { User userFromOldSession = (session == null) ? null : session.getUser(); HttpGet request = new HttpGet("http://" + DOMAIN + "/preload.php?getCommunicationToken"); HttpResponse response = httpClient.execute(request); Session session = new Session(this, response); if (userFromOldSession != null) { // If old session was logged in, make sure the new one is too login(userFromOldSession.email, userFromOldSession.password); } else { this.session = session; } } public InputStream getStream(final Song song) throws IOException, GroovesharkException { return getStream(song.id); } public InputStream getStream(final long songId) throws IOException, GroovesharkException { return getStreamResponse(songId).getEntity().getContent(); } public HttpResponse getStreamResponse(final Song song) throws IOException, GroovesharkException { return getStreamResponse(song.id); } public HttpResponse getStreamResponse(final long songId) throws IOException, GroovesharkException { HttpResponse response = httpClient.execute(new HttpGet(getStreamUrl(songId).toString())); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { EntityUtils.consumeQuietly(response.getEntity()); throw new IOException("API returned " + statusCode + " status code"); } return response; } public URL getStreamUrl(final Song song) throws IOException, GroovesharkException { return getStreamUrl(song.id); } public URL getStreamUrl(final long songId) throws IOException, GroovesharkException { JsonNode response = sendRequest(new RequestBuilder("getStreamKeyFromSongIDEx", false) { @Override void populateParameters(Session session, ObjectNode parameters) { parameters.put("type", 0); parameters.put("prefetch", false); parameters.put("songID", songId); parameters.put("country", session.country); parameters.put("mobile", false); } }); JsonNode result = response.get("result"); if (result.size() == 0) { throw new GroovesharkException.ServerErrorException("Received empty response"); } String ip = result.get("ip").asText(); String streamKey = result.get("streamKey").asText(); return new URL("http://" + ip + "/stream.php?streamKey=" + streamKey); } public List<Song> searchSongs(final String query) throws IOException, GroovesharkException { JsonNode response = sendRequest(new RequestBuilder("getResultsFromSearch", false) { @Override void populateParameters(Session session, ObjectNode parameters) { parameters.put("type", "Songs"); parameters.put("query", query); } }); ArrayList<Song> songs = Lists.newArrayList(); Iterator<JsonNode> elements = response.get("result").get("result").elements(); while (elements.hasNext()) { songs.add(new Song(elements.next())); } return songs; } public List<Song> searchPopularSongs() throws IOException, GroovesharkException { JsonNode response = sendRequest(new RequestBuilder("popularGetSongs", false) { @Override void populateParameters(Session session, ObjectNode parameters) { parameters.put("type", "daily"); } }); ArrayList<Song> songs = Lists.newArrayList(); Iterator<JsonNode> elements = response.get("result").get("Songs").elements(); while (elements.hasNext()) { songs.add(new Song(elements.next())); } return songs; } /** * Logs in as the given user, allowing access to various * authentication-requiring methods in the {@link User} class. * * @param username * @param password * @return The logged in user. Also available via {@link #getUser()}; * @throws IOException * @throws GroovesharkException */ public User login(final String username, final String password) throws IOException, GroovesharkException { JsonNode node = sendRequest(new RequestBuilder("authenticateUser", true) { @Override void populateParameters(Session session, ObjectNode parameters) { parameters.put("username", username); parameters.put("password", password); } }); // Success: the session that created this request is now authenticated, // so we can mark is as such. User user = new User(this, username, password, node); session.setAuthenticated(user); return user; } /** * @return The user that logged in via this client, or null. */ @Nullable public User getUser() { return session.user; } /** * Set whether debug information is written to standard output. Default * value is disabled. */ public void setDebugLoggingEnabled(boolean enabled) { debugLogging = enabled; } }
package com.braintreegateway.util; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLConnection; import java.net.URLDecoder; import java.security.KeyStore; import java.security.Principal; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManagerFactory; import com.braintreegateway.Configuration; import com.braintreegateway.Request; import com.braintreegateway.exceptions.AuthenticationException; import com.braintreegateway.exceptions.AuthorizationException; import com.braintreegateway.exceptions.DownForMaintenanceException; import com.braintreegateway.exceptions.NotFoundException; import com.braintreegateway.exceptions.ServerException; import com.braintreegateway.exceptions.TimeoutException; import com.braintreegateway.exceptions.TooManyRequestsException; import com.braintreegateway.exceptions.UnexpectedException; import com.braintreegateway.exceptions.UpgradeRequiredException; import com.braintreegateway.org.apache.commons.codec.binary.Base64; import org.json.JSONObject; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManagerFactory; public class Http { public static final String LINE_FEED = "\r\n"; private volatile SSLSocketFactory sslSocketFactory; enum RequestMethod { DELETE, GET, POST, PUT; } private Configuration configuration; public Http(Configuration configuration) { this.configuration = configuration; } public NodeWrapper delete(String url) { return httpRequest(RequestMethod.DELETE, url); } public NodeWrapper get(String url) { return httpRequest(RequestMethod.GET, url); } public NodeWrapper post(String url) { return httpRequest(RequestMethod.POST, url, null, null); } public NodeWrapper post(String url, Request request) { return httpRequest(RequestMethod.POST, url, request.toXML(), null); } public NodeWrapper post(String url, String request) { return httpRequest(RequestMethod.POST, url, request, null); } public NodeWrapper postMultipart(String url, String request, File file) { return httpRequest(RequestMethod.POST, url, request, file); } public NodeWrapper put(String url) { return httpRequest(RequestMethod.PUT, url, null, null); } public NodeWrapper put(String url, Request request) { return httpRequest(RequestMethod.PUT, url, request.toXML(), null); } private NodeWrapper httpRequest(RequestMethod requestMethod, String url) { return httpRequest(requestMethod, url, null, null); } private NodeWrapper httpRequest(RequestMethod requestMethod, String url, String postBody, File file) { HttpURLConnection connection = null; NodeWrapper nodeWrapper = null; String boundary = "boundary" + System.currentTimeMillis(); String contentType = file == null ? "application/xml" : "multipart/form-data; boundary=" + boundary; try { connection = buildConnection(requestMethod, url, contentType); Logger logger = configuration.getLogger(); if (postBody != null) { logger.log(Level.FINE, formatSanitizeBodyForLog(postBody)); } if (connection instanceof HttpsURLConnection) { ((HttpsURLConnection) connection).setSSLSocketFactory(getSSLSocketFactory()); } if (postBody != null) { OutputStream outputStream = null; try { outputStream = connection.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true); if (file == null) { outputStream.write(postBody.getBytes("UTF-8")); } else { JSONObject obj = new JSONObject(postBody); Iterator<?> keys = obj.keys(); while (keys.hasNext()) { String key = (String) keys.next(); addFormField(key, (String) obj.get(key), writer, boundary); } addFilePart("file", file, writer, outputStream, boundary); finish(writer, boundary); } } finally { if (outputStream != null) { outputStream.close(); } } } throwExceptionIfErrorStatusCode(connection.getResponseCode(), null); InputStream responseStream = null; try { responseStream = connection.getResponseCode() == 422 ? connection.getErrorStream() : connection.getInputStream(); if ("gzip".equalsIgnoreCase(connection.getContentEncoding())) { responseStream = new GZIPInputStream(responseStream); } String xml = StringUtils.inputStreamToString(responseStream); logger.log(Level.INFO, "[Braintree] [{0}]] {1} {2}", new Object[] { getCurrentTime(), requestMethod.toString(), url }); logger.log(Level.FINE, "[Braintree] [{0}] {1} {2} {3}", new Object[] { getCurrentTime(), requestMethod.toString(), url, connection.getResponseCode() }); if (xml != null) { logger.log(Level.FINE, formatSanitizeBodyForLog(xml)); } if (xml == null || xml.trim().equals("")) { return null; } nodeWrapper = NodeWrapperFactory.instance.create(xml); } finally { if (responseStream != null) { responseStream.close(); } } } catch (SocketTimeoutException e) { throw new TimeoutException(e.getMessage(), e); } catch (IOException e) { throw new UnexpectedException(e.getMessage(), e); } finally { if (connection != null) { connection.disconnect(); } } return nodeWrapper; } private void addFormField(String key, String value, PrintWriter writer, String boundary) { writer.append("--" + boundary).append(LINE_FEED); writer.append("Content-Disposition: form-data; name=\"" + key + "\"").append(LINE_FEED); writer.append(LINE_FEED); writer.append(value).append(LINE_FEED); writer.flush(); } private void addFilePart(String fieldName, File uploadFile, PrintWriter writer, OutputStream outputStream, String boundary) throws IOException { String filename = uploadFile.getName(); writer.append("--" + boundary).append(LINE_FEED); writer.append("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + filename + "\"").append(LINE_FEED); writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(filename)).append(LINE_FEED); writer.append(LINE_FEED); writer.flush(); FileInputStream inputStream = new FileInputStream(uploadFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); inputStream.close(); writer.append(LINE_FEED); writer.flush(); } private void finish(PrintWriter writer, String boundary) { writer.append("--" + boundary + "--").append(LINE_FEED); writer.append(LINE_FEED).flush(); writer.close(); } private String formatSanitizeBodyForLog(String body) { if (body == null) { return body; } Pattern regex = Pattern.compile("(^)", Pattern.MULTILINE); Matcher regexMatcher = regex.matcher(body); if (regexMatcher.find()) { body = regexMatcher.replaceAll("[Braintree] $1"); } regex = Pattern.compile("<number>(.{6}).+?(.{4})</number>"); regexMatcher = regex.matcher(body); if (regexMatcher.find()) { body = regexMatcher.replaceAll("<number>$1******$2</number>"); } body = body.replaceAll("<cvv>.+?</cvv>", "<cvv>***</cvv>"); return body; } private String getCurrentTime() { return new SimpleDateFormat("d/MMM/yyyy HH:mm:ss Z").format(new Date()); } private SSLSocketFactory getSSLSocketFactory() { if (sslSocketFactory == null) { synchronized (this) { if (sslSocketFactory == null) { try { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null); for (String certificateFilename : configuration.getEnvironment().certificateFilenames) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream certStream = null; try { certStream = Http.class.getClassLoader().getResourceAsStream(certificateFilename); Collection<? extends Certificate> coll = cf.generateCertificates(certStream); for (Certificate cert : coll) { if (cert instanceof X509Certificate) { X509Certificate x509cert = (X509Certificate) cert; Principal principal = x509cert.getSubjectDN(); String subject = principal.getName(); keyStore.setCertificateEntry(subject, cert); } } } finally { if (certStream != null) { certStream.close(); } } } KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keyStore, null); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(keyStore); SSLContext sslContext = null; try { // Use TLS v1.2 explicitly for Java 1.6 or Java 7 JVMs that support it but do not turn it on by // default sslContext = SSLContext.getInstance("TLSv1.2"); } catch (NoSuchAlgorithmException e) { sslContext = SSLContext.getInstance("TLS"); } sslContext.init((KeyManager[]) kmf.getKeyManagers(), tmf.getTrustManagers(), SecureRandom.getInstance("SHA1PRNG")); sslSocketFactory = sslContext.getSocketFactory(); } catch (Exception e) { Logger logger = configuration.getLogger(); logger.log(Level.SEVERE, "SSL Verification failed. Error message: {0}", new Object[] { e.getMessage() }); throw new UnexpectedException(e.getMessage(), e); } } } } return sslSocketFactory; } private HttpURLConnection buildConnection(RequestMethod requestMethod, String urlString, String contentType) throws java.io.IOException { URL url = new URL(configuration.getBaseURL() + urlString); int connectTimeout = configuration.getConnectTimeout(); HttpURLConnection connection; if (configuration.usesProxy()) { connection = (HttpURLConnection) url.openConnection(configuration.getProxy()); } else { connection = (HttpURLConnection) url.openConnection(); } connection.setRequestMethod(requestMethod.toString()); connection.addRequestProperty("Accept", "application/xml"); connection.addRequestProperty("User-Agent", "Braintree Java " + Configuration.VERSION); connection.addRequestProperty("X-ApiVersion", Configuration.apiVersion()); connection.addRequestProperty("Authorization", authorizationHeader()); connection.addRequestProperty("Accept-Encoding", "gzip"); connection.setRequestProperty("Content-Type", contentType); connection.setDoOutput(true); connection.setReadTimeout(configuration.getTimeout()); if (connectTimeout > 0) { connection.setConnectTimeout(connectTimeout); } return connection; } public static void throwExceptionIfErrorStatusCode(int statusCode, String message) { String decodedMessage = null; if (message != null) { try { decodedMessage = URLDecoder.decode(message, "UTF-8"); } catch (UnsupportedEncodingException e) { Logger logger = Logger.getLogger("Braintree"); logger.log(Level.FINEST, e.getMessage(), e.getStackTrace()); } } if (isErrorCode(statusCode)) { switch (statusCode) { case 401: throw new AuthenticationException(); case 403: throw new AuthorizationException(decodedMessage); case 404: throw new NotFoundException(); case 426: throw new UpgradeRequiredException(); case 429: throw new TooManyRequestsException(); case 500: throw new ServerException(); case 503: throw new DownForMaintenanceException(); default: throw new UnexpectedException("Unexpected HTTP_RESPONSE " + statusCode); } } } private static boolean isErrorCode(int responseCode) { return responseCode != 200 && responseCode != 201 && responseCode != 422; } public String authorizationHeader() { if (configuration.isAccessToken()) { return "Bearer " + configuration.getAccessToken(); } String credentials; if (configuration.isClientCredentials()) { credentials = configuration.getClientId() + ":" + configuration.getClientSecret(); } else { credentials = configuration.getPublicKey() + ":" + configuration.getPrivateKey(); } return "Basic " + Base64.encodeBase64String(credentials.getBytes()).trim(); } }
package com.clementscode.mmi.swing; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.GridLayout; import java.awt.HeadlessException; import java.awt.Image; import java.awt.RenderingHints; import java.awt.Transparency; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import javax.imageio.ImageIO; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.Timer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.log4j.Logger; import com.clementscode.mmi.MainGui; import com.clementscode.mmi.res.CategoryItem; import com.clementscode.mmi.res.ConfigParser; import com.clementscode.mmi.res.ConfigParser100; import com.clementscode.mmi.res.LegacyConfigParser; import com.clementscode.mmi.res.Session; import com.clementscode.mmi.res.SessionConfig; import com.clementscode.mmi.util.Shuffler; import com.clementscode.mmi.util.Utils; public class Gui implements ActionListener, MediatorListenerCustomer { private Logger logger = Logger.getLogger(this.getClass().getName()); public static final String BROWSE_SESSION_DATA_FILE = "BROWSE_SESSION_DATA_FILE"; public static final String SESSION_DIRECTORY = "SESSION_DIRECTORY"; public static final String ADVT_URL = "http://clementscode.com/avdt"; public static final Object OUTPUT_CSV_FILE_LOCATION = "OUTPUT_CSV_FILE_LOCATION"; public static final Object SESSION_CONFIG_FILENAME = "SESSION_CONFIG_FILENAME"; public static final Object RESOURCES_DIRECTORY = "RESOURCES_DIRECTORY"; // private ImageIcon imgIconCenter; private JButton centerButton; private Queue<CategoryItem> itemQueue = null; private Session session = null; private Timer timer; private Timer betweenTimer; protected static Log log = LogFactory.getLog(Gui.class); private JFrame frame; private String frameTitle = Messages.getString("Gui.FrameTitle"); //$NON-NLS-1$ private ActionRecorder attendingAction; private ActionRecorder independentAction; private ActionRecorder verbalAction; private ActionRecorder modelingAction; private ActionRecorder noAnswerAction; private ActionRecorder quitAction; private ActionRecorder timerAction; private ActionRecorder timerBetweenAction; private ActionRecorder openAction; private JPanel mainPanel; private Mediator mediator; private File tmpDir; private ArrayList<JComponent> lstButtons; private ImageIcon iiSmilingFace, iiSmilingFaceClickToBegin; private JTextField tfSessionName; private static JTextField tfSessionDataFile; private JButton clickToStartButton; private List<String> lstTempDirectories; private LoggingFrame loggingFrame; private ActionRecorder showLoggingFrameAction; // private URL codeBaseUrl = null; private int shownItemCount = 0; private int totalItemCount; private boolean bDebounce = false; // DISGUSTING! and Mysterious. private BufferedImage clearImage; public static Properties preferences; private ActionRecorder toggleButtonsAction; private boolean buttonsVisible; // GLOBALS EVERYWHERE! private CategoryItem currentItem; private ConfigParser parser = null; private ActionRecorder wrongAnswerAction; private ActionRecorder timerTimeDelayAutoAdvance; private int maxHeight; private int maxWidth; public Gui() { loggingFrame = new LoggingFrame(); // TODO: Trim the extra! jnlpSetup(); preferences = loadPreferences(); String tmpDirStr = "/tmp/mmi"; tmpDir = new File(tmpDirStr); tmpDir.mkdirs(); mediator = new Mediator(this); setupActions(mediator); mainPanel = setupMainPanel(); // TODO: Check to see if there's a logic bug here.... frame = new JFrame(frameTitle); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(mainPanel); setupMenus(); disableButtons(); hideButtons(); lstTempDirectories = new ArrayList<String>(); // Register a shutdown thread Runtime.getRuntime().addShutdownHook(new Thread() { // This method is called during shutdown public void run() { // Do shutdown work ... savePreferences(); Utils.deleteTempDirectories(lstTempDirectories); } }); } // private void jnlpSetup() { // try { // String[] sn = javax.jnlp.ServiceManager.getServiceNames(); // for (String string : sn) { // logger.info("A service name is: " + string); // Object obj = javax.jnlp.ServiceManager // .lookup("javax.jnlp.BasicService"); // BasicService bs = (BasicService) obj; // codeBaseUrl = bs.getCodeBase(); // } catch (UnavailableServiceException e) { // logger.error("Could not look up BasicService.", e); // e.printStackTrace(); // } catch (Exception bland) { // logger // .error("Some odd JNLP related problem: bland=" + bland, // bland); private void disableButtons() { for (JComponent jc : lstButtons) { jc.setEnabled(false); } } public void toggleButtons() { if (buttonsVisible) { hideButtons(); } else { showButtons(); } } private void hideButtons() { for (JComponent jc : lstButtons) { jc.setVisible(false); } buttonsVisible = false; } private void showButtons() { for (JComponent jc : lstButtons) { jc.setVisible(true); } buttonsVisible = true; } private void enableButtons() { for (JComponent jc : lstButtons) { jc.setEnabled(true); } } private void setupMenus() { // Create the menu bar. JMenuBar menuBar = new JMenuBar(); // Build the first menu. JMenu menu = new JMenu(Messages.getString("Gui.File")); //$NON-NLS-1$ menu.setMnemonic(KeyEvent.VK_A); menuBar.add(menu); // a group of JMenuItems JMenuItem menuItem = new JMenuItem(openAction); menu.add(menuItem); // menuItem = new JMenuItem(openHttpAction); // menu.add(menuItem); /* * menuItem = new JMenuItem(crudAction); menu.add(menuItem); */ menuItem = new JMenuItem(showLoggingFrameAction); menu.add(menuItem); menuItem = new JMenuItem(quitAction); menu.add(menuItem); menuBar.add(menu); JMenu buttonMenu = new JMenu(Messages.getString("Gui.Buttons")); //$NON-NLS-1$ menuItem = new JMenuItem(attendingAction); buttonMenu.add(menuItem); menuItem = new JMenuItem(independentAction); buttonMenu.add(menuItem); menuItem = new JMenuItem(verbalAction); buttonMenu.add(menuItem); menuItem = new JMenuItem(modelingAction); buttonMenu.add(menuItem); menuItem = new JMenuItem(noAnswerAction); buttonMenu.add(menuItem); menuItem = new JMenuItem(wrongAnswerAction); buttonMenu.add(menuItem); menuItem = new JMenuItem(toggleButtonsAction); buttonMenu.add(menuItem); menuBar.add(buttonMenu); frame.setJMenuBar(menuBar); frame.pack(); frame.setVisible(true); } private JPanel setupMainPanel() { JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); JPanel southPanel = new JPanel(); lstButtons = new ArrayList<JComponent>(); addButton(southPanel, attendingAction); addButton(southPanel, independentAction); addButton(southPanel, verbalAction); addButton(southPanel, modelingAction); addButton(southPanel, noAnswerAction); addButton(southPanel, wrongAnswerAction); JPanel belowSouthPanel = new JPanel(); belowSouthPanel.setLayout(new GridLayout(0, 1)); tfSessionName = new JTextField(40); if (null != session) { tfSessionName.setText(session.getSessionName()); } else { tfSessionName.setText("Session 1"); } belowSouthPanel.add(new LabelAndField("Session Name: ", tfSessionName)); tfSessionDataFile = new JTextField(30); try { if (null != session) { tfSessionDataFile.setText(session.getSessionDataFile() .getCanonicalPath()); } else { tfSessionDataFile.setText((String) preferences .get(OUTPUT_CSV_FILE_LOCATION)); // tfSessionDataFile.setText(System.getProperty("user.home") // + "/avdt.csv"); } } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } JPanel midBelowSouthPanel = new JPanel(); midBelowSouthPanel.add(new LabelAndField("Session Data File: ", tfSessionDataFile)); JButton browse = new JButton("Browse..."); browse.setActionCommand(BROWSE_SESSION_DATA_FILE); browse.addActionListener(this); midBelowSouthPanel.add(browse); belowSouthPanel.add(midBelowSouthPanel); clickToStartButton = new JButton("Click to Start"); belowSouthPanel.add(clickToStartButton); clickToStartButton.setEnabled(false); clickToStartButton.addActionListener(this); // response value. This can be 1 of 4 things: independent (child // answered before the prompt audio), verbal (child answered after the // prompt but before the answer), modeling (child answered anytime after // the answer audio) or the child did not answer. JPanel southContainerPanel = new JPanel(); southContainerPanel.setLayout(new GridLayout(0, 1)); southContainerPanel.add(southPanel); southContainerPanel.add(belowSouthPanel); panel.add(southContainerPanel, BorderLayout.SOUTH); BufferedImage imageData = null; BufferedImage imageDataClickToBegin = null; try { imageData = readImageDataFromClasspath("images/happy-face.jpg"); imageDataClickToBegin = readImageDataFromClasspath("images/happy-face-click-to-begin.jpg"); } catch (Exception e) { // TODO Auto-generated catch block logger.warn("Could not find image from classpath...", e); e.printStackTrace(); } iiSmilingFace = null; if (null != imageData) { iiSmilingFace = new ImageIcon(imageData); iiSmilingFaceClickToBegin = new ImageIcon(imageDataClickToBegin); } if (null == imageData) { try { iiSmilingFace = new ImageIcon(new URL( "http://MattPayne.org/mmi/happy-face.jpg")); iiSmilingFaceClickToBegin = new ImageIcon(new URL( "http://MattPayne.org/mmi/happy-face.jpg")); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } maxHeight = iiSmilingFace.getIconHeight(); maxWidth = iiSmilingFace.getIconWidth(); centerButton = new JButton(iiSmilingFace); centerButton.addActionListener(this); panel.add(centerButton, BorderLayout.CENTER); return panel; } public void backToStartScreen() { frame.setTitle(frameTitle); centerButton.setIcon(iiSmilingFace); refreshGui(); disableButtons(); } private void addButton(JPanel southPanel, ActionRecorder independentAction2) { JButton responseButton = new JButton(independentAction2); southPanel.add(responseButton); lstButtons.add(responseButton); } private BufferedImage readImageDataFromClasspath(String fileName) throws IOException { // Do it this way and no relative path huha is needed. InputStream in = this.getClass().getClassLoader().getResourceAsStream( fileName); return ImageIO.read(in); } public void setupTimer() { if (null != timer) { timer.stop(); // fix for issue } SessionConfig config = session.getConfig(); // DON'T LET THE NAME CHANGES FOOL YOU! int answerDelay = config.getTimeDelayAudioPrompt() + getPromptLen(currentItem.getAudioPrompt()); timer = new Timer(answerDelay * 1000, timerAction); timer.setInitialDelay(config.getTimeDelayAudioSD() * 1000); timer.setRepeats(true); timer.start(); } private void setupBetweenTimer() { if (betweenTimer != null) { // just in case betweenTimer.stop(); } SessionConfig config = session.getConfig(); betweenTimer = new Timer(config.getTimeDelayInterTrial() * 1000, timerBetweenAction); betweenTimer.setRepeats(false); } public Timer getBetweenTimer() { return betweenTimer; } public void startTimerTimeDelayAutoAdvance(int timeDelayAutoAdvance) { Timer xxx = new Timer(timeDelayAutoAdvance * 1000, timerTimeDelayAutoAdvance); xxx.setRepeats(false); xxx.start(); log.info(String.format( "Started timerTimeDelayAutoAdvance timer for %d seconds.", timeDelayAutoAdvance)); } int getPromptLen(File sndFile) { // FIXME I'm a horrible hack if (sndFile == null) { return 0; } AudioInputStream audioInputStream; try { audioInputStream = AudioSystem.getAudioInputStream(sndFile); AudioFormat format = audioInputStream.getFormat(); long frames = audioInputStream.getFrameLength(); audioInputStream.close(); return (int) (frames / format.getFrameRate()); } catch (Exception e) { log.error("Horrible hack blew up, karma", e); return 0; } } public void setupCenterButton() { // // TODO: Call this when we get a new session file read in.... // CategoryItem first = itemQueue.remove(); // log.info(String.format("About to display image: %s from item=%d", // first.getImgFile(), first.getItemNumber())); // imgIconCenter = new ImageIcon(first.getImg()); // // centerButton = new JButton(imgIconCenter); // centerButton.setIcon(imgIconCenter); Dimension max = session.getMaxDimensions(); centerButton.setPreferredSize(max); int width = (int) max.getWidth(); int height = (int) max.getHeight(); clearImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = clearImage.getGraphics(); g.setColor(Color.WHITE); g.fillRect(0, 0, width, height); g.dispose(); } private void setupActions(MediatorListener mediator) { // TODO: Fix bug that control A does not toggle the checkbox // TODO: Make attending not a checkbox. // TODO: Make hot keys come from a properties file. Hopefully ask JNLP // Utils where this program was loaded from and do a http get to there // for the properties file. Properties hotKeysProperties = null; String fileName = "hotkeys.ini"; try { hotKeysProperties = readPropertiesFromClassPath(fileName); } catch (Exception e) { hotKeysProperties = new Properties(); hotKeysProperties.put("Hotkey.Gui.Attending","A"); hotKeysProperties.put("Hotkey.Gui.Independent","1"); hotKeysProperties.put("Hotkey.Gui.Verbal","2"); hotKeysProperties.put("Hotkey.Gui.Modeling","3"); hotKeysProperties.put("Hotkey.Gui.NoAnswer","4"); hotKeysProperties.put("Hotkey.Gui.WrongAnswer","5"); log.warn(String.format( "Problem reading %s. Defaulting hotkeysPropteries=%s", fileName, hotKeysProperties), e); } String hk = (String) hotKeysProperties.get("Hotkey.Gui.Attending"); attendingAction = new ActionRecorder(Messages .getString("Gui.Attending"), null, //$NON-NLS-1$ Messages.getString("Gui.AttendingDescription"), new Integer( //$NON-NLS-1$ KeyEvent.VK_F1), KeyStroke.getKeyStroke(hk), Action.ATTENDING, mediator); hk = (String) hotKeysProperties.get("Hotkey.Gui.Independent"); independentAction = new ActionRecorder(Messages .getString("Gui.Independent"), null, //$NON-NLS-1$ Messages.getString("Gui.IndependentDescription"), new Integer( //$NON-NLS-1$ KeyEvent.VK_F2), KeyStroke.getKeyStroke(hk), Action.INDEPENDENT, mediator); hk = (String) hotKeysProperties.get("Hotkey.Gui.Verbal"); verbalAction = new ActionRecorder( Messages.getString("Gui.Verbal"), null, //$NON-NLS-1$ Messages.getString("Gui.VerbalDescription"), //$NON-NLS-1$ new Integer(KeyEvent.VK_F3), KeyStroke.getKeyStroke(hk), Action.VERBAL, mediator); hk = (String) hotKeysProperties.get("Hotkey.Gui.Modeling"); modelingAction = new ActionRecorder( Messages.getString("Gui.Modeling"), null, //$NON-NLS-1$ Messages.getString("Gui.ModelingDescriptin"), new Integer( //$NON-NLS-1$ KeyEvent.VK_F4), KeyStroke.getKeyStroke(hk), Action.MODELING, mediator); hk = (String) hotKeysProperties.get("Hotkey.Gui.NoAnswer"); noAnswerAction = new ActionRecorder( Messages.getString("Gui.NoAnswer"), null, //$NON-NLS-1$ Messages.getString("Gui.NoAnswerDescription"), new Integer(KeyEvent.VK_F5), //$NON-NLS-1$ KeyStroke.getKeyStroke(hk), Action.NO_ANSWER, mediator); hk = (String) hotKeysProperties.get("Hotkey.Gui.WrongAnswer"); wrongAnswerAction = new ActionRecorder( Messages.getString("Gui.WrongAnswer"), null, //$NON-NLS-1$ Messages.getString("Gui.WrongAnswerDescription"), new Integer(KeyEvent.VK_F5), //$NON-NLS-1$ KeyStroke.getKeyStroke(hk), Action.WRONG_ANSWER, mediator); toggleButtonsAction = new ActionRecorder( Messages.getString("Gui.ToggleButtons"), null, //$NON-NLS-1$ Messages.getString("Gui.ToggleButtons.Description"), new Integer(KeyEvent.VK_L), //$NON-NLS-1$ KeyStroke.getKeyStroke("B"), Action.TOGGLE_BUTTONS, mediator); quitAction = new ActionRecorder( Messages.getString("Gui.Quit"), null, //$NON-NLS-1$ Messages.getString("Gui.QuitDescriptino"), new Integer(KeyEvent.VK_L), //$NON-NLS-1$ KeyStroke.getKeyStroke("control Q"), Action.QUIT, mediator); timerAction = new ActionRecorder( Messages.getString("Gui.TimerSwing"), null, //$NON-NLS-1$ "Quit (Exit) the program", new Integer(KeyEvent.VK_L), //$NON-NLS-1$ KeyStroke.getKeyStroke("control F2"), Action.TIMER, mediator); timerBetweenAction = new ActionRecorder(Messages .getString("Gui.TimerBetweenSwing"), null, //$NON-NLS-1$ "Quit (Exit) the program", new Integer(KeyEvent.VK_L), //$NON-NLS-1$ KeyStroke.getKeyStroke("control F2"), Action.BETWEEN_TIMER, mediator); timerTimeDelayAutoAdvance = new ActionRecorder( Messages.getString("Gui.TimeDelayAutoAdvance"), null, //$NON-NLS-1$ "xxxxxxxxxxxxxx", new Integer(KeyEvent.VK_L), //$NON-NLS-1$ KeyStroke.getKeyStroke("control F2"), Action.CHANGE_DELAY_TIMER, mediator); openAction = new ActionRecorder(Messages.getString("Gui.Open"), null, //$NON-NLS-1$ Messages.getString("Gui.OpenDescription"), //$NON-NLS-1$ new Integer(KeyEvent.VK_L), KeyStroke.getKeyStroke("control O"), Action.OPEN, mediator); showLoggingFrameAction = new ActionRecorder( Messages.getString("Gui.Open.ShowLoggingFrame"), null, //$NON-NLS-1$ Messages.getString("Gui.ShowLoggingFrameDescription"), //$NON-NLS-1$ new Integer(KeyEvent.VK_L), KeyStroke.getKeyStroke("control D"), Action.SHOW_LOGGING_FRAME, mediator); } public Queue<CategoryItem> getItemQueue() { return itemQueue; } public void clearImage() { centerButton.setIcon(new ImageIcon(clearImage)); refreshGui(); } public void switchImage(ImageIcon ii) { setFrameTitle(); centerButton.setIcon(ii); } /* * They use bmp images which don't display with the program right now. I * looked at the code and noticed that you don't use the 'img' field of the * CategoryItem. You use the image file to get a path to the image and read * it in again using an icon. I suspect that it will work better if you use * the image that ImageIO already read into memory. */ public void switchItem(CategoryItem item) { currentItem = item; ImageIcon ii = new ImageIcon(imageOfMaxSize(item.getImg())); switchImage(ii); setupTimer(); } private BufferedImage imageOfMaxSize(BufferedImage img) { BufferedImage bi = img; int w = img.getWidth(); int h = img.getHeight(); if ((w > maxWidth) || (h > maxHeight)) { log.info(String.format("Resizing! since (%d,%d) > (%d,%d)", w, h, maxWidth, maxHeight)); bi = toBufferedImage(getScaledImage(img, maxWidth, maxHeight)); w = bi.getWidth(); h = bi.getHeight(); log.info(String.format("Now bi size is (%d,%d)", w, h)); } return bi; } /** * Resizes an image using a Graphics2D object backed by a BufferedImage. * * @param srcImg * - source image to scale * @param w * - desired width * @param h * - desired height * @return - the new resized image */ private Image getScaledImage(Image srcImg, int w, int h) { // from: BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = resizedImg.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(srcImg, 0, 0, w, h, null); g2.dispose(); return resizedImg; } public static BufferedImage toBufferedImage(Image image) { if (image instanceof BufferedImage) { return (BufferedImage) image; } // This code ensures that all the pixels in the image are loaded image = new ImageIcon(image).getImage(); // Determine if the image has transparent pixels; for this method's // implementation, see Determining If an Image Has Transparent Pixels boolean hasAlpha = false; // hasAlpha(image); // Create a buffered image with a format that's compatible with the // screen BufferedImage bimage = null; GraphicsEnvironment ge = GraphicsEnvironment .getLocalGraphicsEnvironment(); try { // Determine the type of transparency of the new buffered image int transparency = Transparency.OPAQUE; if (hasAlpha) { transparency = Transparency.BITMASK; } // Create the buffered image GraphicsDevice gs = ge.getDefaultScreenDevice(); GraphicsConfiguration gc = gs.getDefaultConfiguration(); bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency); } catch (HeadlessException e) { // The system does not have a screen } if (bimage == null) { // Create a buffered image using the default color model int type = BufferedImage.TYPE_INT_RGB; if (hasAlpha) { type = BufferedImage.TYPE_INT_ARGB; } bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type); } // Copy image to buffered image Graphics g = bimage.createGraphics(); // Paint the image onto the buffered image g.drawImage(image, 0, 0, null); g.dispose(); return bimage; } private void setFrameTitle() { frame.setTitle(frameTitle + String.format("%d of %d", shownItemCount++, totalItemCount)); } public Session getSession() { return session; } public void setSession(Session session) { this.session = session; } public void stopTimer() { if (timer != null) { timer.stop(); } } public void setVisble(boolean b) { frame.setVisible(b); } public void openSession() { bDebounce = false; File file; // TODO: Get application to remember the last place we opened this... String sessionDir = (String) preferences.get(SESSION_DIRECTORY); sessionDir = null == sessionDir ? System.getProperty("user.home") : sessionDir; JFileChooser chooser = new JFileChooser(new File(sessionDir)); int returnVal = chooser.showOpenDialog(frame); if (returnVal == JFileChooser.APPROVE_OPTION) { file = chooser.getSelectedFile(); try { readSessionFile(file); } catch (Exception e) { JOptionPane.showMessageDialog(frame, String.format( "Problem reading %s exception was %s", file, e)); e.printStackTrace(); } preferences.put(SESSION_DIRECTORY, getDirectory(file)); savePreferences(); } displayClickToBegin(); } private Object getDirectory(File file) { String dirStr = file.getAbsolutePath(); int firstSlash = dirStr.lastIndexOf(File.separator); dirStr = dirStr.substring(0, firstSlash); return dirStr; } public static void savePreferences() { if (null != tfSessionDataFile) { String sessionDataFile = tfSessionDataFile.getText(); preferences.put(OUTPUT_CSV_FILE_LOCATION, sessionDataFile); } File preferencesFile = getPreferencesFile(); PrintWriter out; try { out = new PrintWriter(preferencesFile); preferences.store(out, "Config information for " + ADVT_URL + " written on " + new java.util.Date()); out.close(); } catch (Exception e) { log.error("Problem saving preferences to " + preferencesFile, e); e.printStackTrace(); } } public static Properties loadPreferences() { File preferencesFile = getPreferencesFile(); Properties prefs = new Properties(); FileReader in; try { in = new FileReader(preferencesFile); prefs.load(in); in.close(); } catch (Exception e) { log.error("Problem loading preferences from " + preferencesFile, e); e.printStackTrace(); } return prefs; } private static File getPreferencesFile() { String home = System.getProperty("user.home"); String advtSettingsDirectory = home + "/AVDT_Settings"; File preferencesDir = new File(advtSettingsDirectory); if (!preferencesDir.exists()) { createPreferencesDirectory(advtSettingsDirectory); } File prefsFile = new File(advtSettingsDirectory + "/advt_prefs.ini"); return prefsFile; } private static void createPreferencesDirectory(String advtSettingsDirectory) { File dir = new File(advtSettingsDirectory); dir.mkdirs(); try { PrintWriter out = new PrintWriter(advtSettingsDirectory + "/README.txt"); out .println("This directory contains settings for the program AVDT."); out.println("For more information, please visit " + ADVT_URL); out.println("This directory was initially created at " + new java.util.Date()); out.println("Please do not delete these files or this directory."); out.close(); } catch (Exception e) { log.error("Problem making readme in directory: " + advtSettingsDirectory, e); e.printStackTrace(); } } public void useNewSession() { if (bDebounce) { return; } bDebounce = true; shownItemCount = 0;// fix for issue centerButton.removeActionListener(this); clickToStartButton.setEnabled(false); clickToStartButton.setForeground(Color.white); // centerButton.setText(""); if (null != session) { CategoryItem[] copy = Arrays.copyOf(session.getItems(), session .getItems().length); SessionConfig config = session.getConfig(); for (int i = 0; i < config.getShuffleCount(); ++i) { Shuffler.shuffle(copy); } itemQueue = new ConcurrentLinkedQueue<CategoryItem>(); for (CategoryItem item : copy) { // TODO: Is there a collections add all I could use here? itemQueue.add(item); } itemQueue.add(copy[copy.length - 1]); // DISGUSTING! totalItemCount = itemQueue.size() - 1; // DISGUSTING! mediator.setSession(session); setupCenterButton(); setFrameTitle(); refreshGui(); // setupTimer is now done on a per-item basis // setupTimer(); setupBetweenTimer(); enableButtons(); mediator.execute(Action.BETWEEN_TIMER); } } private void readSessionFile(File file) throws Exception { readSessionFile(file, null); } private void readSessionFile(File file, String newItemBase) throws Exception { if (this.parser == null) { // SHOULDN'T ALL OF THIS BE HAPPENING DURING STARTUP? No, the open // menu allows reading new sessions. Properties props = readPropertiesFromClassPath(MainGui.propFile); String[] sndExts = props.getProperty(MainGui.sndKey).split(","); LegacyConfigParser legacy = new LegacyConfigParser(sndExts); this.parser = new ConfigParser(legacy); this.parser.registerVersionParser(new ConfigParser100()); } SessionConfig config = this.parser.parse(file); if (null != newItemBase) { config.setItemBase(newItemBase); // prompts are relative to base in new configs // config.setPrompt(newItemBase + "/prompt.wav"); } session = new Session(config); } public static Properties readPropertiesFromClassPath(String fileName) throws IOException { Properties props = new Properties(); // Do it this way and no relative path huha is needed. InputStream in = Gui.class.getClassLoader() .getResourceAsStream(fileName); props.load(new InputStreamReader(in)); return props; } void refreshGui() { mainPanel.revalidate(); frame.pack(); } private void displayClickToBegin() { centerButton.setEnabled(true); centerButton.addActionListener(this); // fix for issue centerButton.setIcon(iiSmilingFaceClickToBegin); // centerButton.setText("Click to Begin"); centerButton.invalidate(); clickToStartButton.setEnabled(true); clickToStartButton.setForeground(Color.red); refreshGui(); } public void actionPerformed(ActionEvent e) { if ((clickToStartButton == e.getSource()) || (centerButton == e.getSource())) { useNewSession(); } else if (BROWSE_SESSION_DATA_FILE.equals(e.getActionCommand())) { chooseSessionDataFile(); } } private void chooseSessionDataFile() { JFileChooser chooser = new JFileChooser(new File(tfSessionDataFile .getText())); int returnVal = chooser.showSaveDialog(frame); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); try { tfSessionDataFile.setText(file.getCanonicalPath()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void populateSessionName() { session.setSessionName(tfSessionName.getText()); } public void populateSessionDataFile() { String fileName = System.getProperty("user.home") + "/brian.csv"; String str = tfSessionDataFile.getText(); str = "".equals(str) ? fileName : str; session.setSessionDataFile(new File(str)); } public void showLoggingFrame() { loggingFrame.setVisible(true); } }
package com.clinchergt.jtetris; import java.util.Random; import java.util.LinkedList; import java.awt.event.*; public class JTetris{ Piece currentPiece, nextOne, nextTwo, nextThree, holdPiece, temp; Field field; boolean holdEnabled = true, gameOver = false; static Random randomizer = new Random(); int das, lines, direction, countdown; long time; int[] history = {Piece.Z, Piece.S, Piece.Z, Piece.S}; public static final int[] initialHistory = {Piece.Z, Piece.S, Piece.Z, Piece.S}; LinkedList<Integer> previousInputs; Integer right, left, hd, a, b, d, restart; public JTetris(){ reset(); } public void reset(){ field = new Field(); for(int i = 0; i < 4; i++) history[i] = initialHistory[i]; currentPiece = new Piece(randomize(6)); nextOne = new Piece(randomize(6)); nextTwo = new Piece(randomize(6)); nextThree = new Piece(randomize(6)); das = 0; lines = 0; countdown = 60; holdEnabled = true; previousInputs = new LinkedList<Integer>(); holdPiece = null; time = System.currentTimeMillis(); right = new Integer(Keys.RIGHT); left = new Integer(Keys.LEFT); hd = new Integer(Keys.HD); a = new Integer(Keys.A); b = new Integer(Keys.B); d = new Integer(Keys.D); restart = new Integer(Keys.RESTART); } public void process(LinkedList inputs){ if(countdown > 0){ countdown if(inputs.contains(left) || inputs.contains(right)) das++; else das = 0; if(countdown == 0) time = System.currentTimeMillis(); }else{ if(inputs.size() == 0){ previousInputs.clear(); das = 0; return; }else{ if(inputs.contains(hd) && !previousInputs.contains(hd)){ field.lockPiece(currentPiece, field.placePiece(currentPiece)); lines += field.clearLines(); if(lines >= 40){ gameOver = true; } currentPiece = new Piece(nextOne); nextOne = new Piece(nextTwo); nextTwo = new Piece(nextThree); nextThree = new Piece(randomize(6)); holdEnabled = true; } if(inputs.contains(left) && inputs.contains(right)){ if(!previousInputs.contains(left) && previousInputs.contains(right)){ das = 0; direction = -1; }else if(!previousInputs.contains(right) && previousInputs.contains(left)){ das = 0; direction = 1; }else if(!previousInputs.contains(right) && !previousInputs.contains(left)){ direction = 0; } if(direction == 1){ shiftRight(); }else if(direction == -1){ shiftLeft(); } }else{ if(inputs.contains(left)){ if(direction == 1){ das = 0; direction = -1; } shiftLeft(); } if(inputs.contains(right)){ if(direction == -1){ das = 0; direction = 1; } shiftRight(); } } if(inputs.contains(a) && !previousInputs.contains(a)){ currentPiece.rotate(false); if(!currentPiece.isOK()){ currentPiece.x++; if(!currentPiece.isOK()){ currentPiece.x -= 2; if(!currentPiece.isOK()){ currentPiece.x++; currentPiece.rotate(true); } } } } if(inputs.contains(b) && !previousInputs.contains(b)){ currentPiece.rotate(true); if(!currentPiece.isOK()){ currentPiece.x++; if(!currentPiece.isOK()){ currentPiece.x -= 2; if(!currentPiece.isOK()){ currentPiece.x++; currentPiece.rotate(false); } } } } if(inputs.contains(d) && holdEnabled && !previousInputs.contains(d)){ if(holdPiece == null){ holdPiece = new Piece(currentPiece.piece); currentPiece = new Piece(nextOne); nextOne = new Piece(nextTwo); nextTwo = new Piece(nextThree); nextThree = new Piece(randomize(6)); }else{ temp = new Piece(holdPiece); holdPiece = new Piece(currentPiece.piece); currentPiece = new Piece(temp); } holdEnabled = false; } if(inputs.contains(restart) && !previousInputs.contains(restart)){ reset(); } previousInputs.clear(); while(inputs.size() != 0){ previousInputs.add((Integer)inputs.remove()); } } } } public int randomize(int rerolls){ int retries, trial; trial = 0; for(int i = 0; i < rerolls; i++){ trial = randomizer.nextInt(7); if(!contains(trial, history)) i = rerolls; } for(int i = 3; i >= 1;){ history[i] = history[--i]; } history[0] = trial; return trial; } public void shiftLeft(){ if(das == 0){ if(currentPiece.shiftAllowed(false)) currentPiece.x das++; } if(previousInputs.contains(left)){ if(++das >= 8) while(currentPiece.shiftAllowed(false)) currentPiece.x } } public void shiftRight(){ if(das == 0){ if(currentPiece.shiftAllowed(true)) currentPiece.x++; das++; } if(previousInputs.contains(right)){ if(++das >= 8) while(currentPiece.shiftAllowed(true)) currentPiece.x++; } } public boolean contains(int n, int[] a){ boolean present = false; for(int j = 0; j < a.length; j++){ if(n == a[j]) return true; } return false; } }