answer stringlengths 17 10.2M |
|---|
package com.readytalk.oss.dbms;
import java.util.Set;
import java.util.Map;
import java.util.List;
import java.io.InputStream;
import java.io.OutputStream;
/**
* This interface defines an API for using a revision-oriented
* relational database management system. The design centers on
* immutable database revisions from which new revisions may be
* derived by applying patches composed of inserts, updates and
* deletes. It provides methods to do the following:
*
* <ul><li>Define a new, empty database revision by supplying a list
* of tables, each of which has a collection of columns and a primary
* key defined as a subset of those columns
*
* <ul><li>The identity of a row is defined by its primary key, and
* this is what we use when comparing rows while calculating diffs
* and merges</li></ul></li>
*
* <li>Create new revisions by defining and applying SQL-style
* inserts, updates, and deletes</li>
*
* <li>Calculate diffs between revisions and serialize them for
* replication and persistence
*
* <ul><li>To generate a snapshot of an entire database, calculate a
* diff between the empty revision and the revision of
* interest</li></ul></li>
*
* <li>Calculate three-way merges from revisions for concurrency
* control</li>
*
* <li>Define queries using SQL-style relational semantics</li>
*
* <li>Execute queries by supplying two database revisions
*
* <ul><li>The result is two sets of tuples satisfying the query
* constraints:
*
* <ul><li>New tuples which either appear in the second revision
* but not the first or which have changed from the first to the
* second</li>
*
* <li>Obsolete tuples which appear in the first but not the
* second</li></ul></li>
*
* <li>Note that traditional query semantics may be achieved by
* specifying an empty revision as the first parameter and the
* database to be queried as the second</li></ul></li></ul>
*/
public interface DBMS {
/**
* These are the possible column types which may be specified when
* defining a column.
*/
public enum ColumnType {
Integer32, // int
Integer64, // long
String, // String
ByteArray, // instance of DBMS.ByteArray (see below)
Object; // any object instance of any type
}
/**
* Represents a windowed view, or slice, of a byte array bounded by
* the specified offset and length.
*/
public interface ByteArray {
public byte[] array();
public int offset();
public int length();
}
/**
* Opaque type representing a column identifier for use in data
* definition and later to identify a column of interest in a query
* or update.
*/
public interface Column { }
/**
* Opaque type representing a table identifier for use in data
* definition and later to identify a column of interest in a query
* or update.
*/
public interface Table { }
/**
* Opaque type representing an immutable database revision.
*/
public interface Database { }
/**
* Opaque type representing an expression (e.g. constant, column
* reference, or query predicate) for use in queries and updates.
*/
public interface Expression { }
/**
* Opaque type representing an expression that will evaluate to a
* boolean value.
*/
public interface BooleanExpression extends Expression { }
/**
* Opaque type representing a source (e.g. table reference or join)
* from which to derive a query result.
*/
public interface Source { }
/**
* Opaque type representing a specific reference to a column. A
* query may make multiple references to the same column (e.g. when
* joining a table with itself), in which case it is useful to
* represent those references as separate objects for
* disambiguation.
*/
public interface ColumnReference extends Expression { }
/**
* Opaque type representing a specific reference to a table. A
* query may make multiple references to the same tablw (e.g. when
* joining a table with itself), in which case it is useful to
* represent those references as separate objects for
* disambiguation.
*/
public interface TableReference extends Source { }
/**
* Opaque type representing the template for a query which is not
* bound to any specific parameters, analogous to a prepared
* statement in JDBC.
*/
public interface QueryTemplate { }
/**
* Opaque type representing a query which combines a query template
* with a set of specific parameters.
*/
public interface Query { }
/**
* Opaque type representing the template for an insert, update, or
* delete which is not bound to any specific parameters, analogous
* to a prepared statement in JDBC.
*/
public interface PatchTemplate { }
/**
* Opaque type representing a series of inserts, updates, and/or
* deletes which may be applied to a database revision to produce a
* new revision.
*/
public interface Patch { }
/**
* A list of rows produced as part of a query result.
*/
public interface ResultIterator {
public boolean nextRow();
public Object nextItem();
}
/**
* Two lists of rows produced by the execution of a query diff,
* consisting of any rows added or updated and any removed. See
* {@link #diff(Database, Database, Query) diff(Database, Database,
* Query)} for details.
*/
public interface QueryResult {
public ResultIterator added();
public ResultIterator removed();
}
/**
* An interface for providing random access to the fields of a row
* via column identifiers.
*/
public interface Row {
public Object value(Column column);
}
/**
* An interface for resolving conflicts which accepts three versions
* of a row -- the base version and two forks -- and returns a row
* which resolves the conflict in an application-appropriate way.
*/
public interface ConflictResolver {
public Row resolveConflict(Table table,
Database base,
Row baseRow,
Database forkA,
Row forkARow,
Database forkB,
Row forkBRow);
}
/**
* Defines a column identifier which is associated with the
* specified type. The type specified here will be used for dynamic
* type checking whenever a value is inserted or updated in this
* column of a table.
*/
public Column column(ColumnType type);
/**
* Defines a table identifier which is associated with the specified
* set of columns and a primary key. The primary key is defined as
* an ordered list of one or more columns where the order defines
* the indexing order as in an SQL DBMS. The combination of columns
* in the primary key determine the unique identity of each row in
* the table.
*/
public Table table(Set<Column> columns,
List<Column> primaryKey);
/**
* Defines an empty database revision which is associated with the
* specified set of table identifiers.
*/
public Database database(Set<Table> tables);
/**
* Defines a table reference which may be used to unambigously refer
* to a table in a query or update. Such a query or update may
* refer to a table more than once, in which case one must create
* multiple TableReferences to the same table.
*/
public TableReference tableReference(Table table);
/**
* Defines a column reference which may be used to unambigously refer
* to a column in a query or update. Such a query or update may
* refer to a column more than once, in which case one must create
* multiple ColumnReferences to the same table.
*/
public ColumnReference columnReference(TableReference tableReference,
Column column);
/**
* Defines a constant value as an expression for use when defining query and
* patch templates.
*/
public Expression constant(Object value);
/**
* Defines a placeholder as an expression for use when defining
* query and update templates. The actual value of the expression
* will be specified when the template is combined with a list of
* parameter values to define a query or patch.
*/
public Expression parameter();
/**
* Defines a boolean expression which, when evaluated, answers the
* question whether the parameter expressions are equal.
*/
public BooleanExpression equal(Expression a,
Expression b);
/**
* Defines a left outer join which matches each row in the left
* table to a row in the right table (or null if there is no
* corresponding row) according to the specified criterium.
*/
public Source leftJoin(TableReference left,
TableReference right,
BooleanExpression criterium);
/**
* Defines a left outer join which matches each row in the first
* table to a row in the second (excluding rows which have no match)
* according to the specified criterium.
*/
public Source innerJoin(TableReference a,
TableReference b,
BooleanExpression criterium);
/**
* Defines a query template (AKA prepared statement) with the
* specified expressions to be evaluated, the source from which any
* column references in the expression list should be resoved, and
* the criterium for selecting from that source.
*/
public QueryTemplate queryTemplate(List<Expression> expressions,
Source source,
BooleanExpression criterium);
/**
* Defines a query by matching a template with any parameter values
* refered to by that template.
*/
public Query query(QueryTemplate template,
Object ... parameters);
/**
* Executes the specified query and returns a diff which represents
* the changes between the first database revision and the second
* concerning that query.
*
* The result is two sets of tuples satisfying the query
* constraints, including
*
* <ul><li>new tuples which either appear in the second revision but
* not the first or which have changed from the first to the
* second, and</li>
*
* <li>obsolete tuples which appear in the first but not the
* second.</li></ul>
*
* Note that traditional SQL SELECT query semantics may be achieved
* by specifying an empty revision as the first parameter and the
* database to be queried as the second.
*/
public QueryResult diff(Database a,
Database b,
Query query);
/**
* Defines a patch template (AKA prepared statement) which
* represents an insert operation on the specified table. The
* values to be inserted are specified as a map of columns to
* expressions.
*/
public PatchTemplate insertTemplate(Table table,
Map<Column, Expression> values);
/**
* Defines a patch template (AKA prepared statement) which
* represents an update operation on the specified table to be
* applied to rows satisfying the specified criterium. The values
* to be inserted are specified as a map of columns to expressions.
*/
public PatchTemplate updateTemplate(Table table,
BooleanExpression criterium,
Map<Column, Expression> values);
/**
* Defines a patch template (AKA prepared statement) which
* represents a delete operation on the specified table to be
* applied to rows satisfying the specified criterium.
*/
public PatchTemplate deleteTemplate(Table table,
BooleanExpression constraint);
/**
* Defines a patch by matching a template with any parameter values
* refered to by that template.
*/
public Patch patch(PatchTemplate template,
Object ... parameters);
/**
* Defines a patch which combines the effect of several patches
* applied in sequence.
*/
public Patch sequence(Patch ... sequence);
/**
* Creates a new database revision which is the result of applying
* the specified patch to the specified revision.
**/
public Database apply(Database database,
Patch patch);
/**
* Calculates a patch which represents the changes from the first
* database revision specified to the second.
**/
public Patch diff(Database a,
Database b);
/**
* Creates a new database revision which merges the changes
* introduced in forkA relative to base with the changes introduced
* in forkB relative to base. The result is determined as follows:
*
* <ul><li>If a row was inserted into only one of the forks, or if
* it was inserted into both with the same values, include the
* insert in the result</li>
*
* <li>If a row was inserted into both forks with different values,
* defer to the conflict resolver to produce a merged row and
* include an insert of that row in the result</li>
*
* <li>If a row was updated in one fork but not the other, include
* the insert in the result</li>
*
* <li>If a row was updated in both forks such that no values
* conflict, create a new row composed of the changed values from
* both forks and the unchanged values from the base, and include an
* update with that row in the result</li>
*
* <li>If a row was updated in both forks such that one or more
* values conflict, defer to the conflict resolver to produce a
* merged row and include an insert of that row in the result</li>
*
* <li>If a row was updated in one fork but deleted in another,
* include the delete in the result</li></ul>
*/
public Database merge(Database base,
Database forkA,
Database forkB,
ConflictResolver conflictResolver);
/**
* Serializes the specified patch and writes it to the specified
* stream.
*/
public void write(Patch patch,
OutputStream out);
/**
* Deserializes a patch from the specified stream.
*/
public Patch readPatch(InputStream in);
} |
package net.i2p.router;
import java.io.IOException;
import java.io.Writer;
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 java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import net.i2p.data.DataHelper;
import net.i2p.router.networkdb.HandleDatabaseLookupMessageJob;
import net.i2p.util.Clock;
import net.i2p.util.I2PThread;
import net.i2p.util.Log;
/**
* Manage the pending jobs according to whatever algorithm is appropriate, giving
* preference to earlier scheduled jobs.
*
*/
public class JobQueue {
private Log _log;
private RouterContext _context;
/** Integer (runnerId) to JobQueueRunner for created runners */
private final Map<Integer, JobQueueRunner> _queueRunners;
/** a counter to identify a job runner */
private volatile static int _runnerId = 0;
/** list of jobs that are ready to run ASAP */
private BlockingQueue<Job> _readyJobs;
/** list of jobs that are scheduled for running in the future */
private List<Job> _timedJobs;
/** job name to JobStat for that job */
private final Map<String, JobStats> _jobStats;
/** how many job queue runners can go concurrently */
private int _maxRunners = 1;
private QueuePumper _pumper;
/** will we allow the # job runners to grow beyond 1? */
private boolean _allowParallelOperation;
/** have we been killed or are we alive? */
private boolean _alive;
private final Object _jobLock;
/** how many when we go parallel */
private static final int RUNNERS;
static {
long maxMemory = Runtime.getRuntime().maxMemory();
if (maxMemory < 64*1024*1024)
RUNNERS = 3;
else if (maxMemory < 256*1024*1024)
RUNNERS = 4;
else
RUNNERS = 5;
}
/** default max # job queue runners operating */
private final static int DEFAULT_MAX_RUNNERS = 1;
/** router.config parameter to override the max runners @deprecated unimplemented */
private final static String PROP_MAX_RUNNERS = "router.maxJobRunners";
/** how frequently should we check and update the max runners */
private final static long MAX_LIMIT_UPDATE_DELAY = 60*1000;
/** if a job is this lagged, spit out a warning, but keep going */
private long _lagWarning = DEFAULT_LAG_WARNING;
private final static long DEFAULT_LAG_WARNING = 5*1000;
/** @deprecated unimplemented */
private final static String PROP_LAG_WARNING = "router.jobLagWarning";
/** if a job is this lagged, the router is hosed, so spit out a warning (dont shut it down) */
private long _lagFatal = DEFAULT_LAG_FATAL;
private final static long DEFAULT_LAG_FATAL = 30*1000;
/** @deprecated unimplemented */
private final static String PROP_LAG_FATAL = "router.jobLagFatal";
/** if a job takes this long to run, spit out a warning, but keep going */
private long _runWarning = DEFAULT_RUN_WARNING;
private final static long DEFAULT_RUN_WARNING = 5*1000;
/** @deprecated unimplemented */
private final static String PROP_RUN_WARNING = "router.jobRunWarning";
/** if a job takes this long to run, the router is hosed, so spit out a warning (dont shut it down) */
private long _runFatal = DEFAULT_RUN_FATAL;
private final static long DEFAULT_RUN_FATAL = 30*1000;
/** @deprecated unimplemented */
private final static String PROP_RUN_FATAL = "router.jobRunFatal";
/** don't enforce fatal limits until the router has been up for this long */
private long _warmupTime = DEFAULT_WARMUP_TIME;
private final static long DEFAULT_WARMUP_TIME = 10*60*1000;
/** @deprecated unimplemented */
private final static String PROP_WARMUP_TIME = "router.jobWarmupTime";
/** max ready and waiting jobs before we start dropping 'em */
private int _maxWaitingJobs = DEFAULT_MAX_WAITING_JOBS;
private final static int DEFAULT_MAX_WAITING_JOBS = 100;
/** @deprecated unimplemented */
private final static String PROP_MAX_WAITING_JOBS = "router.maxWaitingJobs";
/**
* queue runners wait on this whenever they're not doing anything, and
* this gets notified *once* whenever there are ready jobs
*/
private final Object _runnerLock = new Object();
public JobQueue(RouterContext context) {
_context = context;
_log = context.logManager().getLog(JobQueue.class);
_context.statManager().createRateStat("jobQueue.readyJobs",
"How many ready and waiting jobs there are?",
"JobQueue",
new long[] { 60*1000l, 60*60*1000l, 24*60*60*1000l });
_context.statManager().createRateStat("jobQueue.droppedJobs",
"How many jobs do we drop due to insane overload?",
"JobQueue",
new long[] { 60*1000l, 60*60*1000l, 24*60*60*1000l });
_alive = true;
_readyJobs = new LinkedBlockingQueue();
_timedJobs = new ArrayList(64);
_jobLock = new Object();
_queueRunners = new ConcurrentHashMap(RUNNERS);
_jobStats = new ConcurrentHashMap();
_allowParallelOperation = false;
_pumper = new QueuePumper();
I2PThread pumperThread = new I2PThread(_pumper, "Job Queue Pumper", true);
//pumperThread.setPriority(I2PThread.NORM_PRIORITY+1);
pumperThread.start();
}
/**
* Enqueue the specified job
*
*/
public void addJob(Job job) {
if (job == null || !_alive) return;
// This does nothing
//if (job instanceof JobImpl)
// ((JobImpl)job).addedToQueue();
long numReady = 0;
boolean alreadyExists = false;
boolean dropped = false;
// getNext() is now outside the jobLock, is that ok?
synchronized (_jobLock) {
if (_readyJobs.contains(job))
alreadyExists = true;
numReady = _readyJobs.size();
if (!alreadyExists) {
if (_timedJobs.contains(job))
alreadyExists = true;
}
if (shouldDrop(job, numReady)) {
job.dropped();
dropped = true;
} else {
if (!alreadyExists) {
if (job.getTiming().getStartAfter() <= _context.clock().now()) {
// don't skew us - its 'start after' its been queued, or later
job.getTiming().setStartAfter(_context.clock().now());
if (job instanceof JobImpl)
((JobImpl)job).madeReady();
_readyJobs.offer(job);
} else {
_timedJobs.add(job);
}
}
}
_jobLock.notifyAll();
}
_context.statManager().addRateData("jobQueue.readyJobs", numReady, 0);
if (dropped) {
_context.statManager().addRateData("jobQueue.droppedJobs", 1, 1);
if (_log.shouldLog(Log.ERROR))
_log.error("Dropping job due to overload! # ready jobs: "
+ numReady + ": job = " + job);
}
}
public void removeJob(Job job) {
synchronized (_jobLock) {
_readyJobs.remove(job);
_timedJobs.remove(job);
}
}
/**
* Returns <code>true</code> if a given job is waiting or running;
* <code>false</code> if the job is finished or doesn't exist in the queue.
*/
public boolean isJobActive(Job job) {
if (_readyJobs.contains(job) | _timedJobs.contains(job))
return true;
for (JobQueueRunner runner: _queueRunners.values())
if (runner.getCurrentJob() == job)
return true;
return false;
}
public void timingUpdated() {
synchronized (_jobLock) {
_jobLock.notifyAll();
}
}
public int getReadyCount() {
return _readyJobs.size();
}
public long getMaxLag() {
Job j = _readyJobs.peek();
if (j == null) return 0;
// first job is the one that has been waiting the longest
long startAfter = j.getTiming().getStartAfter();
return _context.clock().now() - startAfter;
}
/**
* are we so overloaded that we should drop the given job?
* This is driven both by the numReady and waiting jobs, the type of job
* in question, and what the router's router.maxWaitingJobs config parameter
* is set to.
*
*/
private boolean shouldDrop(Job job, long numReady) {
if (_maxWaitingJobs <= 0) return false; // dont ever drop jobs
if (!_allowParallelOperation) return false; // dont drop during startup [duh]
Class cls = job.getClass();
if (numReady > _maxWaitingJobs) {
// lets not try to drop too many tunnel messages...
//if (cls == HandleTunnelMessageJob.class)
// return true;
// we don't really *need* to answer DB lookup messages
if (cls == HandleDatabaseLookupMessageJob.class)
return true;
}
return false;
}
public void allowParallelOperation() {
_allowParallelOperation = true;
runQueue(RUNNERS);
}
/** @deprecated do you really want to do this? */
public void restart() {
synchronized (_jobLock) {
_timedJobs.clear();
_readyJobs.clear();
_jobLock.notifyAll();
}
}
void shutdown() {
_alive = false;
_timedJobs.clear();
_readyJobs.clear();
// The JobQueueRunners are NOT daemons,
// so they must be stopped.
Job poison = new PoisonJob();
for (int i = 0; i < _queueRunners.size(); i++)
_readyJobs.offer(poison);
}
boolean isAlive() { return _alive; }
/**
* When did the most recently begin job start?
*/
public long getLastJobBegin() {
long when = -1;
for (JobQueueRunner runner : _queueRunners.values()) {
long cur = runner.getLastBegin();
if (cur > when)
cur = when;
}
return when;
}
/**
* When did the most recently begin job start?
*/
public long getLastJobEnd() {
long when = -1;
for (JobQueueRunner runner : _queueRunners.values()) {
long cur = runner.getLastEnd();
if (cur > when)
cur = when;
}
return when;
}
/**
* retrieve the most recently begin and still currently active job, or null if
* no jobs are running
*/
public Job getLastJob() {
Job j = null;
long when = -1;
for (JobQueueRunner cur : _queueRunners.values()) {
if (cur.getLastBegin() > when) {
j = cur.getCurrentJob();
when = cur.getLastBegin();
}
}
return j;
}
/**
* Blocking call to retrieve the next ready job
*
*/
Job getNext() {
while (_alive) {
try {
Job j = _readyJobs.take();
if (j.getJobId() == POISON_ID)
break;
return j;
} catch (InterruptedException ie) {}
}
if (_log.shouldLog(Log.WARN))
_log.warn("No longer alive, returning null");
return null;
}
/**
* Start up the queue with the specified number of concurrent processors.
* If this method has already been called, it will adjust the number of
* runners to meet the new number. This does not kill jobs running on
* excess threads, it merely instructs the threads to die after finishing
* the current job.
*
*/
public synchronized void runQueue(int numThreads) {
// we're still starting up [serially] and we've got at least one runner,
// so dont do anything
if ( (!_queueRunners.isEmpty()) && (!_allowParallelOperation) ) return;
// we've already enabled parallel operation, so grow to however many are
// specified
if (_queueRunners.size() < numThreads) {
if (_log.shouldLog(Log.INFO))
_log.info("Increasing the number of queue runners from "
+ _queueRunners.size() + " to " + numThreads);
for (int i = _queueRunners.size(); i < numThreads; i++) {
JobQueueRunner runner = new JobQueueRunner(_context, i);
_queueRunners.put(Integer.valueOf(i), runner);
Thread t = new I2PThread(runner, "JobQueue " + (++_runnerId) + '/' + numThreads, false);
//t.setPriority(I2PThread.MAX_PRIORITY-1);
t.start();
}
} else if (_queueRunners.size() == numThreads) {
for (JobQueueRunner runner : _queueRunners.values()) {
runner.startRunning();
}
} else { // numThreads < # runners, so shrink
//for (int i = _queueRunners.size(); i > numThreads; i++) {
// QueueRunner runner = (QueueRunner)_queueRunners.get(new Integer(i));
// runner.stopRunning();
}
}
void removeRunner(int id) { _queueRunners.remove(Integer.valueOf(id)); }
/**
* Responsible for moving jobs from the timed queue to the ready queue,
* adjusting the number of queue runners, as well as periodically updating the
* max number of runners.
*
*/
private final class QueuePumper implements Runnable, Clock.ClockUpdateListener {
public QueuePumper() {
_context.clock().addUpdateListener(this);
}
public void run() {
try {
while (_alive) {
long now = _context.clock().now();
long timeToWait = -1;
List<Job> toAdd = null;
try {
synchronized (_jobLock) {
for (int i = 0; i < _timedJobs.size(); i++) {
Job j = _timedJobs.get(i);
// find jobs due to start before now
long timeLeft = j.getTiming().getStartAfter() - now;
if (timeLeft <= 0) {
if (j instanceof JobImpl)
((JobImpl)j).madeReady();
if (toAdd == null) toAdd = new ArrayList(4);
toAdd.add(j);
_timedJobs.remove(i);
i--; // so the index stays consistent
} else {
if ( (timeToWait <= 0) || (timeLeft < timeToWait) )
timeToWait = timeLeft;
}
}
if (toAdd != null) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Not waiting - we have " + toAdd.size() + " newly ready jobs");
// rather than addAll, which allocs a byte array rv before adding,
// we iterate, since toAdd is usually going to only be 1 or 2 entries
// and since readyJobs will often have the space, we can avoid the
// extra alloc. (no, i'm not just being insane - i'm updating this based
// on some profiling data ;)
for (int i = 0; i < toAdd.size(); i++)
_readyJobs.offer(toAdd.get(i));
_jobLock.notifyAll();
} else {
if (timeToWait < 0)
timeToWait = 30*1000;
else if (timeToWait < 10)
timeToWait = 10;
else if (timeToWait > 10*1000)
timeToWait = 10*1000;
//if (_log.shouldLog(Log.DEBUG))
// _log.debug("Waiting " + timeToWait + " before rechecking the timed queue");
_jobLock.wait(timeToWait);
}
} // synchronize (_jobLock)
} catch (InterruptedException ie) {}
} // while (_alive)
} catch (Throwable t) {
_context.clock().removeUpdateListener(this);
if (_log.shouldLog(Log.ERROR))
_log.error("wtf, pumper killed", t);
}
}
public void offsetChanged(long delta) {
updateJobTimings(delta);
synchronized (_jobLock) {
_jobLock.notifyAll();
}
}
}
/**
* Update the clock data for all jobs in process or scheduled for
* completion.
*/
private void updateJobTimings(long delta) {
synchronized (_jobLock) {
for (int i = 0; i < _timedJobs.size(); i++) {
Job j = _timedJobs.get(i);
j.getTiming().offsetChanged(delta);
}
for (Job j : _readyJobs) {
j.getTiming().offsetChanged(delta);
}
}
synchronized (_runnerLock) {
for (JobQueueRunner runner : _queueRunners.values()) {
Job job = runner.getCurrentJob();
if (job != null)
job.getTiming().offsetChanged(delta);
}
}
}
/**
* calculate and update the job timings
* if it was lagged too much or took too long to run, spit out
* a warning (and if its really excessive, kill the router)
*/
void updateStats(Job job, long doStart, long origStartAfter, long duration) {
if (_context.router() == null) return;
String key = job.getName();
long lag = doStart - origStartAfter; // how long were we ready and waiting?
MessageHistory hist = _context.messageHistory();
long uptime = _context.router().getUptime();
if (lag < 0) lag = 0;
if (duration < 0) duration = 0;
JobStats stats = _jobStats.get(key);
if (stats == null) {
stats = new JobStats(key);
_jobStats.put(key, stats);
// yes, if two runners finish the same job at the same time, this could
// create an extra object. but, who cares, its pushed out of the map
// immediately anyway.
}
stats.jobRan(duration, lag);
String dieMsg = null;
if (lag > _lagWarning) {
dieMsg = "Lag too long for job " + job.getName() + " [" + lag + "ms and a run time of " + duration + "ms]";
} else if (duration > _runWarning) {
dieMsg = "Job run too long for job " + job.getName() + " [" + lag + "ms lag and run time of " + duration + "ms]";
}
if (dieMsg != null) {
if (_log.shouldLog(Log.WARN))
_log.warn(dieMsg);
if (hist != null)
hist.messageProcessingError(-1, JobQueue.class.getName(), dieMsg);
}
if ( (lag > _lagFatal) && (uptime > _warmupTime) ) {
// this is fscking bad - the network at this size shouldn't have this much real contention
// so we're going to DIE DIE DIE
if (_log.shouldLog(Log.WARN))
_log.log(Log.WARN, "The router is either incredibly overloaded or (more likely) there's an error.", new Exception("ttttooooo mmmuuuccccchhhh llllaaagggg"));
//try { Thread.sleep(5000); } catch (InterruptedException ie) {}
//Router.getInstance().shutdown();
return;
}
if ( (uptime > _warmupTime) && (duration > _runFatal) ) {
// slow CPUs can get hosed with ElGamal, but 10s is too much.
if (_log.shouldLog(Log.WARN))
_log.log(Log.WARN, "The router is incredibly overloaded - either you have a 386, or (more likely) there's an error. ", new Exception("ttttooooo sssllloooowww"));
//try { Thread.sleep(5000); } catch (InterruptedException ie) {}
//Router.getInstance().shutdown();
return;
}
}
/** job ID counter changed from int to long so it won't wrap negative */
private static final int POISON_ID = -99999;
private static class PoisonJob implements Job {
public String getName() { return null; }
public long getJobId() { return POISON_ID; }
public JobTiming getTiming() { return null; }
public void runJob() {}
public Exception getAddedBy() { return null; }
public void dropped() {}
}
// the remainder are utility methods for dumping status info
public void renderStatusHTML(Writer out) throws IOException {
List<Job> readyJobs = null;
List<Job> timedJobs = null;
List<Job> activeJobs = new ArrayList(RUNNERS);
List<Job> justFinishedJobs = new ArrayList(RUNNERS);
//out.write("<!-- jobQueue rendering -->\n");
out.flush();
//int states[] = null;
int numRunners = 0;
{
//states = new int[_queueRunners.size()];
int i = 0;
for (Iterator<JobQueueRunner> iter = _queueRunners.values().iterator(); iter.hasNext(); i++) {
JobQueueRunner runner = iter.next();
//states[i] = runner.getState();
Job job = runner.getCurrentJob();
if (job != null) {
activeJobs.add(job);
} else {
job = runner.getLastJob();
if (job != null)
justFinishedJobs.add(job);
}
}
numRunners = _queueRunners.size();
}
synchronized (_jobLock) {
readyJobs = new ArrayList(_readyJobs);
timedJobs = new ArrayList(_timedJobs);
}
//out.write("<!-- jobQueue rendering: after jobLock sync -->\n");
//out.flush();
StringBuilder buf = new StringBuilder(32*1024);
buf.append("<b><div class=\"joblog\"><h3>I2P Job Queue</h3><div class=\"wideload\">Job runners: ").append(numRunners);
//buf.append(" [states=");
//if (states != null)
// for (int i = 0; i < states.length; i++)
// buf.append(states[i]).append(" ");
//buf.append(']');
buf.append("</b><br>\n");
long now = _context.clock().now();
buf.append("<hr><b>Active jobs: ").append(activeJobs.size()).append("</b><ol>\n");
for (int i = 0; i < activeJobs.size(); i++) {
Job j = activeJobs.get(i);
buf.append("<li>[started ").append(DataHelper.formatDuration(now-j.getTiming().getStartAfter())).append(" ago]: ");
buf.append(j.toString()).append("</li>\n");
}
buf.append("</ol>\n");
buf.append("<hr><b>Just finished jobs: ").append(justFinishedJobs.size()).append("</b><ol>\n");
for (int i = 0; i < justFinishedJobs.size(); i++) {
Job j = justFinishedJobs.get(i);
buf.append("<li>[finished ").append(DataHelper.formatDuration(now-j.getTiming().getActualEnd())).append(" ago]: ");
buf.append(j.toString()).append("</li>\n");
}
buf.append("</ol>\n");
buf.append("<hr><b>Ready/waiting jobs: ").append(readyJobs.size()).append("</b><ol>\n");
for (int i = 0; i < readyJobs.size(); i++) {
Job j = readyJobs.get(i);
buf.append("<li>[waiting ");
buf.append(DataHelper.formatDuration(now-j.getTiming().getStartAfter()));
buf.append("]: ");
buf.append(j.toString()).append("</li>\n");
}
buf.append("</ol>\n");
out.flush();
buf.append("<hr><b>Scheduled jobs: ").append(timedJobs.size()).append("</b><ol>\n");
TreeMap<Long, Job> ordered = new TreeMap();
for (int i = 0; i < timedJobs.size(); i++) {
Job j = timedJobs.get(i);
ordered.put(new Long(j.getTiming().getStartAfter()), j);
}
for (Iterator<Job> iter = ordered.values().iterator(); iter.hasNext(); ) {
Job j = iter.next();
long time = j.getTiming().getStartAfter() - now;
buf.append("<li>").append(j.getName()).append(" in ");
buf.append(DataHelper.formatDuration(time)).append("</li>\n");
}
buf.append("</ol></div>\n");
//out.write("<!-- jobQueue rendering: after main buffer, before stats -->\n");
out.flush();
getJobStats(buf);
//out.write("<!-- jobQueue rendering: after stats -->\n");
out.flush();
out.write(buf.toString());
}
/** render the HTML for the job stats */
private void getJobStats(StringBuilder buf) {
buf.append("<table>\n" +
"<tr><th>Job</th><th>Runs</th>" +
"<th>Time</th><th><i>Avg</i></th><th><i>Max</i></th><th><i>Min</i></th>" +
"<th>Pending</th><th><i>Avg</i></th><th><i>Max</i></th><th><i>Min</i></th></tr>\n");
long totRuns = 0;
long totExecTime = 0;
long avgExecTime = 0;
long maxExecTime = -1;
long minExecTime = -1;
long totPendingTime = 0;
long avgPendingTime = 0;
long maxPendingTime = -1;
long minPendingTime = -1;
TreeMap<String, JobStats> tstats = new TreeMap(_jobStats);
for (Iterator<JobStats> iter = tstats.values().iterator(); iter.hasNext(); ) {
JobStats stats = iter.next();
buf.append("<tr>");
buf.append("<td><b>").append(stats.getName()).append("</b></td>");
buf.append("<td align=\"right\">").append(stats.getRuns()).append("</td>");
buf.append("<td align=\"right\">").append(stats.getTotalTime()).append("</td>");
buf.append("<td align=\"right\">").append(stats.getAvgTime()).append("</td>");
buf.append("<td align=\"right\">").append(stats.getMaxTime()).append("</td>");
buf.append("<td align=\"right\">").append(stats.getMinTime()).append("</td>");
buf.append("<td align=\"right\">").append(stats.getTotalPendingTime()).append("</td>");
buf.append("<td align=\"right\">").append(stats.getAvgPendingTime()).append("</td>");
buf.append("<td align=\"right\">").append(stats.getMaxPendingTime()).append("</td>");
buf.append("<td align=\"right\">").append(stats.getMinPendingTime()).append("</td>");
buf.append("</tr>\n");
totRuns += stats.getRuns();
totExecTime += stats.getTotalTime();
if (stats.getMaxTime() > maxExecTime)
maxExecTime = stats.getMaxTime();
if ( (minExecTime < 0) || (minExecTime > stats.getMinTime()) )
minExecTime = stats.getMinTime();
totPendingTime += stats.getTotalPendingTime();
if (stats.getMaxPendingTime() > maxPendingTime)
maxPendingTime = stats.getMaxPendingTime();
if ( (minPendingTime < 0) || (minPendingTime > stats.getMinPendingTime()) )
minPendingTime = stats.getMinPendingTime();
}
if (totRuns != 0) {
if (totExecTime != 0)
avgExecTime = totExecTime / totRuns;
if (totPendingTime != 0)
avgPendingTime = totPendingTime / totRuns;
}
buf.append("<tr class=\"tablefooter\">");
buf.append("<td><b>").append("SUMMARY").append("</b></td>");
buf.append("<td align=\"right\">").append(totRuns).append("</td>");
buf.append("<td align=\"right\">").append(totExecTime).append("</td>");
buf.append("<td align=\"right\">").append(avgExecTime).append("</td>");
buf.append("<td align=\"right\">").append(maxExecTime).append("</td>");
buf.append("<td align=\"right\">").append(minExecTime).append("</td>");
buf.append("<td align=\"right\">").append(totPendingTime).append("</td>");
buf.append("<td align=\"right\">").append(avgPendingTime).append("</td>");
buf.append("<td align=\"right\">").append(maxPendingTime).append("</td>");
buf.append("<td align=\"right\">").append(minPendingTime).append("</td>");
buf.append("</tr></table></div>\n");
}
} |
package au.com.williamhill.flywheel;
import static org.junit.Assert.*;
import org.junit.*;
import org.slf4j.*;
import com.obsidiandynamics.indigo.util.*;
public final class UlimitTest {
@Test
public void test() {
final int minLimit = 1024;
final StringBuilder sb = new StringBuilder();
BashInteractor.execute("ulimit -Sn", true, sb::append);
final int limit = Integer.parseInt(sb.toString().trim());
final Logger logger = LoggerFactory.getLogger(UlimitTest.class);
logger.debug("File limit is {}", limit);
assertTrue("Limit is too low " + limit, limit >= minLimit);
}
} |
package be.rl.j.imc.tests;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.junit.runners.MethodSorters;
import be.rl.j.imc.utils.InputUtils;
@FixMethodOrder(MethodSorters.JVM)
public class TestScanNumberFrench {
private class ResultRule extends TestWatcher {
@Override
protected void succeeded(Description description) {
System.out.println(String.format("\tOk :) \t (%s)", description));
}
@Override
protected void failed(Throwable e, Description description) {
System.out.println(String.format("\tKO :( \t (%s)", description));
}
}
@Rule
public ResultRule simpleRule = new ResultRule();
private static int count = 0;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
private String title;
@Before
public void setUp() throws Exception {
title = String.format("Test #%2d : ", ++count);
System.out.print(title);
}
@After
public void tearDown() throws Exception {
}
@Test
public void test1() {
testScanMyNb("1", 1.);
}
@Test
public void test2() {
testScanMyNb("2", 2.);
}
@Test
public void test3() {
testScanMyNb("2 ", 2.);
}
@Test
public void test4() {
testScanMyNb(" 2 ", 2.);
}
@Test
public void test5() {
testScanMyNb(" 2.5 ", 2.5);
}
@Test
public void test6() {
testScanMyNb(" 2,5 ", 2.5);
}
@Test
public void test7() {
testScanMyNb(" 2,5, ", 2.5);
}
@Test
public void test8() {
testScanMyNb("&&ss 2,5, ,,,s", 2.5);
}
@Test
public void test9() {
testScanMyNb("2,5", 25., true);
}
@Test
public void test10() {
testScanMyNb("25.1", 25., true);
}
private void testScanMyNb(String test, Double expected) {
testScanMyNb(test, expected, false);
}
private void testScanMyNb(String test, Double expected, boolean mustFails) {
try {
Double actual = scansMyNb(test);
int len = 20;
if (test.length() < len) {
String testSpaces = String.format("%" + len + "s", test).substring(0, len - test.length())
.replaceAll(".", ".");
System.out.print(String.format("Testing scansMyNb : \"%" + len + "s\" --> result : \"%2.2f\"",
testSpaces + test, expected));
}
if (mustFails) {
Assert.assertNotEquals(expected, actual);
} else {
Assert.assertEquals(expected, actual);
}
} catch (Exception e) {
Assert.fail(e.getMessage());
}
}
private Double scansMyNb(String str) {
return InputUtils.testInputMyNb(str);
}
} |
package com.dragonheart.test;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import com.dragonheart.dijkstra.Point;
import com.dragonheart.dijkstra.Edge;
import com.dragonheart.dijkstra.DijkstraGraph;
public class testDijkstraGraph {
private Point a, b, c, d, e, f;
private Edge A, B, C, D, E, F, G, H;
private DijkstraGraph graph;
@Before
public void setUp() throws Exception {
a = new Point(2, 0);
b = new Point(0, 2);
c = new Point(2, 2);
d = new Point(5, 2);
e = new Point(2, 5);
f = new Point(0, 5);
A = new Edge(a, b, 1.0);
B = new Edge(a, c, 3.0);
C = new Edge(a, d, 5.0);
D = new Edge(b, c, 1.0);
E = new Edge(b, e, 3.0);
F = new Edge(c, e, 1.0);
G = new Edge(d, e, 1.0);
H = new Edge(b, f, 1.0);
graph = new DijkstraGraph();
graph.addPoint(a);
graph.addPoint(b);
graph.addPoint(c);
graph.addPoint(d);
graph.addPoint(e);
graph.addPoint(f);
graph.addEdge(A);
graph.addEdge(B);
graph.addEdge(C);
graph.addEdge(D);
graph.addEdge(E);
graph.addEdge(F);
graph.addEdge(G);
graph.addEdge(H);
}
/**
* Test method for {@link com.dragonheart.dijkstra.DijkstraGraph#processGraph()}
*/
@Test
public final void testProcessGraph_WhenNoSourcesNodes_ReturnFalse() {
assertFalse(graph.processGraph());
}
/**
* Test method for {@link com.dragonheart.dijkstra.DijkstraGraph#processGraph()}
*/
@Test
public final void testProcessGraph_WithSourceNodes_ReturnTrue() {
graph.setSource(a, 0.0);
assertTrue(graph.processGraph());
}
/**
* Test method for {@link com.dragonheart.dijkstra.DijkstraGraph#processGraph()}
*/
@Test
public final void testProcessGraph_BasicResults() {
graph.setSource(e, 0.0);
graph.processGraph();
List<Point> path = graph.getPathFrom(a);
assertTrue(path.get(0).aggregateCost == 3);
}
/**
* Test method for {@link com.dragonheart.dijkstra.DijkstraGraph#getPathFrom(Point)}
*/
@Test
public final void testGetPathFrom_WithSingleSourceNode() {
graph.setSource(e, 0.0);
graph.processGraph();
List<Point> path = graph.getPathFrom(a);
assertTrue(path.get(0) == a);
assertTrue(path.get(1) == b);
assertTrue(path.get(2) == c);
assertTrue(path.get(3) == e);
}
/**
* Test method for {@link com.dragonheart.dijkstra.DijkstraGraph#getPathFrom(Point)}
*/
@Test
public final void testGetPathFrom_WithMultipleSourceNodes() {
ArrayList<Point> nodes = new ArrayList<Point>();
nodes.add(e);
nodes.add(f);
graph.setSources(nodes, 0.0);
graph.processGraph();
List<Point> path = graph.getPathFrom(a);
assertTrue(path.get(0) == a);
assertTrue(path.get(1) == b);
assertTrue(path.get(2) == f);
}
} |
package com.megaport.api.client;
import com.megaport.api.dto.*;
import com.megaport.api.exceptions.BadRequestException;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class PortOrdersTest {
MegaportApiSession session;
@Before
public void init() throws Exception {
session = new MegaportApiSession(Environment.TRAINING, "admin", "slimweasel94");
assertTrue(session.isValid());
}
@Test
public void testValidatePort() throws Exception {
List<MegaportServiceDto> order = new ArrayList<>();
order.add(createGoodPort());
// prices for this account will be $0
List<ServiceLineItemDto> serviceLineItemDtos = session.validateOrder(order);
assertEquals(1, serviceLineItemDtos.size());
}
@Test
public void testOrderPort() throws Exception {
List<MegaportServiceDto> order = new ArrayList<>();
order.add(createGoodPort());
// prices for this account will be $0
String orderResponse = session.placeOrder(order);
System.out.println(orderResponse);
}
@Test
public void testValidatePortOrderMissingSpeed() throws Exception {
List<MegaportServiceDto> order = new ArrayList<>();
order.add(createBadPortMissingSpeed());
try {
session.validateOrder(order);
fail();
} catch (BadRequestException e) {
e.printStackTrace();
}
}
@Test
public void testValidatePortOrderBadSpeed() throws Exception {
List<MegaportServiceDto> order = new ArrayList<>();
order.add(createBadPortInvalidSpeed());
try {
session.validateOrder(order);
fail();
} catch (BadRequestException e) {
e.printStackTrace();
}
}
@Test
public void testValidatePortNoName() throws Exception {
List<MegaportServiceDto> order = new ArrayList<>();
order.add(createBadPortNoName());
try {
session.validateOrder(order);
fail();
} catch (BadRequestException e) {
e.printStackTrace();
}
}
@Test
public void testValidatePortBadLocation() throws Exception {
List<MegaportServiceDto> order = new ArrayList<>();
order.add(createBadPortBadLocation());
try {
session.validateOrder(order);
fail();
} catch (BadRequestException e) {
e.printStackTrace();
}
}
@Test
public void testValidatePortMissingStatus() throws Exception {
List<MegaportServiceDto> order = new ArrayList<>();
order.add(createBadPortMissingStatus());
try {
session.validateOrder(order);
fail();
} catch (BadRequestException e) {
e.printStackTrace();
}
}
private MegaportServiceDto createGoodPort() {
MegaportServiceDto dto = new MegaportServiceDto();
dto.setLocationId(3);
dto.setTerm(24);
dto.setProductType(ProductType.MEGAPORT);
dto.setProductName("My New Port");
dto.setProvisioningStatus(ProvisioningStatus.DESIGN);
dto.setPortSpeed(10000);
return dto;
}
private MegaportServiceDto createBadPortNoName() {
MegaportServiceDto dto = new MegaportServiceDto();
dto.setLocationId(3);
dto.setTerm(24);
dto.setProductType(ProductType.MEGAPORT);
dto.setProvisioningStatus(ProvisioningStatus.DESIGN);
dto.setPortSpeed(10000);
return dto;
}
private MegaportServiceDto createBadPortMissingSpeed() {
MegaportServiceDto dto = new MegaportServiceDto();
dto.setLocationId(3);
dto.setTerm(24);
dto.setProductType(ProductType.MEGAPORT);
dto.setProductName("My New Port");
dto.setProvisioningStatus(ProvisioningStatus.DESIGN);
return dto;
}
private MegaportServiceDto createBadPortBadLocation() {
MegaportServiceDto dto = new MegaportServiceDto();
dto.setLocationId(-3);
dto.setTerm(24);
dto.setProductType(ProductType.MEGAPORT);
dto.setProductName("My New Port");
dto.setProvisioningStatus(ProvisioningStatus.DESIGN);
dto.setPortSpeed(10000);
return dto;
}
private MegaportServiceDto createBadPortInvalidSpeed() {
MegaportServiceDto dto = new MegaportServiceDto();
dto.setLocationId(-3);
dto.setTerm(24);
dto.setProductType(ProductType.MEGAPORT);
dto.setProductName("My New Port");
dto.setProvisioningStatus(ProvisioningStatus.DESIGN);
dto.setPortSpeed(3);
return dto;
}
private MegaportServiceDto createBadPortMissingStatus() {
MegaportServiceDto dto = new MegaportServiceDto();
dto.setLocationId(-3);
dto.setTerm(24);
dto.setProductType(ProductType.MEGAPORT);
dto.setProductName("My New Port");
dto.setPortSpeed(10000);
return dto;
}
} |
package io.ebean.dbmigration.ddl;
import java.io.StringReader;
import java.util.List;
import org.testng.annotations.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class DdlParserTest {
private DdlParser parser = new DdlParser();
@Test
public void parse_ignoresEmptyLines() throws Exception {
List<String> stmts = parser.parse(new StringReader("\n\none;\n\ntwo;\n\n"));
assertThat(stmts).hasSize(2);
assertThat(stmts).contains("one;","two;");
}
@Test
public void parse_ignoresComments_whenFirst() throws Exception {
List<String> stmts = parser.parse(new StringReader("-- comment\ntwo;"));
assertThat(stmts).hasSize(1);
assertThat(stmts).contains("two;");
}
@Test
public void parse_ignoresEmptyLines_whenFirst() throws Exception {
List<String> stmts = parser.parse(new StringReader("\n\n-- comment\ntwo;\n\n"));
assertThat(stmts).hasSize(1);
assertThat(stmts).contains("two;");
}
@Test
public void parse_inlineEmptyLines_replacedWithSpace() throws Exception {
List<String> stmts = parser.parse(new StringReader("\n\n-- comment\none\ntwo;\n\n"));
assertThat(stmts).hasSize(1);
assertThat(stmts).contains("one two;");
}
@Test
public void parse_ignoresComments() throws Exception {
List<String> stmts = parser.parse(new StringReader("one;\n-- comment\ntwo;"));
assertThat(stmts).hasSize(2);
assertThat(stmts).contains("one;","two;");
}
@Test
public void parse_ignoresEndOfLineComments() throws Exception {
List<String> stmts = parser.parse(new StringReader("one; -- comment\ntwo;"));
assertThat(stmts).containsExactly("one;", "two;");
}
} |
package io.elssa.test.through;
import io.elssa.event.ConcurrentEventReactor;
import io.elssa.event.EventContext;
import io.elssa.event.EventHandler;
import io.elssa.net.ServerMessageRouter;
public class ThroughputServer {
protected static final int PORT = 5050;
protected static final int QUERY_SIZE = 64;
protected static final int REPLY_SIZE = 4096;
private ThroughputEventMap eventMap = new ThroughputEventMap();
private ConcurrentEventReactor reactor;
private ServerMessageRouter messageRouter;
private long counter;
public void start()
throws Exception {
reactor = new ConcurrentEventReactor(this, eventMap, 8);
messageRouter = new ServerMessageRouter();
messageRouter.addListener(reactor);
reactor.start();
messageRouter.listen(PORT);
System.out.println("Listening on port " + PORT);
}
@EventHandler
public void handleMessage(ThroughputMessage msg, EventContext context) {
byte[] payload = msg.getPayload();
counter += payload.length / 100000;
if (counter % 1000 == 0) {
System.out.print('.');
}
}
public static void main(String[] args) throws Exception {
ThroughputServer serv = new ThroughputServer();
serv.start();
}
} |
package io.github.bonigarcia.wdm.test;
import static org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.openqa.selenium.edge.EdgeDriver;
import io.github.bonigarcia.wdm.EdgeDriverManager;
import io.github.bonigarcia.wdm.base.BaseBrowserTst;
/**
* Test with Microsoft Edge.
*
* @author Boni Garcia (boni.gg@gmail.com)
* @since 1.3.0
*/
public class EdgeTest extends BaseBrowserTst {
@BeforeClass
public static void setupClass() {
validOS = IS_OS_WINDOWS;
if (validOS) {
EdgeDriverManager.getInstance().version("3.14393").setup();
}
}
@Before
public void setupTest() {
if (validOS) {
driver = new EdgeDriver();
}
}
@AfterClass
public static void teardownClass() {
validOS = true;
}
} |
package me.lemire.integercompression;
import java.util.Arrays;
import java.util.Random;
import me.lemire.integercompression.differential.Delta;
import me.lemire.integercompression.differential.IntegratedBinaryPacking;
import me.lemire.integercompression.differential.IntegratedComposition;
import me.lemire.integercompression.differential.IntegratedIntegerCODEC;
import me.lemire.integercompression.differential.IntegratedVariableByte;
import me.lemire.integercompression.differential.XorBinaryPacking;
import me.lemire.integercompression.synth.ClusteredDataGenerator;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Just some basic sanity tests.
*
* @author Daniel Lemire
*/
@SuppressWarnings({ "static-method" })
public class BasicTest {
IntegerCODEC[] codecs = {
new IntegratedComposition(new IntegratedBinaryPacking(),
new IntegratedVariableByte()),
new JustCopy(),
new VariableByte(),
new GroupSimple9(),
new IntegratedVariableByte(),
new Composition(new BinaryPacking(), new VariableByte()),
new Composition(new NewPFD(), new VariableByte()),
new Composition(new NewPFDS16(), new VariableByte()),
new Composition(new OptPFDS9(), new VariableByte()),
new Composition(new OptPFDS16(), new VariableByte()),
new Composition(new FastPFOR128(), new VariableByte()),
new Composition(new FastPFOR(), new VariableByte()),
new Simple9(),
new Simple16(),
new GroupSimple9(),
new Composition(new XorBinaryPacking(), new VariableByte()),
new Composition(new DeltaZigzagBinaryPacking(),
new DeltaZigzagVariableByte()) };
@Test
public void saulTest() {
for (IntegerCODEC C : codecs) {
for (int x = 0; x < 50; ++x) {
int[] a = { 2, 3, 4, 5 };
int[] b = new int[90];
int[] c = new int[a.length];
IntWrapper aOffset = new IntWrapper(0);
IntWrapper bOffset = new IntWrapper(x);
C.compress(a, aOffset, a.length, b, bOffset);
int len = bOffset.get() - x;
bOffset.set(x);
IntWrapper cOffset = new IntWrapper(0);
C.uncompress(b, bOffset, len, c, cOffset);
if(!Arrays.equals(a, c)) {
System.out.println("Problem with "+C);
}
assertArrayEquals(a, c);
}
}
}
@Test
public void varyingLengthTest() {
int N = 4096;
int[] data = new int[N];
for (int k = 0; k < N; ++k)
data[k] = k;
for (IntegerCODEC c : codecs) {
System.out.println("[BasicTest.varyingLengthTest] codec = " + c);
for (int L = 1; L <= 128; L++) {
int[] comp = TestUtils.compress(c, Arrays.copyOf(data, L));
int[] answer = TestUtils.uncompress(c, comp, L);
for (int k = 0; k < L; ++k)
if (answer[k] != data[k])
throw new RuntimeException("bug");
}
for (int L = 128; L <= N; L *= 2) {
int[] comp = TestUtils.compress(c, Arrays.copyOf(data, L));
int[] answer = TestUtils.uncompress(c, comp, L);
for (int k = 0; k < L; ++k)
if (answer[k] != data[k]) {
System.out.println(Arrays.toString(Arrays.copyOf(
answer, L)));
System.out.println(Arrays.toString(Arrays.copyOf(data,
L)));
throw new RuntimeException("bug");
}
}
}
}
@Test
public void varyingLengthTest2() {
int N = 128;
int[] data = new int[N];
data[127] = -1;
for (IntegerCODEC c : codecs) {
System.out.println("[BasicTest.varyingLengthTest2] codec = " + c);
try {
// CODEC Simple9 is limited to "small" integers.
if (c.getClass().equals(
Class.forName("me.lemire.integercompression.Simple9")))
continue;
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
// CODEC Simple16 is limited to "small" integers.
if (c.getClass().equals(
Class.forName("me.lemire.integercompression.Simple16")))
continue;
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
// CODEC GroupSimple9 is limited to "small" integers.
if (c.getClass().equals(
Class.forName("me.lemire.integercompression.GroupSimple9")))
continue;
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
for (int L = 1; L <= 128; L++) {
int[] comp = TestUtils.compress(c, Arrays.copyOf(data, L));
int[] answer = TestUtils.uncompress(c, comp, L);
for (int k = 0; k < L; ++k)
if (answer[k] != data[k])
throw new RuntimeException("bug");
}
for (int L = 128; L <= N; L *= 2) {
int[] comp = TestUtils.compress(c, Arrays.copyOf(data, L));
int[] answer = TestUtils.uncompress(c, comp, L);
for (int k = 0; k < L; ++k)
if (answer[k] != data[k])
throw new RuntimeException("bug");
}
}
}
@Test
public void checkDeltaZigzagVB() {
DeltaZigzagVariableByte codec = new DeltaZigzagVariableByte();
DeltaZigzagVariableByte codeco = new DeltaZigzagVariableByte();
testZeroInZeroOut(codec);
test(codec, codeco, 5, 10);
test(codec, codeco, 5, 14);
test(codec, codeco, 2, 18);
}
@Test
public void checkDeltaZigzagPacking() {
DeltaZigzagBinaryPacking codec = new DeltaZigzagBinaryPacking();
testZeroInZeroOut(codec);
testSpurious(codec);
IntegerCODEC compo = new Composition(new DeltaZigzagBinaryPacking(),
new VariableByte());
IntegerCODEC compo2 = new Composition(new DeltaZigzagBinaryPacking(),
new VariableByte());
testZeroInZeroOut(compo);
testUnsorted(compo);
test(compo, compo2, 5, 10);
test(compo, compo2, 5, 14);
test(compo, compo2, 2, 18);
}
@Test
public void checkXorBinaryPacking() {
testZeroInZeroOut(new XorBinaryPacking());
testSpurious(new XorBinaryPacking());
}
@Test
public void checkXorBinaryPacking1() {
IntegerCODEC c = new IntegratedComposition(new XorBinaryPacking(),
new IntegratedVariableByte());
testZeroInZeroOut(c);
}
@Test
public void checkXorBinaryPacking2() {
IntegerCODEC c = new IntegratedComposition(new XorBinaryPacking(),
new IntegratedVariableByte());
testUnsorted(c);
}
@Test
public void checkXorBinaryPacking3() {
IntegerCODEC c = new IntegratedComposition(new XorBinaryPacking(),
new IntegratedVariableByte());
IntegerCODEC co = new IntegratedComposition(new XorBinaryPacking(),
new IntegratedVariableByte());
test(c, co, 5, 10);
test(c, co, 5, 14);
test(c, co, 2, 18);
}
/**
* Verify bitpacking.
*/
@Test
public void verifyBitPacking() {
final int N = 32;
final int TIMES = 1000;
Random r = new Random();
int[] data = new int[N];
int[] compressed = new int[N];
int[] uncompressed = new int[N];
for (int bit = 0; bit < 31; ++bit) {
for (int t = 0; t < TIMES; ++t) {
for (int k = 0; k < N; ++k) {
data[k] = r.nextInt(1 << bit);
}
BitPacking.fastpack(data, 0, compressed, 0, bit);
BitPacking.fastunpack(compressed, 0, uncompressed, 0, bit);
assertArrayEquals(uncompressed, data);
}
}
}
/**
* Verify bitpacking without mask.
*/
@Test
public void verifyWithoutMask() {
final int N = 32;
final int TIMES = 1000;
Random r = new Random();
int[] data = new int[N];
int[] compressed = new int[N];
int[] uncompressed = new int[N];
for (int bit = 0; bit < 31; ++bit) {
for (int t = 0; t < TIMES; ++t) {
for (int k = 0; k < N; ++k) {
data[k] = r.nextInt(1 << bit);
}
BitPacking.fastpackwithoutmask(data, 0, compressed, 0, bit);
BitPacking.fastunpack(compressed, 0, uncompressed, 0, bit);
assertArrayEquals(uncompressed, data);
}
}
}
/**
* @param array
* some array
* @param mask
* provided mask
*/
public static void maskArray(int[] array, int mask) {
for (int i = 0, end = array.length; i < end; ++i) {
array[i] &= mask;
}
}
/**
* Verify bitpacking with exception.
*/
@Test
public void verifyWithExceptions() {
final int N = 32;
final int TIMES = 1000;
Random r = new Random();
int[] data = new int[N];
int[] compressed = new int[N];
int[] uncompressed = new int[N];
for (int bit = 0; bit < 31; ++bit) {
for (int t = 0; t < TIMES; ++t) {
for (int k = 0; k < N; ++k) {
data[k] = r.nextInt();
}
BitPacking.fastpack(data, 0, compressed, 0, bit);
BitPacking.fastunpack(compressed, 0, uncompressed, 0, bit);
// Check assertions.
maskArray(data, ((1 << bit) - 1));
assertArrayEquals(data, uncompressed);
}
}
}
/**
* check that the codecs can be inverted.
*/
@Test
public void basictest() {
test(5, 10);
test(5, 14);
test(2, 18);
}
/**
* check that there is no spurious output.
*/
@Test
public void spuriousouttest() {
testSpurious(new IntegratedBinaryPacking());
testSpurious(new BinaryPacking());
testSpurious(new NewPFD());
testSpurious(new NewPFDS9());
testSpurious(new NewPFDS16());
testSpurious(new OptPFD());
testSpurious(new OptPFDS9());
testSpurious(new OptPFDS16());
testSpurious(new FastPFOR128());
testSpurious(new FastPFOR());
}
/**
* check that an empty array generates an empty array after compression.
*/
@Test
public void zeroinzerouttest() {
testZeroInZeroOut(new IntegratedBinaryPacking());
testZeroInZeroOut(new IntegratedVariableByte());
testZeroInZeroOut(new BinaryPacking());
testZeroInZeroOut(new NewPFD());
testZeroInZeroOut(new NewPFDS9());
testZeroInZeroOut(new NewPFDS16());
testZeroInZeroOut(new OptPFD());
testZeroInZeroOut(new OptPFDS9());
testZeroInZeroOut(new OptPFDS16());
testZeroInZeroOut(new FastPFOR128());
testZeroInZeroOut(new FastPFOR());
testZeroInZeroOut(new VariableByte());
testZeroInZeroOut(new Composition(new IntegratedBinaryPacking(),
new VariableByte()));
testZeroInZeroOut(new Composition(new BinaryPacking(),
new VariableByte()));
testZeroInZeroOut(new Composition(new NewPFD(), new VariableByte()));
testZeroInZeroOut(new Composition(new NewPFDS9(), new VariableByte()));
testZeroInZeroOut(new Composition(new NewPFDS16(), new VariableByte()));
testZeroInZeroOut(new Composition(new OptPFD(), new VariableByte()));
testZeroInZeroOut(new Composition(new OptPFDS9(), new VariableByte()));
testZeroInZeroOut(new Composition(new OptPFDS16(), new VariableByte()));
testZeroInZeroOut(new Composition(new FastPFOR128(), new VariableByte()));
testZeroInZeroOut(new Composition(new FastPFOR(), new VariableByte()));
testZeroInZeroOut(new IntegratedComposition(
new IntegratedBinaryPacking(), new IntegratedVariableByte()));
}
private static void testSpurious(IntegerCODEC c) {
int[] x = new int[1024];
int[] y = new int[0];
IntWrapper i0 = new IntWrapper(0);
IntWrapper i1 = new IntWrapper(0);
for (int inlength = 0; inlength < 32; ++inlength) {
c.compress(x, i0, inlength, y, i1);
assertEquals(0, i1.intValue());
}
}
private static void testZeroInZeroOut(IntegerCODEC c) {
int[] x = new int[0];
int[] y = new int[0];
IntWrapper i0 = new IntWrapper(0);
IntWrapper i1 = new IntWrapper(0);
c.compress(x, i0, 0, y, i1);
assertEquals(0, i1.intValue());
int[] out = new int[0];
IntWrapper outpos = new IntWrapper(0);
c.uncompress(y, i1, 0, out, outpos);
assertEquals(0, outpos.intValue());
}
private static void test(IntegerCODEC c, IntegerCODEC co, int N, int nbr) {
ClusteredDataGenerator cdg = new ClusteredDataGenerator();
for (int sparsity = 1; sparsity < 31 - nbr; sparsity += 4) {
int[][] data = new int[N][];
int max = (1 << (nbr + sparsity));
for (int k = 0; k < N; ++k) {
data[k] = cdg.generateClustered((1 << nbr), max);
}
testCodec(c, co, data, max);
}
}
private static void test(int N, int nbr) {
ClusteredDataGenerator cdg = new ClusteredDataGenerator();
System.out.println("[BasicTest.test] N = " + N + " " + nbr);
for (int sparsity = 1; sparsity < 31 - nbr; sparsity += 4) {
int[][] data = new int[N][];
int max = (1 << (nbr + sparsity));
for (int k = 0; k < N; ++k) {
data[k] = cdg.generateClustered((1 << nbr), max);
}
testCodec(new IntegratedComposition(new IntegratedBinaryPacking(),
new IntegratedVariableByte()),
new IntegratedComposition(new IntegratedBinaryPacking(),
new IntegratedVariableByte()), data, max);
testCodec(new JustCopy(), new JustCopy(), data, max);
testCodec(new VariableByte(), new VariableByte(), data, max);
testCodec(new IntegratedVariableByte(),
new IntegratedVariableByte(), data, max);
testCodec(new Composition(new BinaryPacking(), new VariableByte()),
new Composition(new BinaryPacking(), new VariableByte()),
data, max);
testCodec(new Composition(new NewPFD(), new VariableByte()),
new Composition(new NewPFD(), new VariableByte()), data,
max);
testCodec(new Composition(new NewPFDS9(), new VariableByte()),
new Composition(new NewPFDS9(), new VariableByte()), data,
max);
testCodec(new Composition(new NewPFDS16(), new VariableByte()),
new Composition(new NewPFDS16(), new VariableByte()), data,
max);
testCodec(new Composition(new OptPFD(), new VariableByte()),
new Composition(new OptPFD(), new VariableByte()), data,
max);
testCodec(new Composition(new OptPFDS9(), new VariableByte()),
new Composition(new OptPFDS9(), new VariableByte()), data,
max);
testCodec(new Composition(new OptPFDS16(), new VariableByte()),
new Composition(new OptPFDS16(), new VariableByte()), data,
max);
testCodec(new Composition(new FastPFOR128(), new VariableByte()),
new Composition(new FastPFOR128(), new VariableByte()),
data, max);
testCodec(new Composition(new FastPFOR(), new VariableByte()),
new Composition(new FastPFOR(), new VariableByte()),
data, max);
testCodec(new Simple9(), new Simple9(), data, max);
}
}
private static void testCodec(IntegerCODEC c, IntegerCODEC co,
int[][] data, int max) {
int N = data.length;
int maxlength = 0;
for (int k = 0; k < N; ++k) {
if (data[k].length > maxlength)
maxlength = data[k].length;
}
int[] buffer = new int[maxlength + 1024];
int[] dataout = new int[4 * maxlength + 1024];
// 4x + 1024 to account for the possibility of some negative
// compression.
IntWrapper inpos = new IntWrapper();
IntWrapper outpos = new IntWrapper();
for (int k = 0; k < N; ++k) {
int[] backupdata = Arrays.copyOf(data[k], data[k].length);
inpos.set(1);
outpos.set(0);
if (!(c instanceof IntegratedIntegerCODEC)) {
Delta.delta(backupdata);
}
c.compress(backupdata, inpos, backupdata.length - inpos.get(),
dataout, outpos);
final int thiscompsize = outpos.get() + 1;
inpos.set(0);
outpos.set(1);
buffer[0] = backupdata[0];
co.uncompress(dataout, inpos, thiscompsize - 1, buffer, outpos);
if (!(c instanceof IntegratedIntegerCODEC))
Delta.fastinverseDelta(buffer);
// Check assertions.
assertEquals("length is not match", outpos.get(), data[k].length);
int[] bufferCutout = Arrays.copyOf(buffer, outpos.get());
assertArrayEquals("failed to reconstruct original data", data[k],
bufferCutout);
}
}
/**
* Test for unsorted array.
*/
@Test
public void testUnsortedExample() {
testUnsorted(new VariableByte());
testUnsorted(new IntegratedVariableByte());
testUnsorted(new Composition(new BinaryPacking(), new VariableByte()));
testUnsorted(new Composition(new NewPFD(), new VariableByte()));
testUnsorted(new Composition(new NewPFDS9(), new VariableByte()));
testUnsorted(new Composition(new NewPFDS16(), new VariableByte()));
testUnsorted(new Composition(new OptPFD(), new VariableByte()));
testUnsorted(new Composition(new OptPFDS9(), new VariableByte()));
testUnsorted(new Composition(new OptPFDS16(), new VariableByte()));
testUnsorted(new Composition(new FastPFOR128(), new VariableByte()));
testUnsorted(new Composition(new FastPFOR(), new VariableByte()));
testUnsorted(new IntegratedComposition(new IntegratedBinaryPacking(),
new IntegratedVariableByte()));
testUnsorted(new Composition(new IntegratedBinaryPacking(),
new VariableByte()));
testUnsorted2(new VariableByte());
testUnsorted2(new IntegratedVariableByte());
testUnsorted2(new Composition(new BinaryPacking(), new VariableByte()));
testUnsorted2(new Composition(new NewPFD(), new VariableByte()));
testUnsorted2(new Composition(new NewPFDS9(), new VariableByte()));
testUnsorted2(new Composition(new NewPFDS16(), new VariableByte()));
testUnsorted2(new Composition(new OptPFD(), new VariableByte()));
testUnsorted2(new Composition(new OptPFDS9(), new VariableByte()));
testUnsorted2(new Composition(new OptPFDS16(), new VariableByte()));
testUnsorted2(new Composition(new FastPFOR128(), new VariableByte()));
testUnsorted2(new Composition(new FastPFOR(), new VariableByte()));
testUnsorted3(new IntegratedComposition(new IntegratedBinaryPacking(),
new IntegratedVariableByte()));
testUnsorted3(new Composition(new IntegratedBinaryPacking(),
new VariableByte()));
testUnsorted3(new VariableByte());
testUnsorted3(new IntegratedVariableByte());
testUnsorted3(new Composition(new BinaryPacking(), new VariableByte()));
testUnsorted3(new Composition(new NewPFD(), new VariableByte()));
testUnsorted3(new Composition(new NewPFDS9(), new VariableByte()));
testUnsorted3(new Composition(new NewPFDS16(), new VariableByte()));
testUnsorted3(new Composition(new OptPFD(), new VariableByte()));
testUnsorted3(new Composition(new OptPFDS9(), new VariableByte()));
testUnsorted3(new Composition(new OptPFDS16(), new VariableByte()));
testUnsorted3(new Composition(new FastPFOR128(), new VariableByte()));
testUnsorted3(new Composition(new FastPFOR(), new VariableByte()));
testUnsorted2(new IntegratedComposition(new IntegratedBinaryPacking(),
new IntegratedVariableByte()));
testUnsorted2(new Composition(new IntegratedBinaryPacking(),
new VariableByte()));
}
/**
* @param codec
* provided codec
*/
public void testUnsorted(IntegerCODEC codec) {
int[] lengths = { 133, 1026, 1333333 };
for (int N : lengths) {
int[] data = new int[N];
// initialize the data (most will be small)
for (int k = 0; k < N; k += 1)
data[k] = 3;
// throw some larger values
for (int k = 0; k < N; k += 5)
data[k] = 100;
for (int k = 0; k < N; k += 533)
data[k] = 10000;
data[5] = -311;
// could need more compressing
int[] compressed = new int[(int) Math.ceil(N * 1.01) + 1024];
IntWrapper inputoffset = new IntWrapper(0);
IntWrapper outputoffset = new IntWrapper(0);
codec.compress(data, inputoffset, data.length, compressed,
outputoffset);
// we can repack the data: (optional)
compressed = Arrays.copyOf(compressed, outputoffset.intValue());
int[] recovered = new int[N];
IntWrapper recoffset = new IntWrapper(0);
codec.uncompress(compressed, new IntWrapper(0), compressed.length,
recovered, recoffset);
assertArrayEquals(data, recovered);
}
}
private void testUnsorted2(IntegerCODEC codec) {
int[] data = new int[128];
data[5] = -1;
int[] compressed = new int[1024];
IntWrapper inputoffset = new IntWrapper(0);
IntWrapper outputoffset = new IntWrapper(0);
codec.compress(data, inputoffset, data.length, compressed, outputoffset);
// we can repack the data: (optional)
compressed = Arrays.copyOf(compressed, outputoffset.intValue());
int[] recovered = new int[128];
IntWrapper recoffset = new IntWrapper(0);
codec.uncompress(compressed, new IntWrapper(0), compressed.length,
recovered, recoffset);
assertArrayEquals(data, recovered);
}
private void testUnsorted3(IntegerCODEC codec) {
int[] data = new int[128];
data[127] = -1;
int[] compressed = new int[1024];
IntWrapper inputoffset = new IntWrapper(0);
IntWrapper outputoffset = new IntWrapper(0);
codec.compress(data, inputoffset, data.length, compressed, outputoffset);
// we can repack the data: (optional)
compressed = Arrays.copyOf(compressed, outputoffset.intValue());
int[] recovered = new int[128];
IntWrapper recoffset = new IntWrapper(0);
codec.uncompress(compressed, new IntWrapper(0), compressed.length,
recovered, recoffset);
assertArrayEquals(data, recovered);
}
@Test
public void fastPforTest() {
FastPFOR codec1 = new FastPFOR();
FastPFOR codec2 = new FastPFOR();
int N = FastPFOR.BLOCK_SIZE;
int[] data = new int[N];
for (int i = 0; i < N; i++)
data[i] = 0;
data[126] = -1;
int[] comp = TestUtils.compress(codec1, Arrays.copyOf(data, N));
int[] answer = TestUtils.uncompress(codec2, comp, N);
for (int k = 0; k < N; ++k)
if (answer[k] != data[k])
throw new RuntimeException("bug " + k + " " + answer[k]
+ " != " + data[k]);
}
@Test
public void fastPfor128Test() {
FastPFOR128 codec1 = new FastPFOR128();
FastPFOR128 codec2 = new FastPFOR128();
int N = FastPFOR128.BLOCK_SIZE;
int[] data = new int[N];
for (int i = 0; i < N; i++)
data[i] = 0;
data[126] = -1;
int[] comp = TestUtils.compress(codec1, Arrays.copyOf(data, N));
int[] answer = TestUtils.uncompress(codec2, comp, N);
for (int k = 0; k < N; ++k)
if (answer[k] != data[k])
throw new RuntimeException("bug " + k + " " + answer[k]
+ " != " + data[k]);
}
} |
package com.xpn.xwiki.doc;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.lang.ref.SoftReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.TreeMap;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ecs.filter.CharacterFilter;
import org.apache.velocity.VelocityContext;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.dom.DOMDocument;
import org.dom4j.dom.DOMElement;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.suigeneris.jrcs.diff.Diff;
import org.suigeneris.jrcs.diff.DifferentiationFailedException;
import org.suigeneris.jrcs.diff.Revision;
import org.suigeneris.jrcs.diff.delta.Delta;
import org.suigeneris.jrcs.rcs.Version;
import org.suigeneris.jrcs.util.ToString;
import org.xwiki.bridge.DocumentModelBridge;
import org.xwiki.context.Execution;
import org.xwiki.context.ExecutionContext;
import org.xwiki.context.ExecutionContextException;
import org.xwiki.context.ExecutionContextManager;
import org.xwiki.model.EntityType;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.DocumentReferenceResolver;
import org.xwiki.model.reference.EntityReference;
import org.xwiki.model.reference.EntityReferenceResolver;
import org.xwiki.model.reference.EntityReferenceSerializer;
import org.xwiki.model.reference.WikiReference;
import org.xwiki.rendering.block.Block;
import org.xwiki.rendering.block.HeaderBlock;
import org.xwiki.rendering.block.LinkBlock;
import org.xwiki.rendering.block.MacroBlock;
import org.xwiki.rendering.block.SectionBlock;
import org.xwiki.rendering.block.XDOM;
import org.xwiki.rendering.listener.reference.DocumentResourceReference;
import org.xwiki.rendering.listener.HeaderLevel;
import org.xwiki.rendering.listener.reference.ResourceType;
import org.xwiki.rendering.listener.reference.ResourceReference;
import org.xwiki.rendering.parser.ParseException;
import org.xwiki.rendering.parser.Parser;
import org.xwiki.rendering.renderer.BlockRenderer;
import org.xwiki.rendering.renderer.printer.DefaultWikiPrinter;
import org.xwiki.rendering.renderer.printer.WikiPrinter;
import org.xwiki.rendering.syntax.Syntax;
import org.xwiki.rendering.syntax.SyntaxFactory;
import org.xwiki.rendering.transformation.TransformationContext;
import org.xwiki.rendering.transformation.TransformationException;
import org.xwiki.rendering.transformation.TransformationManager;
import org.xwiki.rendering.util.ParserUtils;
import org.xwiki.velocity.VelocityManager;
import org.xwiki.velocity.XWikiVelocityException;
import com.xpn.xwiki.CoreConfiguration;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiConstant;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.api.DocumentSection;
import com.xpn.xwiki.content.Link;
import com.xpn.xwiki.content.parsers.DocumentParser;
import com.xpn.xwiki.content.parsers.LinkParser;
import com.xpn.xwiki.content.parsers.RenamePageReplaceLinkHandler;
import com.xpn.xwiki.content.parsers.ReplacementResultCollection;
import com.xpn.xwiki.criteria.impl.RevisionCriteria;
import com.xpn.xwiki.doc.rcs.XWikiRCSNodeInfo;
import com.xpn.xwiki.internal.cache.rendering.RenderingCache;
import com.xpn.xwiki.internal.xml.DOMXMLWriter;
import com.xpn.xwiki.internal.xml.XMLWriter;
import com.xpn.xwiki.objects.BaseCollection;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.BaseProperty;
import com.xpn.xwiki.objects.LargeStringProperty;
import com.xpn.xwiki.objects.ListProperty;
import com.xpn.xwiki.objects.ObjectDiff;
import com.xpn.xwiki.objects.classes.BaseClass;
import com.xpn.xwiki.objects.classes.ListClass;
import com.xpn.xwiki.objects.classes.PropertyClass;
import com.xpn.xwiki.objects.classes.StaticListClass;
import com.xpn.xwiki.objects.classes.TextAreaClass;
import com.xpn.xwiki.plugin.query.XWikiCriteria;
import com.xpn.xwiki.render.XWikiVelocityRenderer;
import com.xpn.xwiki.store.XWikiAttachmentStoreInterface;
import com.xpn.xwiki.store.XWikiStoreInterface;
import com.xpn.xwiki.store.XWikiVersioningStoreInterface;
import com.xpn.xwiki.user.api.XWikiRightService;
import com.xpn.xwiki.util.Util;
import com.xpn.xwiki.validation.XWikiValidationInterface;
import com.xpn.xwiki.validation.XWikiValidationStatus;
import com.xpn.xwiki.web.EditForm;
import com.xpn.xwiki.web.ObjectAddForm;
import com.xpn.xwiki.web.Utils;
import com.xpn.xwiki.web.XWikiMessageTool;
import com.xpn.xwiki.web.XWikiRequest;
public class XWikiDocument implements DocumentModelBridge
{
private static final Log LOG = LogFactory.getLog(XWikiDocument.class);
/**
* Regex Pattern to recognize if there's HTML code in a XWiki page.
*/
private static final Pattern HTML_TAG_PATTERN = Pattern
.compile("</?(html|body|img|a|i|b|embed|script|form|input|textarea|object|"
+ "font|li|ul|ol|table|center|hr|br|p) ?([^>]*)>");
/** Regex for finding the first level 1 or 2 heading in the document title, to be used as the document title. */
private static final Pattern HEADING_PATTERN_10 = Pattern.compile("^\\s*+1(?:\\.1)?\\s++(.++)$", Pattern.MULTILINE);
public static final String XWIKI10_SYNTAXID = Syntax.XWIKI_1_0.toIdString();
public static final String XWIKI20_SYNTAXID = Syntax.XWIKI_2_0.toIdString();
private String title;
/**
* Reference to this document's parent.
* <p>
* Note that we're saving the parent reference as a relative reference instead of an absolute one because We want
* the ability (for example) to create a parent reference relative to the current space or wiki so that a copy of
* this XWikiDocument object would retain that relativity. This is for example useful when copying a Wiki into
* another Wiki so that the copied XWikiDcoument's parent reference points to the new wiki.
*/
private EntityReference parentReference;
/**
* Cache the parent reference resolved as an absolute reference for improved performance (so that we don't have to
* resolve the relative reference every time getParentReference() is called.
*/
private DocumentReference parentReferenceCache;
private DocumentReference documentReference;
private String content;
private String meta;
private String format;
/**
* First author of the document.
*/
private String creator;
/**
* The Author is changed when any part of the document changes (content, objects, attachments).
*/
private String author;
/**
* The last user that has changed the document's content (ie not object, attachments). The Content author is only
* changed when the document content changes. Note that Content Author is used to check programming rights on a
* document and this is the reason we need to know the last author who's modified the content since programming
* rights depend on this.
*/
private String contentAuthor;
private String customClass;
private Date contentUpdateDate;
private Date updateDate;
private Date creationDate;
protected Version version;
private long id = 0;
private boolean mostRecent = true;
private boolean isNew = true;
/**
* The reference to the document that is the template for the current document.
*
* @todo this field is not used yet since it's not currently saved in the database.
*/
private DocumentReference templateDocumentReference;
protected String language;
private String defaultLanguage;
private int translation;
/**
* Indicates whether the document is 'hidden', meaning that it should not be returned in public search results.
* WARNING: this is a temporary hack until the new data model is designed and implemented. No code should rely on or
* use this property, since it will be replaced with a generic metadata.
*/
private boolean hidden = false;
/**
* Comment on the latest modification.
*/
private String comment;
/**
* Wiki syntax supported by this document. This is used to support different syntaxes inside the same wiki. For
* example a page can use the Confluence 2.0 syntax while another one uses the XWiki 1.0 syntax. In practice our
* first need is to support the new rendering component. To use the old rendering implementation specify a
* "xwiki/1.0" syntaxId and use a "xwiki/2.0" syntaxId for using the new rendering component.
*/
private Syntax syntax;
/**
* Is latest modification a minor edit.
*/
private boolean isMinorEdit = false;
/**
* Used to make sure the MetaData String is regenerated.
*/
private boolean isContentDirty = true;
/**
* Used to make sure the MetaData String is regenerated.
*/
private boolean isMetaDataDirty = true;
public static final int HAS_ATTACHMENTS = 1;
public static final int HAS_OBJECTS = 2;
public static final int HAS_CLASS = 4;
private int elements = HAS_OBJECTS | HAS_ATTACHMENTS;
/**
* Separator string between database name and space name.
*/
public static final String DB_SPACE_SEP = ":";
/**
* Separator string between space name and page name.
*/
public static final String SPACE_NAME_SEP = ".";
// Meta Data
private BaseClass xClass;
private String xClassXML;
/**
* Map holding document objects indexed by XClass references (i.e. Document References since a XClass reference
* points to a document). The map is not synchronized, and uses a TreeMap implementation to preserve index ordering
* (consistent sorted order for output to XML, rendering in velocity, etc.)
*/
private Map<DocumentReference, List<BaseObject>> xObjects = new TreeMap<DocumentReference, List<BaseObject>>();
private List<XWikiAttachment> attachmentList;
// Caching
private boolean fromCache = false;
private List<BaseObject> xObjectsToRemove = new ArrayList<BaseObject>();
/**
* The view template (vm file) to use. When not set the default view template is used.
*
* @see com.xpn.xwiki.web.ViewAction#render(XWikiContext)
*/
private String defaultTemplate;
private String validationScript;
private Object wikiNode;
/**
* We are using a SoftReference which will allow the archive to be discarded by the Garbage collector as long as the
* context is closed (usually during the request)
*/
private SoftReference<XWikiDocumentArchive> archive;
private XWikiStoreInterface store;
/**
* @see #getOriginalDocument()
*/
private XWikiDocument originalDocument;
/**
* The document structure expressed as a tree of Block objects. We store it for performance reasons since parsing is
* a costly operation that we don't want to repeat whenever some code ask for the XDOM information.
*/
private XDOM xdom;
/**
* Used to resolve a string into a proper Document Reference using the current document's reference to fill the
* blanks.
*/
private DocumentReferenceResolver<String> currentDocumentReferenceResolver = Utils.getComponent(
DocumentReferenceResolver.class, "current");
/**
* Used to resolve a string into a proper Document Reference using the current document's reference to fill the
* blanks.
*/
private DocumentReferenceResolver<String> explicitDocumentReferenceResolver = Utils.getComponent(
DocumentReferenceResolver.class, "explicit");
private EntityReferenceResolver<String> xClassEntityReferenceResolver = Utils.getComponent(
EntityReferenceResolver.class, "xclass");
/**
* Used to resolve a string into a proper Document Reference using the current document's reference to fill the
* blanks, except for the page name for which the default page name is used instead and for the wiki name for which
* the current wiki is used instead of the current document reference's wiki.
*/
private DocumentReferenceResolver<String> currentMixedDocumentReferenceResolver = Utils.getComponent(
DocumentReferenceResolver.class, "currentmixed");
/**
* Used to normalize references.
*/
private DocumentReferenceResolver<EntityReference> currentReferenceDocumentReferenceResolver = Utils.getComponent(
DocumentReferenceResolver.class, "current/reference");
/**
* Used to normalize references.
*/
private DocumentReferenceResolver<EntityReference> explicitReferenceDocumentReferenceResolver = Utils.getComponent(
DocumentReferenceResolver.class, "explicit/reference");
/**
* Used to resolve parent references in the way they are stored externally (database, xml, etc), ie relative or
* absolute.
*/
private EntityReferenceResolver<String> relativeEntityReferenceResolver = Utils.getComponent(
EntityReferenceResolver.class, "relative");
/**
* Used to convert a proper Document Reference to string (compact form).
*/
private EntityReferenceSerializer<String> compactEntityReferenceSerializer = Utils.getComponent(
EntityReferenceSerializer.class, "compact");
/**
* Used to convert a proper Document Reference to string (standard form).
*/
private EntityReferenceSerializer<String> defaultEntityReferenceSerializer = Utils
.getComponent(EntityReferenceSerializer.class);
/**
* Used to convert a Document Reference to string (compact form without the wiki part if it matches the current
* wiki).
*/
private EntityReferenceSerializer<String> compactWikiEntityReferenceSerializer = Utils.getComponent(
EntityReferenceSerializer.class, "compactwiki");
/**
* Used to convert a proper Document Reference to a string but without the wiki name.
*/
private EntityReferenceSerializer<String> localEntityReferenceSerializer = Utils.getComponent(
EntityReferenceSerializer.class, "local");
/**
* Used to emulate an inline parsing.
*/
private ParserUtils parserUtils = new ParserUtils();
/**
* Used to create proper {@link Syntax} objects.
*/
private SyntaxFactory syntaxFactory = Utils.getComponent(SyntaxFactory.class);
private Execution execution = Utils.getComponent(Execution.class);
private RenderingCache renderingCache = Utils.getComponent(RenderingCache.class);
/**
* @since 2.2M1
*/
public XWikiDocument(DocumentReference reference)
{
init(reference);
}
/**
* @deprecated since 2.2M1 use {@link #XWikiDocument(org.xwiki.model.reference.DocumentReference)} instead
*/
@Deprecated
public XWikiDocument()
{
this(null);
}
/**
* Constructor that specifies the local document identifier: space name, document name. {@link #setDatabase(String)}
* must be called afterwards to specify the wiki name.
*
* @param space the space this document belongs to
* @param name the name of the document
* @deprecated since 2.2M1 use {@link #XWikiDocument(org.xwiki.model.reference.DocumentReference)} instead
*/
@Deprecated
public XWikiDocument(String space, String name)
{
this(null, space, name);
}
/**
* Constructor that specifies the full document identifier: wiki name, space name, document name.
*
* @param wiki The wiki this document belongs to.
* @param space The space this document belongs to.
* @param name The name of the document (can contain either the page name or the space and page name)
* @deprecated since 2.2M1 use {@link #XWikiDocument(org.xwiki.model.reference.DocumentReference)} instead
*/
@Deprecated
public XWikiDocument(String wiki, String space, String name)
{
// We allow to specify the space in the name (eg name = "space.page"). In this case the passed space is
// ignored.
// Build an entity reference that will serve as a current context reference against which to resolve if the
// passed name doesn't contain a space.
EntityReference contextReference = null;
if (!StringUtils.isEmpty(space)) {
contextReference = new EntityReference(space, EntityType.SPACE);
if (!StringUtils.isEmpty(wiki)) {
contextReference.setParent(new WikiReference(wiki));
}
} else if (!StringUtils.isEmpty(wiki)) {
contextReference = new WikiReference(wiki);
}
DocumentReference reference;
if (contextReference != null) {
reference = this.currentDocumentReferenceResolver.resolve(name, contextReference);
// Replace the resolved wiki by the passed wiki if not empty/null
if (!StringUtils.isEmpty(wiki)) {
reference.setWikiReference(new WikiReference(wiki));
}
} else {
// Both the wiki and space params are empty/null, thus don't use a context reference.
reference = this.currentDocumentReferenceResolver.resolve(name);
}
init(reference);
}
public XWikiStoreInterface getStore(XWikiContext context)
{
return context.getWiki().getStore();
}
public XWikiAttachmentStoreInterface getAttachmentStore(XWikiContext context)
{
return context.getWiki().getAttachmentStore();
}
public XWikiVersioningStoreInterface getVersioningStore(XWikiContext context)
{
return context.getWiki().getVersioningStore();
}
public XWikiStoreInterface getStore()
{
return this.store;
}
public void setStore(XWikiStoreInterface store)
{
this.store = store;
}
/**
* @return the unique id used to represent the document, as a number. This id is technical and is equivalent to the
* Document Reference + the language of the Document. This technical id should only be used for the storage
* layer and all user APIs should instead use Document Reference and language as they are model-related
* while the id isn't (it's purely technical).
*/
public long getId()
{
// TODO: The implemented below doesn't guarantee a unique id since it uses the hashCode() method which doesn't
// guarantee unicity. From the JDK's javadoc: "It is not required that if two objects are unequal according to
// the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must
// produce distinct integer results.". This needs to be fixed to produce a real unique id since otherwise we
// can have clashes in the database.
// Note: We don't use the wiki name in the document id's computation. The main historical reason is so
// that all things saved in a given wiki's database are always stored relative to that wiki so that
// changing that wiki's name is simpler.
if ((this.language == null) || this.language.trim().equals("")) {
this.id = this.localEntityReferenceSerializer.serialize(getDocumentReference()).hashCode();
} else {
this.id =
(this.localEntityReferenceSerializer.serialize(getDocumentReference()) + ":" + this.language)
.hashCode();
}
return this.id;
}
/**
* @see #getId()
*/
public void setId(long id)
{
this.id = id;
}
/**
* Note that this method cannot be removed for now since it's used by Hibernate for saving a XWikiDocument.
*
* @return the name of the space of the document
* @deprecated since 2.2M1 used {@link #getDocumentReference()} instead
*/
@Deprecated
public String getSpace()
{
return getDocumentReference().getLastSpaceReference().getName();
}
/**
* Note that this method cannot be removed for now since it's used by Hibernate for loading a XWikiDocument.
*
* @deprecated since 2.2M1 used {@link #setDocumentReference(DocumentReference)} instead
*/
@Deprecated
public void setSpace(String space)
{
if (space != null) {
getDocumentReference().getLastSpaceReference().setName(space);
// Clean the absolute parent reference cache to rebuild it next time getParentReference is called.
this.parentReferenceCache = null;
}
}
/**
* Note that this method cannot be removed for now since it's used by Hibernate for saving a XWikiDocument.
*
* @return the name of the space of the document
* @deprecated use {@link #getDocumentReference()} instead
*/
@Deprecated
public String getWeb()
{
return getSpace();
}
/**
* Note that this method cannot be removed for now since it's used by Hibernate for loading a XWikiDocument.
*
* @deprecated use {@link #setDocumentReference(DocumentReference)} instead
*/
@Deprecated
public void setWeb(String space)
{
setSpace(space);
}
public String getVersion()
{
return getRCSVersion().toString();
}
public void setVersion(String version)
{
if (!StringUtils.isEmpty(version)) {
this.version = new Version(version);
}
}
public Version getRCSVersion()
{
if (this.version == null) {
return new Version("1.1");
}
return this.version;
}
public void setRCSVersion(Version version)
{
this.version = version;
}
/**
* @return the copy of this XWikiDocument instance before any modification was made to it. It is reset to the actual
* values when the document is saved in the database. This copy is used for finding out differences made to
* this document (useful for example to send the correct notifications to document change listeners).
*/
public XWikiDocument getOriginalDocument()
{
return this.originalDocument;
}
/**
* @param originalDocument the original document representing this document instance before any change was made to
* it, prior to the last time it was saved
* @see #getOriginalDocument()
*/
public void setOriginalDocument(XWikiDocument originalDocument)
{
this.originalDocument = originalDocument;
}
/**
* @return the parent reference or null if the parent is not set
* @since 2.2M1
*/
public DocumentReference getParentReference()
{
// Ensure we always return absolute document references for the parent since we always want well-constructed
// references and since we store the parent reference as relative internally.
if (this.parentReferenceCache == null && getRelativeParentReference() != null) {
this.parentReferenceCache =
this.explicitReferenceDocumentReferenceResolver.resolve(getRelativeParentReference(),
getDocumentReference());
}
return this.parentReferenceCache;
}
/**
* Note that this method cannot be removed for now since it's used by Hibernate for saving a XWikiDocument.
*
* @return the parent reference stored in the database, which is relative to this document, or an empty string ("")
* if the parent is not set
* @see #getParentReference()
* @deprecated since 2.2M1 use {@link #getParentReference()} instead
*/
@Deprecated
public String getParent()
{
String parentReferenceAsString;
if (getParentReference() != null) {
parentReferenceAsString = this.defaultEntityReferenceSerializer.serialize(getRelativeParentReference());
} else {
parentReferenceAsString = "";
}
return parentReferenceAsString;
}
/**
* @deprecated since 2.2M1 use {@link #getParentReference()} instead
*/
@Deprecated
public XWikiDocument getParentDoc()
{
return new XWikiDocument(getParentReference());
}
/**
* @since 2.2.3
*/
public void setParentReference(EntityReference parentReference)
{
if ((parentReference == null && getRelativeParentReference() != null)
|| (parentReference != null && !parentReference.equals(getRelativeParentReference()))) {
this.parentReference = parentReference;
// Clean the absolute parent reference cache to rebuild it next time getParentReference is called.
this.parentReferenceCache = null;
setMetaDataDirty(true);
}
}
/**
* Convert a full document reference into the proper relative document reference (wiki part is removed if it's the
* same as document wiki) to store as parent.
*
* @deprecated since 2.2.3 use {@link #setParentReference(org.xwiki.model.reference.EntityReference)} instead
*/
@Deprecated
public void setParentReference(DocumentReference parentReference)
{
if (parentReference != null) {
setParent(serializeReference(parentReference, this.compactWikiEntityReferenceSerializer,
getDocumentReference()));
} else {
setParentReference((EntityReference) null);
}
}
/**
* Note that this method cannot be removed for now since it's used by Hibernate for loading a XWikiDocument.
*
* @param parent the reference of the parent relative to the document
* @deprecated since 2.2M1 used {@link #setParentReference(DocumentReference)} instead
*/
@Deprecated
public void setParent(String parent)
{
// If the passed parent is an empty string we also need to set the reference to null. The reason is that
// in the database we store "" when the parent is empty and thus when Hibernate loads this class it'll call
// setParent with "" if the parent had not been set when saved.
if (StringUtils.isEmpty(parent)) {
setParentReference((EntityReference) null);
} else {
setParentReference(this.relativeEntityReferenceResolver.resolve(parent, EntityType.DOCUMENT));
}
}
public String getContent()
{
return this.content;
}
public void setContent(String content)
{
if (content == null) {
content = "";
}
if (!content.equals(this.content)) {
setContentDirty(true);
setWikiNode(null);
}
this.content = content;
// invalidate parsed xdom
this.xdom = null;
}
public void setContent(XDOM content) throws XWikiException
{
setContent(renderXDOM(content, getSyntax()));
}
public String getRenderedContent(Syntax targetSyntax, XWikiContext context) throws XWikiException
{
return getRenderedContent(targetSyntax, true, context);
}
public String getRenderedContent(Syntax targetSyntax, boolean isolateVelocityMacros, XWikiContext context)
throws XWikiException
{
// Note: We are currently duplicating code from the other getRendered signature because some calling
// code is expecting that the rendering will happen in the calling document's context and not in this
// document's context. For example this is true for the Admin page, see
String source = getTranslatedContent(context);
String renderedContent = this.renderingCache.getRenderedContent(getDocumentReference(), source, context);
String documentName =
this.defaultEntityReferenceSerializer.serialize(isolateVelocityMacros ? getDocumentReference() : context
.getDoc().getDocumentReference());
if (renderedContent == null) {
Object isInRenderingEngine = context.get("isInRenderingEngine");
// Mark that we're starting to use the current document as a macro namespace
if (isolateVelocityMacros && (isInRenderingEngine == null || isInRenderingEngine == Boolean.FALSE)) {
try {
Utils.getComponent(VelocityManager.class).getVelocityEngine()
.startedUsingMacroNamespace(documentName);
if (LOG.isDebugEnabled()) {
LOG.debug("Started using velocity macro namespace [" + documentName + "]");
}
} catch (XWikiVelocityException e) {
// Failed to get the Velocity Engine and this to clear Velocity Macro cache. Log this as a warning
// but continue since it's not absolutely critical.
LOG.warn("Failed to notify Velocity Macro cache for the [" + documentName
+ "] namespace. Reason = [" + e.getMessage() + "]");
}
}
try {
// This tells display() methods that we are inside the rendering engine and thus
// that they can return wiki syntax and not HTML syntax (which is needed when
// outside the rendering engine, i.e. when we're inside templates using only
// Velocity for example).
context.put("isInRenderingEngine", true);
// If the Syntax id is "xwiki/1.0" then use the old rendering subsystem. Otherwise use the new one.
if (is10Syntax()) {
renderedContent = context.getWiki().getRenderingEngine().renderDocument(this, context);
} else {
TransformationContext txContext = new TransformationContext();
txContext.setSyntax(getSyntax());
txContext.setId(documentName);
renderedContent = performSyntaxConversion(source, targetSyntax, txContext);
}
this.renderingCache.setRenderedContent(getDocumentReference(), source, renderedContent, context);
} finally {
if (isInRenderingEngine != null) {
context.put("isInRenderingEngine", isInRenderingEngine);
} else {
context.remove("isInRenderingEngine");
}
// Since we configure Velocity to have local macros (i.e. macros visible only to the local context),
// since Velocity caches the velocity macros in a local cache (we use key which is the absolute
// document reference) and since documents can include other documents or panels, we need to make sure
// we empty the local Velocity macro cache at the end of the rendering for the document as otherwise the
// local Velocity macro caches will keep growing as users create new pages.
// Note that we check if we are in the rendering engine as this cleanup must be done only once after the
// document has been rendered but this method can be called recursively. We know it's the initial entry
// point when isInRenderingEngine is false...
if (isolateVelocityMacros && (isInRenderingEngine == null || isInRenderingEngine == Boolean.FALSE)) {
try {
Utils.getComponent(VelocityManager.class).getVelocityEngine()
.stoppedUsingMacroNamespace(documentName);
if (LOG.isDebugEnabled()) {
LOG.debug("Stopped using velocity macro namespace [" + documentName + "]");
}
} catch (XWikiVelocityException e) {
// Failed to get the Velocity Engine and this to clear Velocity Macro cache. Log this as a
// warning
// but continue since it's not absolutely critical.
LOG.warn("Failed to notify Velocity Macro cache for the [" + documentName
+ "] namespace. Reason = [" + e.getMessage() + "]");
}
}
}
}
return renderedContent;
}
public String getRenderedContent(XWikiContext context) throws XWikiException
{
return getRenderedContent(Syntax.XHTML_1_0, context);
}
/**
* @param text the text to render
* @param syntaxId the id of the Syntax used by the passed text (for example: "xwiki/1.0")
* @param context the XWiki Context object
* @return the given text rendered in the context of this document using the passed Syntax
* @since 1.6M1
*/
public String getRenderedContent(String text, String syntaxId, XWikiContext context)
{
return getRenderedContent(text, syntaxId, Syntax.XHTML_1_0.toIdString(), context);
}
/**
* @param text the text to render
* @param sourceSyntaxId the id of the Syntax used by the passed text (for example: "xwiki/1.0")
* @param targetSyntaxId the id of the syntax in which to render the document content
* @return the given text rendered in the context of this document using the passed Syntax
* @since 2.0M3
*/
public String getRenderedContent(String text, String sourceSyntaxId, String targetSyntaxId, XWikiContext context)
{
String result = this.renderingCache.getRenderedContent(getDocumentReference(), text, context);
String documentName = this.defaultEntityReferenceSerializer.serialize(getDocumentReference());
if (result == null) {
Map<String, Object> backup = new HashMap<String, Object>();
Object isInRenderingEngine = context.get("isInRenderingEngine");
try {
backupContext(backup, context);
setAsContextDoc(context);
// Mark that we're starting to use the current document as a macro namespace
if (isInRenderingEngine == null || isInRenderingEngine == Boolean.FALSE) {
try {
Utils.getComponent(VelocityManager.class).getVelocityEngine()
.startedUsingMacroNamespace(documentName);
if (LOG.isDebugEnabled()) {
LOG.debug("Started using velocity macro namespace [" + documentName + "]");
}
} catch (XWikiVelocityException e) {
// Failed to get the Velocity Engine and this to clear Velocity Macro cache. Log this as a
// warning
// but continue since it's not absolutely critical.
LOG.warn("Failed to notify Velocity Macro cache for the [" + documentName
+ "] namespace. Reason = [" + e.getMessage() + "]");
}
}
// This tells display() methods that we are inside the rendering engine and thus
// that they can return wiki syntax and not HTML syntax (which is needed when
// outside the rendering engine, i.e. when we're inside templates using only
// Velocity for example).
context.put("isInRenderingEngine", true);
// If the Syntax id is "xwiki/1.0" then use the old rendering subsystem. Otherwise use the new one.
if (is10Syntax(sourceSyntaxId)) {
result = context.getWiki().getRenderingEngine().renderText(text, this, context);
} else {
SyntaxFactory syntaxFactory = Utils.getComponent(SyntaxFactory.class);
TransformationContext txContext = new TransformationContext();
txContext.setSyntax(syntaxFactory.createSyntaxFromIdString(sourceSyntaxId));
txContext.setId(documentName);
result =
performSyntaxConversion(text, syntaxFactory.createSyntaxFromIdString(targetSyntaxId), txContext);
}
this.renderingCache.setRenderedContent(getDocumentReference(), text, result, context);
} catch (Exception e) {
// Failed to render for some reason. This method should normally throw an exception but this
// requires changing the signature of calling methods too.
LOG.warn(e);
result = "";
} finally {
restoreContext(backup, context);
if (isInRenderingEngine != null) {
context.put("isInRenderingEngine", isInRenderingEngine);
} else {
context.remove("isInRenderingEngine");
}
// Since we configure Velocity to have local macros (i.e. macros visible only to the local context),
// since Velocity caches the velocity macros in a local cache (we use key which is the absolute
// document reference) and since documents can include other documents or panels, we need to make sure
// we empty the local Velocity macro cache at the end of the rendering for the document as otherwise the
// local Velocity macro caches will keep growing as users create new pages.
// Note that we check if we are in the rendering engine as this cleanup must be done only once after the
// document has been rendered but this method can be called recursively. We know it's the initial entry
// point when isInRenderingEngine is false...
if (isInRenderingEngine == null || isInRenderingEngine == Boolean.FALSE) {
try {
Utils.getComponent(VelocityManager.class).getVelocityEngine()
.stoppedUsingMacroNamespace(documentName);
if (LOG.isDebugEnabled()) {
LOG.debug("Stopped using velocity macro namespace [" + documentName + "]");
}
} catch (XWikiVelocityException e) {
// Failed to get the Velocity Engine and this to clear Velocity Macro cache. Log this as a
// warning
// but continue since it's not absolutely critical.
LOG.warn("Failed to notify Velocity Macro cache for the [" + documentName
+ "] namespace. Reason = [" + e.getMessage() + "]");
}
}
}
}
return result;
}
public String getEscapedContent(XWikiContext context) throws XWikiException
{
CharacterFilter filter = new CharacterFilter();
return filter.process(getTranslatedContent(context));
}
/**
* Note that this method cannot be removed for now since it's used by Hibernate for saving a XWikiDocument.
*
* @deprecated since 2.2M1 used {@link #getDocumentReference()} instead
*/
@Deprecated
public String getName()
{
return getDocumentReference().getName();
}
/**
* Note that this method cannot be removed for now since it's used by Hibernate for loading a XWikiDocument.
*
* @deprecated since 2.2M1 used {@link #setDocumentReference(DocumentReference)} instead
*/
@Deprecated
public void setName(String name)
{
if (name != null) {
getDocumentReference().setName(name);
// Clean the absolute parent reference cache to rebuild it next time getParentReference is called.
this.parentReferenceCache = null;
}
}
/**
* {@inheritDoc}
*
* @see org.xwiki.bridge.DocumentModelBridge#getDocumentReference()
* @since 2.2M1
*/
public DocumentReference getDocumentReference()
{
return this.documentReference;
}
/**
* @return the document's space + page name (eg "space.page")
* @deprecated since 2.2M1 use {@link #getDocumentReference()} instead
*/
@Deprecated
public String getFullName()
{
return this.localEntityReferenceSerializer.serialize(getDocumentReference());
}
/**
* @return the docoument's wiki + space + page name (eg "wiki:space.page")
* @deprecated since 2.2M1 use {@link #getDocumentReference()} instead
*/
@Deprecated
public String getPrefixedFullName()
{
return this.defaultEntityReferenceSerializer.serialize(getDocumentReference());
}
/**
* @since 2.2M1
* @deprecated since 2.2.3 don't change the reference of a document once it's been constructed. Instead you can
* clone the doc, rename it or copy it.
*/
@Deprecated
public void setDocumentReference(DocumentReference reference)
{
// Don't allow setting a null reference for now, ie. don't do anything to preserve backward compatibility
// with previous behavior (i.e. {@link #setFullName}.
if (reference != null) {
if (!reference.equals(getDocumentReference())) {
this.documentReference = reference;
setMetaDataDirty(true);
// Clean the absolute parent reference cache to rebuild it next time getParentReference is called.
this.parentReferenceCache = null;
}
}
}
/**
* @deprecated since 2.2M1 use {@link #setDocumentReference(org.xwiki.model.reference.DocumentReference)} instead
*/
@Deprecated
public void setFullName(String name)
{
setFullName(name, null);
}
/**
* @deprecated since 2.2M1 use {@link #setDocumentReference(org.xwiki.model.reference.DocumentReference)} instead
*/
@Deprecated
public void setFullName(String fullName, XWikiContext context)
{
// We ignore the passed full name if it's null to be backward compatible with previous behaviors and to be
// consistent with {@link #setName} and {@link #setSpace}.
if (fullName != null) {
// Note: We use the CurrentMixed Resolver since we want to use the default page name if the page isn't
// specified in the passed string, rather than use the current document's page name.
setDocumentReference(this.currentMixedDocumentReferenceResolver.resolve(fullName));
}
}
/**
* {@inheritDoc}
*
* @see org.xwiki.bridge.DocumentModelBridge#getDocumentName()
* @deprecated replaced by {@link #getDocumentReference()} since 2.2M1
*/
@Deprecated
public org.xwiki.bridge.DocumentName getDocumentName()
{
return new org.xwiki.bridge.DocumentName(getWikiName(), getSpaceName(), getPageName());
}
/**
* {@inheritDoc}
*
* @see DocumentModelBridge#getWikiName()
* @deprecated since 2.2M1 use {@link #getDocumentReference()} instead
*/
@Deprecated
public String getWikiName()
{
return getDatabase();
}
/**
* {@inheritDoc}
*
* @see DocumentModelBridge#getSpaceName()
* @deprecated since 2.2M1 use {@link #getDocumentReference()} instead
*/
@Deprecated
public String getSpaceName()
{
return this.getSpace();
}
/**
* {@inheritDoc}
*
* @see DocumentModelBridge#getSpaceName()
* @deprecated since 2.2M1 use {@link #getDocumentReference()} instead
*/
@Deprecated
public String getPageName()
{
return this.getName();
}
public String getTitle()
{
return (this.title != null) ? this.title : "";
}
/**
* @param context the XWiki context used to get access to the com.xpn.xwiki.render.XWikiRenderingEngine object
* @return the document title. If a title has not been provided, look for a section title in the document's content
* and if not found return the page name. The returned title is also interpreted which means it's allowed to
* use Velocity, Groovy, etc syntax within a title.
* @deprecated use {@link #getRenderedTitle(Syntax, XWikiContext)} instead
*/
@Deprecated
public String getDisplayTitle(XWikiContext context)
{
return getRenderedTitle(Syntax.XHTML_1_0, context);
}
/**
* The first found first or second level header content is rendered with
* {@link com.xpn.xwiki.render.XWikiRenderingEngine#interpretText(String, XWikiDocument, XWikiContext)}.
*
* @param context the XWiki context
* @return the rendered version of the found header content. Empty string if not can be found.
*/
private String getRenderedContentTitle10(XWikiContext context)
{
// 1) Check if the user has provided a title
String title = extractTitle10();
// 3) Last if a title has been found renders it as it can contain macros, velocity code,
// groovy, etc.
if (title.length() > 0) {
// Only needed for xwiki 1.0 syntax, for other syntaxes it's already rendered in #extractTitle
// This will not completely work for scripting code in title referencing variables
// defined elsewhere. In that case it'll only work if those variables have been
// parsed and put in the corresponding scripting context. This will not work for
// breadcrumbs for example.
title = context.getWiki().getRenderingEngine().interpretText(title, this, context);
}
return title;
}
/**
* Get the rendered version of the first or second level first found header content in the document content.
* <ul>
* <li>xwiki/1.0: the first found first or second level header content is rendered with
* {@link com.xpn.xwiki.render.XWikiRenderingEngine#interpretText(String, XWikiDocument, XWikiContext)}</li>
* <li>xwiki/2.0: the first found first or second level content is executed and rendered with renderer for the
* provided syntax</li>
* </ul>
*
* @param outputSyntax the syntax to render to. This is not taken into account for xwiki/1.0 syntax.
* @param context the XWiki context
* @return the rendered version of the title. null or empty (when xwiki/1.0 syntax) string if none can be found
* @throws XWikiException failed to render content
*/
private String getRenderedContentTitle(Syntax outputSyntax, XWikiContext context) throws XWikiException
{
String title = null;
// Protect against cycles. For example that cold happen with a call to getRenderedTitle on current document from
// a script in the first heading block title
Stack<DocumentReference> stackTrace =
(Stack<DocumentReference>) context.get("internal.getRenderedContentTitleStackTrace");
if (stackTrace == null) {
stackTrace = new Stack<DocumentReference>();
context.put("internal.getRenderedContentTitleStackTrace", stackTrace);
} else if (stackTrace.contains(getDocumentReference())) {
// TODO: generate an error message instead ?
return null;
}
stackTrace.push(getDocumentReference());
try {
// Extract and render the document title
if (is10Syntax()) {
title = getRenderedContentTitle10(context);
} else {
List<HeaderBlock> blocks = getXDOM().getChildrenByType(HeaderBlock.class, true);
if (blocks.size() > 0) {
HeaderBlock header = blocks.get(0);
// Check the header depth after which we should return null if no header was found.
int titleHeaderDepth = (int) context.getWiki().ParamAsLong("xwiki.title.headerdepth", 2);
if (header.getLevel().getAsInt() <= titleHeaderDepth) {
XDOM headerXDOM = new XDOM(Collections.<Block> singletonList(header));
// Transform
try {
TransformationContext txContext = new TransformationContext(headerXDOM, getSyntax());
Utils.getComponent(TransformationManager.class).performTransformations(headerXDOM,
txContext);
} catch (TransformationException e) {
// An error happened during one of the transformations. Since the error has been logged
// continue
// TODO: We should have a visual clue for the user in the future to let him know something
// didn't work as expected.
}
// Render
Block headerBlock = headerXDOM.getChildren().get(0);
if (headerBlock instanceof HeaderBlock) {
title = renderXDOM(new XDOM(headerBlock.getChildren()), outputSyntax);
}
}
}
}
} finally {
stackTrace.pop();
}
return title;
}
/**
* Get the rendered version of the title of the document.
* <ul>
* <li>if document <code>title</code> field is not empty: it's returned after a call to
* {@link com.xpn.xwiki.render.XWikiRenderingEngine#interpretText(String, XWikiDocument, XWikiContext)}</li>
* <li>if document <code>title</code> field is empty: see {@link #getRenderedContentTitle(Syntax, XWikiContext)}</li>
* <li>if after the two first step the title is still empty, the page name is returned</li>
* </ul>
*
* @param outputSyntax the syntax to render to. This is not taken into account for xwiki/1.0 syntax.
* @param context the XWiki context
* @return the rendered version of the title
*/
public String getRenderedTitle(Syntax outputSyntax, XWikiContext context)
{
// 1) Check if the user has provided a title
String title = getTitle();
try {
if (!StringUtils.isEmpty(title)) {
title = context.getWiki().getRenderingEngine().interpretText(title, this, context);
// If there's been an error during the Velocity evaluation then consider that the title is empty as a
// fallback.
// TODO: Since interpretText() never throws an exception it's hard to know if there's been an error.
// Right now interpretText() returns some HTML when there's an error, so we need to check the returned
// result for some marker to decide if an error has occurred... Fix this by refactoring the whole
// system used for Velocity evaluation.
if (title.indexOf("<div id=\"xwikierror") == -1) {
if (!outputSyntax.equals(Syntax.HTML_4_01) && !outputSyntax.equals(Syntax.XHTML_1_0)) {
XDOM xdom = parseContent(Syntax.HTML_4_01.toIdString(), title);
this.parserUtils.removeTopLevelParagraph(xdom.getChildren());
title = renderXDOM(xdom, outputSyntax);
}
return title;
}
}
} catch (Exception e) {
LOG.warn(
"Failed to interpret title of document ["
+ this.defaultEntityReferenceSerializer.serialize(getDocumentReference()) + "]", e);
}
try {
// 2) If not, then try to extract the title from the first document section title
title = getRenderedContentTitle(outputSyntax, context);
} catch (Exception e) {
LOG.warn(
"Failed to extract title from content of document ["
+ this.defaultEntityReferenceSerializer.serialize(getDocumentReference()) + "]", e);
}
// 3) No title has been found, return the page name as the title
if (StringUtils.isEmpty(title)) {
title = getDocumentReference().getName();
}
return title;
}
public String extractTitle()
{
String title = "";
try {
if (is10Syntax()) {
title = extractTitle10();
} else {
List<HeaderBlock> blocks = getXDOM().getChildrenByType(HeaderBlock.class, true);
if (blocks.size() > 0) {
HeaderBlock header = blocks.get(0);
if (header.getLevel().compareTo(HeaderLevel.LEVEL2) <= 0) {
XDOM headerXDOM = new XDOM(Collections.<Block> singletonList(header));
// transform
TransformationContext context = new TransformationContext(headerXDOM, getSyntax());
Utils.getComponent(TransformationManager.class).performTransformations(headerXDOM, context);
// render
Block headerBlock = headerXDOM.getChildren().get(0);
if (headerBlock instanceof HeaderBlock) {
title = renderXDOM(new XDOM(headerBlock.getChildren()), Syntax.XHTML_1_0);
}
}
}
}
} catch (Exception e) {
// Don't stop when there's a problem rendering the title.
}
return title;
}
/**
* @return the first level 1 or level 1.1 title text in the document's content or "" if none are found
* @todo this method has nothing to do in this class and should be moved elsewhere
*/
private String extractTitle10()
{
String content = getContent();
Matcher m = HEADING_PATTERN_10.matcher(content);
if (m.find()) {
return m.group(1).trim();
}
return "";
}
public void setTitle(String title)
{
if (title != null && !title.equals(this.title)) {
setContentDirty(true);
}
this.title = title;
}
public String getFormat()
{
return this.format != null ? this.format : "";
}
public void setFormat(String format)
{
this.format = format;
if (!format.equals(this.format)) {
setMetaDataDirty(true);
}
}
public String getAuthor()
{
return this.author != null ? this.author.trim() : "";
}
public String getContentAuthor()
{
return this.contentAuthor != null ? this.contentAuthor.trim() : "";
}
public void setAuthor(String author)
{
if (!getAuthor().equals(author)) {
setMetaDataDirty(true);
}
this.author = author;
}
public void setContentAuthor(String contentAuthor)
{
if (!getContentAuthor().equals(contentAuthor)) {
setMetaDataDirty(true);
}
this.contentAuthor = contentAuthor;
}
public String getCreator()
{
return this.creator != null ? this.creator.trim() : "";
}
public void setCreator(String creator)
{
if (!getCreator().equals(creator)) {
setMetaDataDirty(true);
}
this.creator = creator;
}
public Date getDate()
{
if (this.updateDate == null) {
return new Date();
} else {
return this.updateDate;
}
}
public void setDate(Date date)
{
if ((date != null) && (!date.equals(this.updateDate))) {
setMetaDataDirty(true);
}
// Make sure we drop milliseconds for consistency with the database
if (date != null) {
date.setTime((date.getTime() / 1000) * 1000);
}
this.updateDate = date;
}
public Date getCreationDate()
{
if (this.creationDate == null) {
return new Date();
} else {
return this.creationDate;
}
}
public void setCreationDate(Date date)
{
if ((date != null) && (!date.equals(this.creationDate))) {
setMetaDataDirty(true);
}
// Make sure we drop milliseconds for consistency with the database
if (date != null) {
date.setTime((date.getTime() / 1000) * 1000);
}
this.creationDate = date;
}
public Date getContentUpdateDate()
{
if (this.contentUpdateDate == null) {
return new Date();
} else {
return this.contentUpdateDate;
}
}
public void setContentUpdateDate(Date date)
{
if ((date != null) && (!date.equals(this.contentUpdateDate))) {
setMetaDataDirty(true);
}
// Make sure we drop milliseconds for consistency with the database
if (date != null) {
date.setTime((date.getTime() / 1000) * 1000);
}
this.contentUpdateDate = date;
}
public String getMeta()
{
return this.meta;
}
public void setMeta(String meta)
{
if (meta == null) {
if (this.meta != null) {
setMetaDataDirty(true);
}
} else if (!meta.equals(this.meta)) {
setMetaDataDirty(true);
}
this.meta = meta;
}
public void appendMeta(String meta)
{
StringBuffer buf = new StringBuffer(this.meta);
buf.append(meta);
buf.append("\n");
this.meta = buf.toString();
setMetaDataDirty(true);
}
public boolean isContentDirty()
{
return this.isContentDirty;
}
public void incrementVersion()
{
if (this.version == null) {
this.version = new Version("1.1");
} else {
if (isMinorEdit()) {
this.version = this.version.next();
} else {
this.version = this.version.getBranchPoint().next().newBranch(1);
}
}
}
public void setContentDirty(boolean contentDirty)
{
this.isContentDirty = contentDirty;
}
public boolean isMetaDataDirty()
{
return this.isMetaDataDirty;
}
public void setMetaDataDirty(boolean metaDataDirty)
{
this.isMetaDataDirty = metaDataDirty;
}
public String getAttachmentURL(String filename, XWikiContext context)
{
return getAttachmentURL(filename, "download", context);
}
public String getAttachmentURL(String filename, String action, XWikiContext context)
{
URL url =
context.getURLFactory().createAttachmentURL(filename, getSpace(), getName(), action, null, getDatabase(),
context);
return context.getURLFactory().getURL(url, context);
}
public String getExternalAttachmentURL(String filename, String action, XWikiContext context)
{
URL url =
context.getURLFactory().createAttachmentURL(filename, getSpace(), getName(), action, null, getDatabase(),
context);
return url.toString();
}
public String getAttachmentURL(String filename, String action, String querystring, XWikiContext context)
{
URL url =
context.getURLFactory().createAttachmentURL(filename, getSpace(), getName(), action, querystring,
getDatabase(), context);
return context.getURLFactory().getURL(url, context);
}
public String getAttachmentRevisionURL(String filename, String revision, XWikiContext context)
{
URL url =
context.getURLFactory().createAttachmentRevisionURL(filename, getSpace(), getName(), revision, null,
getDatabase(), context);
return context.getURLFactory().getURL(url, context);
}
public String getAttachmentRevisionURL(String filename, String revision, String querystring, XWikiContext context)
{
URL url =
context.getURLFactory().createAttachmentRevisionURL(filename, getSpace(), getName(), revision, querystring,
getDatabase(), context);
return context.getURLFactory().getURL(url, context);
}
public String getURL(String action, String params, boolean redirect, XWikiContext context)
{
URL url =
context.getURLFactory().createURL(getSpace(), getName(), action, params, null, getDatabase(), context);
if (redirect) {
if (url == null) {
return null;
} else {
return url.toString();
}
} else {
return context.getURLFactory().getURL(url, context);
}
}
public String getURL(String action, boolean redirect, XWikiContext context)
{
return getURL(action, null, redirect, context);
}
public String getURL(String action, XWikiContext context)
{
return getURL(action, false, context);
}
public String getURL(String action, String querystring, XWikiContext context)
{
URL url =
context.getURLFactory().createURL(getSpace(), getName(), action, querystring, null, getDatabase(), context);
return context.getURLFactory().getURL(url, context);
}
public String getURL(String action, String querystring, String anchor, XWikiContext context)
{
URL url =
context.getURLFactory().createURL(getSpace(), getName(), action, querystring, anchor, getDatabase(),
context);
return context.getURLFactory().getURL(url, context);
}
public String getExternalURL(String action, XWikiContext context)
{
URL url =
context.getURLFactory()
.createExternalURL(getSpace(), getName(), action, null, null, getDatabase(), context);
return url.toString();
}
public String getExternalURL(String action, String querystring, XWikiContext context)
{
URL url =
context.getURLFactory().createExternalURL(getSpace(), getName(), action, querystring, null, getDatabase(),
context);
return url.toString();
}
public String getParentURL(XWikiContext context) throws XWikiException
{
XWikiDocument doc = new XWikiDocument(getParentReference());
URL url =
context.getURLFactory()
.createURL(doc.getSpace(), doc.getName(), "view", null, null, getDatabase(), context);
return context.getURLFactory().getURL(url, context);
}
public XWikiDocumentArchive getDocumentArchive(XWikiContext context) throws XWikiException
{
loadArchive(context);
return getDocumentArchive();
}
/**
* Create a new protected {@link com.xpn.xwiki.api.Document} public API to access page information and actions from
* scripting.
*
* @param customClassName the name of the custom {@link com.xpn.xwiki.api.Document} class of the object to create.
* @param context the XWiki context.
* @return a wrapped version of an XWikiDocument. Prefer this function instead of new Document(XWikiDocument,
* XWikiContext)
*/
public com.xpn.xwiki.api.Document newDocument(String customClassName, XWikiContext context)
{
if (!((customClassName == null) || (customClassName.equals("")))) {
try {
return newDocument(Class.forName(customClassName), context);
} catch (ClassNotFoundException e) {
LOG.error("Failed to get java Class object from class name", e);
}
}
return new com.xpn.xwiki.api.Document(this, context);
}
/**
* Create a new protected {@link com.xpn.xwiki.api.Document} public API to access page information and actions from
* scripting.
*
* @param customClass the custom {@link com.xpn.xwiki.api.Document} class the object to create.
* @param context the XWiki context.
* @return a wrapped version of an XWikiDocument. Prefer this function instead of new Document(XWikiDocument,
* XWikiContext)
*/
public com.xpn.xwiki.api.Document newDocument(Class< ? > customClass, XWikiContext context)
{
if (customClass != null) {
try {
Class< ? >[] classes = new Class[] {XWikiDocument.class, XWikiContext.class};
Object[] args = new Object[] {this, context};
return (com.xpn.xwiki.api.Document) customClass.getConstructor(classes).newInstance(args);
} catch (Exception e) {
LOG.error("Failed to create a custom Document object", e);
}
}
return new com.xpn.xwiki.api.Document(this, context);
}
public com.xpn.xwiki.api.Document newDocument(XWikiContext context)
{
String customClass = getCustomClass();
return newDocument(customClass, context);
}
public void loadArchive(XWikiContext context) throws XWikiException
{
if (this.archive == null || this.archive.get() == null) {
XWikiDocumentArchive arch = getVersioningStore(context).getXWikiDocumentArchive(this, context);
// We are using a SoftReference which will allow the archive to be
// discarded by the Garbage collector as long as the context is closed (usually during
// the request)
this.archive = new SoftReference<XWikiDocumentArchive>(arch);
}
}
/**
* @return the {@link XWikiDocumentArchive} for this document. If it is not stored in the document, null is
* returned.
*/
public XWikiDocumentArchive getDocumentArchive()
{
// If there is a soft reference, return it.
if (this.archive != null) {
return this.archive.get();
}
return null;
}
/**
* @return the {@link XWikiDocumentArchive} for this document. If it is not stored in the document, we get it using
* the current context. If there is an exception, null is returned.
*/
public XWikiDocumentArchive loadDocumentArchive()
{
if (getDocumentArchive() != null) {
return getDocumentArchive();
}
XWikiContext xcontext = getXWikiContext();
try {
XWikiDocumentArchive arch = getVersioningStore(xcontext).getXWikiDocumentArchive(this, xcontext);
// Put a copy of the archive in the soft reference for later use if needed.
setDocumentArchive(arch);
return arch;
} catch (Exception e) {
// VersioningStore.getXWikiDocumentArchive may throw an XWikiException, and xcontext or VersioningStore
// may be null (tests)
// To maintain the behavior of this method we can't throw an exception.
// Formerly, null was returned if there was no SoftReference.
LOG.warn("Could not get document archive", e);
return null;
}
}
public void setDocumentArchive(XWikiDocumentArchive arch)
{
// We are using a SoftReference which will allow the archive to be
// discarded by the Garbage collector as long as the context is closed (usually during the
// request)
if (arch != null) {
this.archive = new SoftReference<XWikiDocumentArchive>(arch);
}
}
public void setDocumentArchive(String sarch) throws XWikiException
{
XWikiDocumentArchive xda = new XWikiDocumentArchive(getId());
xda.setArchive(sarch);
setDocumentArchive(xda);
}
public Version[] getRevisions(XWikiContext context) throws XWikiException
{
return getVersioningStore(context).getXWikiDocVersions(this, context);
}
public String[] getRecentRevisions(int nb, XWikiContext context) throws XWikiException
{
try {
Version[] revisions = getVersioningStore(context).getXWikiDocVersions(this, context);
int length = nb;
// 0 means all revisions
if (nb == 0) {
length = revisions.length;
}
if (revisions.length < length) {
length = revisions.length;
}
String[] recentrevs = new String[length];
for (int i = 1; i <= length; i++) {
recentrevs[i - 1] = revisions[revisions.length - i].toString();
}
return recentrevs;
} catch (Exception e) {
return new String[0];
}
}
/**
* Get document versions matching criterias like author, minimum creation date, etc.
*
* @param criteria criteria used to match versions
* @return a list of matching versions
*/
public List<String> getRevisions(RevisionCriteria criteria, XWikiContext context) throws XWikiException
{
List<String> results = new ArrayList<String>();
Version[] revisions = getRevisions(context);
XWikiRCSNodeInfo nextNodeinfo = null;
XWikiRCSNodeInfo nodeinfo;
for (int i = 0; i < revisions.length; i++) {
nodeinfo = nextNodeinfo;
nextNodeinfo = getRevisionInfo(revisions[i].toString(), context);
if (nodeinfo == null) {
continue;
}
// Minor/Major version matching
if (criteria.getIncludeMinorVersions() || !nextNodeinfo.isMinorEdit()) {
// Author matching
if (criteria.getAuthor().equals("") || criteria.getAuthor().equals(nodeinfo.getAuthor())) {
// Date range matching
Date versionDate = nodeinfo.getDate();
if (versionDate.after(criteria.getMinDate()) && versionDate.before(criteria.getMaxDate())) {
results.add(nodeinfo.getVersion().toString());
}
}
}
}
nodeinfo = nextNodeinfo;
if (nodeinfo != null) {
if (criteria.getAuthor().equals("") || criteria.getAuthor().equals(nodeinfo.getAuthor())) {
// Date range matching
Date versionDate = nodeinfo.getDate();
if (versionDate.after(criteria.getMinDate()) && versionDate.before(criteria.getMaxDate())) {
results.add(nodeinfo.getVersion().toString());
}
}
}
return criteria.getRange().subList(results);
}
public XWikiRCSNodeInfo getRevisionInfo(String version, XWikiContext context) throws XWikiException
{
return getDocumentArchive(context).getNode(new Version(version));
}
/**
* @return Is this version the most recent one. False if and only if there are newer versions of this document in
* the database.
*/
public boolean isMostRecent()
{
return this.mostRecent;
}
/**
* must not be used unless in store system.
*
* @param mostRecent - mark document as most recent.
*/
public void setMostRecent(boolean mostRecent)
{
this.mostRecent = mostRecent;
}
/**
* @since 2.2M1
*/
public BaseClass getXClass()
{
if (this.xClass == null) {
this.xClass = new BaseClass();
this.xClass.setDocumentReference(getDocumentReference());
}
return this.xClass;
}
/**
* @deprecated since 2.2M1, use {@link #getXClass()} instead
*/
@Deprecated
public BaseClass getxWikiClass()
{
return getXClass();
}
/**
* @since 2.2M1
*/
public void setXClass(BaseClass xwikiClass)
{
xwikiClass.setDocumentReference(getDocumentReference());
this.xClass = xwikiClass;
}
/**
* @deprecated since 2.2M1, use {@link #setXClass(BaseClass)} instead
*/
@Deprecated
public void setxWikiClass(BaseClass xwikiClass)
{
setXClass(xwikiClass);
}
/**
* @since 2.2M1
*/
public Map<DocumentReference, List<BaseObject>> getXObjects()
{
return this.xObjects;
}
/**
* @deprecated since 2.2M1 use {@link #getXObjects()} instead. Warning: if you used to modify the returned Map note
* that since 2.2M1 this will no longer work and you'll need to call the setXObject methods instead (or
* setxWikiObjects()). Obviously the best is to move to the new API.
*/
@Deprecated
public Map<String, Vector<BaseObject>> getxWikiObjects()
{
// Use a liked hash map to ensure we keep the order stored from the internal objects map.
Map<String, Vector<BaseObject>> objects = new LinkedHashMap<String, Vector<BaseObject>>();
for (Map.Entry<DocumentReference, List<BaseObject>> entry : getXObjects().entrySet()) {
objects.put(this.compactWikiEntityReferenceSerializer.serialize(entry.getKey()), new Vector<BaseObject>(
entry.getValue()));
}
return objects;
}
/**
* @since 2.2M1
*/
public void setXObjects(Map<DocumentReference, List<BaseObject>> objects)
{
this.xObjects = objects;
}
/**
* @deprecated since 2.2M1 use {@link #setXObjects(Map)} instead
*/
@Deprecated
public void setxWikiObjects(Map<String, Vector<BaseObject>> objects)
{
// Use a liked hash map to ensure we keep the order stored from the internal objects map.
Map<DocumentReference, List<BaseObject>> newObjects = new LinkedHashMap<DocumentReference, List<BaseObject>>();
for (Map.Entry<String, Vector<BaseObject>> entry : objects.entrySet()) {
newObjects.put(resolveClassReference(entry.getKey()), new ArrayList<BaseObject>(entry.getValue()));
}
setXObjects(newObjects);
}
/**
* @since 2.2M1
*/
public BaseObject getXObject()
{
return getXObject(getDocumentReference());
}
/**
* @deprecated since 2.2M1 use {@link #getXObject()} instead
*/
@Deprecated
public BaseObject getxWikiObject()
{
return getXObject(getDocumentReference());
}
/**
* @since 2.2M1
*/
public List<BaseClass> getXClasses(XWikiContext context)
{
List<BaseClass> list = new ArrayList<BaseClass>();
// getXObjects() is a TreeMap, with elements sorted by className reference
for (DocumentReference classReference : getXObjects().keySet()) {
BaseClass bclass = null;
List<BaseObject> objects = getXObjects(classReference);
for (BaseObject obj : objects) {
if (obj != null) {
bclass = obj.getXClass(context);
if (bclass != null) {
break;
}
}
}
if (bclass != null) {
list.add(bclass);
}
}
return list;
}
/**
* @deprecated since 2.2M1 use {@link #getXClasses(XWikiContext)} instead
*/
@Deprecated
public List<BaseClass> getxWikiClasses(XWikiContext context)
{
return getXClasses(context);
}
/**
* @since 2.2.3
*/
public int createXObject(EntityReference classReference, XWikiContext context) throws XWikiException
{
DocumentReference absoluteClassReference = resolveClassReference(classReference);
BaseObject object = BaseClass.newCustomClassInstance(absoluteClassReference, context);
object.setDocumentReference(getDocumentReference());
object.setXClassReference(classReference);
List<BaseObject> objects = getXObjects(absoluteClassReference);
if (objects == null) {
objects = new ArrayList<BaseObject>();
setXObjects(absoluteClassReference, objects);
}
objects.add(object);
int nb = objects.size() - 1;
object.setNumber(nb);
setContentDirty(true);
return nb;
}
/**
* @deprecated since 2.2M1 use {@link #createXObject(EntityReference, XWikiContext)} instead
*/
@Deprecated
public int createNewObject(String className, XWikiContext context) throws XWikiException
{
return createXObject(
this.xClassEntityReferenceResolver.resolve(className, EntityType.DOCUMENT, getDocumentReference()), context);
}
/**
* @since 2.2M1
*/
public int getXObjectSize(DocumentReference classReference)
{
try {
return getXObjects().get(classReference).size();
} catch (Exception e) {
return 0;
}
}
/**
* @deprecated since 2.2M1 use {@link #getXObjectSize(DocumentReference)} instead
*/
@Deprecated
public int getObjectNumbers(String className)
{
return getXObjectSize(resolveClassReference(className));
}
/**
* @since 2.2M1
*/
public List<BaseObject> getXObjects(DocumentReference classReference)
{
if (classReference == null) {
return new ArrayList<BaseObject>();
}
return getXObjects().get(classReference);
}
/**
* @deprecated since 2.2M1 use {@link #getXObjects(DocumentReference)} instead
*/
@Deprecated
public Vector<BaseObject> getObjects(String className)
{
List<BaseObject> result = getXObjects(resolveClassReference(className));
return result == null ? null : new Vector<BaseObject>(result);
}
/**
* @since 2.2M1
*/
public void setXObjects(DocumentReference classReference, List<BaseObject> objects)
{
if (objects.isEmpty()) {
getXObjects().put(classReference, objects);
} else {
for (BaseObject baseObject : objects) {
addXObject(classReference, baseObject);
}
}
}
/**
* @deprecated since 2.2M1 use {@link #setXObjects(DocumentReference, List)} instead
*/
@Deprecated
public void setObjects(String className, Vector<BaseObject> objects)
{
setXObjects(resolveClassReference(className), new ArrayList<BaseObject>(objects));
}
/**
* @since 2.2M1
*/
public BaseObject getXObject(DocumentReference classReference)
{
BaseObject result = null;
List<BaseObject> objects = getXObjects().get(classReference);
if (objects != null) {
for (BaseObject object : objects) {
if (object != null) {
result = object;
break;
}
}
}
return result;
}
/**
* @deprecated since 2.2M1 use {@link #getXObject(DocumentReference)} instead
*/
@Deprecated
public BaseObject getObject(String className)
{
return getXObject(resolveClassReference(className));
}
/**
* @since 2.2M1
*/
public BaseObject getXObject(DocumentReference classReference, int nb)
{
try {
return getXObjects().get(classReference).get(nb);
} catch (Exception e) {
return null;
}
}
/**
* @deprecated since 2.2M1 use {@link #getXObject(DocumentReference, int)} instead
*/
@Deprecated
public BaseObject getObject(String className, int nb)
{
return getXObject(resolveClassReference(className), nb);
}
/**
* @since 2.2M1
*/
public BaseObject getXObject(DocumentReference classReference, String key, String value)
{
return getXObject(classReference, key, value, false);
}
/**
* @deprecated since 2.2M1 use {@link #getXObject(DocumentReference, String, String)} instead
*/
@Deprecated
public BaseObject getObject(String className, String key, String value)
{
return getObject(className, key, value, false);
}
/**
* @since 2.2M1
*/
public BaseObject getXObject(DocumentReference classReference, String key, String value, boolean failover)
{
try {
if (value == null) {
if (failover) {
return getXObject(classReference);
} else {
return null;
}
}
List<BaseObject> objects = getXObjects().get(classReference);
if ((objects == null) || (objects.size() == 0)) {
return null;
}
for (int i = 0; i < objects.size(); i++) {
BaseObject obj = objects.get(i);
if (obj != null) {
if (value.equals(obj.getStringValue(key))) {
return obj;
}
}
}
if (failover) {
return getXObject(classReference);
} else {
return null;
}
} catch (Exception e) {
if (failover) {
return getXObject(classReference);
}
e.printStackTrace();
return null;
}
}
/**
* @deprecated since 2.2M1 use {@link #getXObject(DocumentReference, String, String, boolean)} instead
*/
@Deprecated
public BaseObject getObject(String className, String key, String value, boolean failover)
{
return getXObject(resolveClassReference(className), key, value, failover);
}
/**
* @since 2.2M1
* @deprecated use {@link #addXObject(BaseObject)} instead
*/
@Deprecated
public void addXObject(DocumentReference classReference, BaseObject object)
{
List<BaseObject> vobj = getXObjects(classReference);
if (vobj == null) {
setXObject(classReference, 0, object);
} else {
setXObject(classReference, vobj.size(), object);
}
}
/**
* Add the object to the document.
*
* @param object the xobject to add
* @throws NullPointerException if the specified object is null because we need the get the class reference from the
* object
* @since 2.2.3
*/
public void addXObject(BaseObject object)
{
object.setDocumentReference(getDocumentReference());
List<BaseObject> vobj = getXObjects(object.getXClassReference());
if (vobj == null) {
setXObject(0, object);
} else {
setXObject(vobj.size(), object);
}
}
/**
* @deprecated since 2.2M1 use {@link #addXObject(BaseObject)} instead
*/
@Deprecated
public void addObject(String className, BaseObject object)
{
addXObject(resolveClassReference(className), object);
}
/**
* @since 2.2M1
* @deprecated use {@link #setXObject(int, BaseObject)} instead
*/
@Deprecated
public void setXObject(DocumentReference classReference, int nb, BaseObject object)
{
if (object != null) {
object.setDocumentReference(getDocumentReference());
object.setNumber(nb);
}
List<BaseObject> objects = getXObjects(classReference);
if (objects == null) {
objects = new ArrayList<BaseObject>();
setXObjects(classReference, objects);
}
while (nb >= objects.size()) {
objects.add(null);
}
objects.set(nb, object);
setContentDirty(true);
}
/**
* Replaces the object at the specified position and for the specified object xclass.
*
* @param nb index of the element to replace
* @param object the xobject to insert
* @throws NullPointerException if the specified object is null because we need the get the class reference from the
* object
* @since 2.2.3
*/
public void setXObject(int nb, BaseObject object)
{
object.setDocumentReference(getDocumentReference());
object.setNumber(nb);
List<BaseObject> objects = getXObjects(object.getXClassReference());
if (objects == null) {
objects = new ArrayList<BaseObject>();
setXObjects(object.getXClassReference(), objects);
}
while (nb >= objects.size()) {
objects.add(null);
}
objects.set(nb, object);
setContentDirty(true);
}
/**
* @deprecated since 2.2M1 use {@link #setXObject(DocumentReference, int, BaseObject)} instead
*/
@Deprecated
public void setObject(String className, int nb, BaseObject object)
{
setXObject(resolveClassReference(className), nb, object);
}
/**
* @return true if the document is a new one (i.e. it has never been saved) or false otherwise
*/
public boolean isNew()
{
return this.isNew;
}
public void setNew(boolean aNew)
{
this.isNew = aNew;
}
/**
* @since 2.2M1
*/
public void mergeXClass(XWikiDocument templatedoc)
{
BaseClass bclass = getXClass();
BaseClass tbclass = templatedoc.getXClass();
if (tbclass != null) {
if (bclass == null) {
setXClass((BaseClass) tbclass.clone());
} else {
getXClass().merge((BaseClass) tbclass.clone());
}
}
setContentDirty(true);
}
/**
* @deprecated since 2.2M1 use {@link #mergeXClass(XWikiDocument)} instead
*/
@Deprecated
public void mergexWikiClass(XWikiDocument templatedoc)
{
mergeXClass(templatedoc);
}
/**
* @since 2.2M1
*/
public void mergeXObjects(XWikiDocument templatedoc)
{
// TODO: look for each object if it already exist and add it if it doesn't
for (Map.Entry<DocumentReference, List<BaseObject>> entry : templatedoc.getXObjects().entrySet()) {
List<BaseObject> myObjects = getXObjects().get(entry.getKey());
if (myObjects == null) {
myObjects = new ArrayList<BaseObject>();
}
if (!entry.getValue().isEmpty()) {
DocumentReference newXClassReference = null;
for (BaseObject otherObject : entry.getValue()) {
if (otherObject != null) {
BaseObject myObject = otherObject.duplicate(getDocumentReference());
myObjects.add(myObject);
myObject.setNumber(myObjects.size() - 1);
newXClassReference = myObject.getXClassReference();
}
}
setXObjects(newXClassReference, myObjects);
}
}
setContentDirty(true);
}
/**
* @deprecated since 2.2M1 use {@link #mergeXObjects(XWikiDocument)} instead
*/
@Deprecated
public void mergexWikiObjects(XWikiDocument templatedoc)
{
mergeXObjects(templatedoc);
}
/**
* @since 2.2M1
*/
public void cloneXObjects(XWikiDocument templatedoc)
{
cloneXObjects(templatedoc, true);
}
/**
* @since 2.2.3
*/
public void duplicateXObjects(XWikiDocument templatedoc)
{
cloneXObjects(templatedoc, false);
}
/**
* Copy specified document objects into current document.
*
* @param templatedoc the document to copy
* @param keepsIdentity if true it does an exact java copy, otherwise it duplicate objects with the new document
* name (and new class names)
*/
private void cloneXObjects(XWikiDocument templatedoc, boolean keepsIdentity)
{
// clean map
this.xObjects.clear();
// fill map
for (Map.Entry<DocumentReference, List<BaseObject>> entry : templatedoc.getXObjects().entrySet()) {
List<BaseObject> tobjects = entry.getValue();
// clone and insert xobjects
for (BaseObject otherObject : tobjects) {
if (otherObject != null) {
if (keepsIdentity) {
addXObject((BaseObject) otherObject.clone());
} else {
BaseObject newObject = otherObject.duplicate(getDocumentReference());
setXObject(newObject.getNumber(), newObject);
}
} else if (keepsIdentity) {
// set null object to make sure to have exactly the same thing when cloning a document
addXObject(entry.getKey(), null);
}
}
}
}
/**
* @deprecated since 2.2M1 use {@link #cloneXObjects(XWikiDocument)} instead
*/
@Deprecated
public void clonexWikiObjects(XWikiDocument templatedoc)
{
cloneXObjects(templatedoc);
}
/**
* @since 2.2M1
*/
public DocumentReference getTemplateDocumentReference()
{
return this.templateDocumentReference;
}
/**
* @deprecated since 2.2M1 use {@link #getTemplateDocumentReference()} instead
*/
@Deprecated
public String getTemplate()
{
String templateReferenceAsString;
DocumentReference templateDocumentReference = getTemplateDocumentReference();
if (templateDocumentReference != null) {
templateReferenceAsString = this.localEntityReferenceSerializer.serialize(templateDocumentReference);
} else {
templateReferenceAsString = "";
}
return templateReferenceAsString;
}
/**
* @since 2.2M1
*/
public void setTemplateDocumentReference(DocumentReference templateDocumentReference)
{
if ((templateDocumentReference == null && getTemplateDocumentReference() != null)
|| (templateDocumentReference != null && !templateDocumentReference.equals(getTemplateDocumentReference()))) {
this.templateDocumentReference = templateDocumentReference;
setMetaDataDirty(true);
}
}
/**
* @deprecated since 2.2M1 use {@link #setTemplateDocumentReference(DocumentReference)} instead
*/
@Deprecated
public void setTemplate(String template)
{
DocumentReference templateReference = null;
if (!StringUtils.isEmpty(template)) {
templateReference = this.currentMixedDocumentReferenceResolver.resolve(template);
}
setTemplateDocumentReference(templateReference);
}
public String displayPrettyName(String fieldname, XWikiContext context)
{
return displayPrettyName(fieldname, false, true, context);
}
public String displayPrettyName(String fieldname, boolean showMandatory, XWikiContext context)
{
return displayPrettyName(fieldname, showMandatory, true, context);
}
public String displayPrettyName(String fieldname, boolean showMandatory, boolean before, XWikiContext context)
{
try {
BaseObject object = getXObject();
if (object == null) {
object = getFirstObject(fieldname, context);
}
return displayPrettyName(fieldname, showMandatory, before, object, context);
} catch (Exception e) {
return "";
}
}
public String displayPrettyName(String fieldname, BaseObject obj, XWikiContext context)
{
return displayPrettyName(fieldname, false, true, obj, context);
}
public String displayPrettyName(String fieldname, boolean showMandatory, BaseObject obj, XWikiContext context)
{
return displayPrettyName(fieldname, showMandatory, true, obj, context);
}
public String displayPrettyName(String fieldname, boolean showMandatory, boolean before, BaseObject obj,
XWikiContext context)
{
try {
PropertyClass pclass = (PropertyClass) obj.getXClass(context).get(fieldname);
String dprettyName = "";
if (showMandatory) {
dprettyName = context.getWiki().addMandatory(context);
}
if (before) {
return dprettyName + pclass.getPrettyName(context);
} else {
return pclass.getPrettyName(context) + dprettyName;
}
} catch (Exception e) {
return "";
}
}
public String displayTooltip(String fieldname, XWikiContext context)
{
try {
BaseObject object = getXObject();
if (object == null) {
object = getFirstObject(fieldname, context);
}
return displayTooltip(fieldname, object, context);
} catch (Exception e) {
return "";
}
}
public String displayTooltip(String fieldname, BaseObject obj, XWikiContext context)
{
String result = "";
try {
PropertyClass pclass = (PropertyClass) obj.getXClass(context).get(fieldname);
String tooltip = pclass.getTooltip(context);
if ((tooltip != null) && (!tooltip.trim().equals(""))) {
String img =
"<img src=\"" + context.getWiki().getSkinFile("info.gif", context)
+ "\" class=\"tooltip_image\" align=\"middle\" />";
result = context.getWiki().addTooltip(img, tooltip, context);
}
} catch (Exception e) {
}
return result;
}
/**
* @param fieldname the name of the field to display
* @param context the XWiki context
* @return the rendered field
*/
public String display(String fieldname, XWikiContext context)
{
String result = "";
try {
BaseObject object = getXObject();
if (object == null) {
object = getFirstObject(fieldname, context);
}
result = display(fieldname, object, context);
} catch (Exception e) {
LOG.error("Failed to display field [" + fieldname + "] of document ["
+ this.defaultEntityReferenceSerializer.serialize(getDocumentReference()) + "]", e);
}
return result;
}
/**
* @param fieldname the name of the field to display
* @param obj the object containing the field to display
* @param context the XWiki context
* @return the rendered field
*/
public String display(String fieldname, BaseObject obj, XWikiContext context)
{
String type = null;
try {
type = (String) context.get("display");
} catch (Exception e) {
}
if (type == null) {
type = "view";
}
return display(fieldname, type, obj, context);
}
/**
* @param fieldname the name of the field to display
* @param mode the mode to use ("view", "edit", ...)
* @param context the XWiki context
* @return the rendered field
*/
public String display(String fieldname, String mode, XWikiContext context)
{
return display(fieldname, mode, "", context);
}
/**
* @param fieldname the name of the field to display
* @param type the type of the field to display
* @param obj the object containing the field to display
* @param context the XWiki context
* @return the rendered field
*/
public String display(String fieldname, String type, BaseObject obj, XWikiContext context)
{
return display(fieldname, type, "", obj, context);
}
/**
* @param fieldname the name of the field to display
* @param mode the mode to use ("view", "edit", ...)
* @param prefix the prefix to add in the field identifier in edit display for example
* @param context the XWiki context
* @return the rendered field
*/
public String display(String fieldname, String mode, String prefix, XWikiContext context)
{
try {
BaseObject object = getXObject();
if (object == null) {
object = getFirstObject(fieldname, context);
}
if (object == null) {
return "";
} else {
return display(fieldname, mode, prefix, object, context);
}
} catch (Exception e) {
return "";
}
}
/**
* @param fieldname the name of the field to display
* @param type the type of the field to display
* @param obj the object containing the field to display
* @param wrappingSyntaxId the syntax of the content in which the result will be included. This to take care of some
* escaping depending of the syntax.
* @param context the XWiki context
* @return the rendered field
*/
public String display(String fieldname, String type, BaseObject obj, String wrappingSyntaxId, XWikiContext context)
{
return display(fieldname, type, "", obj, wrappingSyntaxId, context);
}
/**
* @param fieldname the name of the field to display
* @param type the type of the field to display
* @param pref the prefix to add in the field identifier in edit display for example
* @param obj the object containing the field to display
* @param context the XWiki context
* @return the rendered field
*/
public String display(String fieldname, String type, String pref, BaseObject obj, XWikiContext context)
{
return display(fieldname, type, pref, obj, context.getWiki().getCurrentContentSyntaxId(getSyntaxId(), context),
context);
}
/**
* @param fieldname the name of the field to display
* @param type the type of the field to display
* @param pref the prefix to add in the field identifier in edit display for example
* @param obj the object containing the field to display
* @param wrappingSyntaxId the syntax of the content in which the result will be included. This to take care of some
* escaping depending of the syntax.
* @param context the XWiki context
* @return the rendered field
*/
public String display(String fieldname, String type, String pref, BaseObject obj, String wrappingSyntaxId,
XWikiContext context)
{
if (obj == null) {
return "";
}
boolean isInRenderingEngine = BooleanUtils.toBoolean((Boolean) context.get("isInRenderingEngine"));
HashMap<String, Object> backup = new HashMap<String, Object>();
try {
backupContext(backup, context);
setAsContextDoc(context);
type = type.toLowerCase();
StringBuffer result = new StringBuffer();
PropertyClass pclass = (PropertyClass) obj.getXClass(context).get(fieldname);
String prefix = pref + obj.getXClass(context).getName() + "_" + obj.getNumber() + "_";
if (pclass == null) {
return "";
} else if (pclass.isCustomDisplayed(context)) {
pclass.displayCustom(result, fieldname, prefix, type, obj, context);
} else if (type.equals("view")) {
pclass.displayView(result, fieldname, prefix, obj, context);
} else if (type.equals("rendered")) {
String fcontent = pclass.displayView(fieldname, prefix, obj, context);
// This mode is deprecated for the new rendering and should also be removed for the old rendering
// since the way to implement this now is to choose the type of rendering to do in the class itself.
// Thus for the new rendering we simply make this mode work like the "view" mode.
if (is10Syntax(wrappingSyntaxId)) {
result.append(getRenderedContent(fcontent, getSyntaxId(), context));
} else {
result.append(fcontent);
}
} else if (type.equals("edit")) {
context.addDisplayedField(fieldname);
// If the Syntax id is "xwiki/1.0" then use the old rendering subsystem and prevent wiki syntax
// rendering using the pre macro. In the new rendering system it's the XWiki Class itself that does the
// escaping. For example for a textarea check the TextAreaClass class.
// If the Syntax id is not "xwiki/1.0", i.e. if the new rendering engine is used then we need to
// protect the content with a <pre> since otherwise whitespaces will be stripped by the HTML macro
// used to surround the object property content (see below).
if (is10Syntax(wrappingSyntaxId)) {
// Don't use pre when not in the rendernig engine since for template we don't evaluate wiki syntax.
if (isInRenderingEngine) {
result.append("{pre}");
}
} else {
result.append("<pre>");
}
pclass.displayEdit(result, fieldname, prefix, obj, context);
if (is10Syntax(wrappingSyntaxId)) {
if (isInRenderingEngine) {
result.append("{/pre}");
}
} else {
result.append("</pre>");
}
} else if (type.equals("hidden")) {
// If the Syntax id is "xwiki/1.0" then use the old rendering subsystem and prevent wiki syntax
// rendering using the pre macro. In the new rendering system it's the XWiki Class itself that does the
// escaping. For example for a textarea check the TextAreaClass class.
if (is10Syntax(wrappingSyntaxId) && isInRenderingEngine) {
result.append("{pre}");
}
pclass.displayHidden(result, fieldname, prefix, obj, context);
if (is10Syntax(wrappingSyntaxId) && isInRenderingEngine) {
result.append("{/pre}");
}
} else if (type.equals("search")) {
// If the Syntax id is "xwiki/1.0" then use the old rendering subsystem and prevent wiki syntax
// rendering using the pre macro. In the new rendering system it's the XWiki Class itself that does the
// escaping. For example for a textarea check the TextAreaClass class.
if (is10Syntax(wrappingSyntaxId) && isInRenderingEngine) {
result.append("{pre}");
}
prefix = obj.getXClass(context).getName() + "_";
pclass.displaySearch(result, fieldname, prefix, (XWikiCriteria) context.get("query"), context);
if (is10Syntax(wrappingSyntaxId) && isInRenderingEngine) {
result.append("{/pre}");
}
} else {
pclass.displayView(result, fieldname, prefix, obj, context);
}
// If we're in new rendering engine we want to wrap the HTML returned by displayView() in
// a {{html/}} macro so that the user doesn't have to do it.
// We test if we're inside the rendering engine since it's also possible that this display() method is
// called
// directly from a template and in this case we only want HTML as a result and not wiki syntax.
// TODO: find a more generic way to handle html macro because this works only for XWiki 1.0 and XWiki 2.0
// Add the {{html}}{{/html}} only when result really contains html since it's not needed for pure text
if (isInRenderingEngine && !is10Syntax(wrappingSyntaxId)
&& (result.indexOf("<") != -1 || result.indexOf(">") != -1)) {
result.insert(0, "{{html clean=\"false\" wiki=\"false\"}}");
result.append("{{/html}}");
}
return result.toString();
} catch (Exception ex) {
// TODO: It would better to check if the field exists rather than catching an exception
// raised by a NPE as this is currently the case here...
LOG.warn("Failed to display field [" + fieldname + "] in [" + type + "] mode for Object of Class ["
+ this.defaultEntityReferenceSerializer.serialize(obj.getDocumentReference()) + "]", ex);
return "";
} finally {
restoreContext(backup, context);
}
}
/**
* @since 2.2M1
*/
public String displayForm(DocumentReference classReference, String header, String format, XWikiContext context)
{
return displayForm(classReference, header, format, true, context);
}
/**
* @deprecated since 2.2M1, use {@link #displayForm(DocumentReference, String, String, XWikiContext)} instead
*/
@Deprecated
public String displayForm(String className, String header, String format, XWikiContext context)
{
return displayForm(className, header, format, true, context);
}
/**
* @since 2.2M1
*/
public String displayForm(DocumentReference classReference, String header, String format, boolean linebreak,
XWikiContext context)
{
List<BaseObject> objects = getXObjects(classReference);
if (format.endsWith("\\n")) {
linebreak = true;
}
BaseObject firstobject = null;
Iterator<BaseObject> foit = objects.iterator();
while ((firstobject == null) && foit.hasNext()) {
firstobject = foit.next();
}
if (firstobject == null) {
return "";
}
BaseClass bclass = firstobject.getXClass(context);
if (bclass.getPropertyList().size() == 0) {
return "";
}
StringBuffer result = new StringBuffer();
VelocityContext vcontext = new VelocityContext();
for (String propertyName : bclass.getPropertyList()) {
PropertyClass pclass = (PropertyClass) bclass.getField(propertyName);
vcontext.put(pclass.getName(), pclass.getPrettyName());
}
result
.append(XWikiVelocityRenderer.evaluate(header, context.getDoc().getPrefixedFullName(), vcontext, context));
if (linebreak) {
result.append("\n");
}
// display each line
for (int i = 0; i < objects.size(); i++) {
vcontext.put("id", new Integer(i + 1));
BaseObject object = objects.get(i);
if (object != null) {
for (String name : bclass.getPropertyList()) {
vcontext.put(name, display(name, object, context));
}
result.append(XWikiVelocityRenderer.evaluate(format, context.getDoc().getPrefixedFullName(), vcontext,
context));
if (linebreak) {
result.append("\n");
}
}
}
return result.toString();
}
/**
* @deprecated since 2.2M1, use {@link #displayForm(DocumentReference, String, String, boolean, XWikiContext)}
* instead
*/
@Deprecated
public String displayForm(String className, String header, String format, boolean linebreak, XWikiContext context)
{
return displayForm(resolveClassReference(className), header, format, linebreak, context);
}
/**
* @since 2.2M1
*/
public String displayForm(DocumentReference classReference, XWikiContext context)
{
List<BaseObject> objects = getXObjects(classReference);
if (objects == null) {
return "";
}
BaseObject firstobject = null;
Iterator<BaseObject> foit = objects.iterator();
while ((firstobject == null) && foit.hasNext()) {
firstobject = foit.next();
}
if (firstobject == null) {
return "";
}
BaseClass bclass = firstobject.getXClass(context);
if (bclass.getPropertyList().size() == 0) {
return "";
}
StringBuffer result = new StringBuffer();
result.append("{table}\n");
boolean first = true;
for (String propertyName : bclass.getPropertyList()) {
if (first == true) {
first = false;
} else {
result.append("|");
}
PropertyClass pclass = (PropertyClass) bclass.getField(propertyName);
result.append(pclass.getPrettyName());
}
result.append("\n");
for (int i = 0; i < objects.size(); i++) {
BaseObject object = objects.get(i);
if (object != null) {
first = true;
for (String propertyName : bclass.getPropertyList()) {
if (first == true) {
first = false;
} else {
result.append("|");
}
String data = display(propertyName, object, context);
data = data.trim();
data = data.replaceAll("\n", " ");
if (data.length() == 0) {
result.append(" ");
} else {
result.append(data);
}
}
result.append("\n");
}
}
result.append("{table}\n");
return result.toString();
}
/**
* @deprecated since 2.2M1, use {@link #displayForm(DocumentReference, XWikiContext)} instead
*/
@Deprecated
public String displayForm(String className, XWikiContext context)
{
return displayForm(resolveClassReference(className), context);
}
public boolean isFromCache()
{
return this.fromCache;
}
public void setFromCache(boolean fromCache)
{
this.fromCache = fromCache;
}
public void readDocMetaFromForm(EditForm eform, XWikiContext context) throws XWikiException
{
String defaultLanguage = eform.getDefaultLanguage();
if (defaultLanguage != null) {
setDefaultLanguage(defaultLanguage);
}
String defaultTemplate = eform.getDefaultTemplate();
if (defaultTemplate != null) {
setDefaultTemplate(defaultTemplate);
}
String creator = eform.getCreator();
if ((creator != null) && (!creator.equals(getCreator()))) {
if ((getCreator().equals(context.getUser()))
|| (context.getWiki().getRightService().hasAdminRights(context))) {
setCreator(creator);
}
}
String parent = eform.getParent();
if (parent != null) {
setParent(parent);
}
// Read the comment from the form
String comment = eform.getComment();
if (comment != null) {
setComment(comment);
}
// Read the minor edit checkbox from the form
setMinorEdit(eform.isMinorEdit());
String tags = eform.getTags();
if (!StringUtils.isEmpty(tags)) {
setTags(tags, context);
}
// Set the Syntax id if defined
String syntaxId = eform.getSyntaxId();
if (syntaxId != null) {
setSyntaxId(syntaxId);
}
}
/**
* add tags to the document.
*/
public void setTags(String tagsStr, XWikiContext context) throws XWikiException
{
BaseClass tagsClass = context.getWiki().getTagClass(context);
StaticListClass tagProp = (StaticListClass) tagsClass.getField(XWikiConstant.TAG_CLASS_PROP_TAGS);
BaseObject tags = getObject(XWikiConstant.TAG_CLASS, true, context);
tags.safeput(XWikiConstant.TAG_CLASS_PROP_TAGS, tagProp.fromString(tagsStr));
setMetaDataDirty(true);
}
public String getTags(XWikiContext context)
{
ListProperty prop = (ListProperty) getTagProperty(context);
return prop != null ? prop.getTextValue() : "";
}
public List<String> getTagsList(XWikiContext context)
{
List<String> tagList = null;
BaseProperty prop = getTagProperty(context);
if (prop != null) {
tagList = (List<String>) prop.getValue();
}
return tagList;
}
private BaseProperty getTagProperty(XWikiContext context)
{
BaseObject tags = getObject(XWikiConstant.TAG_CLASS);
return tags != null ? ((BaseProperty) tags.safeget(XWikiConstant.TAG_CLASS_PROP_TAGS)) : null;
}
public List<String> getTagsPossibleValues(XWikiContext context)
{
List<String> list;
try {
BaseClass tagsClass = context.getWiki().getTagClass(context);
String possibleValues =
((StaticListClass) tagsClass.getField(XWikiConstant.TAG_CLASS_PROP_TAGS)).getValues();
return ListClass.getListFromString(possibleValues);
} catch (XWikiException e) {
LOG.error("Failed to get tag class", e);
list = Collections.emptyList();
}
return list;
}
public void readTranslationMetaFromForm(EditForm eform, XWikiContext context) throws XWikiException
{
String content = eform.getContent();
if (content != null) {
// Cleanup in case we use HTMLAREA
// content = context.getUtil().substitute("s/<br class=\\\"htmlarea\\\"\\/>/\\r\\n/g",
// content);
content = context.getUtil().substitute("s/<br class=\"htmlarea\" \\/>/\r\n/g", content);
setContent(content);
}
String title = eform.getTitle();
if (title != null) {
setTitle(title);
}
}
public void readObjectsFromForm(EditForm eform, XWikiContext context) throws XWikiException
{
for (DocumentReference reference : getXObjects().keySet()) {
List<BaseObject> oldObjects = getXObjects(reference);
List<BaseObject> newObjects = new ArrayList<BaseObject>();
while (newObjects.size() < oldObjects.size()) {
newObjects.add(null);
}
for (int i = 0; i < oldObjects.size(); i++) {
BaseObject oldobject = oldObjects.get(i);
if (oldobject != null) {
BaseClass baseclass = oldobject.getXClass(context);
BaseObject newobject =
(BaseObject) baseclass.fromMap(eform.getObject(baseclass.getName() + "_" + i), oldobject);
newobject.setNumber(oldobject.getNumber());
newobject.setGuid(oldobject.getGuid());
newobject.setDocumentReference(getDocumentReference());
newObjects.set(newobject.getNumber(), newobject);
}
}
getXObjects().put(reference, newObjects);
}
setContentDirty(true);
}
public void readFromForm(EditForm eform, XWikiContext context) throws XWikiException
{
readDocMetaFromForm(eform, context);
readTranslationMetaFromForm(eform, context);
readObjectsFromForm(eform, context);
}
public void readFromTemplate(EditForm eform, XWikiContext context) throws XWikiException
{
String template = eform.getTemplate();
readFromTemplate(template, context);
}
/**
* @since 2.2M1
*/
public void readFromTemplate(DocumentReference templateDocumentReference, XWikiContext context)
throws XWikiException
{
if (templateDocumentReference != null) {
String content = getContent();
if ((!content.equals("\n")) && (!content.equals("")) && !isNew()) {
Object[] args = {this.defaultEntityReferenceSerializer.serialize(getDocumentReference())};
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_APP_DOCUMENT_NOT_EMPTY,
"Cannot add a template to document {0} because it already has content", null, args);
} else {
XWiki xwiki = context.getWiki();
XWikiDocument templatedoc = xwiki.getDocument(templateDocumentReference, context);
if (templatedoc.isNew()) {
Object[] args =
{this.defaultEntityReferenceSerializer.serialize(templateDocumentReference),
this.compactEntityReferenceSerializer.serialize(getDocumentReference())};
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_APP_TEMPLATE_DOES_NOT_EXIST,
"Template document {0} does not exist when adding to document {1}", null, args);
} else {
setTemplateDocumentReference(templateDocumentReference);
setContent(templatedoc.getContent());
// Set the new document syntax as the syntax of the template since the template content
// is copied into the new document
setSyntax(templatedoc.getSyntax());
// If the parent is not set in the current document set the template parent as the parent.
if (getParentReference() == null) {
setParentReference(templatedoc.getParentReference());
}
if (isNew()) {
// We might have received the object from the cache and the template objects might have been
// copied already we need to remove them
setXObjects(new TreeMap<DocumentReference, List<BaseObject>>());
}
// Merge the external objects.
// Currently the choice is not to merge the base class and object because it is not the prefered way
// of using external classes and objects.
mergeXObjects(templatedoc);
}
}
}
setContentDirty(true);
}
/**
* @deprecated since 2.2M1 use {@link #readFromTemplate(DocumentReference, XWikiContext)} instead
*/
@Deprecated
public void readFromTemplate(String template, XWikiContext context) throws XWikiException
{
// Keep the same behavior for backward compatibility
DocumentReference templateDocumentReference = null;
if (StringUtils.isNotEmpty(template)) {
templateDocumentReference = this.currentMixedDocumentReferenceResolver.resolve(template);
}
readFromTemplate(templateDocumentReference, context);
}
/**
* Use the document passed as parameter as the new identity for the current document.
*
* @param document the document containing the new identity
* @throws XWikiException in case of error
*/
private void clone(XWikiDocument document) throws XWikiException
{
setDocumentReference(document.getDocumentReference());
setRCSVersion(document.getRCSVersion());
setDocumentArchive(document.getDocumentArchive());
setAuthor(document.getAuthor());
setContentAuthor(document.getContentAuthor());
setContent(document.getContent());
setContentDirty(document.isContentDirty());
setCreationDate(document.getCreationDate());
setDate(document.getDate());
setCustomClass(document.getCustomClass());
setContentUpdateDate(document.getContentUpdateDate());
setTitle(document.getTitle());
setFormat(document.getFormat());
setFromCache(document.isFromCache());
setElements(document.getElements());
setId(document.getId());
setMeta(document.getMeta());
setMetaDataDirty(document.isMetaDataDirty());
setMostRecent(document.isMostRecent());
setNew(document.isNew());
setStore(document.getStore());
setTemplateDocumentReference(document.getTemplateDocumentReference());
setParent(document.getParent());
setCreator(document.getCreator());
setDefaultLanguage(document.getDefaultLanguage());
setDefaultTemplate(document.getDefaultTemplate());
setValidationScript(document.getValidationScript());
setLanguage(document.getLanguage());
setTranslation(document.getTranslation());
setXClass((BaseClass) document.getXClass().clone());
setXClassXML(document.getXClassXML());
setComment(document.getComment());
setMinorEdit(document.isMinorEdit());
setSyntax(document.getSyntax());
setHidden(document.isHidden());
cloneXObjects(document);
cloneAttachments(document);
this.elements = document.elements;
this.originalDocument = document.originalDocument;
}
@Override
public XWikiDocument clone()
{
return cloneInternal(getDocumentReference(), true);
}
/**
* Duplicate this document and give it a new name.
*
* @since 2.2.3
*/
public XWikiDocument duplicate(DocumentReference newDocumentReference)
{
return cloneInternal(newDocumentReference, false);
}
private XWikiDocument cloneInternal(DocumentReference newDocumentReference, boolean keepsIdentity)
{
XWikiDocument doc = null;
try {
Constructor constructor = getClass().getConstructor(DocumentReference.class);
doc = (XWikiDocument) constructor.newInstance(newDocumentReference);
// use version field instead of getRCSVersion because it returns "1.1" if version==null.
doc.version = this.version;
doc.setDocumentArchive(getDocumentArchive());
doc.setAuthor(getAuthor());
doc.setContentAuthor(getContentAuthor());
doc.setContent(getContent());
doc.setContentDirty(isContentDirty());
doc.setCreationDate(getCreationDate());
doc.setDate(getDate());
doc.setCustomClass(getCustomClass());
doc.setContentUpdateDate(getContentUpdateDate());
doc.setTitle(getTitle());
doc.setFormat(getFormat());
doc.setFromCache(isFromCache());
doc.setElements(getElements());
doc.setId(getId());
doc.setMeta(getMeta());
doc.setMetaDataDirty(isMetaDataDirty());
doc.setMostRecent(isMostRecent());
doc.setNew(isNew());
doc.setStore(getStore());
doc.setTemplateDocumentReference(getTemplateDocumentReference());
doc.setParentReference(getRelativeParentReference());
doc.setCreator(getCreator());
doc.setDefaultLanguage(getDefaultLanguage());
doc.setDefaultTemplate(getDefaultTemplate());
doc.setValidationScript(getValidationScript());
doc.setLanguage(getLanguage());
doc.setTranslation(getTranslation());
doc.setXClass((BaseClass) getXClass().clone());
doc.setXClassXML(getXClassXML());
doc.setComment(getComment());
doc.setMinorEdit(isMinorEdit());
doc.setSyntax(getSyntax());
doc.setHidden(isHidden());
if (keepsIdentity) {
doc.cloneXObjects(this);
doc.cloneAttachments(this);
} else {
doc.duplicateXObjects(this);
doc.copyAttachments(this);
}
doc.elements = this.elements;
doc.originalDocument = this.originalDocument;
} catch (Exception e) {
// This should not happen
LOG.error("Exception while cloning document", e);
}
return doc;
}
/**
* Clone attachments from another document. This implementation expects that this document is the same as the other
* document and thus attachments will be saved in the database in the same place as the ones which they are cloning.
*
* @param sourceDocument an XWikiDocument to copy attachments from
*/
private void cloneAttachments(final XWikiDocument sourceDocument)
{
this.getAttachmentList().clear();
for (XWikiAttachment attach : sourceDocument.getAttachmentList()) {
XWikiAttachment newAttach = (XWikiAttachment) attach.clone();
// Document is set to this because if this document is renamed then the attachment will have a new id
// and be saved somewhere different.
newAttach.setDoc(this);
this.getAttachmentList().add(newAttach);
}
}
/**
* Copy attachments from one document to another. This implementation expects that you are copying the attachment
* from one document to another and thus it should be saved seperately from the original in the database.
*
* @param sourceDocument an XWikiDocument to copy attachments from
*/
public void copyAttachments(XWikiDocument sourceDocument)
{
getAttachmentList().clear();
Iterator<XWikiAttachment> attit = sourceDocument.getAttachmentList().iterator();
while (attit.hasNext()) {
XWikiAttachment attachment = attit.next();
XWikiAttachment newattachment = (XWikiAttachment) attachment.clone();
newattachment.setDoc(this);
// TODO: Why must attachment content must be set dirty --cjdelisle
if (newattachment.getAttachment_content() != null) {
newattachment.getAttachment_content().setContentDirty(true);
}
getAttachmentList().add(newattachment);
}
setContentDirty(true);
}
public void loadAttachments(XWikiContext context) throws XWikiException
{
for (XWikiAttachment attachment : getAttachmentList()) {
attachment.loadContent(context);
attachment.loadArchive(context);
}
}
@Override
public boolean equals(Object object)
{
// Same Java object, they sure are equal
if (this == object) {
return true;
}
XWikiDocument doc = (XWikiDocument) object;
if (!getDocumentReference().equals(doc.getDocumentReference())) {
return false;
}
if (!getAuthor().equals(doc.getAuthor())) {
return false;
}
if (!getContentAuthor().equals(doc.getContentAuthor())) {
return false;
}
if ((getParentReference() != null && !getParentReference().equals(doc.getParentReference()))
|| (getParentReference() == null && doc.getParentReference() != null)) {
return false;
}
if (!getCreator().equals(doc.getCreator())) {
return false;
}
if (!getDefaultLanguage().equals(doc.getDefaultLanguage())) {
return false;
}
if (!getLanguage().equals(doc.getLanguage())) {
return false;
}
if (getTranslation() != doc.getTranslation()) {
return false;
}
if (getDate().getTime() != doc.getDate().getTime()) {
return false;
}
if (getContentUpdateDate().getTime() != doc.getContentUpdateDate().getTime()) {
return false;
}
if (getCreationDate().getTime() != doc.getCreationDate().getTime()) {
return false;
}
if (!getFormat().equals(doc.getFormat())) {
return false;
}
if (!getTitle().equals(doc.getTitle())) {
return false;
}
if (!getContent().equals(doc.getContent())) {
return false;
}
if (!getVersion().equals(doc.getVersion())) {
return false;
}
if ((getTemplateDocumentReference() != null && !getTemplateDocumentReference().equals(
doc.getTemplateDocumentReference()))
|| (getTemplateDocumentReference() == null && doc.getTemplateDocumentReference() != null)) {
return false;
}
if (!getDefaultTemplate().equals(doc.getDefaultTemplate())) {
return false;
}
if (!getValidationScript().equals(doc.getValidationScript())) {
return false;
}
if (!getComment().equals(doc.getComment())) {
return false;
}
if (isMinorEdit() != doc.isMinorEdit()) {
return false;
}
if ((getSyntaxId() != null && !getSyntaxId().equals(doc.getSyntaxId()))
|| (getSyntaxId() == null && doc.getSyntaxId() != null)) {
return false;
}
if (isHidden() != doc.isHidden()) {
return false;
}
if (!getXClass().equals(doc.getXClass())) {
return false;
}
Set<DocumentReference> myObjectClassReferences = getXObjects().keySet();
Set<DocumentReference> otherObjectClassReferences = doc.getXObjects().keySet();
if (!myObjectClassReferences.equals(otherObjectClassReferences)) {
return false;
}
for (DocumentReference reference : myObjectClassReferences) {
List<BaseObject> myObjects = getXObjects(reference);
List<BaseObject> otherObjects = doc.getXObjects(reference);
if (myObjects.size() != otherObjects.size()) {
return false;
}
for (int i = 0; i < myObjects.size(); i++) {
if ((myObjects.get(i) == null && otherObjects.get(i) != null)
|| (myObjects.get(i) != null && otherObjects.get(i) == null)) {
return false;
}
if (myObjects.get(i) == null && otherObjects.get(i) == null) {
continue;
}
if (!myObjects.get(i).equals(otherObjects.get(i))) {
return false;
}
}
}
// We consider that 2 documents are still equal even when they have different original
// documents (see getOriginalDocument() for more details as to what is an original
// document).
return true;
}
/**
* Convert a {@link Document} into an XML string. You should prefer
* {@link #toXML(OutputStream, boolean, boolean, boolean, boolean, XWikiContext)} or
* {@link #toXML(com.xpn.xwiki.internal.xml.XMLWriter, boolean, boolean, boolean, boolean, XWikiContext)} when
* possible to avoid memory load.
*
* @param doc the {@link Document} to convert to a String
* @param context current XWikiContext
* @return an XML representation of the {@link Document}
* @deprecated this method has nothing to do here and is apparently unused
*/
@Deprecated
public String toXML(Document doc, XWikiContext context)
{
String encoding = context.getWiki().getEncoding();
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
XMLWriter wr = new XMLWriter(os, new OutputFormat("", true, encoding));
wr.write(doc);
return os.toString(encoding);
} catch (IOException e) {
LOG.error("Exception while doc.toXML", e);
return "";
}
}
/**
* Retrieve the document in the current context language as an XML string. The rendrered document content and all
* XObjects are included. Document attachments and archived versions are excluded. You should prefer
* toXML(OutputStream, true, true, false, false, XWikiContext)} or toXML(com.xpn.xwiki.util.XMLWriter, true, true,
* false, false, XWikiContext) on the translated document when possible to reduce memory load.
*
* @param context current XWikiContext
* @return a string containing an XML representation of the document in the current context language
* @throws XWikiException when an error occurs during wiki operation
*/
public String getXMLContent(XWikiContext context) throws XWikiException
{
XWikiDocument tdoc = getTranslatedDocument(context);
return tdoc.toXML(true, true, false, false, context);
}
/**
* Retrieve the document as an XML string. All XObject are included. Rendered content, attachments and archived
* version are excluded. You should prefer toXML(OutputStream, true, false, false, false, XWikiContext)} or
* toXML(com.xpn.xwiki.util.XMLWriter, true, false, false, false, XWikiContext) when possible to reduce memory load.
*
* @param context current XWikiContext
* @return a string containing an XML representation of the document
* @throws XWikiException when an error occurs during wiki operation
*/
public String toXML(XWikiContext context) throws XWikiException
{
return toXML(true, false, false, false, context);
}
/**
* Retrieve the document as an XML string. All XObjects attachments and archived version are included. Rendered
* content is excluded. You should prefer toXML(OutputStream, true, false, true, true, XWikiContext)} or
* toXML(com.xpn.xwiki.util.XMLWriter, true, false, true, true, XWikiContext) when possible to reduce memory load.
*
* @param context current XWikiContext
* @return a string containing an XML representation of the document
* @throws XWikiException when an error occurs during wiki operation
*/
public String toFullXML(XWikiContext context) throws XWikiException
{
return toXML(true, false, true, true, context);
}
/**
* Serialize the document into a new entry of an ZipOutputStream in XML format. All XObjects and attachments are
* included. Rendered content is excluded.
*
* @param zos the ZipOutputStream to write to
* @param zipname the name of the new entry to create
* @param withVersions if true, also include archived version of the document
* @param context current XWikiContext
* @throws XWikiException when an error occurs during xwiki operations
* @throws IOException when an error occurs during streaming operations
* @since 2.3M2
*/
public void addToZip(ZipOutputStream zos, String zipname, boolean withVersions, XWikiContext context)
throws XWikiException, IOException
{
ZipEntry zipentry = new ZipEntry(zipname);
zos.putNextEntry(zipentry);
toXML(zos, true, false, true, withVersions, context);
zos.closeEntry();
}
/**
* Serialize the document into a new entry of an ZipOutputStream in XML format. The new entry is named
* 'LastSpaceName/DocumentName'. All XObjects and attachments are included. Rendered content is excluded.
*
* @param zos the ZipOutputStream to write to
* @param withVersions if true, also include archived version of the document
* @param context current XWikiContext
* @throws XWikiException when an error occurs during xwiki operations
* @throws IOException when an error occurs during streaming operations
* @since 2.3M2
*/
public void addToZip(ZipOutputStream zos, boolean withVersions, XWikiContext context) throws XWikiException,
IOException
{
String zipname =
getDocumentReference().getLastSpaceReference().getName() + "/" + getDocumentReference().getName();
String language = getLanguage();
if (!StringUtils.isEmpty(language)) {
zipname += "." + language;
}
addToZip(zos, zipname, withVersions, context);
}
/**
* Serialize the document into a new entry of an ZipOutputStream in XML format. The new entry is named
* 'LastSpaceName/DocumentName'. All XObjects, attachments and archived versions are included. Rendered content is
* excluded.
*
* @param zos the ZipOutputStream to write to
* @param context current XWikiContext
* @throws XWikiException when an error occurs during xwiki operations
* @throws IOException when an error occurs during streaming operations
* @since 2.3M2
*/
public void addToZip(ZipOutputStream zos, XWikiContext context) throws XWikiException, IOException
{
addToZip(zos, true, context);
}
/**
* Serialize the document to an XML string. You should prefer
* {@link #toXML(OutputStream, boolean, boolean, boolean, boolean, XWikiContext)} or
* {@link #toXML(com.xpn.xwiki.internal.xml.XMLWriter, boolean, boolean, boolean, boolean, XWikiContext)} when
* possible to reduce memory load.
*
* @param bWithObjects include XObjects
* @param bWithRendering include the rendered content
* @param bWithAttachmentContent include attachments content
* @param bWithVersions include archived versions
* @param context current XWikiContext
* @return a string containing an XML representation of the document
* @throws XWikiException when an errors occurs during wiki operations
*/
public String toXML(boolean bWithObjects, boolean bWithRendering, boolean bWithAttachmentContent,
boolean bWithVersions, XWikiContext context) throws XWikiException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
toXML(baos, bWithObjects, bWithRendering, bWithAttachmentContent, bWithVersions, context);
return baos.toString(context.getWiki().getEncoding());
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
/**
* Serialize the document to an XML {@link DOMDocument}. All XObject are included. Rendered content, attachments and
* archived version are excluded. You should prefer toXML(OutputStream, true, false, false, false, XWikiContext)} or
* toXML(com.xpn.xwiki.util.XMLWriter, true, false, false, false, XWikiContext) when possible to reduce memory load.
*
* @param context current XWikiContext
* @return a {@link DOMDocument} containing the serialized document.
* @throws XWikiException when an errors occurs during wiki operations
*/
public Document toXMLDocument(XWikiContext context) throws XWikiException
{
return toXMLDocument(true, false, false, false, context);
}
/**
* Serialize the document to an XML {@link DOMDocument}. You should prefer
* {@link #toXML(OutputStream, boolean, boolean, boolean, boolean, XWikiContext)} or
* {@link #toXML(com.xpn.xwiki.internal.xml.XMLWriter, boolean, boolean, boolean, boolean, XWikiContext)} when
* possible to reduce memory load.
*
* @param bWithObjects include XObjects
* @param bWithRendering include the rendered content
* @param bWithAttachmentContent include attachments content
* @param bWithVersions include archived versions
* @param context current XWikiContext
* @return a {@link DOMDocument} containing the serialized document.
* @throws XWikiException when an errors occurs during wiki operations
*/
public Document toXMLDocument(boolean bWithObjects, boolean bWithRendering, boolean bWithAttachmentContent,
boolean bWithVersions, XWikiContext context) throws XWikiException
{
Document doc = new DOMDocument();
DOMXMLWriter wr = new DOMXMLWriter(doc, new OutputFormat("", true, context.getWiki().getEncoding()));
try {
toXML(wr, bWithObjects, bWithRendering, bWithAttachmentContent, bWithVersions, context);
return doc;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Serialize the document to a {@link com.xpn.xwiki.internal.xml.XMLWriter}.
*
* @param bWithObjects include XObjects
* @param bWithRendering include the rendered content
* @param bWithAttachmentContent include attachments content
* @param bWithVersions include archived versions
* @param context current XWikiContext
* @throws XWikiException when an errors occurs during wiki operations
* @throws IOException when an errors occurs during streaming operations
* @since 2.3M2
*/
public void toXML(XMLWriter wr, boolean bWithObjects, boolean bWithRendering, boolean bWithAttachmentContent,
boolean bWithVersions, XWikiContext context) throws XWikiException, IOException
{
// IMPORTANT: we don't use SAX apis here because the specified XMLWriter could be a DOMXMLWriter for retro
// compatibility reasons
Element docel = new DOMElement("xwikidoc");
wr.writeOpen(docel);
Element el = new DOMElement("web");
el.addText(getDocumentReference().getLastSpaceReference().getName());
wr.write(el);
el = new DOMElement("name");
el.addText(getDocumentReference().getName());
wr.write(el);
el = new DOMElement("language");
el.addText(getLanguage());
wr.write(el);
el = new DOMElement("defaultLanguage");
el.addText(getDefaultLanguage());
wr.write(el);
el = new DOMElement("translation");
el.addText("" + getTranslation());
wr.write(el);
el = new DOMElement("parent");
if (getRelativeParentReference() == null) {
// No parent have been specified
el.addText("");
} else {
el.addText(this.defaultEntityReferenceSerializer.serialize(getRelativeParentReference()));
}
wr.write(el);
el = new DOMElement("creator");
el.addText(getCreator());
wr.write(el);
el = new DOMElement("author");
el.addText(getAuthor());
wr.write(el);
el = new DOMElement("customClass");
el.addText(getCustomClass());
wr.write(el);
el = new DOMElement("contentAuthor");
el.addText(getContentAuthor());
wr.write(el);
long d = getCreationDate().getTime();
el = new DOMElement("creationDate");
el.addText("" + d);
wr.write(el);
d = getDate().getTime();
el = new DOMElement("date");
el.addText("" + d);
wr.write(el);
d = getContentUpdateDate().getTime();
el = new DOMElement("contentUpdateDate");
el.addText("" + d);
wr.write(el);
el = new DOMElement("version");
el.addText(getVersion());
wr.write(el);
el = new DOMElement("title");
el.addText(getTitle());
wr.write(el);
el = new DOMElement("template");
if (getTemplateDocumentReference() == null) {
// No template doc have been specified
el.addText("");
} else {
el.addText(this.localEntityReferenceSerializer.serialize(getTemplateDocumentReference()));
}
wr.write(el);
el = new DOMElement("defaultTemplate");
el.addText(getDefaultTemplate());
wr.write(el);
el = new DOMElement("validationScript");
el.addText(getValidationScript());
wr.write(el);
el = new DOMElement("comment");
el.addText(getComment());
wr.write(el);
el = new DOMElement("minorEdit");
el.addText(String.valueOf(isMinorEdit()));
wr.write(el);
el = new DOMElement("syntaxId");
el.addText(getSyntaxId());
wr.write(el);
el = new DOMElement("hidden");
el.addText(String.valueOf(isHidden()));
wr.write(el);
for (XWikiAttachment attach : getAttachmentList()) {
attach.toXML(wr, bWithAttachmentContent, bWithVersions, context);
}
if (bWithObjects) {
// Add Class
BaseClass bclass = getXClass();
if (bclass.getFieldList().size() > 0) {
// If the class has fields, add class definition and field information to XML
wr.write(bclass.toXML(null));
}
// Add Objects (THEIR ORDER IS MOLDED IN STONE!)
for (List<BaseObject> objects : getXObjects().values()) {
for (BaseObject obj : objects) {
if (obj != null) {
BaseClass objclass;
if (StringUtils.equals(getFullName(), obj.getClassName())) {
objclass = bclass;
} else {
objclass = obj.getXClass(context);
}
wr.write(obj.toXML(objclass));
}
}
}
}
// Add Content
el = new DOMElement("content");
// Filter filter = new CharacterFilter();
// String newcontent = filter.process(getContent());
// String newcontent = encodedXMLStringAsUTF8(getContent());
String newcontent = this.content;
el.addText(newcontent);
wr.write(el);
if (bWithRendering) {
el = new DOMElement("renderedcontent");
try {
el.addText(getRenderedContent(context));
} catch (XWikiException e) {
el.addText("Exception with rendering content: " + e.getFullMessage());
}
wr.write(el);
}
if (bWithVersions) {
el = new DOMElement("versions");
try {
el.addText(getDocumentArchive(context).getArchive(context));
wr.write(el);
} catch (XWikiException e) {
LOG.error("Document [" + this.defaultEntityReferenceSerializer.serialize(getDocumentReference())
+ "] has malformed history");
}
}
}
/**
* Serialize the document to an OutputStream.
*
* @param bWithObjects include XObjects
* @param bWithRendering include the rendered content
* @param bWithAttachmentContent include attachments content
* @param bWithVersions include archived versions
* @param context current XWikiContext
* @throws XWikiException when an errors occurs during wiki operations
* @throws IOException when an errors occurs during streaming operations
* @since 2.3M2
*/
public void toXML(OutputStream out, boolean bWithObjects, boolean bWithRendering, boolean bWithAttachmentContent,
boolean bWithVersions, XWikiContext context) throws XWikiException, IOException
{
XMLWriter wr = new XMLWriter(out, new OutputFormat("", true, context.getWiki().getEncoding()));
Document doc = new DOMDocument();
wr.writeDocumentStart(doc);
toXML(wr, bWithObjects, bWithRendering, bWithAttachmentContent, bWithVersions, context);
wr.writeDocumentEnd(doc);
}
protected String encodedXMLStringAsUTF8(String xmlString)
{
if (xmlString == null) {
return "";
}
int length = xmlString.length();
char character;
StringBuffer result = new StringBuffer();
for (int i = 0; i < length; i++) {
character = xmlString.charAt(i);
switch (character) {
case '&':
result.append("&");
break;
case '"':
result.append(""");
break;
case '<':
result.append("<");
break;
case '>':
result.append(">");
break;
case '\n':
result.append("\n");
break;
case '\r':
result.append("\r");
break;
case '\t':
result.append("\t");
break;
default:
if (character < 0x20) {
} else if (character > 0x7F) {
result.append("&
result.append(Integer.toHexString(character).toUpperCase());
result.append(";");
} else {
result.append(character);
}
break;
}
}
return result.toString();
}
protected String getElement(Element docel, String name)
{
Element el = docel.element(name);
if (el == null) {
return "";
} else {
return el.getText();
}
}
public void fromXML(String xml) throws XWikiException
{
fromXML(xml, false);
}
public void fromXML(InputStream is) throws XWikiException
{
fromXML(is, false);
}
public void fromXML(String xml, boolean withArchive) throws XWikiException
{
SAXReader reader = new SAXReader();
Document domdoc;
try {
StringReader in = new StringReader(xml);
domdoc = reader.read(in);
} catch (DocumentException e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_DOC, XWikiException.ERROR_DOC_XML_PARSING,
"Error parsing xml", e, null);
}
fromXML(domdoc, withArchive);
}
public void fromXML(InputStream in, boolean withArchive) throws XWikiException
{
SAXReader reader = new SAXReader();
Document domdoc;
try {
domdoc = reader.read(in);
} catch (DocumentException e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_DOC, XWikiException.ERROR_DOC_XML_PARSING,
"Error parsing xml", e, null);
}
fromXML(domdoc, withArchive);
}
public void fromXML(Document domdoc, boolean withArchive) throws XWikiException
{
Element docel = domdoc.getRootElement();
// If, for some reason, the document name or space are not set in the XML input, we still ensure that the
// constructed XWikiDocument object has a valid name or space (by using current document values if they are
// missing). This is important since document name, space and wiki must always be set in a XWikiDocument
// instance.
String name = getElement(docel, "name");
String space = getElement(docel, "web");
if (StringUtils.isEmpty(name) || StringUtils.isEmpty(space)) {
throw new XWikiException(XWikiException.MODULE_XWIKI_DOC, XWikiException.ERROR_XWIKI_UNKNOWN,
"Invalid XML: \"name\" and \"web\" cannot be empty");
}
EntityReference reference =
new EntityReference(name, EntityType.DOCUMENT, new EntityReference(space, EntityType.SPACE));
reference = this.currentReferenceDocumentReferenceResolver.resolve(reference);
setDocumentReference(new DocumentReference(reference));
String parent = getElement(docel, "parent");
if (StringUtils.isNotEmpty(parent)) {
setParentReference(this.currentMixedDocumentReferenceResolver.resolve(parent));
}
setCreator(getElement(docel, "creator"));
setAuthor(getElement(docel, "author"));
setCustomClass(getElement(docel, "customClass"));
setContentAuthor(getElement(docel, "contentAuthor"));
if (docel.element("version") != null) {
setVersion(getElement(docel, "version"));
}
setContent(getElement(docel, "content"));
setLanguage(getElement(docel, "language"));
setDefaultLanguage(getElement(docel, "defaultLanguage"));
setTitle(getElement(docel, "title"));
setDefaultTemplate(getElement(docel, "defaultTemplate"));
setValidationScript(getElement(docel, "validationScript"));
setComment(getElement(docel, "comment"));
String minorEdit = getElement(docel, "minorEdit");
setMinorEdit(Boolean.valueOf(minorEdit).booleanValue());
String hidden = getElement(docel, "hidden");
setHidden(Boolean.valueOf(hidden).booleanValue());
String strans = getElement(docel, "translation");
if ((strans == null) || strans.equals("")) {
setTranslation(0);
} else {
setTranslation(Integer.parseInt(strans));
}
String archive = getElement(docel, "versions");
if (withArchive && archive != null && archive.length() > 0) {
setDocumentArchive(archive);
}
String sdate = getElement(docel, "date");
if (!sdate.equals("")) {
Date date = new Date(Long.parseLong(sdate));
setDate(date);
}
String contentUpdateDateString = getElement(docel, "contentUpdateDate");
if (!StringUtils.isEmpty(contentUpdateDateString)) {
Date contentUpdateDate = new Date(Long.parseLong(contentUpdateDateString));
setContentUpdateDate(contentUpdateDate);
}
String scdate = getElement(docel, "creationDate");
if (!scdate.equals("")) {
Date cdate = new Date(Long.parseLong(scdate));
setCreationDate(cdate);
}
String syntaxId = getElement(docel, "syntaxId");
if ((syntaxId == null) || (syntaxId.length() == 0)) {
// Documents that don't have syntax ids are considered old documents and thus in
// XWiki Syntax 1.0 since newer documents always have syntax ids.
setSyntax(Syntax.XWIKI_1_0);
} else {
setSyntaxId(syntaxId);
}
List<Element> atels = docel.elements("attachment");
for (Element atel : atels) {
XWikiAttachment attach = new XWikiAttachment();
attach.setDoc(this);
attach.fromXML(atel);
getAttachmentList().add(attach);
}
Element cel = docel.element("class");
BaseClass bclass = new BaseClass();
if (cel != null) {
bclass.fromXML(cel);
setXClass(bclass);
}
List<Element> objels = docel.elements("object");
for (Element objel : objels) {
BaseObject bobject = new BaseObject();
bobject.fromXML(objel);
setXObject(bobject.getNumber(), bobject);
}
// We have been reading from XML so the document does not need a new version when saved
setMetaDataDirty(false);
setContentDirty(false);
// Note: We don't set the original document as that is not stored in the XML, and it doesn't make much sense to
// have an original document for a de-serialized object.
}
/**
* Check if provided xml document is a wiki document.
*
* @param domdoc the xml document.
* @return true if provided xml document is a wiki document.
*/
public static boolean containsXMLWikiDocument(Document domdoc)
{
return domdoc.getRootElement().getName().equals("xwikidoc");
}
public void setAttachmentList(List<XWikiAttachment> list)
{
this.attachmentList = list;
}
public List<XWikiAttachment> getAttachmentList()
{
return this.attachmentList;
}
public void saveAllAttachments(XWikiContext context) throws XWikiException
{
for (XWikiAttachment attachment : this.attachmentList) {
saveAttachmentContent(attachment, context);
}
}
public void saveAllAttachments(boolean updateParent, boolean transaction, XWikiContext context)
throws XWikiException
{
for (XWikiAttachment attachment : this.attachmentList) {
saveAttachmentContent(attachment, updateParent, transaction, context);
}
}
public void saveAttachmentsContent(List<XWikiAttachment> attachments, XWikiContext context) throws XWikiException
{
String database = context.getDatabase();
try {
// We might need to switch database to get the translated content
if (getDatabase() != null) {
context.setDatabase(getDatabase());
}
context.getWiki().getAttachmentStore().saveAttachmentsContent(attachments, this, true, context, true);
} catch (OutOfMemoryError e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE,
"Out Of Memory Exception");
} finally {
if (database != null) {
context.setDatabase(database);
}
}
}
public void saveAttachmentContent(XWikiAttachment attachment, XWikiContext context) throws XWikiException
{
saveAttachmentContent(attachment, true, true, context);
}
public void saveAttachmentContent(XWikiAttachment attachment, boolean bParentUpdate, boolean bTransaction,
XWikiContext context) throws XWikiException
{
String database = context.getDatabase();
try {
// We might need to switch database to
// get the translated content
if (getDatabase() != null) {
context.setDatabase(getDatabase());
}
// We need to make sure there is a version upgrade
setMetaDataDirty(true);
context.getWiki().getAttachmentStore()
.saveAttachmentContent(attachment, bParentUpdate, context, bTransaction);
} catch (OutOfMemoryError e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE,
"Out Of Memory Exception");
} finally {
if (database != null) {
context.setDatabase(database);
}
}
}
public void loadAttachmentContent(XWikiAttachment attachment, XWikiContext context) throws XWikiException
{
String database = context.getDatabase();
try {
// We might need to switch database to
// get the translated content
if (getDatabase() != null) {
context.setDatabase(getDatabase());
}
context.getWiki().getAttachmentStore().loadAttachmentContent(attachment, context, true);
} finally {
if (database != null) {
context.setDatabase(database);
}
}
}
public void deleteAttachment(XWikiAttachment attachment, XWikiContext context) throws XWikiException
{
deleteAttachment(attachment, true, context);
}
public void deleteAttachment(XWikiAttachment attachment, boolean toRecycleBin, XWikiContext context)
throws XWikiException
{
String database = context.getDatabase();
try {
// We might need to switch database to
// get the translated content
if (getDatabase() != null) {
context.setDatabase(getDatabase());
}
try {
// We need to make sure there is a version upgrade
setMetaDataDirty(true);
if (toRecycleBin && context.getWiki().hasAttachmentRecycleBin(context)) {
context.getWiki().getAttachmentRecycleBinStore()
.saveToRecycleBin(attachment, context.getUser(), new Date(), context, true);
}
context.getWiki().getAttachmentStore().deleteXWikiAttachment(attachment, context, true);
} catch (java.lang.OutOfMemoryError e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_APP,
XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE, "Out Of Memory Exception");
}
} finally {
if (database != null) {
context.setDatabase(database);
}
}
}
/**
* Get the wiki document references pointing to this document.
* <p>
* Theses links are stored to the database when documents are saved. You can use "backlinks" in XWikiPreferences or
* "xwiki.backlinks" in xwiki.cfg file to enable links storage in the database.
*
* @param context the XWiki context.
* @return the found wiki document references
* @throws XWikiException error when getting pages names from database.
* @since 2.2M2
*/
public List<DocumentReference> getBackLinkedReferences(XWikiContext context) throws XWikiException
{
return getStore(context).loadBacklinks(getDocumentReference(), true, context);
}
/**
* @deprecated since 2.2M2 use {@link #getBackLinkedReferences(XWikiContext)}
*/
@Deprecated
public List<String> getBackLinkedPages(XWikiContext context) throws XWikiException
{
return getStore(context).loadBacklinks(getFullName(), context, true);
}
/**
* Get a list of unique links from this document to others documents.
* <p>
* <ul>
* <li>1.0 content: get the unique links associated to document from database. This is stored when the document is
* saved. You can use "backlinks" in XWikiPreferences or "xwiki.backlinks" in xwiki.cfg file to enable links storage
* in the database.</li>
* <li>Other content: call {@link #getUniqueLinkedPages(XWikiContext)} and generate the List</li>.
* </ul>
*
* @param context the XWiki context
* @return the found wiki links.
* @throws XWikiException error when getting links from database when 1.0 content.
* @since 1.9M2
*/
public Set<XWikiLink> getUniqueWikiLinkedPages(XWikiContext context) throws XWikiException
{
Set<XWikiLink> links;
if (is10Syntax()) {
links = new LinkedHashSet<XWikiLink>(getStore(context).loadLinks(getId(), context, true));
} else {
Set<String> linkedPages = getUniqueLinkedPages(context);
links = new LinkedHashSet<XWikiLink>(linkedPages.size());
for (String linkedPage : linkedPages) {
XWikiLink wikiLink = new XWikiLink();
wikiLink.setDocId(getId());
wikiLink.setFullName(getFullName());
wikiLink.setLink(linkedPage);
links.add(wikiLink);
}
}
return links;
}
/**
* Extract all the unique static (i.e. not generated by macros) wiki links (pointing to wiki page) from this 1.0
* document's content to others documents.
*
* @param context the XWiki context.
* @return the document names for linked pages, if null an error append.
* @since 1.9M2
*/
private Set<String> getUniqueLinkedPages10(XWikiContext context)
{
Set<String> pageNames;
try {
List<String> list = context.getUtil().getUniqueMatches(getContent(), "\\[(.*?)\\]", 1);
pageNames = new HashSet<String>(list.size());
DocumentReference currentDocumentReference = getDocumentReference();
for (String name : list) {
int i1 = name.indexOf(">");
if (i1 != -1) {
name = name.substring(i1 + 1);
}
i1 = name.indexOf(">");
if (i1 != -1) {
name = name.substring(i1 + 4);
}
i1 = name.indexOf("
if (i1 != -1) {
name = name.substring(0, i1);
}
i1 = name.indexOf("?");
if (i1 != -1) {
name = name.substring(0, i1);
}
// Let's get rid of anything that's not a real link
if (name.trim().equals("") || (name.indexOf("$") != -1) || (name.indexOf(":
|| (name.indexOf("\"") != -1) || (name.indexOf("\'") != -1) || (name.indexOf("..") != -1)
|| (name.indexOf(":") != -1) || (name.indexOf("=") != -1)) {
continue;
}
// generate the link
String newname = StringUtils.replace(Util.noaccents(name), " ", "");
// If it is a local link let's add the space
if (newname.indexOf(".") == -1) {
newname = getSpace() + "." + name;
}
if (context.getWiki().exists(newname, context)) {
name = newname;
} else {
// If it is a local link let's add the space
if (name.indexOf(".") == -1) {
name = getSpace() + "." + name;
}
}
// If the reference is empty, the link is an autolink
if (!StringUtils.isEmpty(name)) {
// The reference may not have the space or even document specified (in case of an empty
// string)
// Thus we need to find the fully qualified document name
DocumentReference documentReference = this.currentDocumentReferenceResolver.resolve(name);
// Verify that the link is not an autolink (i.e. a link to the current document)
if (!documentReference.equals(currentDocumentReference)) {
pageNames.add(this.compactEntityReferenceSerializer.serialize(documentReference));
}
}
}
return pageNames;
} catch (Exception e) {
// This should never happen
LOG.error("Failed to get linked documents", e);
return null;
}
}
/**
* Extract all the unique static (i.e. not generated by macros) wiki links (pointing to wiki page) from this
* document's content to others documents.
*
* @param context the XWiki context.
* @return the document names for linked pages, if null an error append.
* @since 1.9M2
*/
public Set<String> getUniqueLinkedPages(XWikiContext context)
{
Set<String> pageNames;
XWikiDocument contextDoc = context.getDoc();
String contextWiki = context.getDatabase();
try {
// Make sure the right document is used as context document
context.setDoc(this);
// Make sure the right wiki is used as context document
context.setDatabase(getDatabase());
if (is10Syntax()) {
pageNames = getUniqueLinkedPages10(context);
} else {
XDOM dom = getXDOM();
List<LinkBlock> linkBlocks = dom.getChildrenByType(LinkBlock.class, true);
pageNames = new LinkedHashSet<String>(linkBlocks.size());
DocumentReference currentDocumentReference = getDocumentReference();
for (LinkBlock linkBlock : linkBlocks) {
ResourceReference reference = linkBlock.getReference();
if (reference.getType().equals(ResourceType.DOCUMENT)) {
// If the reference is empty, the link is an autolink
if (!StringUtils.isEmpty(reference.getReference())
|| (StringUtils.isEmpty(reference.getParameter(DocumentResourceReference.ANCHOR)) && StringUtils
.isEmpty(reference.getParameter(DocumentResourceReference.QUERY_STRING)))) {
// The reference may not have the space or even document specified (in case of an empty
// string)
// Thus we need to find the fully qualified document name
DocumentReference documentReference =
this.currentDocumentReferenceResolver.resolve(reference.getReference());
// Verify that the link is not an autolink (i.e. a link to the current document)
if (!documentReference.equals(currentDocumentReference)) {
// Since this method is used for saving backlinks and since backlinks must be
// saved with the space and page name but without the wiki part, we remove the wiki
// part before serializing.
// This is a bit of a hack since the default serializer should theoretically fail
// if it's passed an invalid reference.
pageNames.add(this.compactWikiEntityReferenceSerializer.serialize(documentReference));
}
}
}
}
}
} finally {
context.setDoc(contextDoc);
context.setDatabase(contextWiki);
}
return pageNames;
}
/**
* Returns a list of references of all documents which list this document as their parent
* {@link #getChildren(int, int, com.xpn.xwiki.XWikiContext)}
*
* @since 2.2M2
*/
public List<DocumentReference> getChildrenReferences(XWikiContext context) throws XWikiException
{
return getChildrenReferences(0, 0, context);
}
/**
* @deprecated since 2.2M2 use {@link #getChildrenReferences(XWikiContext)}
*/
@Deprecated
public List<String> getChildren(XWikiContext context) throws XWikiException
{
return getChildren(0, 0, context);
}
/**
* Returns a list of references of all documents which list this document as their parent
*
* @param nb The number of results to return.
* @param start The number of results to skip before we begin returning results.
* @param context The {@link com.xpn.xwiki.XWikiContext context}.
* @return the list of document references
* @throws XWikiException If there's an error querying the database.
* @since 2.2M2
*/
public List<DocumentReference> getChildrenReferences(int nb, int start, XWikiContext context) throws XWikiException
{
// Use cases:
// - the parent document reference saved in the database matches the reference of this document, in its fully
// serialized form (eg "wiki:space.page"). Note that this is normally not required since the wiki part
// isn't saved in the database when it matches the current wiki.
// - the parent document reference saved in the database matches the reference of this document, in its
// serialized form without the wiki part (eg "space.page"). The reason we don't need to specify the wiki
// part is because document parents saved in the database don't have the wiki part specified when it matches
// the current wiki.
// - the parent document reference saved in the database matches the page name part of this document's
// reference (eg "page") and the parent document's space is the same as this document's space.
List<String> whereParams =
Arrays.asList(this.defaultEntityReferenceSerializer.serialize(getDocumentReference()),
this.localEntityReferenceSerializer.serialize(getDocumentReference()),
getDocumentReference().getName(), getDocumentReference().getLastSpaceReference().getName());
String whereStatement = "doc.parent=? or doc.parent=? or (doc.parent=? and doc.space=?)";
return context.getWiki().getStore().searchDocumentReferences(whereStatement, nb, start, whereParams, context);
}
/**
* @deprecated since 2.2M2 use {@link #getChildrenReferences(XWikiContext)}
*/
@Deprecated
public List<String> getChildren(int nb, int start, XWikiContext context) throws XWikiException
{
List<String> childrenNames = new ArrayList<String>();
for (DocumentReference reference : getChildrenReferences(nb, start, context)) {
childrenNames.add(this.localEntityReferenceSerializer.serialize(reference));
}
return childrenNames;
}
/**
* @since 2.2M2
*/
public void renameProperties(DocumentReference classReference, Map<String, String> fieldsToRename)
{
List<BaseObject> objects = getXObjects(classReference);
if (objects == null) {
return;
}
for (BaseObject bobject : objects) {
if (bobject == null) {
continue;
}
for (Map.Entry<String, String> entry : fieldsToRename.entrySet()) {
String origname = entry.getKey();
String newname = entry.getValue();
BaseProperty origprop = (BaseProperty) bobject.safeget(origname);
if (origprop != null) {
BaseProperty prop = (BaseProperty) origprop.clone();
bobject.removeField(origname);
prop.setName(newname);
bobject.addField(newname, prop);
}
}
}
setContentDirty(true);
}
/**
* @deprecated since 2.2M2 use {@link #renameProperties(DocumentReference, Map)} instead
*/
@Deprecated
public void renameProperties(String className, Map<String, String> fieldsToRename)
{
renameProperties(resolveClassReference(className), fieldsToRename);
}
/**
* @since 2.2M1
*/
public void addXObjectToRemove(BaseObject object)
{
getXObjectsToRemove().add(object);
setContentDirty(true);
}
/**
* @deprecated since 2.2M2 use {@link #addXObjectToRemove(BaseObject)} )} instead
*/
@Deprecated
public void addObjectsToRemove(BaseObject object)
{
addXObjectToRemove(object);
}
/**
* @since 2.2M2
*/
public List<BaseObject> getXObjectsToRemove()
{
return this.xObjectsToRemove;
}
/**
* @deprecated since 2.2M2 use {@link #getObjectsToRemove()} instead
*/
@Deprecated
public ArrayList<BaseObject> getObjectsToRemove()
{
return (ArrayList<BaseObject>) getXObjectsToRemove();
}
/**
* @since 2.2M1
*/
public void setXObjectsToRemove(List<BaseObject> objectsToRemove)
{
this.xObjectsToRemove = objectsToRemove;
setContentDirty(true);
}
/**
* @deprecated since 2.2M2 use {@link #setXObjectsToRemove(List)} instead
*/
@Deprecated
public void setObjectsToRemove(ArrayList<BaseObject> objectsToRemove)
{
setXObjectsToRemove(objectsToRemove);
}
public List<String> getIncludedPages(XWikiContext context)
{
if (is10Syntax()) {
return getIncludedPagesForXWiki10Syntax(getContent(), context);
} else {
// Find all include macros listed on the page
XDOM dom = getXDOM();
List<String> result = new ArrayList<String>();
for (MacroBlock macroBlock : dom.getChildrenByType(MacroBlock.class, true)) {
// - Add each document pointed to by the include macro
// - Also add all the included pages found in the velocity macro when using the deprecated #include*
// macros
// This should be removed when we fully drop support for the XWiki Syntax 1.0 but for now we want to
// play
// nice with people migrating from 1.0 to 2.0 syntax
if (macroBlock.getId().equalsIgnoreCase("include")) {
String documentName = macroBlock.getParameters().get("document");
if (documentName.indexOf(".") == -1) {
documentName = getSpace() + "." + documentName;
}
result.add(documentName);
} else if (macroBlock.getId().equalsIgnoreCase("velocity")
&& !StringUtils.isEmpty(macroBlock.getContent())) {
// Try to find matching content inside each velocity macro
result.addAll(getIncludedPagesForXWiki10Syntax(macroBlock.getContent(), context));
}
}
return result;
}
}
private List<String> getIncludedPagesForXWiki10Syntax(String content, XWikiContext context)
{
try {
String pattern = "#include(Topic|InContext|Form|Macros|parseGroovyFromPage)\\([\"'](.*?)[\"']\\)";
List<String> list = context.getUtil().getUniqueMatches(content, pattern, 2);
for (int i = 0; i < list.size(); i++) {
String name = list.get(i);
if (name.indexOf(".") == -1) {
list.set(i, getSpace() + "." + name);
}
}
return list;
} catch (Exception e) {
LOG.error("Failed to extract include target from provided content [" + content + "]", e);
return null;
}
}
public List<String> getIncludedMacros(XWikiContext context)
{
return context.getWiki().getIncludedMacros(getSpace(), getContent(), context);
}
public String displayRendered(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context)
throws XWikiException
{
String result = pclass.displayView(pclass.getName(), prefix, object, context);
return getRenderedContent(result, XWIKI10_SYNTAXID, context);
}
public String displayView(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context)
{
return (pclass == null) ? "" : pclass.displayView(pclass.getName(), prefix, object, context);
}
public String displayEdit(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context)
{
return (pclass == null) ? "" : pclass.displayEdit(pclass.getName(), prefix, object, context);
}
public String displayHidden(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context)
{
return (pclass == null) ? "" : pclass.displayHidden(pclass.getName(), prefix, object, context);
}
public String displaySearch(PropertyClass pclass, String prefix, XWikiCriteria criteria, XWikiContext context)
{
return (pclass == null) ? "" : pclass.displaySearch(pclass.getName(), prefix, criteria, context);
}
public XWikiAttachment getAttachment(String filename)
{
for (XWikiAttachment attach : getAttachmentList()) {
if (attach.getFilename().equals(filename)) {
return attach;
}
}
for (XWikiAttachment attach : getAttachmentList()) {
if (attach.getFilename().startsWith(filename + ".")) {
return attach;
}
}
return null;
}
public XWikiAttachment addAttachment(String fileName, InputStream iStream, XWikiContext context)
throws XWikiException, IOException
{
ByteArrayOutputStream bAOut = new ByteArrayOutputStream();
IOUtils.copy(iStream, bAOut);
return addAttachment(fileName, bAOut.toByteArray(), context);
}
public XWikiAttachment addAttachment(String fileName, byte[] data, XWikiContext context) throws XWikiException
{
int i = fileName.indexOf("\\");
if (i == -1) {
i = fileName.indexOf("/");
}
String filename = fileName.substring(i + 1);
// TODO : avoid name clearing when encoding problems will be solved
filename = context.getWiki().clearName(filename, false, true, context);
XWikiAttachment attachment = getAttachment(filename);
if (attachment == null) {
attachment = new XWikiAttachment();
// TODO: Review this code and understand why it's needed.
// Add the attachment in the current doc
getAttachmentList().add(attachment);
}
attachment.setContent(data);
attachment.setFilename(filename);
attachment.setAuthor(context.getUser());
// Add the attachment to the document
attachment.setDoc(this);
return attachment;
}
public BaseObject getFirstObject(String fieldname)
{
// Keeping this function with context null for compatibility reasons.
// It should not be used, since it would miss properties which are only defined in the class
// and not present in the object because the object was not updated
return getFirstObject(fieldname, null);
}
public BaseObject getFirstObject(String fieldname, XWikiContext context)
{
Collection<List<BaseObject>> objectscoll = getXObjects().values();
if (objectscoll == null) {
return null;
}
for (List<BaseObject> objects : objectscoll) {
for (BaseObject obj : objects) {
if (obj != null) {
BaseClass bclass = obj.getXClass(context);
if (bclass != null) {
Set<String> set = bclass.getPropertyList();
if ((set != null) && set.contains(fieldname)) {
return obj;
}
}
Set<String> set = obj.getPropertyList();
if ((set != null) && set.contains(fieldname)) {
return obj;
}
}
}
}
return null;
}
/**
* @since 2.2.3
*/
public void setProperty(EntityReference classReference, String fieldName, BaseProperty value)
{
BaseObject bobject = prepareXObject(classReference);
bobject.safeput(fieldName, value);
}
/**
* @deprecated since 2.2M2 use {@link #setProperty(EntityReference, String, BaseProperty)} instead
*/
@Deprecated
public void setProperty(String className, String fieldName, BaseProperty value)
{
setProperty(this.xClassEntityReferenceResolver.resolve(className, EntityType.DOCUMENT, getDocumentReference()),
fieldName, value);
}
/**
* @since 2.2M2
*/
public int getIntValue(DocumentReference classReference, String fieldName)
{
BaseObject obj = getXObject(classReference, 0);
if (obj == null) {
return 0;
}
return obj.getIntValue(fieldName);
}
/**
* @deprecated since 2.2M2 use {@link #getIntValue(DocumentReference, String)} instead
*/
@Deprecated
public int getIntValue(String className, String fieldName)
{
return getIntValue(resolveClassReference(className), fieldName);
}
/**
* @since 2.2M2
*/
public long getLongValue(DocumentReference classReference, String fieldName)
{
BaseObject obj = getXObject(classReference, 0);
if (obj == null) {
return 0;
}
return obj.getLongValue(fieldName);
}
/**
* @deprecated since 2.2M2 use {@link #getLongValue(DocumentReference, String)} instead
*/
@Deprecated
public long getLongValue(String className, String fieldName)
{
return getLongValue(resolveClassReference(className), fieldName);
}
/**
* @since 2.2M2
*/
public String getStringValue(DocumentReference classReference, String fieldName)
{
BaseObject obj = getXObject(classReference);
if (obj == null) {
return "";
}
String result = obj.getStringValue(fieldName);
if (result.equals(" ")) {
return "";
} else {
return result;
}
}
/**
* @deprecated since 2.2M2 use {@link #getStringValue(DocumentReference, String)} instead
*/
@Deprecated
public String getStringValue(String className, String fieldName)
{
return getStringValue(resolveClassReference(className), fieldName);
}
public int getIntValue(String fieldName)
{
BaseObject object = getFirstObject(fieldName, null);
if (object == null) {
return 0;
} else {
return object.getIntValue(fieldName);
}
}
public long getLongValue(String fieldName)
{
BaseObject object = getFirstObject(fieldName, null);
if (object == null) {
return 0;
} else {
return object.getLongValue(fieldName);
}
}
public String getStringValue(String fieldName)
{
BaseObject object = getFirstObject(fieldName, null);
if (object == null) {
return "";
}
String result = object.getStringValue(fieldName);
if (result.equals(" ")) {
return "";
} else {
return result;
}
}
/**
* @since 2.2.3
*/
public void setStringValue(EntityReference classReference, String fieldName, String value)
{
BaseObject bobject = prepareXObject(classReference);
bobject.setStringValue(fieldName, value);
}
/**
* @deprecated since 2.2M2 use {@link #setStringValue(EntityReference, String, String)} instead
*/
@Deprecated
public void setStringValue(String className, String fieldName, String value)
{
setStringValue(
this.xClassEntityReferenceResolver.resolve(className, EntityType.DOCUMENT, getDocumentReference()),
fieldName, value);
}
/**
* @since 2.2M2
*/
public List getListValue(DocumentReference classReference, String fieldName)
{
BaseObject obj = getXObject(classReference);
if (obj == null) {
return new ArrayList();
}
return obj.getListValue(fieldName);
}
/**
* @deprecated since 2.2M2 use {@link #getListValue(DocumentReference, String)} instead
*/
@Deprecated
public List getListValue(String className, String fieldName)
{
return getListValue(resolveClassReference(className), fieldName);
}
public List getListValue(String fieldName)
{
BaseObject object = getFirstObject(fieldName, null);
if (object == null) {
return new ArrayList();
}
return object.getListValue(fieldName);
}
/**
* @since 2.2.3
*/
public void setStringListValue(EntityReference classReference, String fieldName, List value)
{
BaseObject bobject = prepareXObject(classReference);
bobject.setStringListValue(fieldName, value);
}
/**
* @deprecated since 2.2M2 use {@link #setStringListValue(EntityReference, String, List)} instead
*/
@Deprecated
public void setStringListValue(String className, String fieldName, List value)
{
setStringListValue(
this.xClassEntityReferenceResolver.resolve(className, EntityType.DOCUMENT, getDocumentReference()),
fieldName, value);
}
/**
* @since 2.2.3
*/
public void setDBStringListValue(EntityReference classReference, String fieldName, List value)
{
BaseObject bobject = prepareXObject(classReference);
bobject.setDBStringListValue(fieldName, value);
}
/**
* @deprecated since 2.2M2 use {@link #setDBStringListValue(EntityReference, String, List)} instead
*/
@Deprecated
public void setDBStringListValue(String className, String fieldName, List value)
{
setDBStringListValue(
this.xClassEntityReferenceResolver.resolve(className, EntityType.DOCUMENT, getDocumentReference()),
fieldName, value);
}
/**
* @since 2.2.3
*/
public void setLargeStringValue(EntityReference classReference, String fieldName, String value)
{
BaseObject bobject = prepareXObject(classReference);
bobject.setLargeStringValue(fieldName, value);
}
/**
* @deprecated since 2.2M2 use {@link #setLargeStringValue(EntityReference, String, String)} instead
*/
@Deprecated
public void setLargeStringValue(String className, String fieldName, String value)
{
setLargeStringValue(
this.xClassEntityReferenceResolver.resolve(className, EntityType.DOCUMENT, getDocumentReference()),
fieldName, value);
}
/**
* @since 2.2.3
*/
public void setIntValue(EntityReference classReference, String fieldName, int value)
{
BaseObject bobject = prepareXObject(classReference);
bobject.setIntValue(fieldName, value);
}
/**
* @deprecated since 2.2M2 use {@link #setIntValue(EntityReference, String, int)} instead
*/
@Deprecated
public void setIntValue(String className, String fieldName, int value)
{
setIntValue(this.xClassEntityReferenceResolver.resolve(className, EntityType.DOCUMENT, getDocumentReference()),
fieldName, value);
}
/**
* Note that this method cannot be removed for now since it's used by Hibernate for saving a XWikiDocument.
*
* @deprecated since 2.2M1 use {@link #getDocumentReference()} instead
*/
@Deprecated
public String getDatabase()
{
return getDocumentReference().getWikiReference().getName();
}
/**
* Note that this method cannot be removed for now since it's used by Hibernate for loading a XWikiDocument.
*
* @deprecated since 2.2M1 use {@link #setDocumentReference(DocumentReference)} instead
*/
@Deprecated
public void setDatabase(String database)
{
if (database != null) {
getDocumentReference().getWikiReference().setName(database);
// Clean the absolute parent reference cache to rebuild it next time getParentReference is called.
this.parentReferenceCache = null;
}
}
public String getLanguage()
{
if (this.language == null) {
return "";
} else {
return this.language.trim();
}
}
public void setLanguage(String language)
{
this.language = Util.normalizeLanguage(language);
}
public String getDefaultLanguage()
{
if (this.defaultLanguage == null) {
return "";
} else {
return this.defaultLanguage.trim();
}
}
public void setDefaultLanguage(String defaultLanguage)
{
this.defaultLanguage = defaultLanguage;
setMetaDataDirty(true);
}
public int getTranslation()
{
return this.translation;
}
public void setTranslation(int translation)
{
this.translation = translation;
setMetaDataDirty(true);
}
public String getTranslatedContent(XWikiContext context) throws XWikiException
{
String language = context.getWiki().getLanguagePreference(context);
return getTranslatedContent(language, context);
}
public String getTranslatedContent(String language, XWikiContext context) throws XWikiException
{
XWikiDocument tdoc = getTranslatedDocument(language, context);
String rev = (String) context.get("rev");
if ((rev == null) || (rev.length() == 0)) {
return tdoc.getContent();
}
XWikiDocument cdoc = context.getWiki().getDocument(tdoc, rev, context);
return cdoc.getContent();
}
public XWikiDocument getTranslatedDocument(XWikiContext context) throws XWikiException
{
String language = context.getWiki().getLanguagePreference(context);
return getTranslatedDocument(language, context);
}
public XWikiDocument getTranslatedDocument(String language, XWikiContext context) throws XWikiException
{
XWikiDocument tdoc = this;
if (!((language == null) || (language.equals("")) || language.equals(getDefaultLanguage()))) {
tdoc = new XWikiDocument(getDocumentReference());
tdoc.setLanguage(language);
String database = context.getDatabase();
try {
// We might need to switch database to
// get the translated content
if (getDatabase() != null) {
context.setDatabase(getDatabase());
}
tdoc = getStore(context).loadXWikiDoc(tdoc, context);
if (tdoc.isNew()) {
tdoc = this;
}
} catch (Exception e) {
tdoc = this;
} finally {
context.setDatabase(database);
}
}
return tdoc;
}
public String getRealLanguage(XWikiContext context) throws XWikiException
{
return getRealLanguage();
}
public String getRealLanguage()
{
String lang = getLanguage();
if ((lang.equals("") || lang.equals("default"))) {
return getDefaultLanguage();
} else {
return lang;
}
}
public List<String> getTranslationList(XWikiContext context) throws XWikiException
{
return getStore().getTranslationList(this, context);
}
public List<Delta> getXMLDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context)
throws XWikiException, DifferentiationFailedException
{
return getDeltas(Diff.diff(ToString.stringToArray(fromDoc.toXML(context)),
ToString.stringToArray(toDoc.toXML(context))));
}
public List<Delta> getContentDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context)
throws XWikiException, DifferentiationFailedException
{
return getDeltas(Diff.diff(ToString.stringToArray(fromDoc.getContent()),
ToString.stringToArray(toDoc.getContent())));
}
public List<Delta> getContentDiff(String fromRev, String toRev, XWikiContext context) throws XWikiException,
DifferentiationFailedException
{
XWikiDocument fromDoc = context.getWiki().getDocument(this, fromRev, context);
XWikiDocument toDoc = context.getWiki().getDocument(this, toRev, context);
return getContentDiff(fromDoc, toDoc, context);
}
public List<Delta> getContentDiff(String fromRev, XWikiContext context) throws XWikiException,
DifferentiationFailedException
{
XWikiDocument revdoc = context.getWiki().getDocument(this, fromRev, context);
return getContentDiff(revdoc, this, context);
}
public List<Delta> getLastChanges(XWikiContext context) throws XWikiException, DifferentiationFailedException
{
Version version = getRCSVersion();
try {
String prev = getDocumentArchive(context).getPrevVersion(version).toString();
XWikiDocument prevDoc = context.getWiki().getDocument(this, prev, context);
return getDeltas(Diff.diff(ToString.stringToArray(prevDoc.getContent()),
ToString.stringToArray(getContent())));
} catch (Exception ex) {
LOG.debug("Exception getting differences from previous version: " + ex.getMessage());
}
return new ArrayList<Delta>();
}
public List<Delta> getRenderedContentDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context)
throws XWikiException, DifferentiationFailedException
{
String originalContent, newContent;
originalContent = context.getWiki().getRenderingEngine().renderText(fromDoc.getContent(), fromDoc, context);
newContent = context.getWiki().getRenderingEngine().renderText(toDoc.getContent(), toDoc, context);
return getDeltas(Diff.diff(ToString.stringToArray(originalContent), ToString.stringToArray(newContent)));
}
public List<Delta> getRenderedContentDiff(String fromRev, String toRev, XWikiContext context)
throws XWikiException, DifferentiationFailedException
{
XWikiDocument fromDoc = context.getWiki().getDocument(this, fromRev, context);
XWikiDocument toDoc = context.getWiki().getDocument(this, toRev, context);
return getRenderedContentDiff(fromDoc, toDoc, context);
}
public List<Delta> getRenderedContentDiff(String fromRev, XWikiContext context) throws XWikiException,
DifferentiationFailedException
{
XWikiDocument revdoc = context.getWiki().getDocument(this, fromRev, context);
return getRenderedContentDiff(revdoc, this, context);
}
protected List<Delta> getDeltas(Revision rev)
{
List<Delta> list = new ArrayList<Delta>();
for (int i = 0; i < rev.size(); i++) {
list.add(rev.getDelta(i));
}
return list;
}
public List<MetaDataDiff> getMetaDataDiff(String fromRev, String toRev, XWikiContext context) throws XWikiException
{
XWikiDocument fromDoc = context.getWiki().getDocument(this, fromRev, context);
XWikiDocument toDoc = context.getWiki().getDocument(this, toRev, context);
return getMetaDataDiff(fromDoc, toDoc, context);
}
public List<MetaDataDiff> getMetaDataDiff(String fromRev, XWikiContext context) throws XWikiException
{
XWikiDocument revdoc = context.getWiki().getDocument(this, fromRev, context);
return getMetaDataDiff(revdoc, this, context);
}
public List<MetaDataDiff> getMetaDataDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context)
throws XWikiException
{
List<MetaDataDiff> list = new ArrayList<MetaDataDiff>();
if ((fromDoc == null) || (toDoc == null)) {
return list;
}
if (!fromDoc.getParent().equals(toDoc.getParent())) {
list.add(new MetaDataDiff("parent", fromDoc.getParent(), toDoc.getParent()));
}
if (!fromDoc.getAuthor().equals(toDoc.getAuthor())) {
list.add(new MetaDataDiff("author", fromDoc.getAuthor(), toDoc.getAuthor()));
}
if (!fromDoc.getSpace().equals(toDoc.getSpace())) {
list.add(new MetaDataDiff("web", fromDoc.getSpace(), toDoc.getSpace()));
}
if (!fromDoc.getName().equals(toDoc.getName())) {
list.add(new MetaDataDiff("name", fromDoc.getName(), toDoc.getName()));
}
if (!fromDoc.getLanguage().equals(toDoc.getLanguage())) {
list.add(new MetaDataDiff("language", fromDoc.getLanguage(), toDoc.getLanguage()));
}
if (!fromDoc.getDefaultLanguage().equals(toDoc.getDefaultLanguage())) {
list.add(new MetaDataDiff("defaultLanguage", fromDoc.getDefaultLanguage(), toDoc.getDefaultLanguage()));
}
return list;
}
public List<List<ObjectDiff>> getObjectDiff(String fromRev, String toRev, XWikiContext context)
throws XWikiException
{
XWikiDocument fromDoc = context.getWiki().getDocument(this, fromRev, context);
XWikiDocument toDoc = context.getWiki().getDocument(this, toRev, context);
return getObjectDiff(fromDoc, toDoc, context);
}
public List<List<ObjectDiff>> getObjectDiff(String fromRev, XWikiContext context) throws XWikiException
{
XWikiDocument revdoc = context.getWiki().getDocument(this, fromRev, context);
return getObjectDiff(revdoc, this, context);
}
/**
* Return the object differences between two document versions. There is no hard requirement on the order of the two
* versions, but the results are semantically correct only if the two versions are given in the right order.
*
* @param fromDoc The old ('before') version of the document.
* @param toDoc The new ('after') version of the document.
* @param context The {@link com.xpn.xwiki.XWikiContext context}.
* @return The object differences. The returned list's elements are other lists, one for each changed object. The
* inner lists contain {@link ObjectDiff} elements, one object for each changed property of the object.
* Additionally, if the object was added or removed, then the first entry in the list will be an
* "object-added" or "object-removed" marker.
* @throws XWikiException If there's an error computing the differences.
*/
public List<List<ObjectDiff>> getObjectDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context)
throws XWikiException
{
ArrayList<List<ObjectDiff>> difflist = new ArrayList<List<ObjectDiff>>();
// Since objects could have been deleted or added, we iterate on both the old and the new
// object collections.
// First, iterate over the old objects.
for (List<BaseObject> objects : fromDoc.getXObjects().values()) {
for (BaseObject originalObj : objects) {
// This happens when objects are deleted, and the document is still in the cache
// storage.
if (originalObj != null) {
BaseObject newObj = toDoc.getXObject(originalObj.getXClassReference(), originalObj.getNumber());
List<ObjectDiff> dlist;
if (newObj == null) {
// The object was deleted.
dlist = new BaseObject().getDiff(originalObj, context);
ObjectDiff deleteMarker =
new ObjectDiff(originalObj.getClassName(), originalObj.getNumber(), originalObj.getGuid(),
"object-removed", "", "", "", "");
dlist.add(0, deleteMarker);
} else {
// The object exists in both versions, but might have been changed.
dlist = newObj.getDiff(originalObj, context);
}
if (dlist.size() > 0) {
difflist.add(dlist);
}
}
}
}
// Second, iterate over the objects which are only in the new version.
for (List<BaseObject> objects : toDoc.getXObjects().values()) {
for (BaseObject newObj : objects) {
// This happens when objects are deleted, and the document is still in the cache
// storage.
if (newObj != null) {
BaseObject originalObj = fromDoc.getXObject(newObj.getXClassReference(), newObj.getNumber());
if (originalObj == null) {
// TODO: Refactor this so that getDiff() accepts null Object as input.
// Only consider added objects, the other case was treated above.
originalObj = new BaseObject();
originalObj.setXClassReference(newObj.getXClassReference());
originalObj.setNumber(newObj.getNumber());
originalObj.setGuid(newObj.getGuid());
List<ObjectDiff> dlist = newObj.getDiff(originalObj, context);
ObjectDiff addMarker =
new ObjectDiff(newObj.getClassName(), newObj.getNumber(), newObj.getGuid(), "object-added",
"", "", "", "");
dlist.add(0, addMarker);
if (dlist.size() > 0) {
difflist.add(dlist);
}
}
}
}
}
return difflist;
}
public List<List<ObjectDiff>> getClassDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context)
throws XWikiException
{
ArrayList<List<ObjectDiff>> difflist = new ArrayList<List<ObjectDiff>>();
BaseClass oldClass = fromDoc.getXClass();
BaseClass newClass = toDoc.getXClass();
if ((newClass == null) && (oldClass == null)) {
return difflist;
}
List<ObjectDiff> dlist = newClass.getDiff(oldClass, context);
if (dlist.size() > 0) {
difflist.add(dlist);
}
return difflist;
}
/**
* @param fromDoc
* @param toDoc
* @param context
* @return
* @throws XWikiException
*/
public List<AttachmentDiff> getAttachmentDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context)
throws XWikiException
{
List<AttachmentDiff> difflist = new ArrayList<AttachmentDiff>();
for (XWikiAttachment origAttach : fromDoc.getAttachmentList()) {
String fileName = origAttach.getFilename();
XWikiAttachment newAttach = toDoc.getAttachment(fileName);
if (newAttach == null) {
difflist.add(new AttachmentDiff(fileName, origAttach.getVersion(), null));
} else {
if (!origAttach.getVersion().equals(newAttach.getVersion())) {
difflist.add(new AttachmentDiff(fileName, origAttach.getVersion(), newAttach.getVersion()));
}
}
}
for (XWikiAttachment newAttach : toDoc.getAttachmentList()) {
String fileName = newAttach.getFilename();
XWikiAttachment origAttach = fromDoc.getAttachment(fileName);
if (origAttach == null) {
difflist.add(new AttachmentDiff(fileName, null, newAttach.getVersion()));
}
}
return difflist;
}
/**
* Rename the current document and all the backlinks leading to it. Will also change parent field in all documents
* which list the document we are renaming as their parent.
* <p>
* See {@link #rename(String, java.util.List, com.xpn.xwiki.XWikiContext)} for more details.
*
* @param newDocumentReference the new document reference
* @param context the ubiquitous XWiki Context
* @throws XWikiException in case of an error
* @since 2.2M2
*/
public void rename(DocumentReference newDocumentReference, XWikiContext context) throws XWikiException
{
rename(newDocumentReference, getBackLinkedReferences(context), context);
}
/**
* @deprecated since 2.2M2 use {@link #rename(DocumentReference, XWikiContext)}
*/
@Deprecated
public void rename(String newDocumentName, XWikiContext context) throws XWikiException
{
rename(newDocumentName, getBackLinkedPages(context), context);
}
/**
* Rename the current document and all the links pointing to it in the list of passed backlink documents. The
* renaming algorithm takes into account the fact that there are several ways to write a link to a given page and
* all those forms need to be renamed. For example the following links all point to the same page:
* <ul>
* <li>[Page]</li>
* <li>[Page?param=1]</li>
* <li>[currentwiki:Page]</li>
* <li>[CurrentSpace.Page]</li>
* <li>[currentwiki:CurrentSpace.Page]</li>
* </ul>
* <p>
* Note: links without a space are renamed with the space added and all documents which have the document being
* renamed as parent have their parent field set to "currentwiki:CurrentSpace.Page".
* </p>
*
* @param newDocumentReference the new document reference
* @param backlinkDocumentReferences the list of references of documents to parse and for which links will be
* modified to point to the new document reference
* @param context the ubiquitous XWiki Context
* @throws XWikiException in case of an error
* @since 2.2M2
*/
public void rename(DocumentReference newDocumentReference, List<DocumentReference> backlinkDocumentReferences,
XWikiContext context) throws XWikiException
{
rename(newDocumentReference, backlinkDocumentReferences, getChildrenReferences(context), context);
}
/**
* @deprecated since 2.2M2 use {@link #rename(DocumentReference, java.util.List, com.xpn.xwiki.XWikiContext)}
*/
@Deprecated
public void rename(String newDocumentName, List<String> backlinkDocumentNames, XWikiContext context)
throws XWikiException
{
rename(newDocumentName, backlinkDocumentNames, getChildren(context), context);
}
/**
* Same as {@link #rename(String, List, XWikiContext)} but the list of documents having the current document as
* their parent is passed in parameter.
*
* @param newDocumentReference the new document reference
* @param backlinkDocumentReferences the list of references of documents to parse and for which links will be
* modified to point to the new document reference
* @param childDocumentReferences the list of references of document whose parent field will be set to the new
* document reference
* @param context the ubiquitous XWiki Context
* @throws XWikiException in case of an error
* @since 2.2M2
*/
public void rename(DocumentReference newDocumentReference, List<DocumentReference> backlinkDocumentReferences,
List<DocumentReference> childDocumentReferences, XWikiContext context) throws XWikiException
{
// TODO: Do all this in a single DB transaction as otherwise the state will be unknown if
// something fails in the middle...
// TODO: Why do we verify if the document has just been created and not been saved.
// If the user is trying to rename to the same name... In that case, simply exits for efficiency.
if (isNew() || getDocumentReference().equals(newDocumentReference)) {
return;
}
// Grab the xwiki object, it gets used a few times.
XWiki xwiki = context.getWiki();
// Step 1: Copy the document and all its translations under a new document with the new reference.
xwiki.copyDocument(getDocumentReference(), newDocumentReference, false, context);
// Step 2: For each child document, update its parent reference.
if (childDocumentReferences != null) {
for (DocumentReference childDocumentReference : childDocumentReferences) {
XWikiDocument childDocument = xwiki.getDocument(childDocumentReference, context);
childDocument.setParentReference(newDocumentReference);
String saveMessage =
context.getMessageTool().get("core.comment.renameParent",
Arrays.asList(this.compactEntityReferenceSerializer.serialize(newDocumentReference)));
xwiki.saveDocument(childDocument, saveMessage, true, context);
}
}
// Step 3: For each backlink to rename, parse the backlink document and replace the links with the new name.
// Note: we ignore invalid links here. Invalid links should be shown to the user so
// that they fix them but the rename feature ignores them.
DocumentParser documentParser = new DocumentParser();
// This link handler recognizes that 2 links are the same when they point to the same
// document (regardless of query string, target or alias). It keeps the query string,
// target and alias from the link being replaced.
RenamePageReplaceLinkHandler linkHandler = new RenamePageReplaceLinkHandler();
// Used for replacing links in XWiki Syntax 1.0
Link oldLink = new LinkParser().parse(this.localEntityReferenceSerializer.serialize(getDocumentReference()));
Link newLink = new LinkParser().parse(this.localEntityReferenceSerializer.serialize(newDocumentReference));
for (DocumentReference backlinkDocumentReference : backlinkDocumentReferences) {
XWikiDocument backlinkDocument = xwiki.getDocument(backlinkDocumentReference, context);
if (backlinkDocument.is10Syntax()) {
// Note: Here we cannot do a simple search/replace as there are several ways to point
// to the same document. For example [Page], [Page?param=1], [currentwiki:Page],
// [CurrentSpace.Page] all point to the same document. Thus we have to parse the links
// to recognize them and do the replace.
ReplacementResultCollection result =
documentParser.parseLinksAndReplace(backlinkDocument.getContent(), oldLink, newLink, linkHandler,
getDocumentReference().getLastSpaceReference().getName());
backlinkDocument.setContent((String) result.getModifiedContent());
} else {
backlinkDocument.refactorDocumentLinks(getDocumentReference(), newDocumentReference, context);
}
String saveMessage =
context.getMessageTool().get("core.comment.renameLink",
Arrays.asList(this.compactEntityReferenceSerializer.serialize(newDocumentReference)));
xwiki.saveDocument(backlinkDocument, saveMessage, true, context);
}
// Step 4: Refactor the links contained in the document
XWikiDocument newDocument = xwiki.getDocument(newDocumentReference, context);
XDOM newDocumentXDOM = newDocument.getXDOM();
List<LinkBlock> linkBlockList = newDocumentXDOM.getChildrenByType(LinkBlock.class, true);
XWikiDocument currentContextDoc = context.getDoc();
try {
boolean modified = false;
for (LinkBlock linkBlock : linkBlockList) {
ResourceReference linkReference = linkBlock.getReference();
if (linkReference.getType().equals(ResourceType.DOCUMENT)) {
context.setDoc(this);
DocumentReference currentLinkReference =
this.currentDocumentReferenceResolver.resolve(linkReference.getReference());
context.setDoc(newDocument);
DocumentReference newLinkReference =
this.currentDocumentReferenceResolver.resolve(linkReference.getReference());
if (!newLinkReference.equals(currentLinkReference)) {
modified = true;
linkReference.setReference(this.compactWikiEntityReferenceSerializer
.serialize(currentLinkReference));
}
}
}
// Set new content and save document if needed
if (modified) {
newDocument.setContent(newDocumentXDOM);
xwiki.saveDocument(newDocument, context);
}
} finally {
// Restore original context
context.setDoc(currentContextDoc);
}
// Step 5: Delete the old document
xwiki.deleteDocument(this, context);
// Step 6: The current document needs to point to the renamed document as otherwise it's pointing to an
// invalid XWikiDocument object as it's been deleted...
clone(newDocument);
}
/**
* @deprecated since 2.2M2 use {@link #rename(DocumentReference, List, List, com.xpn.xwiki.XWikiContext)}
*/
@Deprecated
public void rename(String newDocumentName, List<String> backlinkDocumentNames, List<String> childDocumentNames,
XWikiContext context) throws XWikiException
{
List<DocumentReference> backlinkDocumentReferences = new ArrayList<DocumentReference>();
for (String backlinkDocumentName : backlinkDocumentNames) {
backlinkDocumentReferences.add(this.currentMixedDocumentReferenceResolver.resolve(backlinkDocumentName));
}
List<DocumentReference> childDocumentReferences = new ArrayList<DocumentReference>();
for (String childDocumentName : childDocumentNames) {
childDocumentReferences.add(this.currentMixedDocumentReferenceResolver.resolve(childDocumentName));
}
rename(this.currentMixedDocumentReferenceResolver.resolve(newDocumentName), backlinkDocumentReferences,
childDocumentReferences, context);
}
/**
* @since 2.2M1
*/
private void refactorDocumentLinks(DocumentReference oldDocumentReference, DocumentReference newDocumentReference,
XWikiContext context) throws XWikiException
{
String contextWiki = context.getDatabase();
XWikiDocument contextDoc = context.getDoc();
try {
context.setDatabase(getDocumentReference().getWikiReference().getName());
context.setDoc(this);
XDOM xdom = getXDOM();
List<LinkBlock> linkBlockList = xdom.getChildrenByType(LinkBlock.class, true);
for (LinkBlock linkBlock : linkBlockList) {
ResourceReference linkReference = linkBlock.getReference();
if (linkReference.getType().equals(ResourceType.DOCUMENT)) {
DocumentReference documentReference =
this.currentDocumentReferenceResolver.resolve(linkReference.getReference());
if (documentReference.equals(oldDocumentReference)) {
linkReference.setReference(this.compactEntityReferenceSerializer
.serialize(newDocumentReference));
}
}
}
setContent(xdom);
} finally {
context.setDatabase(contextWiki);
context.setDoc(contextDoc);
}
}
/**
* @since 2.2M1
*/
public XWikiDocument copyDocument(DocumentReference newDocumentReference, XWikiContext context)
throws XWikiException
{
loadAttachments(context);
loadArchive(context);
XWikiDocument newdoc = duplicate(newDocumentReference);
newdoc.setOriginalDocument(null);
newdoc.setContentDirty(true);
newdoc.getXClass().setDocumentReference(newDocumentReference);
XWikiDocumentArchive archive = newdoc.getDocumentArchive();
if (archive != null) {
newdoc.setDocumentArchive(archive.clone(newdoc.getId(), context));
}
return newdoc;
}
/**
* @deprecated since 2.2M1 use {@link #copyDocument(DocumentReference, XWikiContext)} instead
*/
@Deprecated
public XWikiDocument copyDocument(String newDocumentName, XWikiContext context) throws XWikiException
{
return copyDocument(this.currentMixedDocumentReferenceResolver.resolve(newDocumentName), context);
}
public XWikiLock getLock(XWikiContext context) throws XWikiException
{
XWikiLock theLock = getStore(context).loadLock(getId(), context, true);
if (theLock != null) {
int timeout = context.getWiki().getXWikiPreferenceAsInt("lock_Timeout", 30 * 60, context);
if (theLock.getDate().getTime() + timeout * 1000 < new Date().getTime()) {
getStore(context).deleteLock(theLock, context, true);
theLock = null;
}
}
return theLock;
}
public void setLock(String userName, XWikiContext context) throws XWikiException
{
XWikiLock lock = new XWikiLock(getId(), userName);
getStore(context).saveLock(lock, context, true);
}
public void removeLock(XWikiContext context) throws XWikiException
{
XWikiLock lock = getStore(context).loadLock(getId(), context, true);
if (lock != null) {
getStore(context).deleteLock(lock, context, true);
}
}
public void insertText(String text, String marker, XWikiContext context) throws XWikiException
{
setContent(StringUtils.replaceOnce(getContent(), marker, text + marker));
context.getWiki().saveDocument(this, context);
}
public Object getWikiNode()
{
return this.wikiNode;
}
public void setWikiNode(Object wikiNode)
{
this.wikiNode = wikiNode;
}
/**
* @since 2.2M1
*/
public String getXClassXML()
{
return this.xClassXML;
}
/**
* @deprecated since 2.2M1 use {@link #getXClassXML()} instead
*/
@Deprecated
public String getxWikiClassXML()
{
return getXClassXML();
}
/**
* @since 2.2M1
*/
public void setXClassXML(String xClassXML)
{
this.xClassXML = xClassXML;
}
/**
* @deprecated since 2.2M1 use {@link #setXClassXML(String)} ()} instead
*/
@Deprecated
public void setxWikiClassXML(String xClassXML)
{
setXClassXML(xClassXML);
}
public int getElements()
{
return this.elements;
}
public void setElements(int elements)
{
this.elements = elements;
}
public void setElement(int element, boolean toggle)
{
if (toggle) {
this.elements = this.elements | element;
} else {
this.elements = this.elements & (~element);
}
}
public boolean hasElement(int element)
{
return ((this.elements & element) == element);
}
/**
* @return "inline" if the document should be edited in inline mode by default or "edit" otherwise.
* @throws XWikiException if an error happens when computing the edit mode
*/
public String getDefaultEditMode(XWikiContext context) throws XWikiException
{
com.xpn.xwiki.XWiki xwiki = context.getWiki();
if (is10Syntax()) {
if (getContent().indexOf("includeForm(") != -1) {
return "inline";
}
} else {
// Algorithm: look in all include macro and for all document included check if one of them
// has an SheetClass object attached to it. If so then the edit mode is inline.
// Find all include macros and extract the document names
for (MacroBlock macroBlock : getXDOM().getChildrenByType(MacroBlock.class, false)) {
// TODO: Is there a good way not to hardcode the macro name? The macro itself shouldn't know
// its own name since it's a deployment time concern.
if ("include".equals(macroBlock.getId())) {
String documentName = macroBlock.getParameter("document");
if (documentName != null) {
// Resolve the document name into a valid Reference
DocumentReference documentReference =
this.currentMixedDocumentReferenceResolver.resolve(documentName);
XWikiDocument includedDocument = xwiki.getDocument(documentReference, context);
if (!includedDocument.isNew()) {
BaseObject sheetClassObject = includedDocument.getObject(XWikiConstant.SHEET_CLASS);
if (sheetClassObject != null) {
// Use the user-defined default edit mode if set.
String defaultEditMode = sheetClassObject.getStringValue("defaultEditMode");
if (StringUtils.isBlank(defaultEditMode)) {
return "inline";
} else {
return defaultEditMode;
}
}
}
}
}
}
}
return "edit";
}
public String getDefaultEditURL(XWikiContext context) throws XWikiException
{
String editMode = getDefaultEditMode(context);
if ("inline".equals(editMode)) {
return getEditURL("inline", "", context);
} else {
com.xpn.xwiki.XWiki xwiki = context.getWiki();
String editor = xwiki.getEditorPreference(context);
return getEditURL("edit", editor, context);
}
}
public String getEditURL(String action, String mode, XWikiContext context) throws XWikiException
{
com.xpn.xwiki.XWiki xwiki = context.getWiki();
String language = "";
XWikiDocument tdoc = (XWikiDocument) context.get("tdoc");
String realLang = tdoc.getRealLanguage(context);
if ((xwiki.isMultiLingual(context) == true) && (!realLang.equals(""))) {
language = realLang;
}
return getEditURL(action, mode, language, context);
}
public String getEditURL(String action, String mode, String language, XWikiContext context)
{
StringBuffer editparams = new StringBuffer();
if (!mode.equals("")) {
editparams.append("xpage=");
editparams.append(mode);
}
if (!language.equals("")) {
if (!mode.equals("")) {
editparams.append("&");
}
editparams.append("language=");
editparams.append(language);
}
return getURL(action, editparams.toString(), context);
}
public String getDefaultTemplate()
{
if (this.defaultTemplate == null) {
return "";
} else {
return this.defaultTemplate;
}
}
public void setDefaultTemplate(String defaultTemplate)
{
this.defaultTemplate = defaultTemplate;
setMetaDataDirty(true);
}
public Vector<BaseObject> getComments()
{
return getComments(true);
}
/**
* @return the syntax of the document
* @since 2.3M1
*/
public Syntax getSyntax()
{
// Can't be initialized in the XWikiDocument constructor because #getDefaultDocumentSyntax() need to create a
// XWikiDocument object to get preferences from wiki preferences pages and would thus generate an infinite loop
if (isNew() && this.syntax == null) {
this.syntax = getDefaultDocumentSyntax();
}
return this.syntax;
}
/**
* {@inheritDoc}
* <p>
* Note that this method cannot be removed for now since it's used by Hibernate for saving a XWikiDocument.
*
* @see org.xwiki.bridge.DocumentModelBridge#getSyntaxId()
* @deprecated since 2.3M1, use {link #getSyntax()} instead
*/
@Deprecated
public String getSyntaxId()
{
return getSyntax().toIdString();
}
/**
* @param syntax the new syntax to set for this document
* @see #getSyntax()
* @since 2.3M1
*/
public void setSyntax(Syntax syntax)
{
this.syntax = syntax;
}
/**
* Note that this method cannot be removed for now since it's used by Hibernate for saving a XWikiDocument.
*
* @param syntaxId the new syntax id to set (eg "xwiki/1.0", "xwiki/2.0", etc)
* @see #getSyntaxId()
* @deprecated since 2.3M1, use {link #setSyntax(Syntax)} instead
*/
@Deprecated
public void setSyntaxId(String syntaxId)
{
Syntax syntax;
// In order to preserve backward-compatibility with previous versions of XWiki in which the notion of Syntax Id
// did not exist, we check the passed syntaxId parameter. Since this parameter comes from the database (it's
// called automatically by Hibernate) it can be NULL or empty. In this case we consider the document is in
// syntax/1.0 syntax.
if (StringUtils.isBlank(syntaxId)) {
syntax = Syntax.XWIKI_1_0;
} else {
try {
syntax = this.syntaxFactory.createSyntaxFromIdString(syntaxId);
} catch (ParseException e) {
syntax = getDefaultDocumentSyntax();
LOG.warn(
"Failed to set syntax [" + syntaxId + "] for ["
+ this.defaultEntityReferenceSerializer.serialize(getDocumentReference())
+ "], setting syntax [" + syntax.toIdString() + "] instead.", e);
}
}
setSyntax(syntax);
}
public Vector<BaseObject> getComments(boolean asc)
{
Vector<BaseObject> list = getObjects("XWiki.XWikiComments");
if (asc) {
return list;
} else {
if (list == null) {
return list;
}
Vector<BaseObject> newlist = new Vector<BaseObject>();
for (int i = list.size() - 1; i >= 0; i
newlist.add(list.get(i));
}
return newlist;
}
}
public boolean isCurrentUserCreator(XWikiContext context)
{
return isCreator(context.getUser());
}
public boolean isCreator(String username)
{
if (username.equals(XWikiRightService.GUEST_USER_FULLNAME)) {
return false;
}
return username.equals(getCreator());
}
public boolean isCurrentUserPage(XWikiContext context)
{
String username = context.getUser();
if (username.equals(XWikiRightService.GUEST_USER_FULLNAME)) {
return false;
}
return context.getUser().equals(getFullName());
}
public boolean isCurrentLocalUserPage(XWikiContext context)
{
String username = context.getLocalUser();
if (username.equals(XWikiRightService.GUEST_USER_FULLNAME)) {
return false;
}
return context.getUser().equals(getFullName());
}
public void resetArchive(XWikiContext context) throws XWikiException
{
boolean hasVersioning = context.getWiki().hasVersioning(context);
if (hasVersioning) {
getVersioningStore(context).resetRCSArchive(this, true, context);
}
}
/**
* Adds an object from an new object creation form.
*
* @since 2.2M2
*/
public BaseObject addXObjectFromRequest(XWikiContext context) throws XWikiException
{
// Read info in object
ObjectAddForm form = new ObjectAddForm();
form.setRequest((HttpServletRequest) context.getRequest());
form.readRequest();
EntityReference classReference =
this.xClassEntityReferenceResolver
.resolve(form.getClassName(), EntityType.DOCUMENT, getDocumentReference());
BaseObject object = newXObject(classReference, context);
BaseClass baseclass = object.getXClass(context);
baseclass.fromMap(
form.getObject(this.localEntityReferenceSerializer.serialize(resolveClassReference(classReference))),
object);
return object;
}
/**
* @deprecated since 2.2M2 use {@link #addXObjectFromRequest(XWikiContext)}
*/
@Deprecated
public BaseObject addObjectFromRequest(XWikiContext context) throws XWikiException
{
return addXObjectFromRequest(context);
}
/**
* Adds an object from an new object creation form.
*
* @since 2.2.3
*/
public BaseObject addXObjectFromRequest(EntityReference classReference, XWikiContext context) throws XWikiException
{
return addXObjectFromRequest(classReference, "", 0, context);
}
/**
* @deprecated since 2.2M2 use {@link #addXObjectFromRequest(EntityReference, XWikiContext)}
*/
@Deprecated
public BaseObject addObjectFromRequest(String className, XWikiContext context) throws XWikiException
{
return addObjectFromRequest(className, "", 0, context);
}
/**
* Adds an object from an new object creation form.
*
* @since 2.2M2
*/
public BaseObject addXObjectFromRequest(DocumentReference classReference, String prefix, XWikiContext context)
throws XWikiException
{
return addXObjectFromRequest(classReference, prefix, 0, context);
}
/**
* @deprecated since 2.2M2 use {@link #addXObjectFromRequest(DocumentReference, String, XWikiContext)}
*/
@Deprecated
public BaseObject addObjectFromRequest(String className, String prefix, XWikiContext context) throws XWikiException
{
return addObjectFromRequest(className, prefix, 0, context);
}
/**
* Adds multiple objects from an new objects creation form.
*
* @since 2.2M2
*/
public List<BaseObject> addXObjectsFromRequest(DocumentReference classReference, XWikiContext context)
throws XWikiException
{
return addXObjectsFromRequest(classReference, "", context);
}
/**
* @deprecated since 2.2M2 use {@link #addXObjectsFromRequest(DocumentReference, XWikiContext)}
*/
@Deprecated
public List<BaseObject> addObjectsFromRequest(String className, XWikiContext context) throws XWikiException
{
return addObjectsFromRequest(className, "", context);
}
/**
* Adds multiple objects from an new objects creation form.
*
* @since 2.2M2
*/
public List<BaseObject> addXObjectsFromRequest(DocumentReference classReference, String pref, XWikiContext context)
throws XWikiException
{
Map map = context.getRequest().getParameterMap();
List<Integer> objectsNumberDone = new ArrayList<Integer>();
List<BaseObject> objects = new ArrayList<BaseObject>();
Iterator it = map.keySet().iterator();
String start = pref + this.localEntityReferenceSerializer.serialize(classReference) + "_";
while (it.hasNext()) {
String name = (String) it.next();
if (name.startsWith(start)) {
int pos = name.indexOf("_", start.length() + 1);
String prefix = name.substring(0, pos);
int num = Integer.decode(prefix.substring(prefix.lastIndexOf("_") + 1)).intValue();
if (!objectsNumberDone.contains(new Integer(num))) {
objectsNumberDone.add(new Integer(num));
objects.add(addXObjectFromRequest(classReference, pref, num, context));
}
}
}
return objects;
}
/**
* @deprecated since 2.2M2 use {@link #addXObjectsFromRequest(DocumentReference, String, XWikiContext)}
*/
@Deprecated
public List<BaseObject> addObjectsFromRequest(String className, String pref, XWikiContext context)
throws XWikiException
{
return addXObjectsFromRequest(resolveClassReference(className), pref, context);
}
/**
* Adds object from an new object creation form.
*
* @since 2.2M2
*/
public BaseObject addXObjectFromRequest(DocumentReference classReference, int num, XWikiContext context)
throws XWikiException
{
return addXObjectFromRequest(classReference, "", num, context);
}
/**
* @deprecated since 2.2M2 use {@link #addXObjectFromRequest(DocumentReference, int, XWikiContext)}
*/
@Deprecated
public BaseObject addObjectFromRequest(String className, int num, XWikiContext context) throws XWikiException
{
return addObjectFromRequest(className, "", num, context);
}
/**
* Adds object from an new object creation form.
*
* @since 2.2.3
*/
public BaseObject addXObjectFromRequest(EntityReference classReference, String prefix, int num, XWikiContext context)
throws XWikiException
{
BaseObject object = newXObject(classReference, context);
BaseClass baseclass = object.getXClass(context);
String newPrefix =
prefix + this.localEntityReferenceSerializer.serialize(resolveClassReference(classReference)) + "_" + num;
baseclass.fromMap(Util.getObject(context.getRequest(), newPrefix), object);
return object;
}
/**
* @deprecated since 2.2M2 use {@link #addXObjectFromRequest(EntityReference, String, int, XWikiContext)}
*/
@Deprecated
public BaseObject addObjectFromRequest(String className, String prefix, int num, XWikiContext context)
throws XWikiException
{
return addXObjectFromRequest(resolveClassReference(className), prefix, num, context);
}
/**
* Adds an object from an new object creation form.
*
* @since 2.2.3
*/
public BaseObject updateXObjectFromRequest(EntityReference classReference, XWikiContext context)
throws XWikiException
{
return updateXObjectFromRequest(classReference, "", context);
}
/**
* @deprecated since 2.2M2 use {@link #updateXObjectFromRequest(EntityReference, XWikiContext)}
*/
@Deprecated
public BaseObject updateObjectFromRequest(String className, XWikiContext context) throws XWikiException
{
return updateObjectFromRequest(className, "", context);
}
/**
* Adds an object from an new object creation form.
*
* @since 2.2.3
*/
public BaseObject updateXObjectFromRequest(EntityReference classReference, String prefix, XWikiContext context)
throws XWikiException
{
return updateXObjectFromRequest(classReference, prefix, 0, context);
}
/**
* @deprecated since 2.2M2 use {@link #updateXObjectFromRequest(EntityReference, String, XWikiContext)}
*/
@Deprecated
public BaseObject updateObjectFromRequest(String className, String prefix, XWikiContext context)
throws XWikiException
{
return updateObjectFromRequest(className, prefix, 0, context);
}
/**
* Adds an object from an new object creation form.
*
* @since 2.2.3
*/
public BaseObject updateXObjectFromRequest(EntityReference classReference, String prefix, int num,
XWikiContext context) throws XWikiException
{
DocumentReference absoluteClassReference = resolveClassReference(classReference);
int nb;
BaseObject oldobject = getXObject(absoluteClassReference, num);
if (oldobject == null) {
nb = createXObject(classReference, context);
oldobject = getXObject(absoluteClassReference, nb);
} else {
nb = oldobject.getNumber();
}
BaseClass baseclass = oldobject.getXClass(context);
String newPrefix = prefix + this.localEntityReferenceSerializer.serialize(absoluteClassReference) + "_" + nb;
BaseObject newobject =
(BaseObject) baseclass.fromMap(Util.getObject(context.getRequest(), newPrefix), oldobject);
newobject.setNumber(oldobject.getNumber());
newobject.setGuid(oldobject.getGuid());
newobject.setDocumentReference(getDocumentReference());
setXObject(nb, newobject);
return newobject;
}
/**
* @deprecated since 2.2M2 use {@link #updateXObjectFromRequest(EntityReference, String, int, XWikiContext)}
*/
@Deprecated
public BaseObject updateObjectFromRequest(String className, String prefix, int num, XWikiContext context)
throws XWikiException
{
return updateXObjectFromRequest(
this.xClassEntityReferenceResolver.resolve(className, EntityType.DOCUMENT, getDocumentReference()), prefix,
num, context);
}
/**
* Adds an object from an new object creation form.
*
* @since 2.2.3
*/
public List<BaseObject> updateXObjectsFromRequest(EntityReference classReference, XWikiContext context)
throws XWikiException
{
return updateXObjectsFromRequest(classReference, "", context);
}
/**
* @deprecated since 2.2M2 use {@link #updateXObjectsFromRequest(EntityReference, XWikiContext)}
*/
@Deprecated
public List<BaseObject> updateObjectsFromRequest(String className, XWikiContext context) throws XWikiException
{
return updateObjectsFromRequest(className, "", context);
}
/**
* Adds multiple objects from an new objects creation form.
*
* @since 2.2.3
*/
public List<BaseObject> updateXObjectsFromRequest(EntityReference classReference, String pref, XWikiContext context)
throws XWikiException
{
DocumentReference absoluteClassReference = resolveClassReference(classReference);
Map map = context.getRequest().getParameterMap();
List<Integer> objectsNumberDone = new ArrayList<Integer>();
List<BaseObject> objects = new ArrayList<BaseObject>();
Iterator it = map.keySet().iterator();
String start = pref + this.localEntityReferenceSerializer.serialize(absoluteClassReference) + "_";
while (it.hasNext()) {
String name = (String) it.next();
if (name.startsWith(start)) {
int pos = name.indexOf("_", start.length() + 1);
String prefix = name.substring(0, pos);
int num = Integer.decode(prefix.substring(prefix.lastIndexOf("_") + 1)).intValue();
if (!objectsNumberDone.contains(new Integer(num))) {
objectsNumberDone.add(new Integer(num));
objects.add(updateXObjectFromRequest(classReference, pref, num, context));
}
}
}
return objects;
}
/**
* @deprecated since 2.2M2 use {@link #updateXObjectsFromRequest(EntityReference, String, XWikiContext)}
*/
@Deprecated
public List<BaseObject> updateObjectsFromRequest(String className, String pref, XWikiContext context)
throws XWikiException
{
return updateXObjectsFromRequest(
this.xClassEntityReferenceResolver.resolve(className, EntityType.DOCUMENT, getDocumentReference()), pref,
context);
}
public boolean isAdvancedContent()
{
String[] matches =
{"<%", "#set", "#include", "#if", "public class", "/* Advanced content */", "## Advanced content",
"/* Programmatic content */", "## Programmatic content"};
String content2 = getContent().toLowerCase();
for (int i = 0; i < matches.length; i++) {
if (content2.indexOf(matches[i].toLowerCase()) != -1) {
return true;
}
}
if (HTML_TAG_PATTERN.matcher(content2).find()) {
return true;
}
return false;
}
public boolean isProgrammaticContent()
{
String[] matches =
{"<%", "\\$xwiki.xWiki", "$context.context", "$doc.document", "$xwiki.getXWiki()", "$context.getContext()",
"$doc.getDocument()", "WithProgrammingRights(", "/* Programmatic content */", "## Programmatic content",
"$xwiki.search(", "$xwiki.createUser", "$xwiki.createNewWiki", "$xwiki.addToAllGroup",
"$xwiki.sendMessage", "$xwiki.copyDocument", "$xwiki.copyWikiWeb", "$xwiki.copySpaceBetweenWikis",
"$xwiki.parseGroovyFromString", "$doc.toXML()", "$doc.toXMLDocument()",};
String content2 = getContent().toLowerCase();
for (int i = 0; i < matches.length; i++) {
if (content2.indexOf(matches[i].toLowerCase()) != -1) {
return true;
}
}
return false;
}
/**
* Remove an XObject from the document. The changes are not persisted until the document is saved.
*
* @param object the object to remove
* @return {@code true} if the object was successfully removed, {@code false} if the object was not found in the
* current document.
* @since 2.2M1
*/
public boolean removeXObject(BaseObject object)
{
List<BaseObject> objects = getXObjects(object.getXClassReference());
// No objects at all, nothing to remove
if (objects == null) {
return false;
}
// Sometimes the object vector is wrongly indexed, meaning that objects are not at the right position
// Check if the right object is in place
int objectPosition = object.getNumber();
if (objectPosition < objects.size()) {
BaseObject storedObject = objects.get(objectPosition);
if (storedObject == null || !storedObject.equals(object)) {
// Try to find the correct position
objectPosition = objects.indexOf(object);
}
} else {
// The object position is greater than the array, that's invalid!
objectPosition = -1;
}
// If the object is not in the document, simply ignore this request
if (objectPosition < 0) {
return false;
}
// We don't remove objects, but set null in their place, so that the object number corresponds to its position
// in the vector
objects.set(objectPosition, null);
// Schedule the object for removal from the storage
addObjectsToRemove(object);
return true;
}
/**
* Remove an XObject from the document. The changes are not persisted until the document is saved.
*
* @param object the object to remove
* @return {@code true} if the object was successfully removed, {@code false} if the object was not found in the
* current document.
* @deprecated since 2.2M1, use {@link #removeXObject(com.xpn.xwiki.objects.BaseObject)} instead
*/
@Deprecated
public boolean removeObject(BaseObject object)
{
return removeXObject(object);
}
/**
* Remove all the objects of a given type (XClass) from the document. The object counter is left unchanged, so that
* future objects will have new (different) numbers. However, on some storage engines the counter will be reset if
* the document is removed from the cache and reloaded from the persistent storage.
*
* @param classReference The XClass reference of the XObjects to be removed.
* @return {@code true} if the objects were successfully removed, {@code false} if no object from the target class
* was in the current document.
* @since 2.2M1
*/
public boolean removeXObjects(DocumentReference classReference)
{
List<BaseObject> objects = getXObjects(classReference);
// No objects at all, nothing to remove
if (objects == null) {
return false;
}
// Schedule the object for removal from the storage
for (BaseObject object : objects) {
if (object != null) {
addObjectsToRemove(object);
}
}
// Empty the vector, retaining its size
int currentSize = objects.size();
objects.clear();
for (int i = 0; i < currentSize; i++) {
objects.add(null);
}
return true;
}
/**
* Remove all the objects of a given type (XClass) from the document. The object counter is left unchanged, so that
* future objects will have new (different) numbers. However, on some storage engines the counter will be reset if
* the document is removed from the cache and reloaded from the persistent storage.
*
* @param className The class name of the objects to be removed.
* @return {@code true} if the objects were successfully removed, {@code false} if no object from the target class
* was in the current document.
* @deprecated since 2.2M1 use {@link #removeXObjects(org.xwiki.model.reference.DocumentReference)} instead
*/
@Deprecated
public boolean removeObjects(String className)
{
return removeXObjects(resolveClassReference(className));
}
/**
* @return the sections in the current document
* @throws XWikiException
*/
public List<DocumentSection> getSections() throws XWikiException
{
if (is10Syntax()) {
return getSections10();
} else {
List<DocumentSection> splitSections = new ArrayList<DocumentSection>();
List<HeaderBlock> headers = getFilteredHeaders();
int sectionNumber = 1;
for (HeaderBlock header : headers) {
// put -1 as index since there is no way to get the position of the header in the source
int documentSectionIndex = -1;
// Need to do the same thing than 1.0 content here
String documentSectionLevel = StringUtils.repeat("1.", header.getLevel().getAsInt() - 1) + "1";
DocumentSection docSection =
new DocumentSection(sectionNumber++, documentSectionIndex, documentSectionLevel, renderXDOM(
new XDOM(header.getChildren()), getSyntax()));
splitSections.add(docSection);
}
return splitSections;
}
}
/**
* Get XWiki context from execution context.
*
* @return the XWiki context for the current thread
*/
private XWikiContext getXWikiContext()
{
Execution execution = Utils.getComponent(Execution.class);
ExecutionContext ec = execution.getContext();
XWikiContext context = null;
if (ec != null) {
context = (XWikiContext) ec.getProperty("xwikicontext");
}
return context;
}
/**
* Filter the headers from a document XDOM based on xwiki.section.depth property from xwiki.cfg file.
*
* @return the filtered headers
*/
private List<HeaderBlock> getFilteredHeaders()
{
List<HeaderBlock> filteredHeaders = new ArrayList<HeaderBlock>();
// get the headers
List<HeaderBlock> headers = getXDOM().getChildrenByType(HeaderBlock.class, true);
// get the maximum header level
int sectionDepth = 2;
XWikiContext context = getXWikiContext();
if (context != null) {
sectionDepth = (int) context.getWiki().getSectionEditingDepth();
}
// filter the headers
for (HeaderBlock header : headers) {
if (header.getLevel().getAsInt() <= sectionDepth) {
filteredHeaders.add(header);
}
}
return filteredHeaders;
}
/**
* @return the sections in the current document
*/
private List<DocumentSection> getSections10()
{
// Pattern to match the title. Matches only level 1 and level 2 headings.
Pattern headingPattern = Pattern.compile("^[ \\t]*+(1(\\.1){0,1}+)[ \\t]++(.++)$", Pattern.MULTILINE);
Matcher matcher = headingPattern.matcher(getContent());
List<DocumentSection> splitSections = new ArrayList<DocumentSection>();
int sectionNumber = 0;
// find title to split
while (matcher.find()) {
++sectionNumber;
String sectionLevel = matcher.group(1);
String sectionTitle = matcher.group(3);
int sectionIndex = matcher.start();
// Initialize a documentSection object.
DocumentSection docSection = new DocumentSection(sectionNumber, sectionIndex, sectionLevel, sectionTitle);
// Add the document section to list.
splitSections.add(docSection);
}
return splitSections;
}
/**
* Return a Document section with parameter is sectionNumber.
*
* @param sectionNumber the index (+1) of the section in the list of all sections in the document.
* @return
* @throws XWikiException error when extracting sections from document
*/
public DocumentSection getDocumentSection(int sectionNumber) throws XWikiException
{
// return a document section according to section number
return getSections().get(sectionNumber - 1);
}
/**
* Return the content of a section.
*
* @param sectionNumber the index (+1) of the section in the list of all sections in the document.
* @return the content of a section or null if the section can't be found.
* @throws XWikiException error when trying to extract section content
*/
public String getContentOfSection(int sectionNumber) throws XWikiException
{
String content = null;
if (is10Syntax()) {
content = getContentOfSection10(sectionNumber);
} else {
List<HeaderBlock> headers = getFilteredHeaders();
if (headers.size() >= sectionNumber) {
SectionBlock section = headers.get(sectionNumber - 1).getSection();
content = renderXDOM(new XDOM(Collections.<Block> singletonList(section)), getSyntax());
}
}
return content;
}
/**
* Return the content of a section.
*
* @param sectionNumber the index (+1) of the section in the list of all sections in the document.
* @return the content of a section
* @throws XWikiException error when trying to extract section content
*/
private String getContentOfSection10(int sectionNumber) throws XWikiException
{
List<DocumentSection> splitSections = getSections();
int indexEnd = 0;
// get current section
DocumentSection section = splitSections.get(sectionNumber - 1);
int indexStart = section.getSectionIndex();
String sectionLevel = section.getSectionLevel();
// Determine where this section ends, which is at the start of the next section of the
// same or a higher level.
for (int i = sectionNumber; i < splitSections.size(); i++) {
DocumentSection nextSection = splitSections.get(i);
String nextLevel = nextSection.getSectionLevel();
if (sectionLevel.equals(nextLevel) || sectionLevel.length() > nextLevel.length()) {
indexEnd = nextSection.getSectionIndex();
break;
}
}
String sectionContent = null;
if (indexStart < 0) {
indexStart = 0;
}
if (indexEnd == 0) {
sectionContent = getContent().substring(indexStart);
} else {
sectionContent = getContent().substring(indexStart, indexEnd);
}
return sectionContent;
}
/**
* Update a section content in document.
*
* @param sectionNumber the index (starting at 1) of the section in the list of all sections in the document.
* @param newSectionContent the new section content.
* @return the new document content.
* @throws XWikiException error when updating content
*/
public String updateDocumentSection(int sectionNumber, String newSectionContent) throws XWikiException
{
String content;
if (is10Syntax()) {
content = updateDocumentSection10(sectionNumber, newSectionContent);
} else {
// Get the current section block
HeaderBlock header = getFilteredHeaders().get(sectionNumber - 1);
XDOM xdom = (XDOM) header.getRoot();
// newSectionContent -> Blocks
List<Block> blocks = parseContent(newSectionContent).getChildren();
int sectionLevel = header.getLevel().getAsInt();
for (int level = 1; level < sectionLevel && blocks.size() == 1 && blocks.get(0) instanceof SectionBlock; ++level) {
blocks = blocks.get(0).getChildren();
}
// replace old current SectionBlock with new Blocks
Block section = header.getSection();
section.getParent().replaceChild(blocks, section);
// render back XDOM to document's content syntax
content = renderXDOM(xdom, getSyntax());
}
return content;
}
/**
* Update a section content in document.
*
* @param sectionNumber the index (+1) of the section in the list of all sections in the document.
* @param newSectionContent the new section content.
* @return the new document content.
* @throws XWikiException error when updating document content with section content
*/
private String updateDocumentSection10(int sectionNumber, String newSectionContent) throws XWikiException
{
StringBuffer newContent = new StringBuffer();
// get document section that will be edited
DocumentSection docSection = getDocumentSection(sectionNumber);
int numberOfSections = getSections().size();
int indexSection = docSection.getSectionIndex();
if (numberOfSections == 1) {
// there is only a sections in document
String contentBegin = getContent().substring(0, indexSection);
newContent = newContent.append(contentBegin).append(newSectionContent);
return newContent.toString();
} else if (sectionNumber == numberOfSections) {
// edit lastest section that doesn't contain subtitle
String contentBegin = getContent().substring(0, indexSection);
newContent = newContent.append(contentBegin).append(newSectionContent);
return newContent.toString();
} else {
String sectionLevel = docSection.getSectionLevel();
int nextSectionIndex = 0;
// get index of next section
for (int i = sectionNumber; i < numberOfSections; i++) {
DocumentSection nextSection = getDocumentSection(i + 1); // get next section
String nextSectionLevel = nextSection.getSectionLevel();
if (sectionLevel.equals(nextSectionLevel)) {
nextSectionIndex = nextSection.getSectionIndex();
break;
} else if (sectionLevel.length() > nextSectionLevel.length()) {
nextSectionIndex = nextSection.getSectionIndex();
break;
}
}
if (nextSectionIndex == 0) {// edit the last section
newContent = newContent.append(getContent().substring(0, indexSection)).append(newSectionContent);
return newContent.toString();
} else {
String contentAfter = getContent().substring(nextSectionIndex);
String contentBegin = getContent().substring(0, indexSection);
newContent = newContent.append(contentBegin).append(newSectionContent).append(contentAfter);
}
return newContent.toString();
}
}
/**
* Computes a document hash, taking into account all document data: content, objects, attachments, metadata... TODO:
* cache the hash value, update only on modification.
*/
public String getVersionHashCode(XWikiContext context)
{
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException ex) {
LOG.error("Cannot create MD5 object", ex);
return hashCode() + "";
}
try {
String valueBeforeMD5 = toXML(true, false, true, false, context);
md5.update(valueBeforeMD5.getBytes());
byte[] array = md5.digest();
StringBuffer sb = new StringBuffer();
for (int j = 0; j < array.length; ++j) {
int b = array[j] & 0xFF;
if (b < 0x10) {
sb.append('0');
}
sb.append(Integer.toHexString(b));
}
return sb.toString();
} catch (Exception ex) {
LOG.error("Exception while computing document hash", ex);
}
return hashCode() + "";
}
public static String getInternalPropertyName(String propname, XWikiContext context)
{
XWikiMessageTool msg = context.getMessageTool();
String cpropname = StringUtils.capitalize(propname);
return (msg == null) ? cpropname : msg.get(cpropname);
}
public String getInternalProperty(String propname)
{
String methodName = "get" + StringUtils.capitalize(propname);
try {
Method method = getClass().getDeclaredMethod(methodName, (Class[]) null);
return (String) method.invoke(this, (Object[]) null);
} catch (Exception e) {
return null;
}
}
public String getCustomClass()
{
if (this.customClass == null) {
return "";
}
return this.customClass;
}
public void setCustomClass(String customClass)
{
this.customClass = customClass;
setMetaDataDirty(true);
}
public void setValidationScript(String validationScript)
{
this.validationScript = validationScript;
setMetaDataDirty(true);
}
public String getValidationScript()
{
if (this.validationScript == null) {
return "";
} else {
return this.validationScript;
}
}
public String getComment()
{
if (this.comment == null) {
return "";
}
return this.comment;
}
public void setComment(String comment)
{
this.comment = comment;
}
public boolean isMinorEdit()
{
return this.isMinorEdit;
}
public void setMinorEdit(boolean isMinor)
{
this.isMinorEdit = isMinor;
}
// methods for easy table update. It is need only for hibernate.
// when hibernate update old database without minorEdit field, hibernate will create field with
// null in despite of notnull in hbm.
// so minorEdit will be null for old documents. But hibernate can't convert null to boolean.
// so we need convert Boolean to boolean
protected Boolean getMinorEdit1()
{
return Boolean.valueOf(isMinorEdit());
}
protected void setMinorEdit1(Boolean isMinor)
{
this.isMinorEdit = (isMinor != null && isMinor.booleanValue());
}
/**
* @since 2.2.3
*/
public BaseObject newXObject(EntityReference classReference, XWikiContext context) throws XWikiException
{
int nb = createXObject(classReference, context);
return getXObject(resolveClassReference(classReference), nb);
}
/**
* @deprecated since 2.2M2 use {@link #newXObject(EntityReference, XWikiContext)}
*/
@Deprecated
public BaseObject newObject(String className, XWikiContext context) throws XWikiException
{
return newXObject(
this.xClassEntityReferenceResolver.resolve(className, EntityType.DOCUMENT, getDocumentReference()), context);
}
/**
* @since 2.2M2
*/
public BaseObject getXObject(DocumentReference classReference, boolean create, XWikiContext context)
{
try {
BaseObject obj = getXObject(classReference);
if ((obj == null) && create) {
return newXObject(classReference, context);
}
if (obj == null) {
return null;
} else {
return obj;
}
} catch (Exception e) {
return null;
}
}
/**
* @deprecated since 2.2M2 use {@link #getXObject(DocumentReference, boolean, XWikiContext)}
*/
@Deprecated
public BaseObject getObject(String className, boolean create, XWikiContext context)
{
return getXObject(resolveClassReference(className), create, context);
}
public boolean validate(XWikiContext context) throws XWikiException
{
return validate(null, context);
}
public boolean validate(String[] classNames, XWikiContext context) throws XWikiException
{
boolean isValid = true;
if ((classNames == null) || (classNames.length == 0)) {
for (DocumentReference classReference : getXObjects().keySet()) {
BaseClass bclass = context.getWiki().getXClass(classReference, context);
List<BaseObject> objects = getXObjects(classReference);
for (BaseObject obj : objects) {
if (obj != null) {
isValid &= bclass.validateObject(obj, context);
}
}
}
} else {
for (int i = 0; i < classNames.length; i++) {
List<BaseObject> objects =
getXObjects(this.currentMixedDocumentReferenceResolver.resolve(classNames[i]));
if (objects != null) {
for (BaseObject obj : objects) {
if (obj != null) {
BaseClass bclass = obj.getXClass(context);
isValid &= bclass.validateObject(obj, context);
}
}
}
}
}
String validationScript = "";
XWikiRequest req = context.getRequest();
if (req != null) {
validationScript = req.get("xvalidation");
}
if ((validationScript == null) || (validationScript.trim().equals(""))) {
validationScript = getValidationScript();
}
if ((validationScript != null) && (!validationScript.trim().equals(""))) {
isValid &= executeValidationScript(context, validationScript);
}
return isValid;
}
public static void backupContext(Map<String, Object> backup, XWikiContext context)
{
backup.put("doc", context.getDoc());
VelocityManager velocityManager = Utils.getComponent(VelocityManager.class);
VelocityContext vcontext = velocityManager.getVelocityContext();
if (vcontext != null) {
backup.put("vdoc", vcontext.get("doc"));
backup.put("vcdoc", vcontext.get("cdoc"));
backup.put("vtdoc", vcontext.get("tdoc"));
}
Map gcontext = (Map) context.get("gcontext");
if (gcontext != null) {
backup.put("gdoc", gcontext.get("doc"));
backup.put("gcdoc", gcontext.get("cdoc"));
backup.put("gtdoc", gcontext.get("tdoc"));
}
// Clone the Execution Context to provide isolation
Execution execution = Utils.getComponent(Execution.class);
ExecutionContext clonedEc;
try {
clonedEc = Utils.getComponent(ExecutionContextManager.class).clone(execution.getContext());
} catch (ExecutionContextException e) {
throw new RuntimeException("Failed to clone the Execution Context", e);
}
execution.pushContext(clonedEc);
}
public static void restoreContext(Map<String, Object> backup, XWikiContext context)
{
// Restore the Execution Context
Execution execution = Utils.getComponent(Execution.class);
execution.popContext();
Map<String, Object> gcontext = (Map<String, Object>) context.get("gcontext");
if (gcontext != null) {
if (backup.get("gdoc") != null) {
gcontext.put("doc", backup.get("gdoc"));
}
if (backup.get("gcdoc") != null) {
gcontext.put("cdoc", backup.get("gcdoc"));
}
if (backup.get("gtdoc") != null) {
gcontext.put("tdoc", backup.get("gtdoc"));
}
}
VelocityManager velocityManager = Utils.getComponent(VelocityManager.class);
VelocityContext vcontext = velocityManager.getVelocityContext();
if (vcontext != null) {
if (backup.get("vdoc") != null) {
vcontext.put("doc", backup.get("vdoc"));
}
if (backup.get("vcdoc") != null) {
vcontext.put("cdoc", backup.get("vcdoc"));
}
if (backup.get("vtdoc") != null) {
vcontext.put("tdoc", backup.get("vtdoc"));
}
}
if (backup.get("doc") != null) {
context.setDoc((XWikiDocument) backup.get("doc"));
}
}
public void setAsContextDoc(XWikiContext context)
{
try {
context.setDoc(this);
com.xpn.xwiki.api.Document apidoc = newDocument(context);
com.xpn.xwiki.api.Document tdoc = apidoc.getTranslatedDocument();
VelocityManager velocityManager = Utils.getComponent(VelocityManager.class);
VelocityContext vcontext = velocityManager.getVelocityContext();
Map<String, Object> gcontext = (Map<String, Object>) context.get("gcontext");
if (vcontext != null) {
vcontext.put("doc", apidoc);
vcontext.put("tdoc", tdoc);
}
if (gcontext != null) {
gcontext.put("doc", apidoc);
gcontext.put("tdoc", tdoc);
}
} catch (XWikiException ex) {
LOG.warn("Unhandled exception setting context", ex);
}
}
/**
* @return the String representation of the previous version of this document or null if this is the first version.
*/
public String getPreviousVersion()
{
XWikiDocumentArchive archive = loadDocumentArchive();
if (archive != null) {
Version prevVersion = archive.getPrevVersion(getRCSVersion());
if (prevVersion != null) {
return prevVersion.toString();
}
}
return null;
}
@Override
public String toString()
{
return getFullName();
}
/**
* Indicates whether the document should be 'hidden' or not, meaning that it should not be returned in public search
* results. WARNING: this is a temporary hack until the new data model is designed and implemented. No code should
* rely on or use this property, since it will be replaced with a generic metadata.
*
* @param hidden The new value of the {@link #hidden} property.
*/
public void setHidden(Boolean hidden)
{
if (hidden == null) {
this.hidden = false;
} else {
this.hidden = hidden;
}
}
/**
* Indicates whether the document is 'hidden' or not, meaning that it should not be returned in public search
* results. WARNING: this is a temporary hack until the new data model is designed and implemented. No code should
* rely on or use this property, since it will be replaced with a generic metadata.
*
* @return <code>true</code> if the document is hidden and does not appear among the results of
* {@link com.xpn.xwiki.api.XWiki#searchDocuments(String)}, <code>false</code> otherwise.
*/
public Boolean isHidden()
{
return this.hidden;
}
/**
* Convert the current document content from its current syntax to the new syntax passed as parameter.
*
* @param targetSyntaxId the syntax to convert to (eg "xwiki/2.0", "xhtml/1.0", etc)
* @throws XWikiException if an exception occurred during the conversion process
*/
public void convertSyntax(String targetSyntaxId, XWikiContext context) throws XWikiException
{
try {
convertSyntax(this.syntaxFactory.createSyntaxFromIdString(targetSyntaxId), context);
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_RENDERING, XWikiException.ERROR_XWIKI_UNKNOWN,
"Failed to convert document to syntax [" + targetSyntaxId + "]", e);
}
}
/**
* Convert the current document content from its current syntax to the new syntax passed as parameter.
*
* @param targetSyntax the syntax to convert to (eg "xwiki/2.0", "xhtml/1.0", etc)
* @throws XWikiException if an exception occurred during the conversion process
*/
public void convertSyntax(Syntax targetSyntax, XWikiContext context) throws XWikiException
{
// convert content
setContent(performSyntaxConversion(getContent(), getSyntaxId(), targetSyntax));
// convert objects
Map<DocumentReference, List<BaseObject>> objectsByClass = getXObjects();
for (List<BaseObject> objects : objectsByClass.values()) {
for (BaseObject bobject : objects) {
if (bobject != null) {
BaseClass bclass = bobject.getXClass(context);
for (Object fieldClass : bclass.getProperties()) {
if (fieldClass instanceof TextAreaClass && ((TextAreaClass) fieldClass).isWikiContent()) {
TextAreaClass textAreaClass = (TextAreaClass) fieldClass;
LargeStringProperty field = (LargeStringProperty) bobject.getField(textAreaClass.getName());
if (field != null) {
field.setValue(performSyntaxConversion(field.getValue(), getSyntaxId(), targetSyntax));
}
}
}
}
}
}
// change syntax
setSyntax(targetSyntax);
}
/**
* @return the XDOM conrrexponding to the document's string content.
*/
public XDOM getXDOM()
{
if (this.xdom == null) {
try {
this.xdom = parseContent(getContent());
} catch (XWikiException e) {
LOG.error("Failed to parse document content to XDOM", e);
}
}
return this.xdom.clone();
}
/**
* @return true if the document has a xwiki/1.0 syntax content
*/
public boolean is10Syntax()
{
return is10Syntax(getSyntaxId());
}
/**
* @return true if the document has a xwiki/1.0 syntax content
*/
public boolean is10Syntax(String syntaxId)
{
return XWIKI10_SYNTAXID.equalsIgnoreCase(syntaxId);
}
private void init(DocumentReference reference)
{
// if the passed reference is null consider it points to the default reference
if (reference == null) {
setDocumentReference(Utils.getComponent(DocumentReferenceResolver.class).resolve(""));
} else {
setDocumentReference(reference);
}
this.updateDate = new Date();
this.updateDate.setTime((this.updateDate.getTime() / 1000) * 1000);
this.contentUpdateDate = new Date();
this.contentUpdateDate.setTime((this.contentUpdateDate.getTime() / 1000) * 1000);
this.creationDate = new Date();
this.creationDate.setTime((this.creationDate.getTime() / 1000) * 1000);
this.content = "";
this.format = "";
this.author = "";
this.language = "";
this.defaultLanguage = "";
this.attachmentList = new ArrayList<XWikiAttachment>();
this.customClass = "";
this.comment = "";
// Note: As there's no notion of an Empty document we don't set the original document
// field. Thus getOriginalDocument() may return null.
}
private boolean executeValidationScript(XWikiContext context, String validationScript) throws XWikiException
{
try {
XWikiValidationInterface validObject =
(XWikiValidationInterface) context.getWiki().parseGroovyFromPage(validationScript, context);
return validObject.validateDocument(this, context);
} catch (Throwable e) {
XWikiValidationStatus.addExceptionToContext(getFullName(), "", e, context);
return false;
}
}
/**
* Convert the passed content from the passed syntax to the passed new syntax.
*
* @param content the content to convert
* @param targetSyntax the new syntax after the conversion
* @param txContext the context when Transformation are executed or null if transformation shouldn't be executed
* @return the converted content in the new syntax
* @throws XWikiException if an exception occurred during the conversion process
* @since 2.4M2
*/
private static String performSyntaxConversion(String content, Syntax targetSyntax, TransformationContext txContext)
throws XWikiException
{
try {
XDOM dom = parseContent(txContext.getSyntax().toIdString(), content);
return performSyntaxConversion(dom, targetSyntax, txContext);
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_RENDERING, XWikiException.ERROR_XWIKI_UNKNOWN,
"Failed to convert document to syntax [" + targetSyntax + "]", e);
}
}
/**
* Convert the passed content from the passed syntax to the passed new syntax.
*
* @param content the content to convert
* @param currentSyntaxId the syntax of the current content to convert
* @param targetSyntax the new syntax after the conversion
* @return the converted content in the new syntax
* @throws XWikiException if an exception occurred during the conversion process
* @since 2.4M2
*/
private static String performSyntaxConversion(String content, String currentSyntaxId, Syntax targetSyntax)
throws XWikiException
{
try {
XDOM dom = parseContent(currentSyntaxId, content);
return performSyntaxConversion(dom, targetSyntax, null);
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_RENDERING, XWikiException.ERROR_XWIKI_UNKNOWN,
"Failed to convert document to syntax [" + targetSyntax + "]", e);
}
}
/**
* Convert the passed content from the passed syntax to the passed new syntax.
*
* @param content the XDOM content to convert, the XDOM can be modified during the transformation
* @param targetSyntax the new syntax after the conversion
* @param txContext the context when Transformation are executed or null if transformation shouldn't be executed
* @return the converted content in the new syntax
* @throws XWikiException if an exception occurred during the conversion process
* @since 2.4M2
*/
private static String performSyntaxConversion(XDOM content, Syntax targetSyntax, TransformationContext txContext)
throws XWikiException
{
try {
if (txContext != null) {
// Transform XDOM
TransformationManager transformations = Utils.getComponent(TransformationManager.class);
if (txContext.getXDOM() == null) {
txContext.setXDOM(content);
}
try {
transformations.performTransformations(content, txContext);
} catch (TransformationException te) {
// An error happened during one of the transformations. Since the error has been logged
// continue
// TODO: We should have a visual clue for the user in the future to let him know something
// didn't work as expected.
}
}
// Render XDOM
return renderXDOM(content, targetSyntax);
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_RENDERING, XWikiException.ERROR_XWIKI_UNKNOWN,
"Failed to convert document to syntax [" + targetSyntax + "]", e);
}
}
/**
* Render privided XDOM into content of the provided syntax identifier.
*
* @param content the XDOM content to render
* @param targetSyntax the syntax identifier of the rendered content
* @return the rendered content
* @throws XWikiException if an exception occurred during the rendering process
*/
private static String renderXDOM(XDOM content, Syntax targetSyntax) throws XWikiException
{
try {
BlockRenderer renderer = Utils.getComponent(BlockRenderer.class, targetSyntax.toIdString());
WikiPrinter printer = new DefaultWikiPrinter();
renderer.render(content, printer);
return printer.toString();
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_RENDERING, XWikiException.ERROR_XWIKI_UNKNOWN,
"Failed to render document to syntax [" + targetSyntax + "]", e);
}
}
private XDOM parseContent(String content) throws XWikiException
{
return parseContent(getSyntaxId(), content);
}
private static XDOM parseContent(String syntaxId, String content) throws XWikiException
{
try {
Parser parser = Utils.getComponent(Parser.class, syntaxId);
return parser.parse(new StringReader(content));
} catch (ParseException e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_RENDERING, XWikiException.ERROR_XWIKI_UNKNOWN,
"Failed to parse content of syntax [" + syntaxId + "]", e);
}
}
private Syntax getDefaultDocumentSyntax()
{
// If there's no parser available for the specified syntax default to XWiki 2.0 syntax
Syntax syntax = Utils.getComponent(CoreConfiguration.class).getDefaultDocumentSyntax();
try {
Utils.getComponent(Parser.class, syntax.toIdString());
} catch (Exception e) {
LOG.warn("Failed to find parser for the default syntax [" + syntax.toIdString()
+ "]. Defaulting to xwiki/2.0 syntax.");
syntax = Syntax.XWIKI_2_0;
}
return syntax;
}
private String serializeReference(DocumentReference reference, EntityReferenceSerializer<String> serializer,
DocumentReference defaultReference)
{
XWikiContext xcontext = getXWikiContext();
String originalWikiName = xcontext.getDatabase();
XWikiDocument originalCurentDocument = xcontext.getDoc();
try {
xcontext.setDatabase(defaultReference.getWikiReference().getName());
xcontext.setDoc(new XWikiDocument(defaultReference));
return serializer.serialize(reference);
} finally {
xcontext.setDoc(originalCurentDocument);
xcontext.setDatabase(originalWikiName);
}
}
/**
* Backward-compatibility method to use in order to resolve a class reference passed as a String into a
* DocumentReference proper.
*
* @return the resolved class reference but using this document's wiki if the passed String doesn't specify a wiki,
* the "XWiki" space if the passed String doesn't specify a space and this document's page if the passed
* String doesn't specify a page.
*/
public DocumentReference resolveClassReference(String documentName)
{
DocumentReference defaultReference =
new DocumentReference(getDocumentReference().getWikiReference().getName(), "XWiki", getDocumentReference()
.getName());
return this.explicitDocumentReferenceResolver.resolve(documentName, defaultReference);
}
/**
* Transforms a XClass reference relative to this document into an absolute reference.
*/
private DocumentReference resolveClassReference(EntityReference reference)
{
DocumentReference defaultReference =
new DocumentReference(getDocumentReference().getWikiReference().getName(), "XWiki", getDocumentReference()
.getName());
return this.explicitReferenceDocumentReferenceResolver.resolve(reference, defaultReference);
}
/**
* @return the relative parent reference, this method should stay private since this the relative saving of the
* parent reference is an implementation detail and from the outside we should only see absolute references
* @since 2.2.3
*/
protected EntityReference getRelativeParentReference()
{
return this.parentReference;
}
private BaseObject prepareXObject(EntityReference classReference)
{
DocumentReference absoluteClassReference = resolveClassReference(classReference);
BaseObject bobject = getXObject(absoluteClassReference);
if (bobject == null) {
bobject = new BaseObject();
bobject.setXClassReference(classReference);
addXObject(bobject);
}
bobject.setDocumentReference(getDocumentReference());
setContentDirty(true);
return bobject;
}
} |
package org.mule.transport;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.mule.DefaultMuleMessage;
import org.mule.api.MuleEvent;
import org.mule.api.MuleEventContext;
import org.mule.api.MuleMessage;
import org.mule.api.transport.PropertyScope;
import org.mule.construct.Flow;
import org.mule.module.client.MuleClient;
import org.mule.tck.functional.EventCallback;
import org.mule.tck.functional.FunctionalTestComponent;
import org.mule.tck.junit4.FunctionalTestCase;
import org.mule.tck.junit4.rule.DynamicPort;
import org.mule.tck.junit4.rule.FreePortFinder;
import org.mule.util.ArrayUtils;
import org.mule.util.concurrent.Latch;
import org.zeromq.ZMQ;
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 static org.junit.Assert.*;
public class ZeroMQTransportTest extends FunctionalTestCase implements EventCallback {
private static final int CONNECT_WAIT = 1000;
@Rule
public DynamicPort requestResponseOnInboundBindFlowPort = new DynamicPort("requestresponse.oninbound.bind.flow.port");
@Rule
public DynamicPort requestResponseOnInboundConnectFlowPort = new DynamicPort("requestresponse.oninbound.connect.flow.port");
@Rule
public DynamicPort subscribeOnInboundNoFilterFlowPort = new DynamicPort("subscribe.oninbound.nofilter.flow.port");
@Rule
public DynamicPort subscribeOnInboundFilterFlowPort = new DynamicPort("subscribe.oninbound.filter.flow.port");
@Rule
public DynamicPort pullOnInboundBindFlowPort = new DynamicPort("pull.oninbound.bind.flow.port");
@Rule
public DynamicPort pullOnInboundConnectFlowPort = new DynamicPort("pull.oninbound.connect.flow.port");
@Rule
public DynamicPort requestResponseOnOutboundBindFlowPort = new DynamicPort("requestresponse.onoutbound.bind.flow.port");
@Rule
public DynamicPort subscribeOnOutboundNoFilterFlowPort = new DynamicPort("subscribe.onoutbound.nofilter.flow.port");
@Rule
public DynamicPort subscribeOnOutboundFilterFlowPort = new DynamicPort("subscribe.onoutbound.filter.flow.port");
@Rule
public DynamicPort requestResponseOnOutboundConnectFlowPort = new DynamicPort("requestresponse.onoutbound.connect.flow.port");
@Rule
public DynamicPort publishFlowSubscriber1Port = new DynamicPort("publish.flow.subscriber1.port");
@Rule
public DynamicPort publishFlowSubscriber2Port = new DynamicPort("publish.flow.subscriber2.port");
@Rule
public DynamicPort pullOnOutboundBindFlowPort = new DynamicPort("pull.onoutbound.bind.flow.port");
@Rule
public DynamicPort pushBindFlowPort = new DynamicPort("push.bind.flow.port");
@Rule
public DynamicPort pullOnOutboundConnectFlowPort = new DynamicPort("pull.onoutbound.connect.flow.port");
@Rule
public DynamicPort pushConnectFlowPort = new DynamicPort("push.connect.flow.port");
@Rule
public DynamicPort pollSubscriberFlowPort = new DynamicPort("poll.subscriber.flow.port");
@Rule
public DynamicPort pollPullFlowPort = new DynamicPort("poll.pull.flow.port");
@Rule
public DynamicPort multiPartMessageOnInboundFlowPort = new DynamicPort("multipartmessage.oninbound.flow.port");
@Rule
public DynamicPort multiPartMessageOnOutboundFlowPort = new DynamicPort("multipartmessage.onoutbound.flow.port");
private static ZMQ.Context zmqContext;
@Override
protected String getConfigResources() {
return "mule-config.xml";
}
public ZeroMQTransportTest() {
this.setDisposeContextPerClass(true);
}
@BeforeClass
public static void oneTimeSetUp() {
zmqContext = ZMQ.context(1);
}
@AfterClass
public static void oneTimeTearDown() {
zmqContext.term();
}
@Test
public void testMultiPartMessageOnOutbound() throws Exception {
MuleClient client = new MuleClient(muleContext);
List messageParts = new ArrayList<String>();
messageParts.add("The quick brown fox ");
messageParts.add("jumps over the lazy dog");
client.dispatch("vm://multipartmessage.onoutbound", new DefaultMuleMessage(messageParts, muleContext));
ZMQ.Socket zmqSocket = zmqContext.socket(ZMQ.REP);
zmqSocket.setReceiveTimeOut(RECEIVE_TIMEOUT);
zmqSocket.connect("tcp://localhost:" + multiPartMessageOnOutboundFlowPort.getNumber());
byte[] firstPart = zmqSocket.recv(0);
assertNotNull(firstPart);
assertEquals("The quick brown fox ", new String(firstPart));
assertTrue(zmqSocket.hasReceiveMore());
byte[] secondPart = zmqSocket.recv(0);
assertNotNull(firstPart);
assertEquals("jumps over the lazy dog", new String(secondPart));
assertFalse(zmqSocket.hasReceiveMore());
zmqSocket.close();
}
@Test
public void testMultiPartMessageOnInbound() throws Exception {
MuleClient client = new MuleClient(muleContext);
ZMQ.Socket zmqSocket = zmqContext.socket(ZMQ.REQ);
zmqSocket.connect("tcp://localhost:" + multiPartMessageOnInboundFlowPort.getNumber());
zmqSocket.send("The quick brown fox ".getBytes(), ZMQ.SNDMORE);
zmqSocket.send("jumps over the lazy dog".getBytes(), 0);
zmqSocket.close();
MuleMessage subscribeMessage = client.request("vm://multipartmessage.oninbound", RECEIVE_TIMEOUT);
assertTrue(subscribeMessage.getPayload() instanceof List);
List<byte[]> messageParts = (List<byte[]>) subscribeMessage.getPayload();
assertEquals("The quick brown fox ", new String(messageParts.get(0)));
assertEquals("jumps over the lazy dog", new String(messageParts.get(1)));
}
@Test
public void testPoll() throws Exception {
MuleClient client = new MuleClient(muleContext);
ZMQ.Socket zmqSocket = zmqContext.socket(ZMQ.PUB); |
package fi.laverca.samples;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.LinkedList;
import javax.swing.JFileChooser;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bouncycastle.util.encoders.Base64;
import org.etsi.uri.TS102204.v1_1_2.Service;
import fi.laverca.FiComAdditionalServices;
import fi.laverca.FiComAdditionalServices.PersonIdAttribute;
import fi.laverca.FiComClient;
import fi.laverca.FiComRequest;
import fi.laverca.FiComResponse;
import fi.laverca.FiComResponseHandler;
import fi.laverca.JvmSsl;
public class SignData {
private static final Log log = LogFactory.getLog(SignData.class);
private static FiComRequest req;
/**
* Connects to MSSP using SSL and waits for response.
* @param phoneNumber
* @param selectedFile
*/
private static void estamblishConnection(String phoneNumber, final File selectedFile) {
log.info("setting up ssl");
JvmSsl.setSSL("etc/laverca-truststore",
"changeit",
"etc/laverca-keystore",
"changeit",
"JKS");
String apId = "http://laverca-eval.fi";
String apPwd = "pfkpfk";
String aeMsspIdUri = "http://dev-ae.mssp.dna.fi";
//TODO: TeliaSonera
//TODO: Elisa
String msspSignatureUrl = "https://dev-ae.mssp.dna.fi/soap/services/MSS_SignaturePort";
String msspStatusUrl = "https://dev-ae.mssp.dna.fi/soap/services/MSS_StatusQueryPort";
String msspReceiptUrl = "https://dev-ae.mssp.dna.fi/soap/services/MSS_ReceiptPort";
log.info("creating FiComClient");
FiComClient fiComClient = new FiComClient(apId,
apPwd,
aeMsspIdUri,
msspSignatureUrl,
msspStatusUrl,
msspReceiptUrl);
final byte[] output = generateSHA1(selectedFile);
String apTransId = "A"+System.currentTimeMillis();
Service noSpamService = FiComAdditionalServices.createNoSpamService("A12", false);
LinkedList<Service> additionalServices = new LinkedList<Service>();
LinkedList<String> attributeNames = new LinkedList<String>();
attributeNames.add(FiComAdditionalServices.PERSON_ID_VALIDUNTIL);
Service personIdService = FiComAdditionalServices.createPersonIdService(attributeNames);
additionalServices.add(personIdService);
try {
log.info("calling signData");
req =
fiComClient.signData(apTransId,
output,
phoneNumber,
noSpamService,
additionalServices,
new FiComResponseHandler() {
@Override
public void onResponse(FiComRequest req, FiComResponse resp) {
log.info("got resp");
printSHA1(output);
responseBox.setText("File path: " + selectedFile.getAbsolutePath()
+ "\n" + responseBox.getText());
try {
responseBox.setText("MSS Signature: " +
new String(Base64.encode(resp.getMSS_StatusResp().
getMSS_Signature().getBase64Signature()), "ASCII") +
"\nSigner: " + resp.getPkcs7Signature().getSignerCn() +
"\n" + responseBox.getText());
for(PersonIdAttribute a : resp.getPersonIdAttributes()) {
log.info(a.getName() + " " + a.getStringValue());
responseBox.setText(a.getStringValue() + "\n" + responseBox.getText());
}
} catch (UnsupportedEncodingException e) {
log.info("Unsupported encoding", e);
} catch (NullPointerException e){
log.info("PersonIDAttributes = null", e);
}
}
@Override
public void onError(FiComRequest req, Throwable throwable) {
log.info("got error", throwable);
}
});
}
catch (IOException e) {
log.info("error establishing connection", e);
}
fiComClient.shutdown();
}
/**
* Generates SHA1 hash from a file and asks for a user to sign it.
* @param args
*/
public static void main(String[] args) {
initUI();
}
/**
*
* @param selectedFile
* @return
*/
public static byte[] generateSHA1(final File selectedFile) {
byte[] output = null;
try {
InputStream is = new FileInputStream(selectedFile);
byte[] buffer = new byte[1024];
MessageDigest md = MessageDigest.getInstance("SHA1");
int numRead;
do {
numRead = is.read(buffer);
if (numRead > 0) {
md.update(buffer, 0, numRead);
}
} while (numRead != -1);
output = md.digest();
} catch (NoSuchAlgorithmException e) {
log.info("error finding algorithm", e);
} catch (FileNotFoundException e) {
log.info("error finding file", e);
} catch (IOException e) {
log.info("i/o error", e);
}
return output;
}
/**
* Prints SHA1 to the <code>responseBox</code>.
* @param buf
*/
public static void printSHA1(byte[] buf) {
Formatter formatter = new Formatter();
for (byte b : buf)
formatter.format("%02x", b);
// Cuts first 8 characters of the hash.
String sha1 = formatter.toString().substring(8).toUpperCase();
String shaTmp = new String();
for (int i = 0; i < sha1.length()/4; i++){
shaTmp += " " + sha1.substring(i*4, i*4+4);
}
hashBox.setText("SHA1: " + shaTmp + "\n" + hashBox.getText());
}
private static void initUI() {
dialFrame = new javax.swing.JFrame();
dialPanel = new javax.swing.JPanel();
lblNumber = new javax.swing.JLabel();
number = new javax.swing.JTextField();
sendButton = new javax.swing.JButton();
browseButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
hashBox = new javax.swing.JTextArea();
dialFrame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
dialFrame.setVisible(true);
final JFileChooser fc = new JFileChooser();
browseButton.setText("Browse...");
browseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fc.showOpenDialog(dialFrame);
}
});
dialFrame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
dialFrame.setVisible(true);
lblNumber.setText("Phone number");
number.setText("+35847001001");
sendButton.setText("Send");
sendButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
initResponse();
estamblishConnection(number.getText(), fc.getSelectedFile());
}
});
hashBox.setColumns(20);
hashBox.setRows(5);
jScrollPane1.setViewportView(hashBox);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(dialPanel);
dialPanel.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(lblNumber)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(sendButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(browseButton))
.addComponent(number, javax.swing.GroupLayout.DEFAULT_SIZE, 248, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 306, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(77, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(lblNumber)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(number, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(sendButton)
.addComponent(browseButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(144, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(dialFrame.getContentPane());
dialFrame.getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(dialPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(dialPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
dialFrame.pack();
fc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
printSHA1(generateSHA1(fc.getSelectedFile()));
}
});
fc.showOpenDialog(dialFrame);
}
private static void initResponse() {
responseFrame = new javax.swing.JFrame();
cancelButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
responseBox = new javax.swing.JTextArea();
callStateProgressBar = new javax.swing.JProgressBar();
responseFrame.setVisible(true);
responseFrame.setResizable(false);
cancelButton.setText("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
req.cancel();
}
});
responseBox.setColumns(20);
responseBox.setRows(5);
jScrollPane1.setViewportView(responseBox);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(responseFrame.getContentPane());
responseFrame.getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(callStateProgressBar, javax.swing.GroupLayout.PREFERRED_SIZE, 252, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(cancelButton)
.addContainerGap(47, Short.MAX_VALUE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(13, 13, 13)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 373, Short.MAX_VALUE)
.addGap(14, 14, 14)))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(callStateProgressBar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 23, Short.MAX_VALUE)
.addComponent(cancelButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(266, 266, 266))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(53, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(21, 21, 21)))
);
responseFrame.pack();
}
private static javax.swing.JFrame dialFrame;
private static javax.swing.JFrame responseFrame;
private static javax.swing.JButton sendButton;
private static javax.swing.JButton cancelButton;
private static javax.swing.JButton browseButton;
private static javax.swing.JLabel lblNumber;
private static javax.swing.JPanel dialPanel;
private static javax.swing.JProgressBar callStateProgressBar;
private static javax.swing.JScrollPane jScrollPane1;
private static javax.swing.JTextArea responseBox;
private static javax.swing.JTextArea hashBox;
private static javax.swing.JTextField number;
} |
package to.etc.domui.state;
import java.util.*;
import to.etc.domui.dom.errors.*;
import to.etc.domui.dom.html.*;
import to.etc.domui.util.*;
final public class UIGoto {
static public final String SINGLESHOT_MESSAGE = "uigoto.msgs";
private UIGoto() {}
static private WindowSession context() {
return PageContext.getRequestContext().getWindowSession();
}
/**
* Destroy the current page and reload the exact same page with the same parameters as a
* new one. This has the effect of fully refreshing all data, and reinitializing the page
* at it's initial state.
*/
static public void reload() {
Page pg = PageContext.getCurrentPage();
Class< ? extends UrlPage> clz = pg.getBody().getClass();
PageParameters pp = pg.getPageParameters();
pg.getConversation().destroy();
context().internalSetNextPage(MoveMode.REPLACE, clz, null, null, pp);
}
/**
* Push (shelve) the current page, then move to a new page. The page is parameterless, and is started in a NEW ConversationContext.
* @param clz
*/
static public void moveSub(final Class< ? extends UrlPage> clz) {
if(clz == null)
throw new IllegalArgumentException("The class to move-to cannot be null");
context().internalSetNextPage(MoveMode.SUB, clz, null, null, null);
}
/**
* Push (shelve) the current page, then move to a new page. The page is started in a NEW ConversationContext.
*
* @param clz
* @param pp
*/
static public void moveSub(final Class< ? extends UrlPage> clz, final PageParameters pp) {
if(clz == null)
throw new IllegalArgumentException("The class to move-to cannot be null");
context().internalSetNextPage(MoveMode.SUB, clz, null, null, pp);
}
/**
* Push (shelve) the current page, then move to a new page. The page is started in a NEW ConversationContext.
*
* @param clz
* @param param A list of parameters, in {@link PageParameters#addParameters(Object...)} format.
*/
static public void moveSub(final Class< ? extends UrlPage> clz, final Object... param) {
if(clz == null)
throw new IllegalArgumentException("The class to move-to cannot be null");
PageParameters pp;
if(param == null || param.length == 0)
pp = null;
else
pp = new PageParameters(param);
context().internalSetNextPage(MoveMode.SUB, clz, null, null, pp);
}
/**
* Push (shelve) the current page, then move to a new page. The page JOINS the conversation context passed; if the page does not accept
* that conversation an exception is thrown.
*
* @param clz
* @param cc
* @param pp
*/
static public void moveSub(final Class< ? extends UrlPage> clz, final ConversationContext cc, final PageParameters pp) {
if(clz == null)
throw new IllegalArgumentException("The class to move-to cannot be null");
if(cc == null)
throw new IllegalArgumentException("The conversation to join with cannot be null");
context().internalSetNextPage(MoveMode.SUB, clz, cc, null, pp);
}
/**
* Clear the entire shelf, then goto a new page. The page uses a NEW ConversationContext.
*
* @param clz
* @param pp
*/
static public void moveNew(final Class< ? extends UrlPage> clz, final PageParameters pp) {
if(clz == null)
throw new IllegalArgumentException("The class to move-to cannot be null");
context().internalSetNextPage(MoveMode.NEW, clz, null, null, pp);
}
/**
* Clear the entire shelf, then goto a new page. The page uses a NEW ConversationContext.
*
* @param clz
* @param param A list of parameters, in {@link PageParameters#addParameters(Object...)} format.
*/
static public void moveNew(final Class< ? extends UrlPage> clz, Object... param) {
if(clz == null)
throw new IllegalArgumentException("The class to move-to cannot be null");
PageParameters pp;
if(param == null || param.length == 0)
pp = null;
else
pp = new PageParameters(param);
context().internalSetNextPage(MoveMode.NEW, clz, null, null, pp);
}
/**
* Clear the entire shelve, then goto a new page. The page uses a NEW ConversationContext.
* @param clz
*/
static public void moveNew(final Class< ? extends UrlPage> clz) {
if(clz == null)
throw new IllegalArgumentException("The class to move-to cannot be null");
context().internalSetNextPage(MoveMode.NEW, clz, null, null, null);
}
/**
* Replace the "current" page with a new page. The current page is destroyed; the shelve stack is not changed.
* @param clz
*/
static public void replace(final Class< ? extends UrlPage> clz) {
if(clz == null)
throw new IllegalArgumentException("The class to move-to cannot be null");
context().internalSetNextPage(MoveMode.REPLACE, clz, null, null, null);
}
/**
* Replace the "current" page with a new page. The current page is destroyed; the shelve stack is not changed.
* @param clz
* @param pp
*/
static public void replace(final Class< ? extends UrlPage> clz, final PageParameters pp) {
if(clz == null)
throw new IllegalArgumentException("The class to move-to cannot be null");
context().internalSetNextPage(MoveMode.REPLACE, clz, null, null, pp);
}
/**
* Replace the "current" page with a new page. The current page is destroyed; the shelve stack is not changed.
* On the new page show the specified message as an UI message.
* @param pg
* @param clz
* @param pp
* @param msg
*/
static public final void replace(Page pg, final Class< ? extends UrlPage> clz, final PageParameters pp, UIMessage msg) {
if(clz == null)
throw new IllegalArgumentException("The class to move-to cannot be null");
List<UIMessage> msgl = new ArrayList<UIMessage>(1);
msgl.add(msg);
WindowSession ws = pg.getConversation().getWindowSession();
ws.setAttribute(UIGoto.SINGLESHOT_MESSAGE, msgl);
context().internalSetNextPage(MoveMode.REPLACE, clz, null, null, pp);
}
static public void redirect(final String targeturl) {
context().internalSetRedirect(targeturl);
}
/**
* Move to the previously-shelved page. That page is UNSHELVED and activated. If the shelve is
* EMPTY when this call is made the application moves back to the HOME page.
*/
static public void back() {
context().internalSetNextPage(MoveMode.BACK, null, null, null, null);
}
/**
* Destroy the current page and replace it with the new page specified. On the new page show the specified
* message as an ERROR message.
*
* @param pg
* @param msg
*/
static public final void clearPageAndReload(Page pg, String msg) {
clearPageAndReload(pg, pg.getBody().getClass(), pg.getPageParameters(), msg);
}
/**
* Destroy the current page and replace it with the new page specified. On the new page show the specified
* message as an ERROR message.
*
* @param pg
* @param target
* @param pp
* @param msg
*/
static public final void clearPageAndReload(Page pg, Class< ? extends UrlPage> target, PageParameters pp, String msg) {
clearPageAndReload(pg, UIMessage.error(Msgs.BUNDLE, Msgs.S_PAGE_CLEARED, msg), pp);
}
/**
* Destroy the current page and replace it with the new page specified. On the new page show the specified
* message.
*
* @param pg
* @param msg
*/
static public final void clearPageAndReload(Page pg, UIMessage msg) {
clearPageAndReload(pg, msg, pg.getPageParameters());
}
/**
* Destroy the current page and replace it with the new page specified. On the new page show the specified
* message.
*
* @param pg
* @param msg
* @param pp
*/
static public final void clearPageAndReload(Page pg, UIMessage msg, PageParameters pp) {
WindowSession ws = pg.getConversation().getWindowSession();
List<UIMessage> msgl = new ArrayList<UIMessage>(1);
msgl.add(msg);
ws.setAttribute(UIGoto.SINGLESHOT_MESSAGE, msgl);
pg.getConversation().destroy();
replace(pg.getBody().getClass(), pp);
}
} |
package org.openremote.security;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.testng.Assert;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.Test;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyStore;
import java.security.Provider;
import java.security.Security;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* Unit tests for shared implementation in abstract {@link org.openremote.security.KeyManager}
* class.
*
* @author <a href="mailto:juha@openremote.org">Juha Lindfors</a>
*/
public class KeyManagerTest
{
// TODO : test loading zero file behavior
// TODO : test saving with non-ascii password
@AfterSuite public void clearSecurityProvider()
{
Provider p = Security.getProvider("BC");
if (p != null)
{
Assert.fail("Tests did not properly remove BouncyCastle provider.");
}
}
/**
* Very basic test runs on StorageType enum to ensure implementation consistency.
*/
@Test public void testStorageTypes()
{
Assert.assertTrue(
KeyManager.Storage.PKCS12.name().equals(KeyManager.Storage.PKCS12.toString())
);
Assert.assertTrue(
KeyManager.Storage.PKCS12.name().equals(KeyManager.Storage.PKCS12.getStorageName())
);
Assert.assertTrue(
KeyManager.Storage.JCEKS.name().equals(KeyManager.Storage.JCEKS.toString())
);
Assert.assertTrue(
KeyManager.Storage.JCEKS.name().equals(KeyManager.Storage.JCEKS.getStorageName())
);
Assert.assertTrue(
KeyManager.Storage.BKS.name().equals(KeyManager.Storage.BKS.toString())
);
Assert.assertTrue(
KeyManager.Storage.BKS.name().equals(KeyManager.Storage.BKS.getStorageName())
);
}
/**
* Tests keystore save when file descriptor is null.
*
* @throws Exception if test fails
*/
@Test public void testSaveWithNullFile() throws Exception
{
TestKeyManager keyMgr = new TestKeyManager();
char[] storePW = new char[] { 'f', 'o', 'o'};
try
{
keyMgr.save(null, storePW);
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
/**
* Tests storing an empty keystore.
*
* @throws Exception if test fails for any reason
*/
@Test public void testEmptyKeystore() throws Exception
{
TestKeyManager keyMgr = new TestKeyManager();
char[] password = new char[] { 'f', 'o', 'o' };
File dest = File.createTempFile("openremote", "tmp");
dest.deleteOnExit();
keyMgr.save(dest.toURI(), password);
KeyStore keystore = KeyStore.getInstance(KeyManager.DEFAULT_KEYSTORE_STORAGE.getStorageName());
keystore.load(new FileInputStream(dest), new char[] { 'f', 'o', 'o' } );
Assert.assertTrue(keystore.size() == 0);
}
/**
* Tests storing an empty keystore with empty keystore password.
*
* @throws Exception if test fails for any reason
*/
@Test public void testEmptyKeystoreWithEmptyPassword() throws Exception
{
TestKeyManager keyMgr = new TestKeyManager();
try
{
File dest = File.createTempFile("openremote", "tmp");
dest.deleteOnExit();
keyMgr.save(dest.toURI(), new char[] {});
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
/**
* Tests storing an empty keystore with null keystore password.
*
* @throws Exception if test fails for any reason
*/
@Test public void testEmptyKeystoreWithNullPassword() throws Exception
{
TestKeyManager keyMgr = new TestKeyManager();
try
{
File dest = File.createTempFile("openremote", "tmp");
dest.deleteOnExit();
keyMgr.save(dest.toURI(), null);
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
/**
* Test error behavior when file path is incorrectly defined.
*/
@Test public void testSaveWithBrokenFile() throws Exception
{
TestKeyManager mgr = new TestKeyManager();
File f = new File("
char[] pw = new char[] { 'p' };
try
{
mgr.save(f.toURI(), pw);
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
/**
* Test behavior when loading keystore with wrong password.
*
* @throws Exception if test fails
*/
@Test public void testWrongPassword() throws Exception
{
JCEKSStorage ks = new JCEKSStorage();
File f = File.createTempFile("openremote", "tmp");
f.deleteOnExit();
ks.add(
"alias",
new KeyStore.SecretKeyEntry(
new SecretKeySpec(new byte[] {'a'}, "test")
),
new KeyStore.PasswordProtection(new char[] {'b'})
);
char[] password = new char[] { 'f', 'o', 'o' };
ks.save(f.toURI(), password);
try
{
ks.load(f.toURI(), new char[] { 0 });
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
/**
* Tests saving and loading secret keys with BouncyCastle UBER storage.
*
* @throws Exception if test fails
*/
@Test public void testLoadExistingKeyStoreUBER() throws Exception
{
try
{
Security.addProvider(SecurityProvider.BC.getProviderInstance());
UBERStorage mgr = new UBERStorage();
mgr.add(
"test",
new KeyStore.SecretKeyEntry(new SecretKeySpec(new byte[] { 'a' }, "foo")),
new KeyStore.PasswordProtection(new char[] { 'b' })
);
File dir = new File(System.getProperty("user.dir"));
File f = new File(dir, "test.keystore." + UUID.randomUUID());
f.deleteOnExit();
char[] pw = new char[] { '1' };
mgr.save(f.toURI(), pw);
pw = new char[] { '1' };
KeyStore keystore = KeyStore.getInstance(KeyManager.Storage.UBER.getStorageName());
keystore.load(new FileInputStream(f), pw);
KeyStore.SecretKeyEntry entry = (KeyStore.SecretKeyEntry)keystore.getEntry(
"test", new KeyStore.PasswordProtection(new char[] {'b'})
);
Assert.assertTrue(Arrays.equals(entry.getSecretKey().getEncoded(), new byte[] {'a'}));
}
finally
{
Security.removeProvider("BC");
}
}
@Test public void testLoadExistingKeyStoreJCEKS() throws Exception
{
JCEKSStorage mgr = new JCEKSStorage();
mgr.add(
"test",
new KeyStore.SecretKeyEntry(new SecretKeySpec(new byte[] { 'a' }, "foo")),
new KeyStore.PasswordProtection(new char[] { 'b' })
);
File dir = new File(System.getProperty("user.dir"));
File f = new File(dir, "test.keystore." + UUID.randomUUID());
f.deleteOnExit();
char[] pw = new char[] { '1' };
mgr.save(f.toURI(), pw);
pw = new char[] { '1' };
KeyStore keystore = KeyStore.getInstance(KeyManager.Storage.JCEKS.getStorageName());
keystore.load(new FileInputStream(f), pw);
KeyStore.SecretKeyEntry entry = (KeyStore.SecretKeyEntry)keystore.getEntry(
"test", new KeyStore.PasswordProtection(new char[] {'b'})
);
Assert.assertTrue(Arrays.equals(entry.getSecretKey().getEncoded(), new byte[] { 'a' }));
}
/**
* Tests error behavior when null file descriptor is used.
*
* @throws Exception if test fails
*/
@Test public void testLoadingNullFile() throws Exception
{
try
{
Security.addProvider(SecurityProvider.BC.getProviderInstance());
UBERStorage mgr = new UBERStorage();
mgr.add(
"test",
new KeyStore.SecretKeyEntry(new SecretKeySpec(new byte[] {'a'}, "foo")),
new KeyStore.PasswordProtection(new char[] {'b'})
);
char[] pw = new char[] { '1' };
try
{
mgr.load(null, pw);
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
finally
{
Security.removeProvider("BC");
}
}
/**
* Tests the error handling behavior when null password is given.
*
* @throws Exception if test fails
*/
@Test public void testLoadingWithNullPassword() throws Exception
{
try
{
Security.addProvider(SecurityProvider.BC.getProviderInstance());
UBERStorage mgr = new UBERStorage();
mgr.add(
"test",
new KeyStore.SecretKeyEntry(new SecretKeySpec(new byte[] { 'a' }, "foo")),
new KeyStore.PasswordProtection(new char[] { 'b' })
);
File dir = new File(System.getProperty("user.dir"));
File f = new File(dir, "test.keystore." + UUID.randomUUID());
f.deleteOnExit();
try
{
mgr.load(f.toURI(), null);
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
finally
{
Security.removeProvider("BC");
}
}
/**
* Tests load behavior when an existing keystore has been corrupted.
*
* @throws Exception if test fails
*/
@Test public void testCorruptJCEKS() throws Exception
{
JCEKSStorage ks = new JCEKSStorage();
ks.add(
"alias",
new KeyStore.SecretKeyEntry(
new SecretKeySpec(new byte[] { 'a' }, "test")
),
new KeyStore.PasswordProtection(new char[] { 'b' })
);
char[] password = new char[] { 'f', 'o', 'o' };
File dir = new File(System.getProperty("user.dir"));
File f = new File(dir, "test.keystore." + UUID.randomUUID());
f.deleteOnExit();
ks.add(
"foobar",
new KeyStore.SecretKeyEntry(
new SecretKeySpec(new byte[] { 'a' }, "test")
),
new KeyStore.PasswordProtection(new char[] { 'b' })
);
ks.save(f.toURI(), password);
FileOutputStream fout = new FileOutputStream(f);
BufferedOutputStream bout = new BufferedOutputStream(fout);
bout.write("Add some garbage".getBytes());
bout.close();
password = new char[] { 'f', 'o', 'o' };
try
{
ks.load(f.toURI(), password);
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
/**
* Test behavior when a secret key is added to storage that does not
* support them.
*
* @throws Exception if test fails
*/
@Test public void testAddingSecretKeyToPKCS12() throws Exception
{
PKCS12Storage ks = new PKCS12Storage();
try
{
ks.add(
"alias",
new KeyStore.SecretKeyEntry(
new SecretKeySpec(new byte[] { 'a' }, "test")
),
new KeyStore.PasswordProtection(new char[] { 'b' })
);
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
/**
* Tests adding a secret key to JCEKS storage.
*
* @throws Exception if test fails
*/
@Test public void testAddingSecretKeyToJCEKS() throws Exception
{
JCEKSStorage ks = new JCEKSStorage();
ks.add(
"alias",
new KeyStore.SecretKeyEntry(
new SecretKeySpec(new byte[] { 'a' }, "test")
),
new KeyStore.PasswordProtection(new char[] { 'b' })
);
char[] password = new char[] { 'f', 'o', 'o' };
File dest = File.createTempFile("openremote", "tmp");
dest.deleteOnExit();
ks.save(dest.toURI(), password);
}
/**
* Tests adding a secret key to BouncyCastle UBER storage.
*
* @throws Exception if test fails
*/
@Test public void testAddingSecretKeyToUBER() throws Exception
{
// UBER implementation requires "BC" to be available as security provider...
try
{
Security.addProvider(new BouncyCastleProvider());
UBERStorage ks = new UBERStorage();
ks.add(
"alias",
new KeyStore.SecretKeyEntry(
new SecretKeySpec(new byte[] { 'a' }, "test")
),
new KeyStore.PasswordProtection(new char[] { 'b' })
);
char[] password = new char[] { 'f', 'o', 'o' };
File dest = File.createTempFile("openremote", "tmp");
dest.deleteOnExit();
ks.save(dest.toURI(), password);
Assert.assertTrue(ks.getStorageType().getStorageName().equals("UBER"));
}
finally
{
Security.removeProvider("BC");
}
}
/**
* Tests error handling behavior on add() with null alias.
*
* @see KeyManager#add(String, java.security.KeyStore.Entry, java.security.KeyStore.ProtectionParameter)
*/
@Test public void testAddNullAlias()
{
TestKeyManager mgr = new TestKeyManager();
try
{
mgr.add(
null,
new KeyStore.SecretKeyEntry(new SecretKeySpec(new byte[] { 'a' }, "foo")),
new KeyStore.PasswordProtection(new char[] { 'b' })
);
Assert.fail("should not get here...");
}
catch (IllegalArgumentException e)
{
// expected...
}
}
/**
* Tests error handling behavior on add() with empty alias.
*
* @see KeyManager#add(String, java.security.KeyStore.Entry, java.security.KeyStore.ProtectionParameter)
*/
@Test public void testAddEmptyAlias()
{
TestKeyManager mgr = new TestKeyManager();
try
{
mgr.add(
"",
new KeyStore.SecretKeyEntry(new SecretKeySpec(new byte[] { 'a' }, "foo")),
new KeyStore.PasswordProtection(new char[] { 'b' })
);
Assert.fail("should not get here...");
}
catch (IllegalArgumentException e)
{
// expected...
}
}
/**
* Tests error handling behavior on add() with empty alias.
*
* @see KeyManager#add(String, java.security.KeyStore.Entry, java.security.KeyStore.ProtectionParameter)
*/
@Test public void testAddNullEntry()
{
TestKeyManager mgr = new TestKeyManager();
try
{
mgr.add(
"test",
null,
new KeyStore.PasswordProtection(new char[] { 'b' })
);
Assert.fail("should not get here...");
}
catch (IllegalArgumentException e)
{
// expected...
}
}
/**
* Basic test to invoke createKeyStore()
*
* @throws Exception if test fails
*/
@Test public void testCreateKeyStore() throws Exception
{
TestKeyManager mgr = new TestKeyManager();
KeyStore store = mgr.createKeyStore();
Assert.assertTrue(store != null);
}
/**
* Tests saving and loading secret keys with BouncyCastle UBER storage.
*
* @throws Exception if test fails
*/
@Test public void testLoadExistingKeyStoreUBER() throws Exception
{
try
{
Security.addProvider(SecurityProvider.BC.getProviderInstance());
UBERStorage mgr = new UBERStorage();
mgr.add(
"test",
new KeyStore.SecretKeyEntry(new SecretKeySpec(new byte[] { 'a' }, "foo")),
new KeyStore.PasswordProtection(new char[] { 'b' })
);
File dir = new File(System.getProperty("user.dir"));
File f = new File(dir, "test.keystore." + UUID.randomUUID());
f.deleteOnExit();
char[] pw = new char[] { '1' };
mgr.save(f.toURI(), pw);
pw = new char[] { '1' };
KeyStore ks = mgr.load(f.toURI(), pw);
KeyStore.SecretKeyEntry entry =
(KeyStore.SecretKeyEntry)ks.getEntry("test", new KeyStore.PasswordProtection(new char[] {'b'}));
Assert.assertTrue(Arrays.equals(entry.getSecretKey().getEncoded(), new byte[] { 'a' }));
}
finally
{
Security.removeProvider("BC");
}
}
@Test public void testLoadExistingKeyStoreJCEKS() throws Exception
{
JCEKSStorage mgr = new JCEKSStorage();
mgr.add(
"test",
new KeyStore.SecretKeyEntry(new SecretKeySpec(new byte[] { 'a' }, "foo")),
new KeyStore.PasswordProtection(new char[] { 'b' })
);
File dir = new File(System.getProperty("user.dir"));
File f = new File(dir, "test.keystore." + UUID.randomUUID());
f.deleteOnExit();
char[] pw = new char[] { '1' };
mgr.save(f.toURI(), pw);
pw = new char[] { '1' };
KeyStore ks = mgr.load(f.toURI(), pw);
KeyStore.SecretKeyEntry entry =
(KeyStore.SecretKeyEntry)ks.getEntry("test", new KeyStore.PasswordProtection(new char[] {'b'}));
Assert.assertTrue(Arrays.equals(entry.getSecretKey().getEncoded(), new byte[] { 'a' }));
}
/**
* Tests error behavior when null file descriptor is used.
*
* @throws Exception if test fails
*/
@Test public void testLoadingNullFile() throws Exception
{
try
{
Security.addProvider(SecurityProvider.BC.getProviderInstance());
UBERStorage mgr = new UBERStorage();
mgr.add(
"test",
new KeyStore.SecretKeyEntry(new SecretKeySpec(new byte[] {'a'}, "foo")),
new KeyStore.PasswordProtection(new char[] {'b'})
);
char[] pw = new char[] { '1' };
try
{
mgr.load(null, pw);
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
finally
{
Security.removeProvider("BC");
}
}
/**
* Tests the error handling behavior when null password is given.
*
* @throws Exception if test fails
*/
@Test public void testLoadingWithNullPassword() throws Exception
{
try
{
Security.addProvider(SecurityProvider.BC.getProviderInstance());
UBERStorage mgr = new UBERStorage();
mgr.add(
"test",
new KeyStore.SecretKeyEntry(new SecretKeySpec(new byte[] { 'a' }, "foo")),
new KeyStore.PasswordProtection(new char[] { 'b' })
);
File dir = new File(System.getProperty("user.dir"));
File f = new File(dir, "test.keystore." + UUID.randomUUID());
f.deleteOnExit();
try
{
mgr.load(f.toURI(), null);
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
finally
{
Security.removeProvider("BC");
}
}
private static class TestKeyManager extends KeyManager
{
// no op, just to test abstract superclass implementation...
}
private static class JCEKSStorage extends KeyManager
{
private static Provider findJCEKSProvider()
{
Map<String, String> props = new HashMap<String, String>();
props.put("keystore.jceks", "");
Provider[] providers = Security.getProviders(props);
if (providers.length == 0)
{
Assert.fail("Cannot find a security provider for Sun JCEKS");
return null;
}
else
{
return providers[0];
}
}
JCEKSStorage()
{
super(StorageType.JCEKS, findJCEKSProvider());
}
}
/**
* UBER keystorage from BouncyCastle.
*/
private static class UBERStorage extends KeyManager
{
UBERStorage()
{
super(StorageType.UBER, new BouncyCastleProvider());
}
}
/**
* Test KeyManager implementation that attempts to load/create a keystore of a type
* that is not available in the security provider.
*/
private static class UnavailableBKS extends KeyManager
{
UnavailableBKS()
{
super(StorageType.BKS, new EmptyProvider());
}
}
/**
* PKCS12 storage from a default security prover.
*/
private static class PKCS12Storage extends KeyManager
{
PKCS12Storage()
{
super(StorageType.PKCS12, null);
}
}
private static class BrokenStorageManager extends KeyManager
{
BrokenStorageManager()
{
super(null, new BouncyCastleProvider());
}
}
/**
* An empty test security provider used for some test cases.
*/
private static class EmptyProvider extends Provider
{
EmptyProvider()
{
super("Empty Test Provider", 0.0, "Testing");
}
}
} |
package org.psjava.example;
import static org.junit.Assert.*;
import org.junit.Test;
import org.psjava.algo.graph.shortestpath.AllPairShortestPath;
import org.psjava.algo.graph.shortestpath.AllPairShortestPathResult;
import org.psjava.algo.graph.shortestpath.BellmanFord;
import org.psjava.algo.graph.shortestpath.Dijkstra;
import org.psjava.algo.graph.shortestpath.FloydWarshall;
import org.psjava.algo.graph.shortestpath.Johnson;
import org.psjava.algo.graph.shortestpath.SingleSourceShortestPathResult;
import org.psjava.algo.graph.shortestpath.SingleSourceShortestPath;
import org.psjava.ds.graph.MutableDirectedWeightedGraph;
import org.psjava.ds.heap.BinaryHeapFactory;
import org.psjava.goods.GoodSingleSourceShortestPath;
import org.psjava.math.ns.IntegerNumberSystem;
public class ShortestPathExample {
@Test
public void example() {
// Let's construct a graph.
MutableDirectedWeightedGraph<Integer> graph = new MutableDirectedWeightedGraph<Integer>();
graph.insertVertex("A");
graph.insertVertex("B");
graph.insertVertex("C");
graph.insertVertex("D");
graph.addEdge("A", "C", 100);
graph.addEdge("A", "B", 10);
graph.addEdge("B", "C", 20);
// Then calculate distances from a single source - 'A'.
// Choose algorithm, and do it.
SingleSourceShortestPath algorithm1 = GoodSingleSourceShortestPath.getInstance();
SingleSourceShortestPathResult<Integer> result1 = algorithm1.calc(graph, "A", IntegerNumberSystem.getInstance());
int a2c = result1.getDistance("C");
boolean reachableOfD = result1.isReachable("D");
assertEquals(30, a2c);
assertFalse(reachableOfD);
// The good one should be Dijkstra's Algorithm with binary heap. but you
// can specify to another algorithm. Followings are some possibles.
new Dijkstra(new BinaryHeapFactory());
new BellmanFord(); // Capable for negative edge.
// Let's get the shortest paths of all pairs. Floyd Warshall's algorithm is the simplest implementation.
AllPairShortestPath algoritm2 = new FloydWarshall();
AllPairShortestPathResult<Integer> result2 = algoritm2.calc(graph, IntegerNumberSystem.getInstance());
int a2b = result2.getDistance("A", "B");
int b2a = result2.getDistance("B", "C");
assertEquals(10, a2b);
assertEquals(20, b2a);
// There are other algorithms to get shortest paths of all pairs.
new FloydWarshall(); // Simplest.
new Johnson(new BellmanFord(), new Dijkstra(new BinaryHeapFactory())); // Good for spase tree. Also capable in negative edges.
}
} |
package org.sonar.plugins.stash;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import org.apache.commons.lang3.StringUtils;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.plugins.stash.client.StashClient;
import org.sonar.plugins.stash.client.StashCredentials;
import org.sonar.plugins.stash.fixtures.MavenSonarFixtures;
import org.sonar.plugins.stash.fixtures.SonarQubeRule;
import org.sonar.plugins.stash.fixtures.SonarScanner;
import org.sonar.plugins.stash.issue.collector.DiffReportSample;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import static org.sonar.plugins.stash.client.StashClientTest.aJsonResponse;
public class CompleteITCase {
protected static SonarScanner sonarScanner;
protected static File sourcesDir;
protected static final String stashUser = "myUser";
protected static final String stashPassword = "myPassword";
protected static final String stashProject = "PROJ";
protected static final String stashRepo = "REPO";
protected static final String sonarQubeKey = "SomeKey";
protected static final String sonarQubeName = "Integration test project";
protected static final int stashPullRequest = 42;
@Rule
public WireMockRule wireMock = new WireMockRule(WireMockConfiguration.options().port(8080));
@ClassRule
public static SonarQubeRule sonarqube = new SonarQubeRule(MavenSonarFixtures.getSonarqube(9000));
@BeforeClass
public static void setUpClass() throws Exception {
sonarqube.get().installPlugin(new File(System.getProperty("test.plugin.archive")));
sonarqube.start();
sonarqube.get().createProject(sonarQubeKey, sonarQubeName);
sonarScanner = MavenSonarFixtures.getSonarScanner();
sourcesDir = new File(System.getProperty("test.sources.dir"));
sourcesDir.mkdirs();
}
@Test
public void basicTest() throws Exception {
String jsonUser = "{\"name\":\"SonarQube\", \"email\":\"sq@email.com\", \"id\":1, \"slug\":\"sonarqube\"}";
String jsonPullRequest = DiffReportSample.baseReport;
wireMock.stubFor(
WireMock.get(WireMock.urlPathEqualTo(
urlPath("rest", "api", "1.0", "users", stashUser)))
.willReturn(aJsonResponse()
.withBody(jsonUser)
)
);
wireMock.stubFor(
WireMock.get(WireMock.urlPathEqualTo(
repoPath(stashProject, stashRepo, "pull-requests", String.valueOf(stashPullRequest), "diff")))
.withQueryParam("withComments", WireMock.equalTo(String.valueOf(true)))
.willReturn(aJsonResponse()
.withBody(jsonPullRequest)
)
);
wireMock.stubFor(
WireMock.post(WireMock.urlPathEqualTo(
repoPath(stashProject, stashRepo, "pull-requests", String.valueOf(stashPullRequest), "comments")))
.withRequestBody(WireMock.equalToJson("{\"text\":\"
.willReturn(aJsonResponse()
.withStatus(201)
.withBody("{}")
)
);
scan();
wireMock.verify(WireMock.getRequestedFor(WireMock.urlPathMatching(".*" + stashUser + "$")));
wireMock.verify(WireMock.getRequestedFor(WireMock.urlPathMatching(".*diff$")));
wireMock.verify(WireMock.postRequestedFor(WireMock.urlPathMatching(".*comments$")));
}
@Test
public void testUserAgent() throws Exception {
String jsonUser = "{\"name\":\"SonarQube\", \"email\":\"sq@email.com\", \"id\":1, \"slug\":\"sonarqube\"}";
wireMock.stubFor(WireMock.any(WireMock.anyUrl()).willReturn(WireMock.aResponse().withHeader("Content-Type", "application/json").withBody(jsonUser)));
StashClient client = new StashClient("http://127.0.0.1:" + wireMock.port(), new StashCredentials("some", "thing"), 300);
client.getUser("sonarqube");
wireMock.verify(WireMock.getRequestedFor(WireMock.anyUrl()).withHeader("User-Agent", WireMock.containing(" Stash/")));
}
private String repoPath(String project, String repo, String... parts) {
return urlPath("rest", "api", "1.0", "projects", project, "repos", repo, urlPath(false, parts));
}
private String urlPath(String... parts) {
return urlPath(true, parts);
}
private String urlPath(boolean leading, String... parts) {
String prefix = "";
if (leading) {
prefix = "/";
}
return prefix + StringUtils.join(parts, '/');
}
protected void scan() throws Exception {
List<File> sources = new ArrayList<>();
sources.add(sourcesDir);
Properties extraProps = new Properties();
//extraProps.setProperty("sonar.analysis.mode", "incremental");
extraProps.setProperty("sonar.stash.url", "http://127.0.0.1:" + wireMock.port());
extraProps.setProperty("sonar.stash.login", stashUser);
extraProps.setProperty("sonar.stash.password", stashPassword);
extraProps.setProperty("sonar.stash.notification", "true");
extraProps.setProperty("sonar.stash.project", stashProject);
extraProps.setProperty("sonar.stash.repository", stashRepo);
extraProps.setProperty("sonar.stash.pullrequest.id", String.valueOf(stashPullRequest));
extraProps.setProperty("sonar.log.level", "DEBUG");
sonarScanner.scan(sonarqube.get(), sourcesDir, sources, sonarQubeKey, sonarQubeName, "0.0.0Final39", extraProps);
}
} |
package com.tamsiree.rxkit;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.tamsiree.rxkit.interfaces.OnDoListener;
import com.tamsiree.rxkit.interfaces.OnSimpleListener;
import com.tamsiree.rxkit.view.RxToast;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* @author tamsiree
* @date 2016/1/24
* RxTool
* <p>
* For the brave souls who get this far: You are the chosen ones,
* the valiant knights of programming who toil away, without rest,
* fixing our most awful code. To you, true saviors, kings of men,
* I say this: never gonna give you up, never gonna let you down,
* never gonna run around and desert you. Never gonna make you cry,
* never gonna say goodbye. Never gonna tell a lie and hurt you.
* <p>
*
*
*
*
*/
public class RxTool {
@SuppressLint("StaticFieldLeak")
private static Context context;
private static long lastClickTime;
/**
*
*
* @param context
*/
public static void init(Context context) {
RxTool.context = context.getApplicationContext();
// RxCrashTool.init(context);
RxLogTool.init(context);
}
/**
* Context Context
* <p>
* ApplicationContext
*
* @return ApplicationContext
*/
public static Context getContext() {
if (context != null) {
return context;
}
throw new NullPointerException("init()");
}
public static void delayToDo(long delayTime, final OnSimpleListener onSimpleListener) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
//execute the task
onSimpleListener.doSomething();
}
}, delayTime);
}
/**
*
*
* @param textView
* @param waitTime
* @param interval
* @param hint
*/
public static void countDown(final TextView textView, long waitTime, long interval, final String hint) {
textView.setEnabled(false);
android.os.CountDownTimer timer = new android.os.CountDownTimer(waitTime, interval) {
@SuppressLint("DefaultLocale")
@Override
public void onTick(long millisUntilFinished) {
textView.setText(String.format(" %d S", millisUntilFinished / 1000));
}
@Override
public void onFinish() {
textView.setEnabled(true);
textView.setText(hint);
}
};
timer.start();
}
/**
* listView
*
* @param listView
*/
public static void fixListViewHeight(ListView listView) {
// ListView
ListAdapter listAdapter = listView.getAdapter();
int totalHeight = 0;
if (listAdapter == null) {
return;
}
for (int index = 0, len = listAdapter.getCount(); index < len; index++) {
View listViewItem = listAdapter.getView(index, null, listView);
// View
listViewItem.measure(0, 0);
totalHeight += listViewItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
// listView.getDividerHeight()
// params.heightListView
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
/**
* MD532
*
* @param MStr :
* @return
*/
public static String Md5(String MStr) {
try {
final MessageDigest mDigest = MessageDigest.getInstance("MD5");
mDigest.update(MStr.getBytes());
return bytesToHexString(mDigest.digest());
} catch (NoSuchAlgorithmException e) {
return String.valueOf(MStr.hashCode());
}
}
private static String bytesToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);
}
return sb.toString();
}
/**
* id
* <p>
* ,ID
* <p>
*
* getResources().getIdentifier("ic_launcher", "drawable", getPackageName());
*
* @param context
* @param name
* @param defType
* @return
*/
public final static int getResIdByName(Context context, String name, String defType) {
return context.getResources().getIdentifier(name, defType, context.getPackageName());
}
public static boolean isFastClick(int millisecond) {
long curClickTime = System.currentTimeMillis();
long interval = (curClickTime - lastClickTime);
if (0 < interval && interval < millisecond) {
// lastClickTime
return true;
}
lastClickTime = curClickTime;
return false;
}
/**
* Edittext
*
* @param editText
*/
public static void setEdTwoDecimal(EditText editText) {
setEdDecimal(editText, 2);
}
/**
*
* @param editText
*/
public static void setEdType(final EditText editText) {
editText.addTextChangedListener(new TextWatcher() {
@Override
public void
beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void
onTextChanged(CharSequence s, int start, int before, int count) {
String editable = editText.getText().toString();
String str = stringFilter(editable);
if (!editable.equals(str)) {
editText.setText(str);
editText.setSelection(str.length());
}
}
@Override
public void
afterTextChanged(Editable s) {
}
});
}
/**
* //
*
* @param str
* @return
* @throws PatternSyntaxException
*/
public static String stringFilter(String str) throws PatternSyntaxException {
String regEx = "[^0-9\u4E00-\u9FA5]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
return m.replaceAll("").trim();
}
public static void setEdDecimal(EditText editText, int count) {
if (count < 0) {
count = 0;
}
count += 1;
editText.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER);
final int finalCount = count;
editText.setFilters(new InputFilter[]{new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (".".contentEquals(source) && dest.toString().length() == 0) {
return "0.";
}
if (dest.toString().contains(".")) {
int index = dest.toString().indexOf(".");
int mlength = dest.toString().substring(index).length();
if (mlength == finalCount) {
return "";
}
}
if (dest.toString().equals("0") && source.equals("0")) {
return "";
}
return null;
}
}});
}
/**
* @param editText
* @param number
* 1 -> 1
* 2 -> 01
* 3 -> 001
* 4 -> 0001
* @param isStartForZero 000
* true -> 000
* false -> 001
*/
public static void setEditNumberAuto(final EditText editText, final int number, final boolean isStartForZero) {
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
setEditNumber(editText, number, isStartForZero);
}
}
});
}
/**
* @param editText
* @param number
* 1 -> 1
* 2 -> 01
* 3 -> 001
* 4 -> 0001
* @param isStartForZero 000
* true -> 000
* false -> 001
*/
public static void setEditNumber(EditText editText, int number, boolean isStartForZero) {
StringBuilder s = new StringBuilder(editText.getText().toString());
StringBuilder temp = new StringBuilder();
int i;
for (i = s.length(); i < number; ++i) {
s.insert(0, "0");
}
if (!isStartForZero) {
for (i = 0; i < number; ++i) {
temp.append("0");
}
if (s.toString().equals(temp.toString())) {
s = new StringBuilder(temp.substring(1) + "1");
}
}
editText.setText(s.toString());
}
/**
*
* @return
*/
public static Handler getBackgroundHandler() {
HandlerThread thread = new HandlerThread("background");
thread.start();
return new Handler(thread.getLooper());
}
public static void initFastClickAndVibrate(Context mContext, OnDoListener onRxSimple) {
if (RxTool.isFastClick(RxConstants.FAST_CLICK_TIME)) {
RxToast.normal("");
return;
} else {
RxVibrateTool.vibrateOnce(mContext, RxConstants.VIBRATE_TIME);
onRxSimple.doSomething();
}
}
} |
package org.jdesktop.swingx.renderer;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.swing.AbstractAction;
import javax.swing.AbstractButton;
import javax.swing.AbstractListModel;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.DefaultListCellRenderer;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JTree;
import javax.swing.ListCellRenderer;
import javax.swing.ListModel;
import javax.swing.LookAndFeel;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.Border;
import javax.swing.filechooser.FileSystemView;
import javax.swing.plaf.basic.BasicTreeUI;
import javax.swing.table.TableCellRenderer;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreePath;
import org.jdesktop.swingx.InteractiveTestCase;
import org.jdesktop.swingx.JXButton;
import org.jdesktop.swingx.JXFrame;
import org.jdesktop.swingx.JXList;
import org.jdesktop.swingx.JXPanel;
import org.jdesktop.swingx.JXTable;
import org.jdesktop.swingx.JXTree;
import org.jdesktop.swingx.JXTreeTable;
import org.jdesktop.swingx.border.DropShadowBorder;
import org.jdesktop.swingx.decorator.ColorHighlighter;
import org.jdesktop.swingx.decorator.ComponentAdapter;
import org.jdesktop.swingx.decorator.HighlightPredicate;
import org.jdesktop.swingx.decorator.Highlighter;
import org.jdesktop.swingx.decorator.PainterHighlighter;
import org.jdesktop.swingx.decorator.PatternPredicate;
import org.jdesktop.swingx.painter.MattePainter;
import org.jdesktop.swingx.rollover.RolloverProducer;
import org.jdesktop.swingx.rollover.RolloverRenderer;
import org.jdesktop.swingx.test.ComponentTreeTableModel;
import org.jdesktop.swingx.test.XTestUtils;
import org.jdesktop.swingx.treetable.FileSystemModel;
import org.jdesktop.swingx.treetable.TreeTableModel;
import org.jdesktop.test.AncientSwingTeam;
import com.sun.java.swing.plaf.motif.MotifLookAndFeel;
/**
* Test around known issues of SwingX renderers. <p>
*
* Ideally, there would be at least one failing test method per open
* Issue in the issue tracker. Plus additional failing test methods for
* not fully specified or not yet decided upon features/behaviour.
*
* @author Jeanette Winzenburg
*/
public class RendererIssues extends InteractiveTestCase {
private static final Logger LOG = Logger.getLogger(RendererIssues.class
.getName());
public static void main(String[] args) {
setSystemLF(true);
RendererIssues test = new RendererIssues();
try {
// test.runInteractiveTests();
test.runInteractiveTests("interactive.*ToolTip.*");
// test.runInteractiveTests(".*XLabel.*");
// test.runInteractiveTests(".*Color.*");
// test.runInteractiveTests("interactive.*ColumnControl.*");
// test.runInteractiveTests("interactive.*Hyperlink.*");
} catch (Exception e) {
System.err.println("exception when executing interactive tests:");
e.printStackTrace();
}
}
/**
* example to configure treeTable hierarchical column with
* custom icon and content mapping. The nodes are actually of type File.
*
* Problem:
* painting on resizing tree column sluggish, especially if the PatternHighlighter
* is on. Reason seems to be the FileSystemView - prepare time increases with
* number of accesses.
*/
public void interactiveTreeTableCustomIconsPerformance() {
// modify the file model to return the file itself for the hierarchical column
TreeTableModel model = new FileSystemModel() {
@Override
public Object getValueAt(Object node, int column) {
if (column == 0) {
return node;
}
return super.getValueAt(node, column);
}
};
final JXTreeTable table = new JXTreeTable(model);
table.setAutoResizeMode(JXTable.AUTO_RESIZE_OFF);
StringValue sv = new StringValue() {
public String getString(Object value) {
if (value instanceof File) {
return FileSystemView.getFileSystemView().getSystemDisplayName((File) value)
+ " Type: "
+ FileSystemView.getFileSystemView().getSystemTypeDescription((File) value)
;
}
return TO_STRING.getString(value);
}
};
IconValue iv = new IconValue() {
public Icon getIcon(Object value) {
if (value instanceof File) {
return FileSystemView.getFileSystemView().getSystemIcon((File) value);
}
return null;
}};
final DefaultTreeRenderer treeRenderer = new DefaultTreeRenderer(iv, sv);
table.setTreeCellRenderer(treeRenderer);
// string based. Note: this example is locale dependent
String folderDescription = ".*ordner.*";
PatternPredicate predicate = new PatternPredicate(Pattern.compile(folderDescription, 0), 0, -1);
final Highlighter hl = new ColorHighlighter(predicate, null, Color.RED);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -1);
final Date lastYear = calendar.getTime();
// install value based highlighter
HighlightPredicate valueBased = new HighlightPredicate() {
public boolean isHighlighted(Component renderer,
ComponentAdapter adapter) {
if (!(adapter.getValue() instanceof File)) return false;
File file = (File) adapter.getValue();
Date date = new Date(file.lastModified());
return date.after(lastYear);
}
};
final ColorHighlighter back = new ColorHighlighter(valueBased, Color.YELLOW, null);
JXFrame frame =showWithScrollingInFrame(table, "TreeTable: performance bottleneck is FileSystemView");
Action toggleBack = new AbstractAction("toggleBackHighlighter") {
boolean hasBack;
public void actionPerformed(ActionEvent e) {
if (hasBack) {
table.removeHighlighter(back);
} else {
table.addHighlighter(back);
}
hasBack = !hasBack;
}
};
addAction(frame, toggleBack);
Action togglePattern = new AbstractAction("togglePatternHighlighter") {
boolean hasBack;
public void actionPerformed(ActionEvent e) {
if (hasBack) {
table.removeHighlighter(hl);
} else {
table.addHighlighter(hl);
}
hasBack = !hasBack;
}
};
addAction(frame, togglePattern);
// accessing the FileSystemView is slooooww
// increasingly costly over time, shows particularly
// when the patternHighlighter is on
// (probably because that increases the number
// of queries to the systemView
final JLabel timeL = new JLabel("stop-watch");
Action timer = new AbstractAction("start") {
public void actionPerformed(ActionEvent e) {
timeL.setText("started");
long time = System.currentTimeMillis();
for (int i = 0; i < 2000; i++) {
table.prepareRenderer(table.getCellRenderer(0, 0), 0, 0);
}
timeL.setText("stopped: " + (System.currentTimeMillis() - time));
}
};
addAction(frame, timer);
addStatusComponent(frame, timeL);
addStatusMessage(frame, "node is File - string/value based highlighters same");
}
/**
* Playing with rollover for visual clue if cell editable.
* The old problem: cursor shoudn't be altered by the rollover
* controller but by the rollover renderer.
*/
public void interactiveRolloverEffects() {
JXTable table = new JXTable(new AncientSwingTeam());
table.setDefaultRenderer(Boolean.class, new DefaultTableRenderer(new RolloverCheckBox()));
showWithScrollingInFrame(table, "checkbox rollover effect");
}
public static class RolloverCheckBox extends CheckBoxProvider
implements RolloverRenderer {
boolean wasEditable;
@Override
protected void configureState(CellContext context) {
super.configureState(context);
if (context.getComponent() != null) {
Point p = (Point) context.getComponent()
.getClientProperty(RolloverProducer.ROLLOVER_KEY);
if (/*hasFocus || */(p != null && (p.x >= 0) &&
(p.x == context.getColumn()) && (p.y == context.getRow()))) {
rendererComponent.getModel().setRollover(true);
} else {
rendererComponent.getModel().setRollover(false);
}
}
}
@Override
protected void format(CellContext context) {
// TODO Auto-generated method stub
super.format(context);
wasEditable = context.isEditable();
}
public void doClick() {
}
public boolean isEnabled() {
return wasEditable;
}
}
public void interactiveToolTipList() {
final JXTree table = new JXTree(new ComponentTreeTableModel(new JXFrame()));
table.expandAll();
// quick model for long values
ListModel model = new AbstractListModel() {
public Object getElementAt(int index) {
return table.getPathForRow(index).getLastPathComponent();
}
public int getSize() {
return table.getRowCount();
}
};
JXList list = new JXList(model) {
@Override
public String getToolTipText(MouseEvent event) {
int row = locationToIndex(event.getPoint());
Rectangle r = getCellBounds(row, row);
if (r == null)
return super.getToolTipText(event);
ListCellRenderer renderer = getCellRenderer();
Component comp = renderer.getListCellRendererComponent(this, getElementAt(row), row, isSelectedIndex(row), false);
if (comp.getPreferredSize().width <= getVisibleRect().width) return null;
renderer = ((DelegatingRenderer) renderer).getDelegateRenderer();
if (renderer instanceof StringValue) {
return ((StringValue) renderer).getString(getElementAt(row));
}
return null;
}
@Override
public Point getToolTipLocation(MouseEvent event) {
int row = locationToIndex(event.getPoint());
Rectangle r = getCellBounds(row, row);
if (r != null) {
if (!getComponentOrientation().isLeftToRight()) {
r.translate(r.width, 0);
}
return r.getLocation();
}
return super.getToolTipLocation(event);
}
};
JXFrame frame = wrapWithScrollingInFrame(list, "list tooltip");
addComponentOrientationToggle(frame);
show(frame, 300, 300);
}
public void interactiveToolTipTable() {
JXTreeTable treeTable = new JXTreeTable(new ComponentTreeTableModel(new JXFrame()));
treeTable.expandAll();
JXTable table = new JXTable(treeTable.getModel()) {
@Override
public String getToolTipText(MouseEvent event) {
int column = columnAtPoint(event.getPoint());
int row = rowAtPoint(event.getPoint());
TableCellRenderer renderer = getCellRenderer(row, column);
Component comp = prepareRenderer(renderer, row, column);
if (comp.getPreferredSize().width <= getColumn(column).getWidth()) return null;
if (renderer instanceof StringValue) {
return ((StringValue) renderer).getString(getValueAt(row, column));
}
return null;
}
@Override
public Point getToolTipLocation(MouseEvent event) {
int column = columnAtPoint(event.getPoint());
int row = rowAtPoint(event.getPoint());
Rectangle cellRect = getCellRect(row, column, false);
if (!getComponentOrientation().isLeftToRight()) {
cellRect.translate(cellRect.width, 0);
}
// PENDING JW: otherwise we get a small (borders only) tooltip for null
// core issue? Yeh, the logic in tooltipManager is crooked.
// but this here is ehem ... rather arbitrary.
return getValueAt(row, column) == null ? null : cellRect.getLocation();
// return null;
}
};
table.setColumnControlVisible(true);
JXFrame frame = wrapWithScrollingInFrame(table, "tooltip");
addComponentOrientationToggle(frame);
show(frame);
}
public void interactiveToolTipTree() {
ComponentTreeTableModel model = new ComponentTreeTableModel(new JXFrame());
JXTree tree = new JXTree(model) {
@Override
public String getToolTipText(MouseEvent event) {
int row = getRowForLocation(event.getX(), event.getY());
if (row < 0) return null;
TreeCellRenderer renderer = getCellRenderer();
TreePath path = getPathForRow(row);
Object lastPath = path.getLastPathComponent();
Component comp = renderer.getTreeCellRendererComponent(this,
lastPath, isRowSelected(row), isExpanded(row),
getModel().isLeaf(lastPath), row, false);
int width = getVisibleRect().width;
if (comp.getPreferredSize().width <= width ) return null;
if (renderer instanceof JXTree.DelegatingRenderer) {
renderer = ((JXTree.DelegatingRenderer) renderer).getDelegateRenderer();
if (renderer instanceof StringValue) {
return ((StringValue) renderer).getString(lastPath);
}
}
return null;
}
private int getVisibleWidth() {
int width = getVisibleRect().width;
int indent = (((BasicTreeUI)getUI()).getLeftChildIndent() + ((BasicTreeUI)getUI()).getRightChildIndent());
return width;
}
@Override
public Point getToolTipLocation(MouseEvent event) {
return null;
}
};
tree.expandAll();
tree.setCellRenderer(new DefaultTreeRenderer());
// I'm registered to do tool tips so we can draw tips for the renderers
ToolTipManager toolTipManager = ToolTipManager.sharedInstance();
toolTipManager.registerComponent(tree);
JXFrame frame = showWithScrollingInFrame(tree, "tooltip");
addComponentOrientationToggle(frame);
show(frame, 400, 400);
}
/**
* PENDING JW: really fancify or remove ;-)
*/
public void interactiveTreeFancyButton() {
JXTree tree = new JXTree();
tree.setRowHeight(30);
MattePainter painter = new MattePainter(Color.YELLOW);
Highlighter hl = new PainterHighlighter(HighlightPredicate.ROLLOVER_ROW, painter);
tree.addHighlighter(hl);
ComponentProvider provider = new NormalButtonProvider(StringValue.TO_STRING, JLabel.LEADING);
tree.setCellRenderer(new DefaultTreeRenderer(provider));
tree.setRolloverEnabled(true);
showWithScrollingInFrame(tree, "Fancy..");
}
public void interactiveFancyButton() {
JXButton button = new JXButton("Dummy .... but lonnnnnnngg");
button.setBorder(BorderFactory.createCompoundBorder(new DropShadowBorder(), button.getBorder()));
JXPanel panel = new JXPanel();
panel.add(button);
showInFrame(panel, "Fancy..");
}
public static class NormalButtonProvider extends CheckBoxProvider
implements RolloverRenderer {
private Border border;
/**
* @param toString
* @param leading
*/
public NormalButtonProvider(StringValue toString, int leading) {
super(toString, leading);
setBorderPainted(true);
}
@Override
protected void configureState(CellContext context) {
super.configureState(context);
rendererComponent.setBorder(border);
Point p = (Point) context.getComponent().getClientProperty(
RolloverProducer.ROLLOVER_KEY);
if (/* hasFocus || */(p != null && (p.x >= 0)
&& (p.x == context.getColumn()) && (p.y == context.getRow()))) {
rendererComponent.getModel().setRollover(true);
} else {
rendererComponent.getModel().setRollover(false);
}
}
@Override
protected AbstractButton createRendererComponent() {
JXButton button = new JXButton();
border = BorderFactory.createCompoundBorder(
new DropShadowBorder(),
button.getBorder());
return button;
}
public void doClick() {
// TODO Auto-generated method stub
}
public boolean isEnabled() {
// TODO Auto-generated method stub
return true;
}
}
/**
* Issue #794-swingx: tooltip must be reset.
*
* Here: TreeTableCellRenderer (the tree used for rendering the hierarchical
* column)
*
*/
public void testToolTipResetTreeTableTreeRenderer() {
JXTreeTable treeTable = new JXTreeTable(new ComponentTreeTableModel(new JXPanel()));
JComponent label = (JComponent) treeTable.prepareRenderer(treeTable.getCellRenderer(0, 0), 0, 0);
String tip = "some tip";
label.setToolTipText(tip);
assertEquals("sanity: tooltip must be set", tip, label.getToolTipText());
// prepare again
label = (JComponent) treeTable.prepareRenderer(treeTable.getCellRenderer(0, 0), 0, 0);
assertEquals("tooltip must be reset in each prepare", null, label.getToolTipText());
}
/**
* Issue #774-swingx: support per node-type icons.
*
* postponed to 0.9.x - will break all interface implementors.
*
*/
public void testNodeTypeIcons() {
CellContext<JTree> context = new TreeCellContext();
context.installContext(null, "dummy", -1, -1, false, false, false, true);
final Icon custom = XTestUtils.loadDefaultIcon();
IconValue iv = new IconValue() {
public Icon getIcon(Object value) {
// TODO Auto-generated method stub
return custom;
}
};
WrappingProvider provider = new WrappingProvider(iv);
WrappingIconPanel comp = provider.getRendererComponent(context);
assertEquals(custom, comp.getIcon());
}
/**
* base interaction with list: focused, not-selected uses UI border.
* Moved from ListRendererTest: failes on the new server (what's the default LF there?)
* TODO: fix and reinstate the test
* @throws UnsupportedLookAndFeelException
*/
public void testListFocusBorder() throws UnsupportedLookAndFeelException {
LookAndFeel lf = UIManager.getLookAndFeel();
try {
UIManager.setLookAndFeel(new MotifLookAndFeel());
JList list = new JList(new Object[] {1, 2, 3});
ListCellRenderer coreListRenderer = new DefaultListCellRenderer();
ListCellRenderer xListRenderer = new DefaultListRenderer();
// access ui colors
Border focusBorder = UIManager.getBorder("List.focusCellHighlightBorder");
// sanity
assertNotNull(focusBorder);
// JW: this looks suspicious ...
// RAH: line below makes hudson fail the test tho it runs fine locally ...
assertNotSame(focusBorder, UIManager.getBorder("Table.focusCellHighlightBorder"));
// need to prepare directly - focus is true only if list is focusowner
JComponent coreComponent = (JComponent) coreListRenderer.getListCellRendererComponent(list,
null, 0, false, true);
// sanity: known standard behaviour
assertEquals(focusBorder, coreComponent.getBorder());
// prepare extended
JComponent xComponent = (JComponent) xListRenderer.getListCellRendererComponent(list,
null, 0, false, true);
// assert behaviour same as standard
assertEquals(coreComponent.getBorder(), xComponent.getBorder());
} finally {
UIManager.setLookAndFeel(lf);
}
}
/**
* test if renderer properties are updated on LF change. <p>
* Note: this can be done examplary only. Here: we use the
* font of a rendererComponent returned by a HyperlinkProvider for
* comparison. There's nothing to test if the font are equal
* in System and crossplattform LF. <p>
*
* There are spurious problems when toggling UI (since when?)
* with LinkRenderer
* "no ComponentUI class for: org.jdesktop.swingx.LinkRenderer$1"
* that's the inner class JXHyperlink which overrides updateUI.
*
* PENDING: this was moved from tableUnitTest - had been passing with
* LinkRenderer but with HyperlinkProvider
* now is failing (on server with defaultToSystem == false, locally win os
* with true), probably due to slightly different setup now
* in renderer defaultVisuals? It resets the font to table's which
* LinkRenderer didn't. Think whether to change the provider go back
* to hyperlink font?
*/
public void testUpdateRendererOnLFChange() {
boolean defaultToSystemLF = true;
setSystemLF(defaultToSystemLF);
TableCellRenderer comparison = new DefaultTableRenderer(new HyperlinkProvider());
TableCellRenderer linkRenderer = new DefaultTableRenderer(new HyperlinkProvider());
JXTable table = new JXTable(2, 3);
Component comparisonComponent = comparison.getTableCellRendererComponent(table, null, false, false, 0, 0);
Font comparisonFont = comparisonComponent.getFont();
table.getColumnModel().getColumn(0).setCellRenderer(linkRenderer);
setSystemLF(!defaultToSystemLF);
SwingUtilities.updateComponentTreeUI(comparisonComponent);
if (comparisonFont.equals(comparisonComponent.getFont())) {
LOG.info("cannot run test - equal font " + comparisonFont);
return;
}
SwingUtilities.updateComponentTreeUI(table);
Component rendererComp = table.prepareRenderer(table.getCellRenderer(0, 0), 0, 0);
assertEquals("renderer font must be updated",
comparisonComponent.getFont(), rendererComp.getFont());
}
/**
* RendererLabel NPE with null Graphics. While expected,
* the exact location is not.
* NPE in JComponent.paintComponent finally block
*
*/
public void testLabelNPEPaintComponentOpaque() {
JRendererLabel label = new JRendererLabel();
label.setOpaque(true);
label.paintComponent(null);
}
/**
* RendererLabel NPE with null Graphics. While expected,
* the exact location is not.
* NPE in JComponent.paintComponent finally block
*
*/
public void testLabelNPEPaintComponent() {
JRendererLabel label = new JRendererLabel();
label.setOpaque(false);
label.paintComponent(null);
}
} |
package tlc2.tool.liveness;
import java.io.IOException;
import tlc2.output.EC;
import tlc2.output.MP;
import tlc2.output.StatePrinter;
import tlc2.tool.Action;
import tlc2.tool.EvalException;
import tlc2.tool.StateVec;
import tlc2.tool.TLCState;
import tlc2.tool.TLCStateInfo;
import tlc2.tool.Tool;
import tlc2.util.FP64;
import tlc2.util.LongObjTable;
import tlc2.util.LongVec;
import tlc2.util.MemObjectStack;
import tlc2.util.ObjectStack;
import tlc2.util.Vect;
import tlc2.util.statistics.DummyBucketStatistics;
import tlc2.util.statistics.IBucketStatistics;
public class LiveCheck1 implements ILiveCheck {
/**
* Implementation of liveness checking based on MP book.
*/
private Tool myTool;
private String metadir;
private Action[] actions;
private OrderOfSolution[] solutions;
private BEGraph[] bgraphs;
private StateVec stateTrace = null;
/* The following are the data needed in the scc search. */
private static final long MAX_FIRST = 0x2000000000000000L;
private static final long MAX_SECOND = 0x5000000000000000L;
private OrderOfSolution currentOOS = null;
private PossibleErrorModel currentPEM = null;
private ObjectStack comStack = null;
/* firstNum ranges from 1 to MAX_FIRST. */
private long firstNum = 1;
/* secondNum ranges from MAX_FIRST+1 to MAX_SECOND. */
private long secondNum = MAX_FIRST + 1;
private long startSecondNum = secondNum;
/* thirdNum ranges from MAX_SECOND+1 to MAX_VALUE. */
private long thirdNum = MAX_SECOND + 1;
private long startThirdNum = thirdNum;
/* The number assigned to a new component found by checkSccs. */
private long numFirstCom = secondNum;
/**
* The starting number assigned to new components found by the many
* checkSccs1 calls.
*/
private long numSecondCom = thirdNum;
/**
* The initial state used for the current checking. It is used in generating
* the error trace.
*/
private BEGraphNode initNode = null;
public LiveCheck1(Tool tool) {
myTool = tool;
solutions = Liveness.processLiveness(myTool, metadir);
bgraphs = new BEGraph[0];
}
public void init(Tool tool, Action[] acts, String mdir) {
myTool = tool;
metadir = mdir;
actions = acts;
solutions = Liveness.processLiveness(myTool, metadir);
bgraphs = new BEGraph[solutions.length];
for (int i = 0; i < solutions.length; i++) {
bgraphs[i] = new BEGraph(metadir, solutions[i].hasTableau());
}
}
/**
* This method resets the behavior graph so that we can recompute the SCCs.
*/
public void reset() {
for (int i = 0; i < bgraphs.length; i++) {
bgraphs[i].resetNumberField();
}
}
private void initSccParams(OrderOfSolution os) {
currentOOS = os;
comStack = new MemObjectStack(metadir, "comstack");
firstNum = 1;
secondNum = MAX_FIRST + 1;
thirdNum = MAX_SECOND + 1;
startSecondNum = secondNum;
startThirdNum = thirdNum;
numFirstCom = secondNum;
numSecondCom = thirdNum;
}
/**
* This method constructs the behavior graph from an OrderOfSolution and a
* state trace (a sequence of states). Assume trace.length > 0. It returns
* the set of initial states.
*/
Vect constructBEGraph(OrderOfSolution os) {
Vect initNodes = new Vect(1);
int slen = os.getCheckState().length;
int alen = os.getCheckAction().length;
TLCState srcState = stateTrace.elementAt(0); // the initial state
long srcFP = srcState.fingerPrint();
boolean[] checkStateRes = os.checkState(srcState);
boolean[] checkActionRes = os.checkAction(srcState, srcState);
if (!os.hasTableau()) {
// If there is no tableau, construct begraph with trace.
LongObjTable allNodes = new LongObjTable(127);
BEGraphNode srcNode = new BEGraphNode(srcFP);
srcNode.setCheckState(checkStateRes);
srcNode.addTransition(srcNode, slen, alen, checkActionRes);
allNodes.put(srcFP, srcNode);
initNodes.addElement(srcNode);
for (int i = 1; i < stateTrace.size(); i++) {
TLCState destState = stateTrace.elementAt(i);
long destFP = destState.fingerPrint();
BEGraphNode destNode = (BEGraphNode) allNodes.get(destFP);
if (destNode == null) {
destNode = new BEGraphNode(destFP);
destNode.setCheckState(os.checkState(srcState));
destNode.addTransition(destNode, slen, alen, os.checkAction(destState, destState));
srcNode.addTransition(destNode, slen, alen, os.checkAction(srcState, destState));
allNodes.put(destFP, destNode);
} else if (!srcNode.transExists(destNode)) {
srcNode.addTransition(destNode, slen, alen, os.checkAction(srcState, destState));
}
srcNode = destNode;
srcState = destState;
}
} else {
// If there is tableau, construct begraph of (tableau X trace).
LongObjTable allNodes = new LongObjTable(255);
Vect srcNodes = new Vect();
int initCnt = os.getTableau().getInitCnt();
for (int i = 0; i < initCnt; i++) {
TBGraphNode tnode = os.getTableau().getNode(i);
if (tnode.isConsistent(srcState, myTool)) {
BEGraphNode destNode = new BTGraphNode(srcFP, tnode.index);
destNode.setCheckState(checkStateRes);
initNodes.addElement(destNode);
srcNodes.addElement(destNode);
allNodes.put(FP64.Extend(srcFP, tnode.index), destNode);
}
}
for (int i = 0; i < srcNodes.size(); i++) {
BEGraphNode srcNode = (BEGraphNode) srcNodes.elementAt(i);
TBGraphNode tnode = srcNode.getTNode(os.getTableau());
for (int j = 0; j < tnode.nextSize(); j++) {
TBGraphNode tnode1 = tnode.nextAt(j);
long destFP = FP64.Extend(srcFP, tnode1.index);
BEGraphNode destNode = (BEGraphNode) allNodes.get(destFP);
if (destNode != null) {
srcNode.addTransition(destNode, slen, alen, checkActionRes);
}
}
}
for (int i = 1; i < stateTrace.size(); i++) {
Vect destNodes = new Vect();
TLCState destState = stateTrace.elementAt(i);
long destStateFP = destState.fingerPrint();
checkStateRes = os.checkState(destState);
checkActionRes = os.checkAction(srcState, destState);
for (int j = 0; j < srcNodes.size(); j++) {
BEGraphNode srcNode = (BEGraphNode) srcNodes.elementAt(j);
TBGraphNode tnode = srcNode.getTNode(os.getTableau());
for (int k = 0; k < tnode.nextSize(); k++) {
TBGraphNode tnode1 = tnode.nextAt(k);
long destFP = FP64.Extend(destStateFP, tnode1.index);
BEGraphNode destNode = (BEGraphNode) allNodes.get(destFP);
if (destNode == null) {
if (tnode1.isConsistent(destState, myTool)) {
destNode = new BTGraphNode(destStateFP, tnode1.index);
destNode.setCheckState(checkStateRes);
srcNode.addTransition(destNode, slen, alen, checkActionRes);
destNodes.addElement(destNode);
allNodes.put(destFP, destNode);
}
} else if (!srcNode.transExists(destNode)) {
srcNode.addTransition(destNode, slen, alen, checkActionRes);
}
}
}
checkActionRes = os.checkAction(destState, destState);
for (int j = 0; j < destNodes.size(); j++) {
BEGraphNode srcNode = (BEGraphNode) destNodes.elementAt(j);
TBGraphNode tnode = srcNode.getTNode(os.getTableau());
for (int k = 0; k < tnode.nextSize(); k++) {
TBGraphNode tnode1 = tnode.nextAt(k);
long destFP = FP64.Extend(destStateFP, tnode1.index);
BEGraphNode destNode = (BEGraphNode) allNodes.get(destFP);
if (destNode == null) {
if (tnode1.isConsistent(destState, myTool)) {
destNode = new BTGraphNode(destStateFP, tnode1.index);
destNode.setCheckState(checkStateRes);
srcNode.addTransition(destNode, slen, alen, checkActionRes);
destNodes.addElement(destNode);
allNodes.put(destFP, destNode);
}
} else if (!srcNode.transExists(destNode)) {
srcNode.addTransition(destNode, slen, alen, checkActionRes);
}
}
}
srcNodes = destNodes;
srcState = destState;
}
}
return initNodes;
}
/**
* This method adds new nodes into the behavior graph when a new initial
* state is generated.
*/
public void addInitState(TLCState state, long stateFP) {
for (int soln = 0; soln < solutions.length; soln++) {
OrderOfSolution os = solutions[soln];
BEGraph bgraph = bgraphs[soln];
int slen = os.getCheckState().length;
int alen = os.getCheckAction().length;
boolean[] checkStateRes = os.checkState(state);
boolean[] checkActionRes = os.checkAction(state, state);
// Adding nodes and transitions:
if (!os.hasTableau()) {
// if there is no tableau ...
BEGraphNode node = new BEGraphNode(stateFP);
node.setCheckState(checkStateRes);
bgraph.addInitNode(node);
node.addTransition(node, slen, alen, checkActionRes);
bgraph.allNodes.putBENode(node);
} else {
// if there is tableau ...
// Add edges induced by root --> state:
int initCnt = os.getTableau().getInitCnt();
for (int i = 0; i < initCnt; i++) {
TBGraphNode tnode = os.getTableau().getNode(i);
if (tnode.isConsistent(state, myTool)) {
BTGraphNode destNode = new BTGraphNode(stateFP, tnode.index);
destNode.setCheckState(checkStateRes);
bgraph.addInitNode(destNode);
bgraph.allNodes.putBTNode(destNode);
// Add edges induced by state --> state:
addNodesForStut(state, stateFP, destNode, checkStateRes, checkActionRes, os, bgraph);
}
}
}
// we are done with this state:
bgraph.allNodes.setDone(stateFP);
}
}
/* (non-Javadoc)
* @see tlc2.tool.liveness.ILiveCheck#addNextState(tlc2.tool.TLCState, long, tlc2.tool.StateVec, tlc2.util.LongVec)
*/
public void addNextState(TLCState s0, long fp0, StateVec nextStates, LongVec nextFPs) throws IOException {
for (int i = 0; i < nextStates.size(); i++) {
final TLCState s2 = nextStates.elementAt(i);
final long fp2 = nextFPs.elementAt(i);
addNextState(s0, fp0, s2, fp2);
}
}
/**
* This method adds new nodes into the behavior graph when a new state is
* generated. The argument s2 is the new state. The argument s1 is parent
* state of s2.
*/
public synchronized void addNextState(TLCState s1, long fp1, TLCState s2, long fp2) {
for (int soln = 0; soln < solutions.length; soln++) {
OrderOfSolution os = solutions[soln];
BEGraph bgraph = bgraphs[soln];
int slen = os.getCheckState().length;
int alen = os.getCheckAction().length;
// Adding node and transitions:
if (!os.hasTableau()) {
// if there is no tableau ...
BEGraphNode node1 = bgraph.allNodes.getBENode(fp1);
BEGraphNode node2 = bgraph.allNodes.getBENode(fp2);
if (node2 == null) {
node2 = new BEGraphNode(fp2);
node2.setCheckState(os.checkState(s2));
node1.addTransition(node2, slen, alen, os.checkAction(s1, s2));
node2.addTransition(node2, slen, alen, os.checkAction(s2, s2));
bgraph.allNodes.putBENode(node2);
} else if (!node1.transExists(node2)) {
boolean[] checkActionRes = os.checkAction(s1, s2);
node1.addTransition(node2, slen, alen, checkActionRes);
}
} else {
// if there is tableau ...
BTGraphNode[] srcNodes = bgraph.allNodes.getBTNode(fp1);
if (srcNodes == null)
{
continue; // nothing to add
}
boolean[] checkStateRes = null;
// Add edges induced by s1 --> s2:
boolean[] checkActionRes = os.checkAction(s1, s2);
boolean[] checkActionRes1 = null;
for (int i = 0; i < srcNodes.length; i++) {
BTGraphNode srcNode = srcNodes[i];
TBGraphNode tnode = os.getTableau().getNode(srcNode.getIndex());
for (int j = 0; j < tnode.nextSize(); j++) {
TBGraphNode tnode1 = tnode.nextAt(j);
BTGraphNode destNode = bgraph.allNodes.getBTNode(fp2, tnode1.index);
if (destNode == null) {
if (tnode1.isConsistent(s2, myTool)) {
destNode = new BTGraphNode(fp2, tnode1.index);
if (checkStateRes == null) {
checkStateRes = os.checkState(s2);
}
destNode.setCheckState(checkStateRes);
srcNode.addTransition(destNode, slen, alen, checkActionRes);
int idx = bgraph.allNodes.putBTNode(destNode);
// add edges induced by s2 --> s2:
if (checkActionRes1 == null) {
checkActionRes1 = os.checkAction(s2, s2);
}
addNodesForStut(s2, fp2, destNode, checkStateRes, checkActionRes1, os, bgraph);
// if s2 is done, we have to do something for
// destNode:
if (bgraph.allNodes.isDone(idx)) {
addNextState(s2, fp2, destNode, os, bgraph);
}
}
} else if (!srcNode.transExists(destNode)) {
srcNode.addTransition(destNode, slen, alen, checkActionRes);
}
}
}
}
}
}
/**
* This method is called for each new node created. It generates nodes
* induced by a stuttering state transition.
*/
private void addNodesForStut(TLCState state, long fp, BTGraphNode node, boolean[] checkState,
boolean[] checkAction, OrderOfSolution os, BEGraph bgraph) {
int slen = os.getCheckState().length;
int alen = os.getCheckAction().length;
TBGraphNode tnode = node.getTNode(os.getTableau());
for (int i = 0; i < tnode.nextSize(); i++) {
TBGraphNode tnode1 = tnode.nextAt(i);
BTGraphNode destNode = bgraph.allNodes.getBTNode(fp, tnode1.index);
if (destNode == null) {
if (tnode1.isConsistent(state, myTool)) {
destNode = new BTGraphNode(fp, tnode1.index);
destNode.setCheckState(checkState);
node.addTransition(destNode, slen, alen, checkAction);
bgraph.allNodes.putBTNode(destNode);
addNodesForStut(state, fp, destNode, checkState, checkAction, os, bgraph);
}
} else {
node.addTransition(destNode, slen, alen, checkAction);
}
}
}
/**
* This method takes care of the case that a new node (s, t) is generated
* after s has been done. So, we still have to compute the children of (s,
* t). Hopefully, this case will not occur very frequently.
*/
private void addNextState(TLCState s, long fp, BTGraphNode node, OrderOfSolution os, BEGraph bgraph) {
TBGraphNode tnode = node.getTNode(os.getTableau());
int slen = os.getCheckState().length;
int alen = os.getCheckAction().length;
boolean[] checkStateRes = null;
boolean[] checkActionRes = null;
for (int i = 0; i < actions.length; i++) {
Action curAction = actions[i];
StateVec nextStates = myTool.getNextStates(curAction, s);
for (int j = 0; j < nextStates.size(); j++) {
// Add edges induced by s -> s1:
TLCState s1 = nextStates.elementAt(j);
long fp1 = s1.fingerPrint();
boolean[] checkActionRes1 = null;
for (int k = 0; k < tnode.nextSize(); k++) {
TBGraphNode tnode1 = tnode.nextAt(k);
BTGraphNode destNode = bgraph.allNodes.getBTNode(fp1, tnode1.index);
if (destNode == null) {
if (tnode1.isConsistent(s1, myTool)) {
destNode = new BTGraphNode(fp1, tnode1.index);
if (checkStateRes == null) {
checkStateRes = os.checkState(s1);
}
if (checkActionRes == null) {
checkActionRes = os.checkAction(s, s1);
}
destNode.setCheckState(checkStateRes);
node.addTransition(destNode, slen, alen, checkActionRes);
if (checkActionRes1 == null) {
checkActionRes1 = os.checkAction(s1, s1);
}
addNodesForStut(s1, fp1, destNode, checkStateRes, checkActionRes1, os, bgraph);
int idx = bgraph.allNodes.putBTNode(destNode);
if (bgraph.allNodes.isDone(idx)) {
addNextState(s1, fp1, destNode, os, bgraph);
}
}
} else if (!node.transExists(destNode)) {
if (checkActionRes == null) {
checkActionRes = os.checkAction(s, s1);
}
node.addTransition(destNode, slen, alen, checkActionRes);
}
}
}
}
}
public synchronized void setDone(long fp) {
for (int soln = 0; soln < solutions.length; soln++) {
bgraphs[soln].allNodes.setDone(fp);
}
}
/**
* Checks if the partial behavior graph constructed up to now contains any
* "bad" cycle. A "bad" cycle gives rise to a violation of liveness
* property.
*/
public synchronized boolean check() {
int slen = solutions.length;
if (slen == 0) {
return true;
}
for (int soln = 0; soln < slen; soln++) {
OrderOfSolution oos = solutions[soln];
// Liveness.printTBGraph(oos.tableau);
// ToolIO.err.println(bgraphs[soln].toString());
// We now compute the SCCs of the graph. If we find any SCC
// that is fulfilling and satisfies any of PEM's, then that
// SCC contains a "bad" cycle.
initSccParams(oos);
BEGraph bgraph = bgraphs[soln];
int numOfInits = bgraph.initSize();
for (int i = 0; i < numOfInits; i++) {
initNode = bgraph.getInitNode(i);
if (initNode.getNumber() == 0) {
checkSccs(initNode);
}
}
}
// Previous for loop with throw LivenessException anyway, thus no harm
// returning true regardless.
return true;
}
/**
* Checks if the behavior graph constructed from a state trace contains any
* "bad" cycle.
*/
public void checkTrace(final StateVec trace) {
stateTrace = trace;
for (int soln = 0; soln < solutions.length; soln++) {
OrderOfSolution os = solutions[soln];
Vect initNodes = constructBEGraph(os);
// Liveness.printTBGraph(os.tableau);
// ToolIO.err.println(os.behavior.toString());
// We now compute the SCCs of the graph. If we find any SCC
// that is fulfilling and satisfies any of PEM's, then that
// SCC contains a "bad" cycle.
initSccParams(os);
int numOfInits = initNodes.size();
for (int i = 0; i < numOfInits; i++) {
initNode = (BEGraphNode) initNodes.elementAt(i);
if (initNode.getNumber() == 0) {
checkSccs(initNode);
}
}
}
}
/* Print out the error state trace. */
void printErrorTrace(final BEGraphNode node) throws IOException {
MP.printError(EC.TLC_TEMPORAL_PROPERTY_VIOLATED);
MP.printError(EC.TLC_COUNTER_EXAMPLE);
// First, find a "bad" cycle from the "bad" scc.
ObjectStack cycleStack = new MemObjectStack(metadir, "cyclestack");
int slen = currentOOS.getCheckState().length;
int alen = currentOOS.getCheckAction().length;
long lowNum = thirdNum - 1;
boolean[] AEStateRes = new boolean[currentPEM.AEState.length];
boolean[] AEActionRes = new boolean[currentPEM.AEAction.length];
boolean[] promiseRes = new boolean[currentOOS.getPromises().length];
int cnt = AEStateRes.length + AEActionRes.length + promiseRes.length;
BEGraphNode curNode = node;
while (cnt > 0) {
curNode.setNumber(thirdNum);
int cnt0 = cnt;
_next: while (true) {
// Check AEState:
for (int i = 0; i < currentPEM.AEState.length; i++) {
int idx = currentPEM.AEState[i];
if (!AEStateRes[i] && curNode.getCheckState(idx)) {
AEStateRes[i] = true;
cnt
}
}
// Check if the component is fulfilling. (See MP page 453.)
// Note that the promises are precomputed and stored in oos.
for (int i = 0; i < currentOOS.getPromises().length; i++) {
LNEven promise = currentOOS.getPromises()[i];
TBPar par = curNode.getTNode(currentOOS.getTableau()).getPar();
if (!promiseRes[i] && par.isFulfilling(promise)) {
promiseRes[i] = true;
cnt
}
}
if (cnt <= 0) {
break;
}
// Check AEAction:
BEGraphNode nextNode1 = null;
BEGraphNode nextNode2 = null;
int cnt1 = cnt;
for (int i = 0; i < curNode.nextSize(); i++) {
BEGraphNode node1 = curNode.nextAt(i);
long num = node1.getNumber();
if (lowNum <= num && num <= thirdNum) {
nextNode1 = node1;
for (int j = 0; j < currentPEM.AEAction.length; j++) {
int idx = currentPEM.AEAction[j];
if (!AEActionRes[j] && curNode.getCheckAction(slen, alen, i, idx)) {
AEActionRes[j] = true;
cnt
}
}
}
if (cnt < cnt1) {
cycleStack.push(curNode);
curNode = node1;
thirdNum++;
break _next;
}
if (lowNum <= num && num < thirdNum) {
nextNode2 = node1;
}
}
if (cnt < cnt0) {
cycleStack.push(curNode);
curNode = nextNode1;
thirdNum++;
break;
}
// Backtrack if needed:
while (nextNode2 == null) {
curNode = (BEGraphNode) cycleStack.pop();
for (int i = 0; i < curNode.nextSize(); i++) {
BEGraphNode node1 = curNode.nextAt(i);
long num = node1.getNumber();
if (lowNum <= num && num < thirdNum) {
cycleStack.push(curNode);
nextNode2 = node1;
break;
}
}
}
cycleStack.push(curNode);
curNode = nextNode2;
curNode.setNumber(thirdNum);
}
}
// Close the path to form a cycle. curNode has not been pushed on
// cycleStack.
curNode.setNumber(++thirdNum);
_done: while (curNode != node) {
boolean found = false;
for (int i = 0; i < curNode.nextSize(); i++) {
BEGraphNode nextNode = curNode.nextAt(i);
long num = nextNode.getNumber();
if (lowNum <= num && num < thirdNum) {
cycleStack.push(curNode);
if (nextNode == node) {
break _done;
}
found = true;
curNode = nextNode;
curNode.setNumber(thirdNum);
break;
}
}
if (!found) {
curNode = (BEGraphNode) cycleStack.pop();
}
}
if (cycleStack.size() == 0) {
cycleStack.push(curNode);
}
// Now, print the error trace. We first construct the prefix that
// led to the bad cycle. The nodes on prefix and cycleStack then
// form the complete counter example.
int stateNum = 0;
BEGraphNode[] prefix = BEGraph.getPath(initNode, node);
TLCStateInfo[] states = new TLCStateInfo[prefix.length];
// Recover the initial state:
long fp = prefix[0].stateFP;
TLCStateInfo sinfo = myTool.getState(fp);
if (sinfo == null) {
throw new EvalException(EC.TLC_FAILED_TO_RECOVER_INIT);
}
states[stateNum++] = sinfo;
// Recover the successor states:
for (int i = 1; i < states.length; i++) {
long fp1 = prefix[i].stateFP;
if (fp1 != fp) {
sinfo = myTool.getState(fp1, sinfo.state);
if (sinfo == null) {
throw new EvalException(EC.TLC_FAILED_TO_RECOVER_NEXT);
}
states[stateNum++] = sinfo;
}
fp = fp1;
}
// Print the prefix:
TLCState lastState = null;
for (int i = 0; i < stateNum; i++) {
StatePrinter.printState(states[i], lastState, i + 1);
lastState = states[i].state;
}
// Print the cycle:
int cyclePos = stateNum;
long[] fps = new long[cycleStack.size()];
int idx = fps.length;
while (idx > 0) {
fps[--idx] = ((BEGraphNode) cycleStack.pop()).stateFP;
}
// Assert.assert(fps.length > 0);
sinfo = states[stateNum - 1];
for (int i = 1; i < fps.length; i++) {
if (fps[i] != fps[i - 1]) {
sinfo = myTool.getState(fps[i], sinfo.state);
if (sinfo == null) {
throw new EvalException(EC.TLC_FAILED_TO_RECOVER_NEXT);
}
StatePrinter.printState(sinfo, lastState, ++stateNum);
lastState = sinfo.state;
}
}
if (node.stateFP == lastState.fingerPrint()) {
StatePrinter.printStutteringState(++stateNum);
} else {
MP.printMessage(EC.TLC_BACK_TO_STATE, "" + cyclePos);
}
}
/**
* checkSubcomponent checks if a subcomponent satisfies the AEs of the
* current PEM, and is fulfilling. The subcomponents are those after pruning
* EAs. When a counterexample is found, it throws a LiveException exception.
*/
void checkSubcomponent(BEGraphNode node) {
int slen = currentOOS.getCheckState().length;
int alen = currentOOS.getCheckAction().length;
boolean[] AEStateRes = new boolean[currentPEM.AEState.length];
boolean[] AEActionRes = new boolean[currentPEM.AEAction.length];
boolean[] promiseRes = new boolean[currentOOS.getPromises().length];
ObjectStack stack = new MemObjectStack(metadir, "subcomstack");
node.incNumber();
stack.push(node);
while (stack.size() != 0) {
BEGraphNode curNode = (BEGraphNode) stack.pop();
// Check AEState:
for (int i = 0; i < currentPEM.AEState.length; i++) {
if (!AEStateRes[i]) {
int idx = currentPEM.AEState[i];
AEStateRes[i] = curNode.getCheckState(idx);
}
}
// Check AEAction:
int nsz = curNode.nextSize();
for (int i = 0; i < nsz; i++) {
BEGraphNode node1 = curNode.nextAt(i);
long num = node1.getNumber();
if (num >= thirdNum) {
for (int j = 0; j < currentPEM.AEAction.length; j++) {
if (!AEActionRes[j]) {
int idx = currentPEM.AEAction[j];
AEActionRes[j] = curNode.getCheckAction(slen, alen, i, idx);
}
}
}
if (num == thirdNum) {
node1.incNumber();
stack.push(node1);
}
}
// Check that the component is fulfilling. (See MP page 453.)
// Note that the promises are precomputed and stored in oos.
for (int i = 0; i < currentOOS.getPromises().length; i++) {
LNEven promise = currentOOS.getPromises()[i];
TBPar par = curNode.getTNode(currentOOS.getTableau()).getPar();
if (par.isFulfilling(promise)) {
promiseRes[i] = true;
}
}
}
// Get the number right, so all nodes have numbers < thirdNum.
thirdNum += 2;
// We find a counterexample if all three conditions are satisfied.
for (int i = 0; i < currentPEM.AEState.length; i++) {
if (!AEStateRes[i]) {
return;
}
}
for (int i = 0; i < currentPEM.AEAction.length; i++) {
if (!AEActionRes[i]) {
return;
}
}
for (int i = 0; i < currentOOS.getPromises().length; i++) {
if (!promiseRes[i]) {
return;
}
}
// This component must contain a counter-example because all three
// conditions are satisfied. So, print a counter-example!
try {
printErrorTrace(node);
} catch (IOException e) {
MP.printError(EC.GENERAL, "printing an error trace", e);
// changed
// call
// April
// 2012
}
throw new LiveException("LiveCheck: Found error trace.");
}
/**
* The method checkSccs finds strongly connected components, and checks the
* current oos. We use Tarjan's algorithm described in
* "Depth-First Search and Linear Graph Algorithms" to compute the strongly
* connected components.
*/
long checkSccs(BEGraphNode node) {
long lowlink = firstNum++;
node.setNumber(lowlink);
comStack.push(node);
int nsz = node.nextSize();
for (int i = 0; i < nsz; i++) {
BEGraphNode destNode = node.nextAt(i);
long destNum = destNode.getNumber();
if (destNum == 0) {
destNum = checkSccs(destNode);
}
if (destNum < lowlink) {
lowlink = destNum;
}
}
if (lowlink == node.getNumber()) {
// The nodes on the stack from top to node consist of a
// component. Check it as soon as one is found.
checkComponent(node);
}
return lowlink;
}
/* This method checks whether a scc satisfies currentPEM. */
void checkComponent(BEGraphNode node) {
Vect nodes = extractComponent(node);
if (nodes != null) {
PossibleErrorModel[] pems = currentOOS.getPems();
for (int i = 0; i < pems.length; i++) {
currentPEM = pems[i];
startSecondNum = secondNum;
startThirdNum = thirdNum;
for (int j = nodes.size() - 1; j >= 0; j
BEGraphNode node1 = (BEGraphNode) nodes.elementAt(j);
if (node1.getNumber() < startThirdNum) {
checkSccs1(node1);
}
}
}
}
}
/**
* Returns the set of nodes in a nontrivial component. Returns null for a
* trivial one. It also assigns a new number to all the nodes in the
* component.
*/
Vect extractComponent(BEGraphNode node) {
BEGraphNode node1 = (BEGraphNode) comStack.pop();
if (node == node1 && !node.transExists(node)) {
node.setNumber(MAX_FIRST);
return null;
}
Vect nodes = new Vect();
numFirstCom = secondNum++;
numSecondCom = thirdNum;
node1.setNumber(numFirstCom);
nodes.addElement(node1);
while (node != node1) {
node1 = (BEGraphNode) comStack.pop();
node1.setNumber(numFirstCom);
nodes.addElement(node1);
}
return nodes;
}
long checkSccs1(BEGraphNode node) {
long lowlink = secondNum++;
node.setNumber(lowlink);
comStack.push(node);
int nsz = node.nextSize();
for (int i = 0; i < nsz; i++) {
BEGraphNode destNode = node.nextAt(i);
long destNum = destNode.getNumber();
if ((numFirstCom <= destNum)
&& node.getCheckAction(currentOOS.getCheckState().length, currentOOS.getCheckAction().length, i,
currentPEM.EAAction)) {
if ((destNum < startSecondNum) || (numSecondCom <= destNum && destNum < startThirdNum)) {
destNum = checkSccs1(destNode);
}
if (destNum < lowlink) {
lowlink = destNum;
}
}
}
if (lowlink == node.getNumber()) {
// The nodes on the stack from top to node consist of a
// component. Check it as soon as it is found.
if (extractComponent1(node)) {
checkSubcomponent(node);
}
}
return lowlink;
}
boolean extractComponent1(BEGraphNode node) {
BEGraphNode node1 = (BEGraphNode) comStack.pop();
if (node == node1 && !canStutter(node)) {
node.setNumber(thirdNum++);
return false;
}
node1.setNumber(thirdNum);
while (node != node1) {
node1 = (BEGraphNode) comStack.pop();
node1.setNumber(thirdNum);
}
return true;
}
boolean canStutter(BEGraphNode node) {
int slen = currentOOS.getCheckState().length;
int alen = currentOOS.getCheckAction().length;
for (int i = 0; i < node.nextSize(); i++) {
BEGraphNode node1 = node.nextAt(i);
if (node.equals(node1)) {
long nodeNum = node.getNumber();
return ((numFirstCom <= nodeNum) && node.getCheckAction(slen, alen, i, currentPEM.EAAction));
}
}
return false;
}
/* (non-Javadoc)
* @see tlc2.tool.liveness.ILiveCheck#finalCheck()
*/
public boolean finalCheck() throws Exception {
return check();
}
/* (non-Javadoc)
* @see tlc2.tool.liveness.ILiveCheck#getMetaDir()
*/
public String getMetaDir() {
return metadir;
}
/* (non-Javadoc)
* @see tlc2.tool.liveness.ILiveCheck#getTool()
*/
public Tool getTool() {
return myTool;
}
/* (non-Javadoc)
* @see tlc2.tool.liveness.ILiveCheck#getOutDegreeStatistics()
*/
public IBucketStatistics getOutDegreeStatistics() {
return new DummyBucketStatistics();
}
/* (non-Javadoc)
* @see tlc2.tool.liveness.ILiveCheck#getChecker(int)
*/
public ILiveChecker getChecker(int idx) {
return null;
}
/* (non-Javadoc)
* @see tlc2.tool.liveness.ILiveCheck#getNumChecker()
*/
public int getNumChecker() {
return 0;
}
/* (non-Javadoc)
* @see tlc2.tool.liveness.ILiveCheck#close()
*/
public void close() throws IOException {
// Intentional no op - LiveCheck1 has no disk files.
}
/* (non-Javadoc)
* @see tlc2.tool.liveness.ILiveCheck#beginChkpt()
*/
public void beginChkpt() throws IOException {
// Intentional no op - LiveCheck1 has no disk files.
}
/* (non-Javadoc)
* @see tlc2.tool.liveness.ILiveCheck#commitChkpt()
*/
public void commitChkpt() throws IOException {
// Intentional no op - LiveCheck1 has no disk files.
}
/* (non-Javadoc)
* @see tlc2.tool.liveness.ILiveCheck#recover()
*/
public void recover() throws IOException {
// Intentional no op - LiveCheck1 has no disk files.
}
/* (non-Javadoc)
* @see tlc2.tool.liveness.ILiveCheck#calculateInDegreeDiskGraphs(tlc2.util.statistics.IBucketStatistics)
*/
public IBucketStatistics calculateInDegreeDiskGraphs(IBucketStatistics aGraphStats) throws IOException {
return new DummyBucketStatistics();
}
/* (non-Javadoc)
* @see tlc2.tool.liveness.ILiveCheck#calculateOutDegreeDiskGraphs(tlc2.util.statistics.IBucketStatistics)
*/
public IBucketStatistics calculateOutDegreeDiskGraphs(IBucketStatistics aGraphStats) throws IOException {
return new DummyBucketStatistics();
}
} |
package asw1013.ui;
import asw1013.entity.User;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Image;
import java.net.URL;
import javax.swing.GroupLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
import javax.swing.SwingConstants;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
/**
* ListCellRenderer
*
* @author al333z
*/
public class UserListCellRenderer extends JPanel implements ListCellRenderer {
private static final int LIST_CELL_ICON_SIZE = 36;
private JLabel userLabel = null;
private JLabel messageLabel = null;
private JLabel timeLabel = null;
private JLabel imageLabel = null;
// base url, to retrieve pics
private URL base = null;
public UserListCellRenderer(URL documentBase) {
base = documentBase;
userLabel = new JLabel(" ");
messageLabel = new JLabel(" ");
timeLabel = new JLabel(" ");
imageLabel = new JLabel();
imageLabel.setOpaque(true);
imageLabel.setHorizontalAlignment(JLabel.CENTER);
imageLabel.setVerticalAlignment(JLabel.CENTER);
int imageSize = LIST_CELL_ICON_SIZE + 4;
imageLabel.setBorder(new CompoundBorder(
new LineBorder(Color.BLACK, 1),
new EmptyBorder(1, 1, 1, 1)));
imageLabel.setBackground(Color.WHITE);
GroupLayout layout = new GroupLayout(this);
setLayout(layout);
layout.setAutoCreateContainerGaps(true);
layout.setAutoCreateGaps(true);
GroupLayout.SequentialGroup hg = layout.createSequentialGroup();
layout.setHorizontalGroup(hg);
hg.
addComponent(imageLabel, imageSize, imageSize, imageSize).
addGroup(layout.createParallelGroup().
addComponent(userLabel, 10, 10, Integer.MAX_VALUE).
addComponent(messageLabel, 10, 10, Integer.MAX_VALUE).
addComponent(timeLabel, 10, 10, Integer.MAX_VALUE)
);
GroupLayout.ParallelGroup vg = layout.createParallelGroup();
layout.setVerticalGroup(vg);
vg.
addComponent(imageLabel, GroupLayout.Alignment.CENTER, imageSize, imageSize, imageSize).
addGroup(layout.createSequentialGroup().
addComponent(userLabel).
addComponent(messageLabel).
addComponent(timeLabel));
layout.linkSize(SwingConstants.VERTICAL, imageLabel);
setOpaque(true);
}
public JComponent getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
String user = null;
String message = null;
String time = null;
boolean following = false;
if (value instanceof User) {
User usr = (User) value;
user = usr.username;
message = usr.email;
following = !(usr.following==null);
}
if (user == null) {
user = "";
}
if (message == null) {
message = "";
}
if (time == null) {
time = "";
}
userLabel.setText(user);
messageLabel.setText(message);
timeLabel.setText(time);
// get user picture, if any
try {
String path = "http://si-tomcat.csr.unibo.it:8080/~mattia.baldani/pic?username="+user;
imageLabel.setIcon(getImageIcon(path, imageLabel.getSize()));
} catch (Exception ex) {
imageLabel.setIcon(null);
}
if (isSelected) {
adjustColors(list.getSelectionBackground(),
list.getSelectionForeground(), this, messageLabel, userLabel);
} else {
// followed user are highlighted
if(!following) {
adjustColors(list.getBackground(),
list.getForeground(), this, messageLabel, userLabel);
} else {
adjustColors(Color.decode("#ffffcc"),
list.getForeground(), this, messageLabel, userLabel);
}
}
return this;
}
private void adjustColors(Color bg, Color fg, JComponent... components) {
for (JComponent c : components) {
c.setForeground(fg);
c.setBackground(bg);
}
}
// utility to get picture icon
private Icon getImageIcon(String path, Dimension size) throws Exception {
if (path != null) {
Image image = SoftReferenceImageCache.getInstance().getImage(new URL(path));
if (image != null) {
return new ImageIcon(image);
}
}
return null;
}
} |
package server;
import org.restlet.Component;
import org.restlet.Server;
import org.restlet.data.Protocol;
public class Launcher extends Component {
public static void main(String[] args) throws Exception {
new Launcher().start();
}
public Launcher() {
Server server = new Server(Protocol.HTTP, 8000);
getServers().add(server);
//server.getContext().getParameters().set("tracing", "true");
getClients().add(Protocol.CLAP);
getDefaultHost().attachDefault(new RegattaApplication());
Base.getBase();
System.out.println("Server started on port 8000.");
System.out.println("Application is now available on http://localhost:8000/web/index.html");
}
} |
package org.hd.d.edh;
import java.util.Arrays;
import org.hd.d.edh.FUELINST.TrafficLightsInterface;
/**Main (command-line) entry-point for the data handler.
*/
public final class Main
{
/**Print a summary of command options to stderr. */
public static void printOptions()
{
System.err.println("Commands/options");
System.err.println(" -help");
System.err.println(" This summary/help.");
System.err.println(" trafficLights [-class full.generator.classname] {args}");
System.err.println(" FUELINST outfile.html TIBCOfile.gz {TIBCOfile.gz*}");
System.err.println(" FUELINST outfile.html <directory> [regex-filematch-pattern]");
}
/**Accepts command-line arguments.
*
* Accepts the following commands:
* <ul>
* <li>trafficLights [-class full.generator.classname] {args}<br />
* Using the default implementation,
* args consists of one optional filename.html
* from which other output file names (for flags, xhtml, caches, etc)
* are derived.
* <p>
* Shows red/yellow/green 'start your appliance now' indication
* based primarily on current UK grid carbon intensity.
* Can write HTML output for EOU site if output filename is supplied,
* else writes a summary on System.out.
* Will also delete outfile.html.flag file if status is GREEN, else will create it,
* which is useful for automated remote 200/404 status check.
* <p>
* If a full class name is supplied
* then it is passed the remaining arguments
* and may interpret them as it wishes.
* </li>
* <li>FUELINST outfile.html TIBCOfile.gz {TIBCOfile.gz*}</li>
* <li>FUELINST outfile.html <directory> [regex-filematch-pattern]<br />
* Extracts fuel mix and carbon-intensity info,
* from one or more historical TIBCO GZipped format files
* either listed as explicit files
* or as a directory and an optional regex pattern to accept files by name,
* and then is parsed into MW by fuel type
* or converted to intensity in units of kgCO2/kWh
* with various analyses performed over the data.
* </li>
* </ul>
*/
public static void main(final String[] args)
{
if((args.length < 1) || "-help".equals(args[0]))
{
printOptions();
return; // Not an error.
}
// Command is first argument.
final String command = args[0];
try
{
if("FUELINST".equals(command))
{
FUELINSTHistorical.doHistoricalAnalysis(args);
return; // Completed.
}
else if("trafficLights".equals(command))
{
final TrafficLightsInterface impl;
// Check if "-class" "name" optional args are present.
final boolean classSpecified = (args.length >= 2) && "-class".equals(args[1]);
// If first optional argument is "-class"
// then attempt to create an instance of the specified class.
if(classSpecified)
{
final String classname = args[2];
System.out.println("Class specified: " + classname);
impl = (TrafficLightsInterface) Class.forName(classname).newInstance();
}
// Else use the default implementation.
else
{ impl = (new FUELINST.TrafficLightsDEFAULT()); }
// Pass in trailing args (if any) to impl;
// leading 'trafficLights' (and possible -class name) is omitted.
impl.doTrafficLights(Arrays.copyOfRange(args, classSpecified ? 3 : 1, args.length));
return; // Completed.
}
else if("extraTweet".equals(command))
{
final int minMsg = 9; // Minimum plausible Tweet length.
if((args.length < 2) || (null == args[1]) || (args[1].length() < minMsg))
{
System.err.println("extraTweet tweet missing or too short");
System.exit(1);
}
else
{
final String messageText = args[1];
final TwitterUtils.TwitterDetails td = TwitterUtils.getTwitterHandle(false);
TwitterUtils.setTwitterStatusIfChanged(td, null, messageText);
}
return; // Completed.
}
}
catch(final Throwable e)
{
System.err.println("FAILED command: " + command);
e.printStackTrace();
System.exit(1);
}
// Unrecognised/unhandled command.
System.err.println("Unrecognised or unhandled command: " + command);
printOptions();
System.exit(1);
}
} |
package org.cache2k.benchmark;
import org.junit.After;
import com.carrotsearch.junitbenchmarks.AbstractBenchmark;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cache2k.benchmark.util.AccessTrace;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Map;
import java.util.TreeMap;
/**
* @author Jens Wilke; created: 2013-12-08
*/
public class BenchmarkingBase extends AbstractBenchmark {
static Map<String,String> benchmarkName2csv = new TreeMap<>();
static HashSet<String> onlyOneResult = new HashSet<>();
protected BenchmarkCacheFactory factory = new Cache2kFactory();
BenchmarkCache<Integer, Integer> cache = null;
public BenchmarkCache<Integer, Integer> freshCache(int _maxElements) {
if (cache != null) {
throw new IllegalStateException("Two caches in one test? Please call destroyCache() first");
}
return cache = factory.create(_maxElements);
}
public void destroyCache() {
if (cache != null) {
cache.destroy();
cache = null;
}
}
@After
public void tearDown() {
destroyCache();
}
public final void runBenchmark(BenchmarkCache<Integer, Integer> c, AccessTrace t) {
int[] _trace = t.getArray();
for (int v : _trace) {
c.get(v);
}
}
public final int runBenchmark(AccessTrace t, int _cacheSize) {
BenchmarkCache<Integer, Integer> c = freshCache(_cacheSize);
runBenchmark(c, t);
logHitRate(c, t, c.getMissCount());
c.destroy();
return
((t.getTraceLength() - c.getMissCount()) * 10000 + t.getTraceLength() / 2) / t.getTraceLength();
}
public void logHitRate(BenchmarkCache c, AccessTrace _trace, long _missCount) {
int _optHitRate = _trace.getOptHitRate(c.getCacheSize()).get4digit();
String _testName = extractTestName();
if (onlyOneResult.contains(_testName)) {
return;
}
onlyOneResult.add(_testName);
System.out.println("Requesting GC...");
try {
Runtime.getRuntime().gc();
Thread.sleep(55);
Runtime.getRuntime().gc();
Thread.sleep(55);
} catch (Exception ex) { }
long _usedMem = 0;
long _total;
long _total2;
do {
_total = Runtime.getRuntime().totalMemory();
try {
Thread.sleep(255);
} catch (Exception ex) { }
long _free = Runtime.getRuntime().freeMemory();
_total2 = Runtime.getRuntime().totalMemory();
_usedMem = _total - _free;
} while (_total != _total2);
saveHitRate(_testName, c.getCacheSize(), _trace, _optHitRate, _missCount, _usedMem);
if (c != null) {
c.checkIntegrity();
String _cacheStatistics = c.getStatistics();
System.out.println(_cacheStatistics);
}
System.out.flush();
}
void saveHitRate(String _testName, int _cacheSize, AccessTrace _trace, int _optHitRate, long _missCount, long _usedMem) {
double _hitRateTimes100 =
(_trace.getTraceLength() - _missCount) * 100D / _trace.getTraceLength();
String _hitRate = String.format("%.2f", _hitRateTimes100);
String s = "";
if (_cacheSize > 0) {
s += "size=" + _cacheSize + ", ";
}
s += "accessCount=" + _trace.getTraceLength();
s += ", missCount=" + _missCount + ", hitRatePercent=" + _hitRate;
if (_optHitRate >= 0) {
s += ", optHitRatePercent=" + String.format("%.2f", _optHitRate * 1D / 100);
}
s += ", randomHitRatePercent=" + String.format("%.2f", _trace.getRandomHitRate(_cacheSize).getFactor() * 100);
s += ", uniqueValues=" + _trace.getValueCount();
s += ", usedMem=" + _usedMem;
System.out.println(_testName + ": " + s);
int idx = _testName.lastIndexOf('.');
String _cacheImplementation = _testName.substring(0, idx);
String _benchmarkName = _testName.substring(idx + 1);
String _csvLine =
_benchmarkName + "|" +
_cacheImplementation + "|" +
String.format("%.2f", _hitRateTimes100) + "|" +
_cacheSize + "|" +
_trace.getTraceLength() + "|" +
_trace.getValueCount() + "|" +
String.format("%.2f", _optHitRate * 1D / 100) + "|" +
String.format("%.2f", _trace.getRandomHitRate(_cacheSize).getFactor() * 100) + "|" +
_usedMem;
benchmarkName2csv.put(_testName, _csvLine);
writeCsv();
}
void writeCsv() {
String s = System.getProperty("cache2k.benchmark.result.csv");
if (s == null) {
return;
}
try {
PrintWriter w = new PrintWriter(new FileWriter(s));
for (String k : benchmarkName2csv.keySet()) {
w.println(benchmarkName2csv.get(k));
}
w.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
String extractTestName() {
Exception e = new Exception();
int idx = 1;
StackTraceElement[] _stackTrace = e.getStackTrace();
do {
String n = _stackTrace[idx].getMethodName();
idx++;
if (n.startsWith("benchmark") || n.startsWith("test")) {
return this.getClass().getName() + "." + _stackTrace[idx - 1].getMethodName();
}
} while (true);
}
} |
package be.ecam.moneyrain;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.widget.TextView;
public class Player extends Movable {
private boolean pushing = false;
private int lives;
private int score;
public Player(Point screenSize, Point position, Point speed){
super(screenSize, position, speed);
setImage(R.drawable.persosmall);
this.position.x = screenSize.x/2;
this.position.y = screenSize.y-imageSize.y;
}
public void move(){
if (pushing)
moveRight();
else
moveLeft();
}
public void moveRight(){
if(checkCollision() != "right")
position.x += speed.x;
}
public void moveLeft(){
if(checkCollision() != "left")
position.x += -speed.x;
}
public void setPushing(){
if(pushing == true)
pushing = false;
else
pushing = true;
}
public boolean itemCaught(Item item){
Point itemPos = new Point(item.getPosition());
Point itemSize = new Point(item.getImageSize());
if( itemPos.y+itemSize.y > position.y && itemPos.x+itemSize.x > position.x && itemPos.x < (position.x+imageSize.x) ) {
switch(item.getImageID())
{
case R.drawable.bombesmall:
setLives(getLives()-1);
break;
case R.drawable.piecesmall:
incrementScore(10);
break;
case R.drawable.billetsmall:
incrementScore(100);
}
return true;
}
else
return false;
}
public int getLives() {
return lives;
}
public void setLives(int lives) {
this.lives = lives;
}
public int getScore() {
return score;
}
public void incrementScore(int score) {
this.score += score;
}
} |
package com.adjust.sdk;
import android.net.Uri;
public class AdjustInstance {
private String referrer;
private long referrerClickTime;
private ActivityHandler activityHandler;
private static Logger getLogger() {
return AdjustFactory.getLogger();
}
public void onCreate(AdjustConfig adjustConfig) {
if (activityHandler != null) {
getLogger().error("Adjust already initialized");
return;
}
adjustConfig.referrer = this.referrer;
adjustConfig.referrerClickTime = this.referrerClickTime;
activityHandler = ActivityHandler.getInstance(adjustConfig);
}
public void trackEvent(Event event) {
if (!checkActivityHandler()) return;
activityHandler.trackEvent(event);
}
public void onResume() {
if (!checkActivityHandler()) return;
activityHandler.trackSubsessionStart();
}
public void onPause() {
if (!checkActivityHandler()) return;
activityHandler.trackSubsessionEnd();
}
public void setEnabled(boolean enabled) {
if (!checkActivityHandler()) return;
activityHandler.setEnabled(enabled);
}
public boolean isEnabled() {
if (!checkActivityHandler()) return false;
return activityHandler.isEnabled();
}
public void appWillOpenUrl(Uri url) {
if (!checkActivityHandler()) return;
long clickTime = System.currentTimeMillis();
activityHandler.readOpenUrl(url, clickTime);
}
public void sendReferrer(String referrer) {
long clickTime = System.currentTimeMillis();
// sendReferrer might be triggered before Adjust
if (activityHandler == null) {
// save it to inject in the config before launch
this.referrer = referrer;
this.referrerClickTime = clickTime;
} else {
activityHandler.sendReferrer(referrer, clickTime);
}
}
public void setOfflineMode(boolean enabled) {
if (!checkActivityHandler()) return;
activityHandler.setOfflineMode(enabled);
}
private boolean checkActivityHandler() {
if (activityHandler == null) {
getLogger().error("Please initialize Adjust by calling 'onCreate' before");
return false;
} else {
return true;
}
}
} |
import java.net.DatagramSocket;
import java.time.Instant;
import java.util.UUID;
public class Main {
private static int deviceId;
private static int gradient = 0; // the server is always the sink in the network
public static void main(String[] args) {
System.out.println("Hello server");
deviceId = Integer.parseInt(args[0]);
initialization();
}
/**
* This function initializes the gradient network
*/
private static void initialization() {
try {
DatagramSocket socket = new DatagramSocket(Constants.portNumber);
Utils.broadcast(
Utils.createNetworkPacket(
true, gradient, deviceId, Instant.now().toString(), UUID.randomUUID().toString()),
socket);
} catch(Exception E) {
System.out.println("Socket exception error: " + E);
}
}
} |
package yuku.alkitab.base.dialog;
import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.ListView;
import yuku.afw.V;
import yuku.afw.widget.EasyAdapter;
import yuku.alkitab.R;
import yuku.alkitab.base.App;
import yuku.alkitab.base.S;
import yuku.alkitab.base.U;
import yuku.alkitab.base.ac.BookmarkListActivity;
import yuku.alkitab.base.model.Bookmark2;
import yuku.alkitab.base.model.Label;
import yuku.alkitab.base.storage.Db;
import yuku.alkitab.base.util.Sqlitil;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class ExportBookmarkDialog extends DialogFragment {
public static final String TAG = ExportBookmarkDialog.class.getSimpleName();
public static interface Listener {
void onOk(Uri uri);
}
LayoutInflater inflater;
Listener listener;
@Override
public void onAttach(final Activity activity) {
super.onAttach(activity);
this.listener = (Listener) activity;
}
@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
this.inflater = inflater;
View view = inflater.inflate(R.layout.dialog_export, container, false);
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
final Button bOk = V.get(view, R.id.bOk);
final Button bCancel = V.get(view, R.id.bCancel);
ListView lsBookmark = V.get(view, R.id.lsBookmark);
final BookmarkAdapter adapter = new BookmarkAdapter();
adapter.load();
lsBookmark.setAdapter(adapter);
lsBookmark.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) {
CheckedTextView checkedTextView = V.get(view, android.R.id.text1);
boolean isChecked = checkedTextView.isChecked();
List<ItemAdapter> items = adapter.items;
items.get(position).checks = !isChecked;
checkedTextView.setChecked(!isChecked);
if (items.get(position).type == ItemType.allBookmarks) {
for (ItemAdapter itemAdapter : items) {
if (itemAdapter.type == ItemType.label || itemAdapter.type == ItemType.unlabel) {
itemAdapter.checks = !isChecked;
}
}
}
if ((items.get(position).type == ItemType.label || items.get(position).type == ItemType.unlabel) && isChecked == true) {
for (ItemAdapter itemAdapter : items) {
if (itemAdapter.type == ItemType.allBookmarks) {
itemAdapter.checks = false;
break;
}
}
}
if ((items.get(position).type == ItemType.label || items.get(position).type == ItemType.unlabel) && isChecked == false) {
boolean allChecked = true;
for (ItemAdapter itemAdapter : items) {
if (itemAdapter.type == ItemType.label || itemAdapter.type == ItemType.unlabel) {
if (itemAdapter.checks == true) {
continue;
} else {
allChecked = false;
}
}
}
if (allChecked) {
for (ItemAdapter itemAdapter : items) {
if (itemAdapter.type == ItemType.allBookmarks) {
itemAdapter.checks = true;
break;
}
}
}
}
adapter.notifyDataSetChanged();
boolean enable = false;
for (ItemAdapter itemAdapter : adapter.items) {
if (itemAdapter.checks) {
enable = true;
break;
}
}
bOk.setEnabled(enable);
}
});
bCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
ExportBookmarkDialog.this.dismiss();
}
});
bOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
boolean showNoLabelBookmarks = false;
List<Label> exportedLabels = new ArrayList<Label>();
boolean showNotes = false;
boolean showHighlights = false;
for (ItemAdapter itemAdapter : adapter.items) {
if (itemAdapter.type == ItemType.notes && itemAdapter.checks) {
showNotes = true;
} else if (itemAdapter.type == ItemType.highlight && itemAdapter.checks) {
showHighlights = true;
} else if (itemAdapter.type == ItemType.unlabel && itemAdapter.checks) {
showNoLabelBookmarks = true;
} else if (itemAdapter.type == ItemType.label && itemAdapter.checks) {
exportedLabels.add(itemAdapter.label);
}
}
ExportData data = getAllData(showNoLabelBookmarks, exportedLabels, showNotes, showHighlights);
final File file = writeHtml(data);
final Uri uri = new Uri.Builder().scheme("content").authority(getString(R.string.file_provider_authority)).encodedPath("cache/" + file.getName()).build();
listener.onOk(uri);
ExportBookmarkDialog.this.dismiss();
}
});
return view;
}
private ExportData getAllData(boolean showNoLabelBookmarks, List<Label> exportedlabels, boolean showNotes, boolean showHighlights) {
List<Bookmark2> noLabelBookmarks = new ArrayList<Bookmark2>();
List<Pair<Label, List<Bookmark2>>> labeledBookmarks = new ArrayList<Pair<Label, List<Bookmark2>>>();
List<Bookmark2> notes = new ArrayList<Bookmark2>();
List<Bookmark2> highlights = new ArrayList<Bookmark2>();
//no label
if (showNoLabelBookmarks) {
Cursor cursor = S.getDb().listBookmarks(Db.Bookmark2.kind_bookmark, BookmarkListActivity.LABELID_noLabel, Db.Bookmark2.addTime, false);
while (cursor.moveToNext()) {
Bookmark2 bookmark = Bookmark2.fromCursor(cursor);
noLabelBookmarks.add(bookmark);
}
cursor.close();
}
//with label
if (exportedlabels.size() > 0) {
for (Label label : exportedlabels) {
List<Bookmark2> bookmarks = new ArrayList<Bookmark2>();
Cursor cursor = S.getDb().listBookmarks(Db.Bookmark2.kind_bookmark, label._id, Db.Bookmark2.addTime, false);
while (cursor.moveToNext()) {
Bookmark2 bookmark = Bookmark2.fromCursor(cursor);
bookmarks.add(bookmark);
}
cursor.close();
if (bookmarks.size() > 0) {
Pair<Label, List<Bookmark2>> pair = new Pair<Label, List<Bookmark2>>(label, bookmarks);
labeledBookmarks.add(pair);
}
}
}
//notes
if (showNotes) {
Cursor cursor = S.getDb().listBookmarks(Db.Bookmark2.kind_note, 0, Db.Bookmark2.addTime, false);
while (cursor.moveToNext()) {
Bookmark2 bookmark = Bookmark2.fromCursor(cursor);
notes.add(bookmark);
}
cursor.close();
}
//highlight
if (showHighlights) {
Cursor cursor = S.getDb().listBookmarks(Db.Bookmark2.kind_highlight, 0, Db.Bookmark2.addTime, false);
while (cursor.moveToNext()) {
Bookmark2 bookmark2 = Bookmark2.fromCursor(cursor);
highlights.add(bookmark2);
}
cursor.close();
}
ExportData exportData = new ExportData();
exportData.noLabelBookmarks = noLabelBookmarks;
exportData.labeledBookmarks = labeledBookmarks;
exportData.notes = notes;
exportData.highlights = highlights;
return exportData;
}
class ExportData {
List<Bookmark2> noLabelBookmarks;
List<Pair<Label, List<Bookmark2>>> labeledBookmarks;
List<Bookmark2> notes;
List<Bookmark2> highlights;
}
private File writeHtml(ExportData data) {
List<Bookmark2> noLabelBookmarks = data.noLabelBookmarks;
List<Pair<Label, List<Bookmark2>>> labeledBookmarks = data.labeledBookmarks;
List<Bookmark2> notes = data.notes;
List<Bookmark2> highlights = data.highlights;
File file = new File(App.context.getCacheDir(), "exported-markers-" + UUID.randomUUID().toString() + ".html");
try {
OutputStreamWriter osw = new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(file)), "utf-8");
PrintWriter pw = new PrintWriter(osw);
//write classes
String str = "<html>\n" +
"<head>\n" +
"\t<style type=\"text/css\">\n" +
"\t\tbody {\n" +
"\t\t\tfont-family: sans-serif;\n" +
"\t\t\tfont-size: 11pt;\n" +
"\t\t}\n" +
"\t\th1 {\n" +
"\t\t\tfont-size: 140%;\n" +
"\t\t}\n" +
"\t\tdl {\n" +
"\t\t\tmargin-bottom: 3em;\n" +
"\t\t}\n" +
"\t\tdt {\n" +
"\t\t\tmargin-bottom: 1em;\n" +
"\t\t\tmargin-left: 1em;\n" +
"\t\t}\n" +
"\t\t.label {\n" +
"\t\t\tfont-size: 120%;\n" +
"\t\t\tfont-weight: bold;\n" +
"\t\t}\n" +
"\t\t#bookmark_list .title, #note_list .reference, #highlight_list .reference {\n" +
"\t\t\tfont-size: 120%;\n" +
"\t\t}\n" +
"\t\t.times {\n" +
"\t\t\tfloat: right;\n" +
"\t\t\tfont-size: 80%;\n" +
"\t\t}\n" +
"\t\t#bookmark_list .reference {\n" +
"\t\t\ttext-decoration: underline;\n" +
"\t\t}\n" +
"\t</style>\n" +
"</head>\n";
pw.print(str);
pw.print("<body>\n");
if (noLabelBookmarks.size() + labeledBookmarks.size() > 0) {
pw.print("<h1>" + getString(R.string.pembatas_buku) + "</h1>\n<dl id='bookmark_list'>\n");
//write no label bookmarks
if (noLabelBookmarks.size() > 0) {
printBookmarks(pw, null, noLabelBookmarks);
}
//write labeled bookmarks
if (labeledBookmarks.size() > 0) {
for (Pair<Label, List<Bookmark2>> pair : labeledBookmarks) {
printBookmarks(pw, pair.first, pair.second);
}
}
pw.print("</dl>\n");
}
//write notes
if (notes.size() > 0) {
pw.print("<h1>" + getString(R.string.bmcat_notes) + "</h1>\n<dl id='note_list'>\n");
for (Bookmark2 note : notes) {
String reference = S.activeVersion.reference(note.ari);
pw.print("<dt>\n");
pw.print("<span class='reference' data-ari='" + note.ari + "'>" + reference + "</span>\n");
printTimes(pw, note);
pw.print("<span class='text'>" + note.caption + "</span>\n");
pw.print("</dt>\n");
}
pw.print("</dl>\n");
}
//write highlights
if (highlights.size() > 0) {
pw.print("<h1>" + getString(R.string.bmcat_highlights) + "</h1>\n");
pw.print("<dl id='highlight_list'>\n");
for (Bookmark2 highlight : highlights) {
String verseText = S.activeVersion.loadVerseText(highlight.ari);
verseText = U.removeSpecialCodes(verseText);
String backgroundString = "";
String colorString = getColorString(U.decodeHighlight(highlight.caption));
if (colorString != null) {
backgroundString = " data-bgcolor='" + colorString + "' style='background-color: #" + colorString;
}
String reference = S.activeVersion.reference(highlight.ari);
pw.print("<dt>\n");
pw.print("<span class='reference' data-ari='" + highlight.ari + "'>" + reference + "</span>\n");
printTimes(pw, highlight);
pw.print("<span class='snippet'" + backgroundString + "'>" + verseText + "</span>\n");
pw.print("</dt>\n");
}
pw.print("</dl>\n");
}
pw.print("</body>\n</html>\n");
pw.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
private void printBookmarks(final PrintWriter pw, final Label label, final List<Bookmark2> bookmarks) {
String labelName = getString(R.string.me_no_labels);
String backgroundString = "";
if (label != null) {
String colorString = getColorString(U.decodeLabelBackgroundColor(label.backgroundColor));
if (colorString != null) {
backgroundString = " data-bgcolor='" + colorString + "' style='background-color: #" + colorString;
}
labelName = label.title;
}
pw.print("<span class='label'" + backgroundString + "'>" + labelName + "</span>\n");
for (Bookmark2 bookmark : bookmarks) {
String verseText = S.activeVersion.loadVerseText(bookmark.ari);
verseText = U.removeSpecialCodes(verseText);
pw.print("<dt>\n");
pw.print("<span class='title'>" + bookmark.caption + "</span>\n");
printTimes(pw, bookmark);
pw.print("<span class='reference' data-ari='" + bookmark.ari + "'>" + bookmark.caption + "</span> <span class='snippet'>" + verseText + "</span>\n");
pw.print("</dt>\n");
}
}
private void printTimes(final PrintWriter pw, final Bookmark2 bookmark) {
pw.print("<span class='times'>\n");
pw.print("<span class='createTime' data-unixtime='" + bookmark.addTime.getTime() + "'>" + Sqlitil.toLocaleDateMedium(bookmark.addTime) + "</span>\n");
pw.print("<span class='modifyTime' data-unixtime='" + bookmark.modifyTime.getTime() + "'>" + getString(R.string.me_edited_modify_date, Sqlitil.toLocaleDateMedium(bookmark.modifyTime)) + "</span>\n");
pw.print("</span><br/>\n");
}
private String getColorString(final int color) {
if (color == -1) {
return null;
}
StringBuilder sb = new StringBuilder(10);
String h = Integer.toHexString(color);
for (int x = h.length(); x < 6; x++) {
sb.append('0');
}
sb.append(h);
return sb.toString();
}
public enum ItemType {notes, highlight, allBookmarks, label, unlabel}
class ItemAdapter {
ItemType type;
boolean checks;
Label label;
}
class BookmarkAdapter extends EasyAdapter {
List<Bookmark2> bookmarks = new ArrayList<Bookmark2>();
List<Label> labels;
List<ItemAdapter> items;
void load() {
labels = S.getDb().listAllLabels();
Cursor cursor = S.getDb().listAllBookmarks();
try {
while (cursor.moveToNext()) {
Bookmark2 bookmark = Bookmark2.fromCursor(cursor);
bookmarks.add(bookmark);
}
} finally {
cursor.close();
}
items = new ArrayList<ItemAdapter>(labels.size() + 4);
for (int i = 0; i < labels.size() + 4; i++) {
ItemAdapter itemAdapter = new ItemAdapter();
itemAdapter.checks = true;
if (i == 0) {
itemAdapter.type = ItemType.notes;
} else if (i == 1) {
itemAdapter.type = ItemType.highlight;
} else if (i == 2) {
itemAdapter.type = ItemType.allBookmarks;
} else if (i == 3) {
itemAdapter.type = ItemType.unlabel;
} else {
itemAdapter.type = ItemType.label;
itemAdapter.label = labels.get(i - 4);
}
items.add(itemAdapter);
}
}
@Override
public int getCount() {
return 4 + labels.size();
}
@Override
public View newView(final int position, final ViewGroup parent) {
return inflater.inflate(android.R.layout.simple_list_item_multiple_choice, parent, false);
}
@Override
public void bindView(final View view, final int position, final ViewGroup parent) {
CheckedTextView textView = V.get(view, android.R.id.text1);
if (position == 0) {
textView.setText(R.string.me_all_notes);
} else if (position == 1) {
textView.setText(R.string.me_all_highlights);
} else if (position == 2) {
textView.setText(R.string.me_all_bookmarks);
} else if (position == 3) {
textView.setText("– " + getString(R.string.me_no_labels));
} else {
textView.setText("– " + labels.get(position - 4).title);
}
textView.setChecked(items.get(position).checks);
}
}
} |
package analogsection;
import java.awt.LayoutManager;
import java.util.ArrayList;
import javax.swing.ImageIcon;
/**
*
* @author Stephen
*/
public class InformationGUIAllSections extends javax.swing.JPanel {
/**
* Creates new form HangmanGUIPanel
*/
// variables
Information analogInfo;
Information digitalInfo;
Information plasticInfo;
Information woodInfo;
Information analogComp;
Information analogSignals;
Information analogDiag;
Information digitalComp;
Information digitalDiag;
private String infoDisplayed;
private int count,imgSelector,imgSelectorDigital,imgSelectorPlastic,imgSelectorWood,imgSelectorAnaComp,imgSelectorAnaSignals,imgSelectorDiagTools ,imgSelectorDigit,i ;
protected static int infoSelected;
private String[] arrayTest;
private ArrayList <String> info;
// private Image displayedImg;
private ImageIcon ImgDisplayedLbl;
public InformationGUIAllSections() {
initComponents();
this.setSize(400,450);
imageChangeLbl.setVisible(false);
analogInfo = new Information();
digitalInfo = new Information();
plasticInfo = new Information();
woodInfo = new Information();
analogComp = new Information();
analogDiag = new Information();
analogSignals = new Information();
digitalComp = new Information();
digitalDiag = new Information();
infoDisplayed = "";
count = 0;
imgSelector = 0;
infoLbl.setText("");
imgSelectorDigital = 10;
imgSelectorPlastic = 21;
imgSelectorWood = 32;
imgSelectorAnaComp = 43;
imgSelectorAnaSignals = 54;
imgSelectorDiagTools = 65;
imgSelectorDigit = 76;
digitalComp = new Information();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
detailsLbl = new javax.swing.JLabel();
exitBtn = new javax.swing.JButton();
titleLbl = new javax.swing.JLabel();
backBtn = new javax.swing.JButton();
nextBtn = new javax.swing.JButton();
imageChangeLbl = new javax.swing.JLabel();
infoLbl = new javax.swing.JLabel();
backgroundLbl = new javax.swing.JLabel();
setLayout(null);
detailsLbl.setBackground(new java.awt.Color(255, 255, 255));
detailsLbl.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N
detailsLbl.setForeground(new java.awt.Color(51, 153, 255));
detailsLbl.setText("Details:");
add(detailsLbl);
detailsLbl.setBounds(10, 190, 110, 30);
exitBtn.setBackground(new java.awt.Color(0, 153, 255));
exitBtn.setText("Exit");
exitBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitBtnActionPerformed(evt);
}
});
add(exitBtn);
exitBtn.setBounds(220, 390, 150, 40);
titleLbl.setFont(new java.awt.Font("Apple Chancery", 1, 18)); // NOI18N
titleLbl.setText("Information");
add(titleLbl);
titleLbl.setBounds(140, 0, 150, 40);
backBtn .setOpaque(false);
backBtn .setContentAreaFilled(false);
backBtn.setBorderPainted(false);
backBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
backBtnActionPerformed(evt);
}
});
add(backBtn);
backBtn.setBounds(0, -1, 70, 40);
nextBtn.setOpaque(false);
nextBtn.setContentAreaFilled(false);
nextBtn.setBorderPainted(false);
nextBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nextBtnActionPerformed(evt);
}
});
add(nextBtn);
nextBtn.setBounds(310, 0, 90, 40);
add(imageChangeLbl);
imageChangeLbl.setBounds(90, 50, 280, 140);
add(infoLbl);
infoLbl.setBounds(10, 266, 380, 120);
backgroundLbl.setIcon(new javax.swing.ImageIcon(getClass().getResource("/analogsection/InformationGUI.png"))); // NOI18N
add(backgroundLbl);
backgroundLbl.setBounds(-2, 0, 400, 450);
}// </editor-fold>//GEN-END:initComponents
private void exitBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitBtnActionPerformed
// * A series of if statements checking which panel to go back to,
// * The imgSelector variable will determine which
// * Screen to terevers back to.
//Resets the image holder label to have no imageIco when reset
imageChangeLbl.setIcon(null);
//resets the text to nothing when the information is exited
infoLbl.setText("");
//resets the info slide counter to 0
count = 0;
// resets each of yhe sections counters
analogInfo.setCount(count);
digitalInfo.setCount(count);
plasticInfo.setCount(count);
woodInfo.setCount(count);
analogComp.setCount(count);
analogSignals.setCount(count);
analogDiag.setCount(count);
if (Information.getInfoType() == 1) {
LayoutManager layout = getParent().getLayout();
if (layout instanceof java.awt.CardLayout) {
java.awt.CardLayout cl = (java.awt.CardLayout) layout;
cl.show(getParent(), "AnalogInfoMainScreen");
}
}//end of condition
else if (Information.getInfoType() == 2) {
LayoutManager layout = getParent().getLayout();
if (layout instanceof java.awt.CardLayout) {
java.awt.CardLayout cl = (java.awt.CardLayout) layout;
cl.show(getParent(), "DigitalSectionGUI");
}
}
else if(Information.getInfoType() == 3){
LayoutManager layout = getParent().getLayout();
if (layout instanceof java.awt.CardLayout) {
java.awt.CardLayout cl = (java.awt.CardLayout)layout;
cl.show(getParent(), "PlasticMainGUI");
}
}else if(Information.getInfoType() == 4){
LayoutManager layout = getParent().getLayout();
if (layout instanceof java.awt.CardLayout) {
java.awt.CardLayout cl = (java.awt.CardLayout)layout;
cl.show(getParent(), "WoodMainPanel");
}
}else if(Information.getInfoType() == 5){
LayoutManager layout = getParent().getLayout();
if (layout instanceof java.awt.CardLayout) {
java.awt.CardLayout cl = (java.awt.CardLayout)layout;
cl.show(getParent(), "AnalogInfoMainScreen");
}
}else if(Information.getInfoType() == 6){
LayoutManager layout = getParent().getLayout();
if (layout instanceof java.awt.CardLayout) {
java.awt.CardLayout cl = (java.awt.CardLayout)layout;
cl.show(getParent(), "AnalogInfoMainScreen");
}
}else if(Information.getInfoType() == 7){
LayoutManager layout = getParent().getLayout();
if (layout instanceof java.awt.CardLayout) {
java.awt.CardLayout cl = (java.awt.CardLayout)layout;
cl.show(getParent(), "AnalogMainScreen");
}
}
}//GEN-LAST:event_exitBtnActionPerformed
private void nextBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nextBtnActionPerformed
imageChangeLbl.setVisible(true);
infoSelected = Information.getInfoType();
//error check
System.out.println(infoSelected);
if (infoSelected == 1) {
// * anonymous inner class, to set the info.
// * anonymous inner class creates an extra class file, which can slow the programs startup, by the extra memory needed
// * anonymous inner class extends the class of the object being constructed and has a "This."
// * referance to the instance of the object constructed
ArrayList<String> info = new ArrayList<String>() {
{
add("A capacitor stores and releases charge");
add("Electrons are used in batteries");
add("There are many different electronic signals");
add("ADC are used to convert analog signals to digital repersentation");
add("Resistors are like shiedls");
add("Resistors are measured in ohms");
add("breadbords are used for creating circuits");
add("A.C stands for alternating current ");
add("D.C stands for direct current ");
add("Diode is used eract the flow of current");
}
};
//info = new String[]{"A capacitor stores and releases charge",
//"Electrons are used in batteries", "There are many different electronic signals",
//"ADC are used to convert analog signals to digital repersentation",
//"Resistors are like shiedls", "Resistors are measured in ohms",
//"breadbords are used for creating circuits", "fgtd", "ggffg", "gfddrf"};
analogInfo.setInfo(info);
if (count < 10 && imgSelector < 10) {
//imgSelector = 0;
analogInfo.setImageUsed(imgSelector);
analogInfo.setUrls();
ImgDisplayedLbl = analogInfo.AddImageUsingURLS();
imgSelector++;
//Information.setCount(count = 0);
analogInfo.setCount(count);
count++;
imageChangeLbl.setIcon(ImgDisplayedLbl);
infoDisplayed = analogInfo.DisplayInfo();
infoLbl.setText(infoDisplayed);
}
} else if (infoSelected == 2) {
//digital part
//working
//add information here
// anonymous inner class, to set the info
ArrayList<String> info = new ArrayList<String>() {
{
add("A capacitor stores and releases charge");
add("Electrons are used in batteries");
add("There are many different electronic signals");
add("ADC are used to convert analog signals to digital repersentation");
add("Resistors are like shiedls");
add("Resistors are measured in ohms");
add("breadbords are used for creating circuits");
add("A.C stands for alternating current ");
add("D.C stands for direct current ");
add("Diode is used eract the flow of current");
}
};
digitalInfo.setInfo(info);
//Information.setCount(count = 0);
// infoDisplayed = Information.DisplayInfo();
if (count < 10 && imgSelectorDigital < 21) {
digitalInfo.setImageUsed(imgSelectorDigital);
digitalInfo.setUrls();
ImgDisplayedLbl = digitalInfo.AddImageUsingURLS();
imgSelectorDigital++;
//Information.setCount(count = 0);
digitalInfo.setCount(count);
count++;
imageChangeLbl.setIcon(ImgDisplayedLbl);
infoDisplayed = digitalInfo.DisplayInfo();
infoLbl.setText(infoDisplayed);
// break;
}
} else if (infoSelected == 3) {
//plastic part
//set info here
ArrayList<String> info = new ArrayList<String>() {
{
add("A capacitor stores and releases charge");
add("Electrons are used in batteries");
add("There are many different electronic signals");
add("ADC are used to convert analog signals to digital repersentation");
add("Resistors are like shiedls");
add("Resistors are measured in ohms");
add("breadbords are used for creating circuits");
add("A.C stands for alternating current ");
add("D.C stands for direct current ");
add("Diode is used eract the flow of current");
}
};
plasticInfo.setInfo(info);
//Information.setCount(count = 0);
// infoDisplayed = Information.DisplayInfo();
if (count < 10 && imgSelectorPlastic < 32) {
plasticInfo.setImageUsed(imgSelectorPlastic);
plasticInfo.setUrls();
ImgDisplayedLbl = plasticInfo.AddImageUsingURLS();
imgSelectorPlastic++;
//Information.setCount(count = 0);
plasticInfo.setCount(count);
count++;
imageChangeLbl.setIcon(ImgDisplayedLbl);
infoDisplayed = plasticInfo.DisplayInfo();
infoLbl.setText(infoDisplayed);
}
} else if (infoSelected == 4) {
//wood part
//add info here
ArrayList<String> info = new ArrayList<String>() {
{
add("W");
add("O");
add("O");
add("D");
add("G");
add("o");
add("E");
add("s");
add("here");
add(":)");
}
};
woodInfo.setInfo(info);
//Information.setCount(count = 0);
// infoDisplayed = Information.DisplayInfo();
if (count < 10 && imgSelectorWood < 43) {
woodInfo.setImageUsed(imgSelectorWood);
woodInfo.setUrls();
ImgDisplayedLbl = woodInfo.AddImageUsingURLS();
imgSelectorWood++;
//Information.setCount(count = 0);
woodInfo.setCount(count);
count++;
imageChangeLbl.setIcon(ImgDisplayedLbl);
infoDisplayed = woodInfo.DisplayInfo();
infoLbl.setText(infoDisplayed);
}
} else if (infoSelected == 5) {
// * anonymous inner class, to set the info.
// * anonymous inner class creates an extra class file, which can slow the programs startup, by the extra memory needed
// * anonymous inner class extends the class of the object being constructed and has a "This."
// * referance to the instance of the object constructed
ArrayList<String> info = new ArrayList<String>() {
{
add("A capacitor stores and releases charge");
add("Electrons are used in batteries");
add("There are many different electronic signals");
add("ADC are used to convert analog signals to digital repersentation");
add("Resistors are like shiedls");
add("Resistors are measured in ohms");
add("breadbords are used for creating circuits");
add("A.C stands for alternating current ");
add("D.C stands for direct current ");
add("Diode is used eract the flow of current");
}
};
//info = new String[]{"A capacitor stores and releases charge",
//"Electrons are used in batteries", "There are many different electronic signals",
//"ADC are used to convert analog signals to digital repersentation",
//"Resistors are like shiedls", "Resistors are measured in ohms",
//"breadbords are used for creating circuits", "fgtd", "ggffg", "gfddrf"};
analogComp.setInfo(info);
if (count < 10 && imgSelectorAnaComp < 53) {
//imgSelector = 0;
analogComp.setImageUsed(imgSelectorAnaComp);
analogComp.setUrls();
ImgDisplayedLbl = analogComp.AddImageUsingURLS();
imgSelectorAnaComp++;
//Information.setCount(count = 0);
analogComp.setCount(count);
count++;
imageChangeLbl.setIcon(ImgDisplayedLbl);
infoDisplayed = analogComp.DisplayInfo();
infoLbl.setText(infoDisplayed);
}
} else if (infoSelected == 6) {
//digital part
//working
//add information here
// anonymous inner class, to set the info
ArrayList<String> info = new ArrayList<String>() {
{
add("A capacitor stores and releases charge");
add("Electrons are used in batteries");
add("There are many different electronic signals");
add("ADC are used to convert analog signals to digital repersentation");
add("Resistors are like shiedls");
add("Resistors are measured in ohms");
add("breadbords are used for creating circuits");
add("A.C stands for alternating current ");
add("D.C stands for direct current ");
add("Diode is used eract the flow of current");
}
};
analogSignals.setInfo(info);
//Information.setCount(count = 0);
// infoDisplayed = Information.DisplayInfo();
if(count < 10 && imgSelectorAnaSignals < 65) {
analogSignals.setImageUsed(imgSelectorAnaSignals);
analogSignals.setUrls();
ImgDisplayedLbl = analogSignals.AddImageUsingURLS();
imgSelectorAnaSignals++;
//Information.setCount(count = 0);
analogSignals.setCount(count);
count++;
imageChangeLbl.setIcon(ImgDisplayedLbl);
infoDisplayed = analogSignals.DisplayInfo();
infoLbl.setText(infoDisplayed);
// break;
}
}//end of slector if
else if (infoSelected == 7) {
//digital part
//working
//add information here
// anonymous inner class, to set the info
ArrayList<String> info = new ArrayList<String>() {
{
add("A capacitor stores and releases charge");
add("Electrons are used in batteries");
add("There are many different electronic signals");
add("ADC are used to convert analog signals to digital repersentation");
add("Resistors are like shiedls");
add("Resistors are measured in ohms");
add("breadbords are used for creating circuits");
add("A.C stands for alternating current ");
add("D.C stands for direct current ");
add("Diode is used eract the flow of current");
}
};
analogDiag.setInfo(info);
//Information.setCount(count = 0);
// infoDisplayed = Information.DisplayInfo();
//not working
if (count < 10 && imgSelectorDiagTools < 74) {
analogDiag.setImageUsed(imgSelectorDiagTools);
analogDiag.setUrls();
ImgDisplayedLbl = analogDiag.AddImageUsingURLS();
imgSelectorDiagTools++;
//Information.setCount(count = 0);
analogDiag.setCount(count);
count++;
imageChangeLbl.setIcon(ImgDisplayedLbl);
infoDisplayed = analogDiag.DisplayInfo();
infoLbl.setText(infoDisplayed);
// break;
}
}//end of slector if
else if (infoSelected == 8) {
// * anonymous inner class, to set the info.
// * anonymous inner class creates an extra class file, which can slow the programs startup, by the extra memory needed
// * anonymous inner class extends the class of the object being constructed and has a "This."
// * referance to the instance of the object constructed
ArrayList<String> info = new ArrayList<String>() {
{
add("A capacitor stores and releases charge");
add("Electrons are used in batteries");
add("There are many different electronic signals");
add("ADC are used to convert analog signals to digital repersentation");
add("Resistors are like shiedls");
add("Resistors are measured in ohms");
add("breadbords are used for creating circuits");
add("A.C stands for alternating current ");
add("D.C stands for direct current ");
add("Diode is used eract the flow of current");
}
};
//info = new String[]{"A capacitor stores and releases charge",
//"Electrons are used in batteries", "There are many different electronic signals",
//"ADC are used to convert analog signals to digital repersentation",
//"Resistors are like shiedls", "Resistors are measured in ohms",
//"breadbords are used for creating circuits", "fgtd", "ggffg", "gfddrf"};
digitalComp.setInfo(info);
if (count < 10 && imgSelectorAnaComp < 53) {
//imgSelector = 0;
digitalComp.setImageUsed(imgSelectorAnaComp);
digitalComp.setUrls();
ImgDisplayedLbl = digitalComp.AddImageUsingURLS();
imgSelectorAnaComp++;
//Information.setCount(count = 0);
digitalComp.setCount(count);
count++;
imageChangeLbl.setIcon(ImgDisplayedLbl);
infoDisplayed = digitalComp.DisplayInfo();
infoLbl.setText(infoDisplayed);
}
} else if (infoSelected == 9) {
// * anonymous inner class, to set the info.
// * anonymous inner class creates an extra class file, which can slow the programs startup, by the extra memory needed
// * anonymous inner class extends the class of the object being constructed and has a "This."
// * referance to the instance of the object constructed
ArrayList<String> info = new ArrayList<String>() {
{
add("A capacitor stores and releases charge");
add("Electrons are used in batteries");
add("There are many different electronic signals");
add("ADC are used to convert analog signals to digital repersentation");
add("Resistors are like shiedls");
add("Resistors are measured in ohms");
add("breadbords are used for creating circuits");
add("A.C stands for alternating current ");
add("D.C stands for direct current ");
add("Diode is used eract the flow of current");
}
};
digitalDiag.setInfo(info);
if (count < 10 && imgSelectorAnaComp < 53) {
//imgSelector = 0;
digitalDiag.setImageUsed(imgSelectorAnaComp);
digitalDiag.setUrls();
ImgDisplayedLbl = digitalDiag.AddImageUsingURLS();
imgSelectorAnaComp++;
//Information.setCount(count = 0);
digitalDiag.setCount(count);
count++;
imageChangeLbl.setIcon(ImgDisplayedLbl);
infoDisplayed = digitalDiag.DisplayInfo();
infoLbl.setText(infoDisplayed);
}
}
System.out.println("index:" + count + "Message:" + infoDisplayed);
}//GEN-LAST:event_nextBtnActionPerformed
private void backBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backBtnActionPerformed
// TODO add your handling code here:
if (infoSelected == 1) {
if (count > 0 && imgSelector > 0) {
count
imgSelector
analogInfo.setCount(count);
analogInfo.setImageUsed(imgSelector);
analogInfo.setUrls();
infoDisplayed = analogInfo.DisplayInfo();
ImgDisplayedLbl = analogInfo.AddImageUsingURLS();
infoLbl.setText(infoDisplayed);
imageChangeLbl.setIcon(ImgDisplayedLbl);
}
// if(imgSelector > 0){
// imgSelector--;
// analogInfo.setImageUsed(imgSelector);
// analogInfo.setUrls();
// ImgDisplayedLbl = analogInfo.AddImageUsingURLS();
// imageChangeLbl.setIcon(ImgDisplayedLbl);
} else if (infoSelected == 2) {
if (count > 0 && imgSelectorDigital > 9) {
count
imgSelectorDigital
digitalInfo.setCount(count);
digitalInfo.setImageUsed(imgSelectorDigital);
digitalInfo.setUrls();
infoDisplayed = digitalInfo.DisplayInfo();
ImgDisplayedLbl = digitalInfo.AddImageUsingURLS();
infoLbl.setText(infoDisplayed);
imageChangeLbl.setIcon(ImgDisplayedLbl);
}
}//end of else if
else if (infoSelected == 3) {
if (count > 0 && imgSelectorPlastic > 20) {
count
imgSelectorPlastic
plasticInfo.setCount(count);
plasticInfo.setImageUsed(imgSelectorPlastic);
plasticInfo.setUrls();
infoDisplayed = plasticInfo.DisplayInfo();
ImgDisplayedLbl = plasticInfo.AddImageUsingURLS();
infoLbl.setText(infoDisplayed);
imageChangeLbl.setIcon(ImgDisplayedLbl);
}
} else if (infoSelected == 4) {
if (count > 0 && imgSelectorWood > 33) {
count
imgSelectorWood
woodInfo.setCount(count);
woodInfo.setImageUsed(imgSelectorWood);
woodInfo.setUrls();
infoDisplayed = woodInfo.DisplayInfo();
ImgDisplayedLbl = woodInfo.AddImageUsingURLS();
infoLbl.setText(infoDisplayed);
imageChangeLbl.setIcon(ImgDisplayedLbl);
}
} else if (infoSelected == 5) {
if (count > 0 && imgSelectorAnaComp > 42) {
count
imgSelectorAnaComp
analogComp.setCount(count);
analogComp.setImageUsed(imgSelectorAnaComp);
analogComp.setUrls();
infoDisplayed = analogComp.DisplayInfo();
ImgDisplayedLbl = analogComp.AddImageUsingURLS();
infoLbl.setText(infoDisplayed);
imageChangeLbl.setIcon(ImgDisplayedLbl);
}
}else if (infoSelected == 6) {
if (count > 0 && imgSelectorAnaSignals > 54) {
count
imgSelectorAnaSignals
analogSignals.setCount(count);
analogSignals.setImageUsed(imgSelectorAnaSignals);
analogSignals.setUrls();
infoDisplayed = analogSignals.DisplayInfo();
ImgDisplayedLbl = analogSignals.AddImageUsingURLS();
infoLbl.setText(infoDisplayed);
imageChangeLbl.setIcon(ImgDisplayedLbl);
}
}else if (infoSelected == 7) {
if (count > 0 && imgSelectorDiagTools > 65) {
count
imgSelectorDiagTools
analogDiag.setCount(count);
analogDiag.setImageUsed(imgSelectorDiagTools);
analogDiag.setUrls();
infoDisplayed = analogDiag.DisplayInfo();
ImgDisplayedLbl = analogDiag.AddImageUsingURLS();
infoLbl.setText(infoDisplayed);
imageChangeLbl.setIcon(ImgDisplayedLbl);
}
}else if (infoSelected == 8) {
if (count > 0 && imgSelectorAnaComp > 42) {
count
imgSelectorAnaComp
digitalComp.setCount(count);
digitalComp.setImageUsed(imgSelectorAnaComp);
digitalComp.setUrls();
infoDisplayed = digitalComp.DisplayInfo();
ImgDisplayedLbl = digitalComp.AddImageUsingURLS();
infoLbl.setText(infoDisplayed);
imageChangeLbl.setIcon(ImgDisplayedLbl);
}
}else if (infoSelected == 9) {
if (count > 0 && imgSelectorAnaComp > 42) {
count
imgSelectorAnaComp
digitalDiag.setCount(count);
digitalDiag.setImageUsed(imgSelectorAnaComp);
digitalDiag.setUrls();
infoDisplayed = digitalDiag.DisplayInfo();
ImgDisplayedLbl = digitalDiag.AddImageUsingURLS();
infoLbl.setText(infoDisplayed);
imageChangeLbl.setIcon(ImgDisplayedLbl);
}
}else{
System.out.print("An error occourd");
}
System.out.println("index:"+count + "Message:" + infoDisplayed);
}//GEN-LAST:event_backBtnActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton backBtn;
private javax.swing.JLabel backgroundLbl;
private javax.swing.JLabel detailsLbl;
private javax.swing.JButton exitBtn;
private javax.swing.JLabel imageChangeLbl;
private javax.swing.JLabel infoLbl;
private javax.swing.JButton nextBtn;
private javax.swing.JLabel titleLbl;
// End of variables declaration//GEN-END:variables
} |
package net.somethingdreadful.MAL.tasks;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import com.crashlytics.android.Crashlytics;
import net.somethingdreadful.MAL.ContentManager;
import net.somethingdreadful.MAL.R;
import net.somethingdreadful.MAL.Theme;
import net.somethingdreadful.MAL.account.AccountService;
import net.somethingdreadful.MAL.api.APIHelper;
import net.somethingdreadful.MAL.api.BaseModels.AnimeManga.Anime;
import net.somethingdreadful.MAL.api.BaseModels.AnimeManga.Manga;
import net.somethingdreadful.MAL.api.MALApi;
import net.somethingdreadful.MAL.widgets.Widget1;
import java.util.ArrayList;
import java.util.Arrays;
public class NetworkTask extends AsyncTask<String, Void, Object> {
private TaskJob job;
private MALApi.ListType type;
private Activity activity = null;
private Context context;
private Bundle data;
private NetworkTaskListener callback;
private Object taskResult;
private final TaskJob[] arrayTasks = {TaskJob.GETLIST, TaskJob.FORCESYNC, TaskJob.GETMOSTPOPULAR, TaskJob.GETTOPRATED,
TaskJob.GETJUSTADDED, TaskJob.GETUPCOMING, TaskJob.SEARCH, TaskJob.REVIEWS};
public NetworkTask(TaskJob job, MALApi.ListType type, Activity activity, Bundle data, NetworkTaskListener callback) {
if (job == null || type == null || activity == null)
throw new IllegalArgumentException("job, type and context must not be null");
this.job = job;
this.type = type;
this.activity = activity;
this.data = data;
this.callback = callback;
}
public NetworkTask(TaskJob job, MALApi.ListType type, Context context, NetworkTaskListener callback) {
if (job == null || type == null || context == null)
throw new IllegalArgumentException("job, type and context must not be null");
this.job = job;
this.type = type;
this.context = context;
this.data = new Bundle();
this.callback = callback;
}
private Context getContext() {
return context != null ? context : activity;
}
private boolean isAnimeTask() {
return type.equals(MALApi.ListType.ANIME);
}
private boolean isArrayList() {
return Arrays.asList(arrayTasks).contains(job);
}
@Override
protected Object doInBackground(String... params) {
if (job == null) {
Crashlytics.log(Log.ERROR, "Atarashii", "NetworkTask.doInBackground(): No job identifier, don't know what to do");
return null;
}
if (!APIHelper.isNetworkAvailable(getContext()) && !job.equals(TaskJob.GETLIST) && !job.equals(TaskJob.GETDETAILS)) {
if (activity != null)
Theme.Snackbar(activity, R.string.toast_error_noConnectivity);
return null;
}
int page = 1;
if (data != null && data.containsKey("page")) {
page = data.getInt("page", 1);
Crashlytics.setInt("Page", page);
} else
Crashlytics.setInt("Page", 0);
taskResult = null;
ContentManager mManager = new ContentManager(activity);
if (!AccountService.isMAL() && APIHelper.isNetworkAvailable(getContext()))
mManager.verifyAuthentication();
try {
switch (job) {
case GETLIST:
if (params != null)
taskResult = isAnimeTask() ? mManager.getAnimeListFromDB(params[0], Integer.parseInt(params[1]), params[2]) : mManager.getMangaListFromDB(params[0], Integer.parseInt(params[1]), params[2]);
break;
case FORCESYNC:
if (params != null) {
/* FORCESYNC may not require authentication if there are no dirty records to update, so a forced sync would even
* work if the password has changed, which would be strange for the user. So do an Auth-Check before syncing
*
* this will throw an RetrofitError-Exception if the credentials are wrong
*/
if (AccountService.isMAL())
mManager.verifyAuthentication();
if (isAnimeTask()) {
mManager.cleanDirtyAnimeRecords();
mManager.downloadAnimeList(AccountService.getUsername());
taskResult = mManager.getAnimeListFromDB(params[0], Integer.parseInt(params[1]), params[2]);
} else {
mManager.cleanDirtyMangaRecords();
mManager.downloadMangaList(AccountService.getUsername());
taskResult = mManager.getMangaListFromDB(params[0], Integer.parseInt(params[1]), params[2]);
}
Widget1.forceRefresh(getContext());
}
break;
case GETMOSTPOPULAR:
taskResult = isAnimeTask() ? mManager.getMostPopularAnime(page).getAnime() : mManager.getMostPopularManga(page).getManga();
break;
case GETTOPRATED:
taskResult = isAnimeTask() ? mManager.getTopRatedAnime(page).getAnime() : mManager.getTopRatedManga(page).getManga();
break;
case GETJUSTADDED:
taskResult = isAnimeTask() ? mManager.getJustAddedAnime(page).getAnime() : mManager.getJustAddedManga(page).getManga();
break;
case GETUPCOMING:
taskResult = isAnimeTask() ? mManager.getUpcomingAnime(page).getAnime() : mManager.getUpcomingManga(page).getManga();
break;
case GETDETAILS:
if (data != null && data.containsKey("recordID"))
if (isAnimeTask()) {
// Get Anime from database
Anime record = mManager.getAnime(data.getInt("recordID", -1));
if (APIHelper.isNetworkAvailable(activity)) {
// Get records from the website
// Check for synopsis for relation.
if (record == null || (record.getSynopsis() == null && AccountService.isMAL()))
record = mManager.getAnimeRecord(data.getInt("recordID", -1));
// Check if the record is on the animelist.
// after that load details if synopsis == null or else return the DB record
if ((record.getSynopsis() == null || params[0].equals("true")) && record.getWatchedStatus() != null) {
Crashlytics.log(Log.INFO, "Atarashii", String.format("NetworkTask.doInBackground(): TaskJob = %s & %sID = %s", job, type, record.getId()));
taskResult = mManager.updateWithDetails(record.getId(), record);
} else {
taskResult = record;
}
} else if (record != null) {
taskResult = record;
} else {
Theme.Snackbar(activity, R.string.toast_error_noConnectivity);
}
} else {
// Get Manga from database
Manga record = mManager.getManga(data.getInt("recordID", -1));
if (APIHelper.isNetworkAvailable(activity)) {
// Get records from the website
if (record == null || record.getSynopsis() == null)
record = mManager.getMangaRecord(data.getInt("recordID", -1));
// Check if the record is on the mangalist
// load details if synopsis == null or else return the DB record
if ((record.getSynopsis() == null || params[0].equals("true")) && record.getReadStatus() != null) {
Crashlytics.log(Log.INFO, "Atarashii", String.format("NetworkTask.doInBackground(): TaskJob = %s & %sID = %s", job, type, record.getId()));
taskResult = mManager.updateWithDetails(record.getId(), record);
} else {
taskResult = record;
}
} else if (record != null) {
taskResult = record;
} else {
Theme.Snackbar(activity, R.string.toast_error_noConnectivity);
}
}
break;
case SEARCH:
if (params != null)
taskResult = isAnimeTask() ? mManager.searchAnime(params[0], page) : mManager.searchManga(params[0], page);
break;
case REVIEWS:
if (params != null)
taskResult = isAnimeTask() ? mManager.getAnimeReviews(Integer.parseInt(params[0]), page) : mManager.getMangaReviews(Integer.parseInt(params[0]), page);
break;
default:
Crashlytics.log(Log.ERROR, "Atarashii", "NetworkTask.doInBackground(): " + String.format("%s-task invalid job identifier %s", type.toString(), job.name()));
}
/* if result is still null at this point there was no error but the API returned an empty result
* (e. g. an empty anime-/mangalist), so create an empty list to let the callback know that
* there was no error
*/
if (taskResult == null)
return isArrayList() ? new ArrayList<>() : null;
} catch (Exception e) {
Theme.logTaskCrash(this.getClass().getSimpleName(), "doInBackground(): " + String.format("%s-task error on job %s", type.toString(), job.name()), e);
return isArrayList() && !job.equals(TaskJob.FORCESYNC) && !job.equals(TaskJob.GETLIST) ? new ArrayList<>() : null;
}
return taskResult;
}
@Override
protected void onPostExecute(Object result) {
if (callback != null) {
if (result != null)
callback.onNetworkTaskFinished(taskResult, job, type, data, false);
else
callback.onNetworkTaskError(job, type, data, false);
}
}
public interface NetworkTaskListener {
void onNetworkTaskFinished(Object result, TaskJob job, MALApi.ListType type, Bundle data, boolean cancelled);
void onNetworkTaskError(TaskJob job, MALApi.ListType type, Bundle data, boolean cancelled);
}
} |
package de.htwg.battleship.aview.gui;
import de.htwg.battleship.controller.IMasterController;
import de.htwg.battleship.model.IPlayer;
import de.htwg.battleship.model.IShip;
import de.htwg.battleship.observer.IObserver;
import static de.htwg.battleship.util.StatCollection.createMap;
import static de.htwg.battleship.util.StatCollection.fillMap;
import static de.htwg.battleship.util.StatCollection.heightLenght;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map;
import java.util.Set;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.LineBorder;
/**
* Graphical User Interface for the Game
*
* @version 1.00
* @since 2014-12-20
*/
@SuppressWarnings("serial")
public final class GUI extends JFrame implements IObserver {
/**
* Constant that indicates how long the JPopupDialogs should be shown before
* they close automatically.
*/
private static final long DISPLAYTIME = 1000L;
/**
* width/height for the description labels.
*/
private static final int DESCRIPTION_WIDTH_HEIGHT = 40;
/**
* space for yAxis.
*/
private static final int Y_AXIS_GAP = 30;
/**
* space for xAxis.
*/
private static final int X_AXIS_GAP = 10;
/**
* height of the bottom label.
*/
private static final int BOTTOM_HEIGHT = 50;
/**
* width of the east label.
*/
private static final int EAST_WIDTH = 100;
/**
* width of the mainframe.
*/
private static final int FRAME_WIDTH = 1000;
/**
* height of the mainframe.
*/
private static final int FRAME_HEIGHT = 610;
/**
* Dimension for Buttons in the JLabel east.
*/
private static final Dimension EAST_BUTTONS = new Dimension(90, 30);
/**
* Dimension for playername frame.
*/
private static final Dimension PLAYER_FRAME = new Dimension(300, 150);
/**
* Dimension for the menuFrame.
*/
private static final Dimension MENU_FRAME_SIZE = new Dimension(800, 500);
/**
* set Bound for playerframe button.
*/
private static final Rectangle PLAYER_FRAME_BUTTON
= new Rectangle(75, 80, 150, 30);
/**
* set Bounds for playerframe label.
*/
private static final Rectangle PLAYER_FRAME_LABEL
= new Rectangle(25, 5, 250, 30);
/**
* set Bounds for playerframe textfield.
*/
private static final Rectangle PLAYER_FRAME_TEXT
= new Rectangle(25, 40, 250, 30);
/**
* set Bounds for menuframe startbutton.
*/
private static final Rectangle MENU_FRAME_START_BUTTON
= new Rectangle(300, 240, 200, 50);
/**
* set Bounds for menuframe exitbutton.
*/
private static final Rectangle MENU_FRAME_EXIT_BUTTON
= new Rectangle(300, 310, 200, 50);
/**
* default Font.
*/
private static final Font FONT = new Font("Helvetica", Font.BOLD, 12);
/**
* Border for selected Field.
*/
private static final LineBorder SELECTED = new LineBorder(Color.RED, 4);
/**
* JButton to start or later to restart the Game.
*/
private final JButton start = new JButton("Start Game");
/**
* JButton to exit the whole game right at the beginning or at the end.
*/
private final JButton exit = new JButton("Exit");
/**
* JButton to show the Gamefield of player1 after the Game.
*/
private final JButton endPlayer1 = new JButton();
/**
* JButton to show the Gamefield of player2 after the Game.
*/
private final JButton endPlayer2 = new JButton();
/**
* Button to place a ship in horizontal direction.
*/
private final JButton hor = new JButton("horizontal");
/**
* Button to place a ship in vertical direction.
*/
private final JButton ver = new JButton("vertical");
/**
* JButton[][] for the Field. Button named with: 'x + " " + y'
*/
private final JButton[][] buttonField
= new JButton[heightLenght][heightLenght];
/**
* default Background for mainframe.
*/
private final ImageIcon background
= new ImageIcon(getClass().getResource("background.jpg"));
/**
* default background for the menuframe.
*/
private final ImageIcon backgroundMenu
= new ImageIcon(getClass().getResource("background_menu.jpg"));
/**
* default ImageIcon for non-hitted fields.
*/
private final ImageIcon wave
= new ImageIcon(getClass().getResource("wave.jpg"));
/**
* ImageIcon for missed shots.
*/
private final ImageIcon miss
= new ImageIcon(getClass().getResource("miss.jpg"));
/**
* ImageIcon for ship placed fields.
*/
private final ImageIcon ship
= new ImageIcon(getClass().getResource("ship.jpg"));
/**
* ImageIcon for hitted fields with ship.
*/
private final ImageIcon hit
= new ImageIcon(getClass().getResource("ship_hit.jpg"));
/**
* ImageIcon for JLabels with invisible background.
*/
private final ImageIcon invisible
= new ImageIcon(getClass().getResource("invisible.png"));
/**
* To save the MasterController for all of the several UIs.
*/
private final IMasterController master;
/**
* Container which contains all object of the mainframe.
*/
private final Container container;
/**
* JLabel for the center of the mainframe.
*/
private JLabel center;
/**
* JLabel for the east side of the mainframe.
*/
private JLabel east;
/**
* JLabel for the x-Axis description.
*/
private JLabel xAxis;
/**
* JLabel for the y-Axis description.
*/
private JLabel yAxis;
/**
* JLabel to send out instructions.
*/
private JLabel ausgabe;
/**
* JButton where the Ship should be placed.
*/
private JButton shipPlacePosition;
/**
* JDialog which has to be saved that the program can dispose them after its
* not in use anymore.
*/
private JFrame notifyframe;
/**
* JTextField where the player should input his name.
*/
private JTextField player;
/**
* JFrame for the menu.
*/
private JFrame menuFrame;
/**
* Public Contructor to create a GUI.
*
* @param master MasterController which is the same for all UI
*/
public GUI(final IMasterController master) {
master.addObserver(this);
this.master = master;
//Initialize mainFrame
this.setTitle("Battleship");
this.setIconImage(new ImageIcon(
getClass().getResource("frame_icon.jpg")).getImage());
this.setResizable(false);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.container = new JLabel(background);
this.add(container);
//Initialize Menu
this.menuFrame();
//start Game
this.newGame();
}
/**
* Method build the menuframe.
*/
private void menuFrame() {
this.menuFrame = new JFrame("Battleship");
this.menuFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
//build Buttons
this.start.setBounds(MENU_FRAME_START_BUTTON);
this.exit.setBounds(MENU_FRAME_EXIT_BUTTON);
this.start.setIcon(new ImageIcon(
getClass().getResource("menubutton_1.jpg")));
this.start.setRolloverIcon(new ImageIcon(
getClass().getResource("menubutton_1_mouseover.jpg")));
this.start.setBorder(null);
this.exit.setIcon(new ImageIcon(
getClass().getResource("menubutton_2.jpg")));
this.exit.setRolloverIcon(new ImageIcon(
getClass().getResource("menubutton_2_mouseover.jpg")));
this.exit.setBorder(null);
this.start.addActionListener(new MenuListener());
this.exit.addActionListener(new MenuListener());
//Container setup
JLabel startContainer = new JLabel(backgroundMenu);
startContainer.setLayout(null);
startContainer.add(start);
startContainer.add(exit);
//Frame setup
this.menuFrame.add(startContainer);
this.menuFrame.setSize(MENU_FRAME_SIZE);
this.menuFrame.setResizable(false);
this.menuFrame.setLocationRelativeTo(null);
this.menuFrame.setIconImage(new ImageIcon(
getClass().getResource("frame_icon.jpg")).getImage());
this.menuFrame.setVisible(true);
}
/**
* Method to initialize the GUI for the fields.
*/
public void newGame() {
hor.addActionListener(new PlaceListener());
ver.addActionListener(new PlaceListener());
//new Layout
container.setLayout(new BorderLayout(0, 0));
//panel for the left description
JLabel left = new JLabel();
left.setPreferredSize(new Dimension(DESCRIPTION_WIDTH_HEIGHT,
FRAME_HEIGHT
- BOTTOM_HEIGHT
- DESCRIPTION_WIDTH_HEIGHT));
left.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
yAxis = new JLabel();
yAxis.setPreferredSize(new Dimension(DESCRIPTION_WIDTH_HEIGHT,
FRAME_HEIGHT
- BOTTOM_HEIGHT
- DESCRIPTION_WIDTH_HEIGHT
- Y_AXIS_GAP));
yAxis.setLayout(new GridLayout(heightLenght, 1));
yAxis.setVerticalTextPosition(SwingConstants.CENTER);
left.add(yAxis);
container.add(left, BorderLayout.WEST);
//panel for top description
JLabel top = new JLabel();
top.setPreferredSize(
new Dimension(FRAME_WIDTH, DESCRIPTION_WIDTH_HEIGHT));
top.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
xAxis = new JLabel();
xAxis.setLayout(new GridLayout(1, heightLenght));
xAxis.setPreferredSize(new Dimension(
FRAME_WIDTH
- DESCRIPTION_WIDTH_HEIGHT
- EAST_WIDTH
- X_AXIS_GAP,
DESCRIPTION_WIDTH_HEIGHT));
//panel for the place in the higher left corner
JLabel leftHigherCorner = new JLabel();
leftHigherCorner.setPreferredSize(
new Dimension(DESCRIPTION_WIDTH_HEIGHT,
DESCRIPTION_WIDTH_HEIGHT));
// adding components
top.add(leftHigherCorner);
top.add(xAxis);
container.add(top, BorderLayout.NORTH);
//build gameField
center = new JLabel();
buildGameField();
container.add(center, BorderLayout.CENTER);
//bottom
JLabel bottom = new JLabel();
bottom.setPreferredSize(new Dimension(FRAME_WIDTH, BOTTOM_HEIGHT));
bottom.setLayout(new FlowLayout());
ausgabe = new JLabel();
ausgabe.setHorizontalTextPosition(SwingConstants.CENTER);
ausgabe.setVerticalTextPosition(SwingConstants.CENTER);
ausgabe.setPreferredSize(new Dimension(FRAME_WIDTH, BOTTOM_HEIGHT));
ausgabe.setHorizontalAlignment(SwingConstants.CENTER);
ausgabe.setFont(GUI.FONT);
ausgabe.setForeground(Color.WHITE);
ausgabe.setIcon(new ImageIcon(
getClass().getResource("invisible_ausgabe.png")));
bottom.add(ausgabe);
this.setSize(FRAME_WIDTH, FRAME_HEIGHT);
this.setLocationRelativeTo(null);
container.add(bottom, BorderLayout.SOUTH);
//right
east = new JLabel();
east.setPreferredSize(new Dimension(EAST_WIDTH, 1));
east.setLayout(new FlowLayout(FlowLayout.LEFT));
container.add(east, BorderLayout.EAST);
}
/**
* Utility-Method to Build the main Gamefield.
*/
private void buildGameField() {
GridLayout gl = new GridLayout(heightLenght, heightLenght);
center.setLayout(gl);
for (int y = 0; y < heightLenght; y++) {
JLabel xLabel = new JLabel();
JLabel yLabel = new JLabel();
xLabel.setHorizontalTextPosition(SwingConstants.CENTER);
xLabel.setVerticalTextPosition(SwingConstants.CENTER);
yLabel.setHorizontalTextPosition(SwingConstants.CENTER);
yLabel.setVerticalTextPosition(SwingConstants.CENTER);
xLabel.setForeground(Color.WHITE);
yLabel.setForeground(Color.WHITE);
xLabel.setText(" " + (y + 1));
yLabel.setText(" " + (char) ('A' + y));
yAxis.add(yLabel);
xAxis.add(xLabel);
for (int x = 0; x < heightLenght; x++) {
String name = x + " " + y;
this.buttonField[x][y] = new JButton();
this.buttonField[x][y].setName(name);
this.buttonField[x][y].setIcon(wave);
center.add(buttonField[x][y]);
}
}
}
/**
* Utility-Method to create a JDialog where the user should insert his name.
*
* @param playernumber indicates the player number
*/
private void getPlayername(final int playernumber) {
this.setVisible(false);
PlayerListener pl = new PlayerListener();
JLabel icon = new JLabel(background);
icon.setPreferredSize(PLAYER_FRAME);
JLabel text = new JLabel(invisible);
text.setHorizontalTextPosition(SwingConstants.CENTER);
text.setForeground(Color.WHITE);
text.setText("please insert playername " + playernumber);
text.setBounds(PLAYER_FRAME_LABEL);
player = new JTextField();
player.setBorder(new LineBorder(Color.BLACK, 1));
player.setFont(GUI.FONT);
player.setBounds(PLAYER_FRAME_TEXT);
JButton submit = new JButton("OK");
submit.setIcon(new ImageIcon(
getClass().getResource("playername_button.jpg")));
submit.setRolloverIcon(new ImageIcon(
getClass().getResource("playername_button_mouseover.jpg")));
submit.setBorder(null);
submit.setBounds(PLAYER_FRAME_BUTTON);
submit.addActionListener(pl);
notifyframe = new JFrame();
notifyframe.setIconImage(new ImageIcon(
getClass().getResource("frame_icon.jpg")).getImage());
notifyframe.add(icon);
notifyframe.setSize(PLAYER_FRAME);
icon.setLayout(null);
icon.add(text);
icon.add(player);
icon.add(submit);
notifyframe.setResizable(false);
notifyframe.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
notifyframe.setLocationRelativeTo(getParent());
notifyframe.getRootPane().setDefaultButton(submit);
notifyframe.toFront();
notifyframe.setVisible(true);
}
/**
* Utility-Method to add the 'place'-Button and a ComboBox to the main
* frame.
*/
private void placeShip() {
this.setVisible(false);
east.remove(hor);
east.remove(ver);
resetPlaceButton();
this.ver.setPreferredSize(EAST_BUTTONS);
this.ver.setIcon(new ImageIcon(getClass().getResource("vertical.jpg")));
this.ver.setRolloverIcon(new ImageIcon(
getClass().getResource("vertical_mouseover.jpg")));
this.ver.setBorder(null);
this.hor.setPreferredSize(EAST_BUTTONS);
this.hor.setIcon(new ImageIcon(
getClass().getResource("horizontal.jpg")));
this.hor.setRolloverIcon(new ImageIcon(
getClass().getResource("horizontal_mouseover.jpg")));
this.hor.setBorder(null);
east.add(hor);
east.add(ver);
this.setVisible(true);
}
/**
* Utility-Method to update the image-icons of the gamefield buttons.
* @param player current player
* @param hideShips boolean
*/
private void updateGameField(final IPlayer player,
final boolean hideShips) {
IShip[] shipList = player.getOwnBoard().getShipList();
Map<Integer, Set<Integer>> map = createMap();
fillMap(shipList, map, player.getOwnBoard().getShips());
for (int y = 0; y < heightLenght; y++) {
for (int x = 0; x < heightLenght; x++) {
boolean isShip = false;
this.buttonField[x][y].setBorder(new JButton().getBorder());
for (Integer value : map.get(y)) {
if (value == x) {
if (player.getOwnBoard().isHit(x, y)) {
this.buttonField[x][y].setIcon(hit);
} else {
if (hideShips) {
this.buttonField[x][y].setIcon(wave);
} else {
this.buttonField[x][y].setIcon(ship);
}
}
isShip = true;
}
}
if (!isShip) {
if (player.getOwnBoard().isHit(x, y)) {
this.buttonField[x][y].setIcon(miss);
} else {
this.buttonField[x][y].setIcon(wave);
}
}
}
}
}
/**
* Utility-Method to reset the selected button in the place states.
*/
private void resetPlaceButton() {
if (shipPlacePosition != null) {
shipPlacePosition.setBorder(new JButton().getBorder());
shipPlacePosition = null;
}
}
/**
* Utility-Method to show the Gamefield after the Game.
*/
private void endGame() {
this.setVisible(false);
for (JButton[] buttonArray : buttonField) {
for (JButton button : buttonArray) {
removeListener(button);
}
}
this.endPlayer1.setPreferredSize(EAST_BUTTONS);
this.endPlayer2.setPreferredSize(EAST_BUTTONS);
this.endPlayer1.setBorder(null);
this.endPlayer2.setBorder(null);
this.endPlayer1.setIcon(new ImageIcon(
getClass().getResource("end_playername.jpg")));
this.endPlayer2.setIcon(new ImageIcon(
getClass().getResource("end_playername.jpg")));
this.endPlayer1.setRolloverIcon(new ImageIcon(
getClass().getResource("end_playername_mouseover.jpg")));
this.endPlayer2.setRolloverIcon(new ImageIcon(
getClass().getResource("end_playername_mouseover.jpg")));
this.endPlayer1.setVerticalTextPosition(SwingConstants.CENTER);
this.endPlayer2.setVerticalTextPosition(SwingConstants.CENTER);
this.endPlayer1.setHorizontalTextPosition(SwingConstants.CENTER);
this.endPlayer2.setHorizontalTextPosition(SwingConstants.CENTER);
this.endPlayer1.setText(master.getPlayer1().getName());
this.endPlayer2.setText(master.getPlayer2().getName());
this.endPlayer1.setFont(GUI.FONT);
this.endPlayer2.setFont(GUI.FONT);
this.endPlayer1.setForeground(Color.WHITE);
this.endPlayer2.setForeground(Color.WHITE);
this.endPlayer1.addActionListener(new WinListener());
this.endPlayer2.addActionListener(new WinListener());
JButton finish = new JButton();
finish.setBorder(null);
finish.setPreferredSize(EAST_BUTTONS);
finish.setIcon(new ImageIcon(getClass().getResource("finish.jpg")));
finish.setRolloverIcon(new ImageIcon(
getClass().getResource("finish_mouseover.jpg")));
finish.addActionListener(new WinListener());
east.add(this.endPlayer1);
east.add(this.endPlayer2);
east.add(finish);
this.setVisible(true);
}
/**
* Utility-Method to get the Mainframe
*/
private JFrame getThis() {
return this;
}
@Override
public void update() {
switch (master.getCurrentState()) {
case START:
break;
case GETNAME1:
menuFrame.dispose();
getPlayername(1);
break;
case GETNAME2:
notifyframe.dispose();
getPlayername(2);
break;
case PLACE1:
notifyframe.dispose();
this.setVisible(true);
resetPlaceButton();
activateListener(new PlaceListener());
updateGameField(master.getPlayer1(), false);
placeShip();
ausgabe.setText(master.getPlayer1().getName()
+ " now place the ship with the length of "
+ (master.getPlayer1().getOwnBoard().getShips() + 2));
break;
case PLACE2:
resetPlaceButton();
activateListener(new PlaceListener());
updateGameField(master.getPlayer2(), false);
placeShip();
ausgabe.setText(master.getPlayer2().getName()
+ " now place the ship with the length of "
+ (master.getPlayer2().getOwnBoard().getShips() + 2));
break;
case FINALPLACE1:
updateGameField(master.getPlayer1(), false);
resetPlaceButton();
break;
case FINALPLACE2:
updateGameField(master.getPlayer2(), false);
resetPlaceButton();
break;
case PLACEERR:
new JPopupDialog(this, "Placement error",
"<html>Cannot place a ship there due to a collision or <br>"
+ "the ship is out of the field!</html>",
(DISPLAYTIME * 2), false);
break;
case SHOOT1:
this.setVisible(false);
east.remove(hor);
east.remove(ver);
this.setVisible(true);
activateListener(new ShootListener());
updateGameField(master.getPlayer2(), true);
ausgabe.setText(master.getPlayer1().getName()
+ " is now at the turn to shoot");
break;
case SHOOT2:
activateListener(new ShootListener());
updateGameField(master.getPlayer1(), true);
ausgabe.setText(master.getPlayer2().getName()
+ " is now at the turn to shoot");
break;
case HIT:
new JPopupDialog(this, "Shot Result",
"Your shot was a Hit!!", DISPLAYTIME, false);
break;
case MISS:
new JPopupDialog(this, "Shot Result",
"Your shot was a Miss!!", DISPLAYTIME, false);
break;
case WIN1:
updateGameField(master.getPlayer2(), false);
String msg = master.getPlayer1().getName() + " has won!!";
ausgabe.setText(msg);
new JPopupDialog(this, "Winner!", msg,
DISPLAYTIME, false);
break;
case WIN2:
updateGameField(master.getPlayer1(), false);
msg = master.getPlayer2().getName() + " has won!!";
ausgabe.setText(msg);
new JPopupDialog(this, "Winner!", msg,
DISPLAYTIME, false);
break;
case END:
endGame();
break;
case WRONGINPUT:
// isn't needed in the GUI, help-state for a UI where you
// can give input at the false states
break;
default:
break;
}
}
/**
* Method to activate a new Action Listener to the JButton[][]-Matrix. uses
* the removeListener-Method
*
* @param newListener the new Listener of the button matrix
*/
private void activateListener(final ActionListener newListener) {
for (JButton[] buttonArray : buttonField) {
for (JButton button : buttonArray) {
removeListener(button);
button.addActionListener(newListener);
}
}
}
/**
* Method which removes all Listener from a button.
* @param button specified button
*/
private void removeListener(final JButton button) {
if (button == null) {
return;
}
ActionListener[] actionList = button.getActionListeners();
for (ActionListener acLst : actionList) {
button.removeActionListener(acLst);
}
}
/**
* ActionListener for the State of the Game in which the Player has to set
* his Ships on the field. PLACE1 / PLACE2 / FINALPLACE1 / FINALPLACE2
*/
private class PlaceListener implements ActionListener {
@Override
public void actionPerformed(final ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button.equals(hor) || button.equals(ver)) {
if (shipPlacePosition != null) {
String[] parts = shipPlacePosition.getName().split(" ");
if (button.equals(hor)) {
master.placeShip(Integer.valueOf(parts[0]),
Integer.valueOf(parts[1]), true);
} else {
master.placeShip(Integer.valueOf(parts[0]),
Integer.valueOf(parts[1]), false);
}
} else {
new JPopupDialog(getThis(), "Placement error",
"Please choose a field to place the ship",
DISPLAYTIME, false);
}
} else {
if (shipPlacePosition != null
&& !shipPlacePosition.equals(button)) {
switchColor(shipPlacePosition);
}
String[] parts = button.getName().split(" ");
JButton select = buttonField
[Integer.valueOf(parts[0])][Integer.valueOf(parts[1])];
switchColor(select);
}
}
/**
* Method to switch the colour of a button.
*
* @param select specified Button
*/
private void switchColor(final JButton select) {
if (!select.getBorder().equals(SELECTED)) {
select.setBorder(SELECTED);
shipPlacePosition = select;
} else {
select.setBorder(new JButton().getBorder());
shipPlacePosition = null;
}
}
}
/**
* ActionListener for the State of the Game in which the Player has to shoot
* on the other Players board. SHOOT1 / SHOOT2
*/
private class ShootListener implements ActionListener {
@Override
public void actionPerformed(final ActionEvent e) {
JButton button = (JButton) e.getSource();
String[] name = button.getName().split(" ");
int x = Integer.parseInt(name[0]);
int y = Integer.parseInt(name[1]);
master.shoot(x, y);
}
}
/**
* ActionListener for the State of the game where the game is over and the
* game starts. START / END
*/
private class MenuListener implements ActionListener {
@Override
public void actionPerformed(final ActionEvent e) {
menuFrame.setVisible(false);
JButton target = (JButton) e.getSource();
if (target.getText().equals("Exit")) {
System.exit(0);
} else {
master.startGame();
}
}
}
/**
* ActionListener for the GETNAME 1 / 2 - States.
*/
private class PlayerListener implements ActionListener {
@Override
public void actionPerformed(final ActionEvent e) {
notifyframe.setVisible(false);
master.setPlayerName(player.getText());
}
}
/**
* ActionListener for the WIN 1 / 2 - States.
*/
private class WinListener implements ActionListener {
@Override
public final void actionPerformed(final ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button.equals(endPlayer1)) {
updateGameField(master.getPlayer2(), false);
} else if (button.equals(endPlayer2)) {
updateGameField(master.getPlayer1(), false);
} else {
setVisible(false);
east.removeAll();
menuFrame.setVisible(true);
menuFrame.toBack();
menuFrame.toFront();
}
}
}
} |
package org.voovan.tools.cache;
import org.voovan.Global;
import org.voovan.tools.CollectionSearch;
import org.voovan.tools.TEnv;
import org.voovan.tools.hashwheeltimer.HashWheelTask;
import org.voovan.tools.hashwheeltimer.HashWheelTimer;
import org.voovan.tools.json.annotation.NotJSON;
import org.voovan.tools.log.Logger;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
public class CachedHashMap<K,V> extends ConcurrentHashMap<K,V> implements CacheMap<K, V>{
protected final static HashWheelTimer wheelTimer = new HashWheelTimer(60, 1000);
private Function<K, V> supplier = null;
private boolean asyncBuild = true;
private int interval = 1;
private boolean autoRemove = true;
private Function destory;
private long expire = 0;
static {
wheelTimer.rotate();
}
private ConcurrentHashMap<K, TimeMark> cacheMark = new ConcurrentHashMap<K, TimeMark>();
private int maxSize;
/**
*
* @param maxSize ,
*/
public CachedHashMap(Integer maxSize){
this.maxSize = maxSize == null ? Integer.MAX_VALUE : maxSize;
}
public CachedHashMap(){
this.maxSize = Integer.MAX_VALUE;
}
/**
* Function
* @return Function
*/
public Function<K, V> getSupplier(){
return supplier;
}
/**
* Function
* @param buildFunction Function
* @param asyncBuild
* @return CachedHashMap
*/
public CachedHashMap<K, V> supplier(Function<K, V> buildFunction, boolean asyncBuild){
this.supplier = buildFunction;
this.asyncBuild = asyncBuild;
this.autoRemove = false;
return this;
}
/**
* Function
* @param buildFunction Function
* @return CachedHashMap
*/
public CachedHashMap<K, V> supplier(Function<K, V> buildFunction){
supplier(buildFunction, true);
this.autoRemove = false;
return this;
}
/**
*
* @return
*/
public Function getDestory() {
return destory;
}
/**
*
* @param destory , null , null
* @return CachedHashMap
*/
public CachedHashMap<K, V> destory(Function destory) {
this.destory = destory;
return this;
}
/**
*
* @param maxSize
* @return CachedHashMap
*/
public CachedHashMap<K, V> maxSize(int maxSize) {
this.maxSize = maxSize;
return this;
}
/**
*
* @param interval , :,
* @return CachedHashMap
*/
public CachedHashMap<K, V> interval(int interval) {
this.interval = interval;
return this;
}
/**
*
* @param autoRemove true: , false:
* @return CachedHashMap
*/
public CachedHashMap<K, V> autoRemove(boolean autoRemove) {
this.autoRemove = autoRemove;
return this;
}
/**
*
* @return
*/
public long getExpire() {
return expire;
}
/**
*
* @param expire
* @return CachedHashMap
*/
public CachedHashMap expire(long expire) {
this.expire = expire;
return this;
}
/**
*
* @return
*/
public ConcurrentHashMap<K, TimeMark> getCacheMark() {
return cacheMark;
}
/**
* CachedHashMap
* @return CachedHashMap
*/
public CachedHashMap<K, V> create(){
final CachedHashMap cachedHashMap = this;
if(interval >= 1) {
wheelTimer.addTask(new HashWheelTask() {
@Override
public void run() {
if (!cachedHashMap.getCacheMark().isEmpty()) {
for (TimeMark timeMark : (TimeMark[]) cachedHashMap.getCacheMark().values().toArray(new TimeMark[0])) {
if (timeMark.isExpire()) {
if (autoRemove) {
if(destory!= null) {
// null , null
if (destory.apply(cachedHashMap.get(timeMark.key)) == null) {
cachedHashMap.remove(timeMark.getKey());
cachedHashMap.cacheMark.remove(timeMark.getKey());
} else {
timeMark.refresh(true);
}
} else {
cachedHashMap.cacheMark.remove(timeMark.getKey());
cachedHashMap.remove(timeMark.getKey());
}
} else if (cachedHashMap.getSupplier() != null) {
cachedHashMap.createCache(timeMark.getKey(), cachedHashMap.supplier, timeMark.getExpireTime());
timeMark.refresh(true);
}
}
}
fixSize();
}
}
}, interval);
}
return this;
}
private void createCache(K key, Function<K, V> supplier, Long createExpire){
if(supplier==null){
return;
}
CachedHashMap cachedHashMap = this;
TimeMark timeMark = null;
synchronized (cacheMark) {
timeMark = cacheMark.get(key);
if (timeMark == null) {
timeMark = new TimeMark(this, key, createExpire);
cacheMark.put(key, timeMark);
}
}
TimeMark finalTimeMark = timeMark;
Long finalCreateExpire = createExpire;
synchronized (timeMark.createFlag) {
//, timeMark.createFlag ,
if (timeMark.tryLockOnCreate()) {
if (asyncBuild) {
Global.getThreadPool().execute(new Runnable() {
@Override
public void run() {
System.out.println("create");
generator(key, supplier, finalTimeMark, finalCreateExpire);
}
});
}
else {
generator(key, supplier, timeMark, createExpire);
}
}
}
try {
TEnv.wait(10*1000, ()-> finalTimeMark.isOnCreate());
} catch (TimeoutException e) {
Logger.error("wait supplier timeout: ", e);
}
}
private void generator(K key, Function<K, V> supplier, TimeMark timeMark, Long createExpire){
try {
synchronized (supplier) {
V value = supplier.apply(key);
timeMark.refresh(true);
if(expire==Long.MAX_VALUE) {
this.put(key, value);
} else {
this.put(key, value, createExpire);
}
}
} catch (Exception e){
Logger.error("Create with supplier failed: ", e);
} finally {
timeMark.releaseCreateLock();
}
}
/**
*
*
* @param key
* @param appointedSupplier
* @param createExpire
* @param refresh
* @return
*/
@Override
public V get(Object key, Function<K, V> appointedSupplier, Long createExpire, boolean refresh){
if(cacheMark.containsKey(key) &&
!cacheMark.get(key).isExpire() &&
!cacheMark.get(key).isOnCreate()) {
cacheMark.get(key).refresh(refresh);
} else {
appointedSupplier = appointedSupplier==null ? supplier : appointedSupplier;
createExpire = createExpire==null ? expire : createExpire;
createCache((K)key, appointedSupplier, createExpire);
}
return super.get(key);
}
@Override
public void putAll(Map<? extends K, ? extends V> m){
putAll(m, expire);
}
/**
* Map
* @param m Map
* @param expire
*/
public void putAll(Map<? extends K, ? extends V> m, long expire){
for (Entry<? extends K, ? extends V> e : m.entrySet()) {
cacheMark.put(e.getKey(), new TimeMark(this, e.getKey(), expire));
}
super.putAll(m);
}
@Override
public V put(K key, V value){
put(key, value, expire);
return value;
}
/**
*
* @param key
* @param value
* @param expire
* @return
*/
public V put(K key, V value, long expire){
if (key == null || value == null){
throw new NullPointerException();
}
cacheMark.putIfAbsent(key, new TimeMark(this, key, expire));
return super.put(key, value);
}
/**
*
* @param key
* @param value
* @return , ,,: null
*/
public V putIfAbsent(K key, V value){
return putIfAbsent(key, value, expire);
}
/**
*
* @param key
* @param value
* @param expire
* @return , ,,: null
*/
public V putIfAbsent(K key, V value, long expire){
if (key == null || value == null){
throw new NullPointerException();
}
V result = super.putIfAbsent(key, value);
cacheMark.putIfAbsent(key, new TimeMark(this, key, expire));
if(result!=null){
return result;
} else {
return null;
}
}
/**
*
* @param key
* @return true: , false:
*/
public boolean isExpire(String key){
return cacheMark.get(key).isExpire();
}
private void fixSize() {
int diffSize = this.size() - maxSize;
if (diffSize > 0) {
TimeMark[] removedTimeMark = (TimeMark[]) CollectionSearch.newInstance(cacheMark.values()).addCondition("expireTime", CollectionSearch.Operate.NOT_EQUAL, 0L)
.addCondition("lastTime", CollectionSearch.Operate.LESS, System.currentTimeMillis()-1000)
.sort("visitCount")
.limit(10 * diffSize)
.sort("lastTime")
.limit(diffSize)
.search()
.toArray(new TimeMark[0]);
for (TimeMark timeMark : removedTimeMark) {
System.out.println("remove");
cacheMark.remove(timeMark.getKey());
this.remove(timeMark.getKey());
}
}
}
@Override
public long getTTL(K key) {
return cacheMark.get(key).getExpireTime();
}
/**
*
*
* @param key
* @param expire
*/
@Override
public boolean setTTL(K key, long expire) {
TimeMark timeMark = cacheMark.get(key);
if(timeMark==null && !cacheMark.containsKey(key)){
return false;
} else {
timeMark.setExpireTime(expire);
timeMark.refresh(true);
}
return true;
}
@Override
public V remove(Object key){
cacheMark.remove(key);
return super.remove(key);
}
@Override
public boolean remove(Object key, Object value){
cacheMark.remove(key);
return super.remove(key, value);
}
@Override
public void clear() {
cacheMark.clear();
super.clear();
}
private class TimeMark<K> {
@NotJSON
private CachedHashMap<K,V> mainMap;
private K key;
private AtomicLong expireTime = new AtomicLong(0);
private AtomicLong lastTime = new AtomicLong(0);
private volatile AtomicLong visitCount = new AtomicLong(0);
private volatile AtomicBoolean createFlag = new AtomicBoolean(false);
public TimeMark(CachedHashMap<K,V> mainMap, K key, long expireTime){
this.key = key;
this.mainMap = mainMap;
this.expireTime.set(expireTime);
visitCount.set(0);
refresh(true);
}
public void refresh(boolean updateLastTime){
visitCount.incrementAndGet();
if(updateLastTime) {
this.lastTime.set(System.currentTimeMillis());
}
}
/**
*
* @return true: , false:
*/
public boolean isExpire(){
if(expireTime.get()>0 && System.currentTimeMillis() - lastTime.get() >= expireTime.get()*1000){
return true;
} else {
return false;
}
}
public CachedHashMap<K, V> getMainMap() {
return mainMap;
}
public K getKey() {
return key;
}
public long getExpireTime() {
return expireTime.get();
}
public void setExpireTime(long expireTime) {
this.expireTime.set(expireTime);
}
public Long getLastTime() {
return lastTime.get();
}
public AtomicLong getVisitCount() {
return visitCount;
}
public boolean isOnCreate(){
return createFlag.get();
}
public boolean tryLockOnCreate() {
return createFlag.compareAndSet(false, true);
}
public void releaseCreateLock() {
createFlag.set(false);
}
}
} |
package org.voovan.tools.collection;
import org.rocksdb.*;
import org.voovan.Global;
import org.voovan.tools.TByte;
import org.voovan.tools.TFile;
import org.voovan.tools.Varint;
import org.voovan.tools.exception.ParseException;
import org.voovan.tools.exception.RocksMapException;
import org.voovan.tools.log.Logger;
import org.voovan.tools.serialize.TSerialize;
import java.io.Closeable;
import java.io.File;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.*;
import java.util.Comparator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
public class RocksMap<K, V> implements SortedMap<K, V>, Closeable {
static {
RocksDB.loadLibrary();
}
public final static String DEFAULT_DB_NAME = "Default";
private static byte[] DATA_BYTES = "data".getBytes();
// db TransactionDB
private static Map<String, RocksDB> ROCKSDB_MAP = new ConcurrentHashMap<String, RocksDB>();
// TransactionDB
private static Map<RocksDB, Map<String, ColumnFamilyHandle>> COLUMN_FAMILY_HANDLE_MAP = new ConcurrentHashMap<RocksDB, Map<String, ColumnFamilyHandle>>();
private static String DEFAULT_DB_PATH = ".rocksdb"+ File.separator;
private static String DEFAULT_WAL_PATH = DEFAULT_DB_PATH + ".wal"+ File.separator;
/**
*
* @return
*/
public static String getDefaultDbPath() {
return DEFAULT_DB_PATH;
}
/**
*
* @param defaultDbPath
*/
public static void setDefaultDbPath(String defaultDbPath) {
DEFAULT_DB_PATH = defaultDbPath.endsWith(File.separator) ? defaultDbPath : defaultDbPath + File.separator;
}
/**
* WAL
* @return WAL
*/
public static String getDefaultWalPath() {
return DEFAULT_WAL_PATH;
}
/**
* WAL
* @param defaultWalPath WAL
*/
public static void setDefaultWalPath(String defaultWalPath) {
DEFAULT_WAL_PATH = defaultWalPath.endsWith(File.separator) ? defaultWalPath : defaultWalPath + File.separator;;
}
/**
*
* @param rocksDB RocksDB
* @param columnFamilyName
* @return
*/
private static ColumnFamilyHandle getColumnFamilyHandler(RocksDB rocksDB, String columnFamilyName) {
return COLUMN_FAMILY_HANDLE_MAP.get(rocksDB).get(columnFamilyName);
}
/**
* RocksDB
* @param rocksDB RocksDB
*/
private static void closeRocksDB(RocksDB rocksDB) {
for (ColumnFamilyHandle columnFamilyHandle : COLUMN_FAMILY_HANDLE_MAP.get(rocksDB).values()) {
columnFamilyHandle.close();
}
try {
rocksDB.syncWal();
} catch (RocksDBException e) {
e.printStackTrace();
}
rocksDB.close();
COLUMN_FAMILY_HANDLE_MAP.remove(rocksDB);
}
public static byte[] serialize(Object obj) {
return obj == null ? new byte[0] : TSerialize.serialize(obj);
}
public static Object unserialize(byte[] obj) {
return obj==null || obj.length == 0 ? null : TSerialize.unserialize(obj);
}
public transient DBOptions dbOptions;
public transient ReadOptions readOptions;
public transient WriteOptions writeOptions;
public transient ColumnFamilyOptions columnFamilyOptions;
private transient RocksDB rocksDB;
private transient ColumnFamilyHandle dataColumnFamilyHandle;
private transient ThreadLocal<Transaction> threadLocalTransaction = new ThreadLocal<Transaction>();
private transient ThreadLocal<Integer> threadLocalSavePointCount = ThreadLocal.withInitial(()->new Integer(0));
private transient String dbname;
private transient String dataPath;
private transient String walPath;
private transient String columnFamilyName;
private transient Boolean readOnly;
private transient Boolean isDuplicate = false;
private transient int transactionLockTimeout = 5000;
public RocksMap() {
this(null, null, null, null, null, null, null);
}
/**
*
* @param columnFamilyName
*/
public RocksMap(String columnFamilyName) {
this(null, columnFamilyName, null, null, null, null, null);
}
/**
*
* @param dbname ,
* @param columnFamilyName
*/
public RocksMap(String dbname, String columnFamilyName) {
this(dbname, columnFamilyName, null, null, null, null, null);
}
/**
*
* @param readOnly
*/
public RocksMap(boolean readOnly) {
this(null, null, null, null, null, null, readOnly);
}
/**
*
* @param columnFamilyName
* @param readOnly
*/
public RocksMap(String columnFamilyName, boolean readOnly) {
this(null, columnFamilyName, null, null, null, null, readOnly);
}
/**
*
* @param dbname ,
* @param columnFamilyName
* @param readOnly
*/
public RocksMap(String dbname, String columnFamilyName, boolean readOnly) {
this(dbname, columnFamilyName, null, null, null, null, readOnly);
}
/**
*
* @param dbname ,
* @param columnFamilyName
* @param dbOptions DBOptions
* @param readOptions ReadOptions
* @param writeOptions WriteOptions
* @param columnFamilyOptions
* @param readOnly
*/
public RocksMap(String dbname, String columnFamilyName, ColumnFamilyOptions columnFamilyOptions, DBOptions dbOptions, ReadOptions readOptions, WriteOptions writeOptions, Boolean readOnly) {
this.dbname = dbname == null ? DEFAULT_DB_NAME : dbname;
this.columnFamilyName = columnFamilyName == null ? "voovan_default" : columnFamilyName;
this.readOptions = readOptions == null ? new ReadOptions() : readOptions;
this.writeOptions = writeOptions == null ? new WriteOptions() : writeOptions;
this.columnFamilyOptions = columnFamilyOptions == null ? new ColumnFamilyOptions() : columnFamilyOptions;
this.readOnly = readOnly == null ? false : readOnly;
Options options = new Options();
options.setCreateIfMissing(true);
options.setCreateMissingColumnFamilies(true);
if(dbOptions == null) {
//Rocksdb
this.dbOptions = new DBOptions(options);
} else {
this.dbOptions = dbOptions;
}
this.dataPath = DEFAULT_DB_PATH + this.dbname;
this.walPath = DEFAULT_WAL_PATH +this.dbname;
this.dbOptions.useDirectIoForFlushAndCompaction();
this.dbOptions.setWalDir(walPath);
TFile.mkdir(dataPath);
TFile.mkdir(this.dbOptions.walDir());
rocksDB = ROCKSDB_MAP.get(this.dbname);
try {
if (rocksDB == null || this.readOnly) {
List<ColumnFamilyDescriptor> DEFAULT_CF_DESCRIPTOR_LIST = new ArrayList<ColumnFamilyDescriptor>();
{
List<byte[]> columnFamilyNameBytes = RocksDB.listColumnFamilies(new Options(), DEFAULT_DB_PATH + this.dbname);
if (columnFamilyNameBytes.size() > 0) {
for (byte[] columnFamilyNameByte : columnFamilyNameBytes) {
ColumnFamilyDescriptor columnFamilyDescriptor = new ColumnFamilyDescriptor(columnFamilyNameByte, this.columnFamilyOptions);
DEFAULT_CF_DESCRIPTOR_LIST.add(columnFamilyDescriptor);
}
}
if (DEFAULT_CF_DESCRIPTOR_LIST.size() == 0) {
DEFAULT_CF_DESCRIPTOR_LIST.add( new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY, this.columnFamilyOptions));
}
}
//ColumnFamilyHandle
List<ColumnFamilyHandle> columnFamilyHandleList = new ArrayList<ColumnFamilyHandle>();
// Rocksdb
if (this.readOnly) {
rocksDB = TransactionDB.openReadOnly(this.dbOptions, DEFAULT_DB_PATH + this.dbname, DEFAULT_CF_DESCRIPTOR_LIST, columnFamilyHandleList);
} else {
rocksDB = TransactionDB.open(this.dbOptions, new TransactionDBOptions(), DEFAULT_DB_PATH + this.dbname, DEFAULT_CF_DESCRIPTOR_LIST, columnFamilyHandleList);
ROCKSDB_MAP.put(this.dbname, rocksDB);
}
Map<String, ColumnFamilyHandle> columnFamilyHandleMap = new ConcurrentHashMap<String, ColumnFamilyHandle>();
for(ColumnFamilyHandle columnFamilyHandle : columnFamilyHandleList) {
columnFamilyHandleMap.put(new String(columnFamilyHandle.getName()), columnFamilyHandle);
}
COLUMN_FAMILY_HANDLE_MAP.put(rocksDB, columnFamilyHandleMap);
}
choseColumnFamily(this.columnFamilyName);
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap initilize failed, " + e.getMessage(), e);
}
}
private RocksMap(RocksMap<K,V> rocksMap, String columnFamilyName, boolean shareTransaction){
this.dbOptions = new DBOptions(rocksMap.dbOptions);
this.readOptions = new ReadOptions(rocksMap.readOptions);
this.writeOptions = new WriteOptions(rocksMap.writeOptions);
this.columnFamilyOptions = new ColumnFamilyOptions(rocksMap.columnFamilyOptions);
this.rocksDB = rocksMap.rocksDB;
if(shareTransaction) {
this.threadLocalTransaction = rocksMap.threadLocalTransaction;
this.threadLocalSavePointCount = rocksMap.threadLocalSavePointCount;
} else {
this.threadLocalTransaction = ThreadLocal.withInitial(()->null);
this.threadLocalSavePointCount = ThreadLocal.withInitial(()->new Integer(0));
}
this.dbname = rocksMap.dbname;
this.columnFamilyName = columnFamilyName;
this.readOnly = rocksMap.readOnly;
this.transactionLockTimeout = rocksMap.transactionLockTimeout;
this.isDuplicate = true;
this.choseColumnFamily(columnFamilyName);
}
/**
* , RocksMap
* @param cfName
* @return RocksMap
*/
public RocksMap<K,V> duplicate(String cfName){
return new RocksMap<K, V>(this, cfName, true);
}
/**
* RocksMAp
* @param cfName
* @param shareTransaction true: , false:
* @return RocksMap
*/
public RocksMap<K,V> duplicate(String cfName, boolean shareTransaction){
return new RocksMap<K, V>(this, cfName, shareTransaction);
}
public String getDbname() {
return dbname;
}
public String getDataPath() {
return dataPath;
}
public String getWalPath() {
return walPath;
}
public String getColumnFamilyName() {
return columnFamilyName;
}
public Boolean getReadOnly() {
return readOnly;
}
public int savePointCount() {
return threadLocalSavePointCount.get();
}
public RocksDB getRocksDB(){
return rocksDB;
}
/**
*
* @param dbName db
* @param backupPath , null
* @return BackupableDBOptions
*/
public static BackupableDBOptions createBackupableOption(String dbName, String backupPath) {
String defaultBackPath = backupPath==null ? DEFAULT_DB_PATH+".backups"+File.separator+dbName+File.separator : backupPath;
TFile.mkdir(defaultBackPath);
return new BackupableDBOptions(defaultBackPath);
}
public static BackupableDBOptions createBackupableOption(String dbName) {
return createBackupableOption(dbName, null);
}
public static BackupableDBOptions createBackupableOption(RocksMap rocksMap) {
return createBackupableOption(rocksMap.getDbname(), null);
}
/**
*
* @param backupableDBOptions
* @param beforeFlush flush
* @return
*/
public String createBackup(BackupableDBOptions backupableDBOptions, boolean beforeFlush) {
if(backupableDBOptions==null) {
backupableDBOptions = createBackupableOption(this.dbname);
}
try {
BackupEngine backupEngine = BackupEngine.open(rocksDB.getEnv(), backupableDBOptions);
backupEngine.createNewBackup(this.rocksDB, beforeFlush);
return backupableDBOptions.backupDir();
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap createBackup failed , " + e.getMessage(), e);
}
}
public String createBackup(BackupableDBOptions backupableDBOptions) {
return createBackup(backupableDBOptions, false);
}
public String createBackup() {
return createBackup(null, false);
}
/**
*
* @param backupableDBOptions
* @return
*/
public List<BackupInfo> getBackupInfo(BackupableDBOptions backupableDBOptions) {
if(backupableDBOptions==null) {
backupableDBOptions = createBackupableOption(this.dbname);
}
try {
BackupEngine backupEngine = BackupEngine.open(RocksEnv.getDefault(), backupableDBOptions);
return backupEngine.getBackupInfo();
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap getBackupInfo failed , " + e.getMessage(), e);
}
}
public List<BackupInfo> getBackupInfo() {
return getBackupInfo(null);
}
/**
*
* @param dbName ,
* @param backupableDBOptions
* @param keepLogfile wal
*/
public static void restoreLatestBackup(String dbName, BackupableDBOptions backupableDBOptions, Boolean keepLogfile) {
if(backupableDBOptions==null) {
backupableDBOptions = createBackupableOption(dbName);
}
try {
String dataPath = DEFAULT_DB_PATH + dbName;
String walPath = DEFAULT_WAL_PATH + dbName;
RestoreOptions restoreOptions = new RestoreOptions(keepLogfile);
BackupEngine backupEngine = BackupEngine.open(RocksEnv.getDefault(), backupableDBOptions);
backupEngine.restoreDbFromLatestBackup(dataPath, walPath, restoreOptions);
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap restoreFromLatestBackup failed , " + e.getMessage(), e);
}
}
public static void restoreLatestBackup() {
restoreLatestBackup(DEFAULT_DB_NAME, null, true);
}
/**
*
* @param backupId id
* @param dbName ,
* @param backupableDBOptions
* @param keepLogfile wal
*/
public static void restore(int backupId, String dbName, BackupableDBOptions backupableDBOptions, Boolean keepLogfile) {
if(backupableDBOptions==null) {
backupableDBOptions = createBackupableOption(dbName);
}
try {
String dataPath = DEFAULT_DB_PATH + dbName;
String walPath = DEFAULT_WAL_PATH + dbName;
RestoreOptions restoreOptions = new RestoreOptions(keepLogfile);
BackupEngine backupEngine = BackupEngine.open(RocksEnv.getDefault(), backupableDBOptions);
backupEngine.restoreDbFromBackup(backupId, dataPath, walPath, restoreOptions);
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap restore failed , " + e.getMessage(), e);
}
}
public static void restore(int backupId) throws RocksDBException {
restoreLatestBackup(DEFAULT_DB_NAME, null, true);
}
/**
*
* @param dbName
* @param backupableDBOptions
* @param number
*/
public static void PurgeOldBackups(String dbName, BackupableDBOptions backupableDBOptions, int number) {
if(backupableDBOptions==null) {
backupableDBOptions = createBackupableOption(dbName);
}
try {
BackupEngine backupEngine = BackupEngine.open(RocksEnv.getDefault(), backupableDBOptions);
backupEngine.purgeOldBackups(number);
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap PurgeOldBackups failed , " + e.getMessage(), e);
}
}
public int getColumnFamilyId(){
return getColumnFamilyId(this.columnFamilyName);
}
public void compact(){
try {
rocksDB.compactRange(dataColumnFamilyHandle);
} catch (RocksDBException e) {
throw new RocksMapException("compact failed", e);
}
}
public void compactRange(K start, K end){
try {
rocksDB.compactRange(dataColumnFamilyHandle, serialize(start), serialize(end));
} catch (RocksDBException e) {
throw new RocksMapException("compact failed", e);
}
}
private String getProperty(ColumnFamilyHandle columnFamilyHandle, String name) {
try {
return rocksDB.getProperty(columnFamilyHandle, "rocksdb." + name);
} catch (RocksDBException e) {
throw new RocksMapException("getProperty failed", e);
}
}
public String getProperty(String columnFamilyName, String name) {
try {
ColumnFamilyHandle columnFamilyHandle = getColumnFamilyHandler(rocksDB, columnFamilyName);
if(columnFamilyHandle != null) {
return rocksDB.getProperty(columnFamilyHandle, "rocksdb." + name);
} else {
return "ColumnFamily: " + columnFamilyName + " not exists";
}
} catch (RocksDBException e) {
throw new RocksMapException("getProperty failed", e);
}
}
public String getProperty(String name) {
try {
return rocksDB.getProperty(this.dataColumnFamilyHandle, "rocksdb." + name);
} catch (RocksDBException e) {
throw new RocksMapException("getProperty failed", e);
}
}
/**
*
* @return
*/
public Long getLastSequence() {
return rocksDB.getLatestSequenceNumber();
}
/**
*
* @param sequenceNumber
* @param withSerial
* @return
*/
public List<RocksWalRecord> getWalSince(Long sequenceNumber, boolean withSerial) {
return getWalBetween(sequenceNumber, null, null, withSerial);
}
/**
*
* @param startSequence
* @param filter ,
* @param withSerial
* @return
*/
public List<RocksWalRecord> getWalSince(Long startSequence, BiFunction<Integer, Integer, Boolean> filter, boolean withSerial) {
return getWalBetween(startSequence, null, filter, withSerial);
}
/**
*
* @param startSequence
* @param endSequence
* @param withSerial
* @return
*/
public List<RocksWalRecord> getWalSince(Long startSequence, Long endSequence, boolean withSerial) {
return getWalBetween(startSequence, endSequence, null, withSerial);
}
/**
*
* start end
* @param startSequence
* @param endSequence
* @param filter ,
* @param withSerial
* @return
*/
public List<RocksWalRecord> getWalBetween(Long startSequence, Long endSequence, BiFunction<Integer, Integer, Boolean> filter, boolean withSerial) {
try (TransactionLogIterator transactionLogIterator = rocksDB.getUpdatesSince(startSequence)) {
ArrayList<RocksWalRecord> rocksWalRecords = new ArrayList<RocksWalRecord>();
if(startSequence > getLastSequence()) {
return rocksWalRecords;
}
if(endSequence!=null && startSequence > endSequence) {
throw new RocksMapException("startSequence is large than endSequence");
}
long seq = 0l;
while (transactionLogIterator.isValid()) {
TransactionLogIterator.BatchResult batchResult = transactionLogIterator.getBatch();
if (batchResult.sequenceNumber() < startSequence) {
transactionLogIterator.next();
continue;
}
if(endSequence!=null && batchResult.sequenceNumber() > endSequence) {
break;
}
seq = batchResult.sequenceNumber();
try (WriteBatch writeBatch = batchResult.writeBatch()) {
List<RocksWalRecord> rocksWalRecordBySeq = RocksWalRecord.parse(ByteBuffer.wrap(writeBatch.data()), filter, withSerial);
rocksWalRecords.addAll(rocksWalRecordBySeq);
writeBatch.clear();
}
transactionLogIterator.next();
}
if(rocksWalRecords.size() > 0)
Logger.debug("wal between: " + startSequence + "->" + endSequence + ", " + rocksWalRecords.get(0).getSequence() + "->" + rocksWalRecords.get(rocksWalRecords.size()-1).getSequence());
return rocksWalRecords;
} catch (RocksDBException e) {
throw new RocksMapException("getUpdatesSince failed, " + e.getMessage(), e);
}
}
public int getColumnFamilyId(String columnFamilyName){
ColumnFamilyHandle columnFamilyHandle = getColumnFamilyHandler(rocksDB, columnFamilyName);
if(columnFamilyHandle!=null){
return columnFamilyHandle.getID();
} else {
throw new RocksMapException("ColumnFamily [" + columnFamilyName +"] not found.");
}
}
/**
* Columnt
* @param cfName columnFamily
* @return RocksMap
*/
public RocksMap<K, V> choseColumnFamily(String cfName) {
try {
dataColumnFamilyHandle = getColumnFamilyHandler(rocksDB, cfName);
if (dataColumnFamilyHandle == null) {
ColumnFamilyDescriptor columnFamilyDescriptor = new ColumnFamilyDescriptor(cfName.getBytes(), columnFamilyOptions);
dataColumnFamilyHandle = rocksDB.createColumnFamily(columnFamilyDescriptor);
COLUMN_FAMILY_HANDLE_MAP.get(rocksDB).putIfAbsent(new String(dataColumnFamilyHandle.getName()), dataColumnFamilyHandle);
}
this.columnFamilyName = cfName;
return this;
} catch(RocksDBException e){
throw new RocksMapException("RocksMap initilize failed, " + e.getMessage(), e);
}
}
/**
*
* @return
*/
public int getTransactionLockTimeout() {
return transactionLockTimeout;
}
/**
*
* @param transactionLockTimeout
*/
public void setTransactionLockTimeout(int transactionLockTimeout) {
this.transactionLockTimeout = transactionLockTimeout;
}
/**
* (, ,)
*
* savepoint , , , savepont
* @param transFunction , Null ,
* @param <T>
* @return null: , null:
*/
public <T> T withTransaction(Function<RocksMap<K, V>, T> transFunction) {
return withTransaction(-1, true, false, transFunction);
}
/**
*
*
* savepoint , , , savepont
* @param expire
* @param deadlockDetect
* @param withSnapShot
* @param transFunction , Null ,
* @param <T>
* @return null: , null:
*/
public <T> T withTransaction(long expire, boolean deadlockDetect, boolean withSnapShot, Function<RocksMap<K, V>, T> transFunction) {
beginTransaction(expire, deadlockDetect, withSnapShot);
try {
T object = transFunction.apply(this);
if (object == null) {
rollback(false);
} else {
commit();
}
return object;
} catch (Throwable e) {
rollback(false);
throw e;
}
}
/**
*
*
* : -1, :true, : false
*/
public void beginTransaction() {
beginTransaction(-1, true, false);
}
/**
*
*
*
*
* snapshot
*
* snapshotsnapshot(head)()
* @param expire
* @param deadlockDetect
* @param withSnapShot
*/
public void beginTransaction(long expire, boolean deadlockDetect, boolean withSnapShot) {
baseBeginTransaction(expire, deadlockDetect, withSnapShot);
}
/**
*
*
*
*
* snapshot
*
* snapshotsnapshot(head)()
* @param expire
* @param deadlockDetect
* @param withSnapShot
* @return Transaction
*/
private Transaction baseBeginTransaction(long expire, boolean deadlockDetect, boolean withSnapShot) {
Transaction transaction = threadLocalTransaction.get();
if(transaction==null) {
transaction = createTransaction(expire, deadlockDetect, withSnapShot);
threadLocalTransaction.set(transaction);
} else {
savePoint();
}
return transaction;
}
private Transaction createTransaction(long expire, boolean deadlockDetect, boolean withSnapShot) {
if(readOnly){
throw new RocksMapException("RocksMap Not supported operation in read only mode");
}
TransactionOptions transactionOptions = new TransactionOptions();
transactionOptions.setExpiration(expire);
transactionOptions.setDeadlockDetect(deadlockDetect);
transactionOptions.setSetSnapshot(withSnapShot);
transactionOptions.setLockTimeout(transactionLockTimeout);
Transaction transaction = ((TransactionDB) rocksDB).beginTransaction(writeOptions, transactionOptions);
transactionOptions.close();
return transaction;
}
private void closeTransaction() {
Transaction transaction = threadLocalTransaction.get();
if(transaction!=null) {
transaction.close();
threadLocalTransaction.set(null);
}
}
private Transaction getTransaction(){
Transaction transaction = threadLocalTransaction.get();
if(transaction==null){
throw new RocksMapException("RocksMap is not in transaction model");
}
return transaction;
}
public void savePoint() {
Transaction transaction = getTransaction();
try {
transaction.setSavePoint();
threadLocalSavePointCount.set(threadLocalSavePointCount.get()+1);
} catch (RocksDBException e) {
throw new RocksMapException("commit failed, " + e.getMessage(), e);
}
}
public void rollbackSavePoint(){
Transaction transaction = getTransaction();
try {
transaction.rollbackToSavePoint();
threadLocalSavePointCount.set(threadLocalSavePointCount.get()-1);
} catch (RocksDBException e) {
throw new RocksMapException("commit failed, " + e.getMessage(), e);
}
}
public void commit() {
Transaction transaction = getTransaction();
if(threadLocalSavePointCount.get() == 0) {
commit(transaction);
} else {
threadLocalSavePointCount.set(threadLocalSavePointCount.get()-1);
}
}
private void commit(Transaction transaction) {
if (transaction != null) {
try {
transaction.commit();
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap commit failed, " + e.getMessage(), e);
} finally {
closeTransaction();
}
} else {
throw new RocksMapException("RocksMap is not in transaction model");
}
}
public void rollback() {
rollback(true);
}
/**
*
* @param all true: , false: savepoint
*/
public void rollback(boolean all) {
Transaction transaction = getTransaction();
if(all) {
rollback(transaction);
} else if(threadLocalSavePointCount.get()==0) {
rollback(transaction);
} else {
rollbackSavePoint();
}
}
private void rollback(Transaction transaction) {
if (transaction != null) {
try {
transaction.rollback();
} catch(RocksDBException e){
throw new RocksMapException("RocksMap rollback failed, " + e.getMessage(), e);
} finally{
closeTransaction();
}
} else {
throw new RocksMapException("RocksMap is not in transaction model");
}
}
@Override
public Comparator<? super K> comparator() {
return null;
}
private RocksIterator getIterator(){
Transaction transaction = threadLocalTransaction.get();
if(transaction!=null) {
return transaction.getIterator(readOptions, dataColumnFamilyHandle);
} else {
return rocksDB.newIterator(dataColumnFamilyHandle, readOptions);
}
}
@Override
public SortedMap<K,V> subMap(K fromKey, K toKey) {
TreeMap<K,V> subMap = new TreeMap<K,V>();
try (RocksIterator iterator = getIterator()){
byte[] fromKeyBytes = serialize(fromKey);
byte[] toKeyBytes = serialize(toKey);
if (fromKeyBytes == null) {
iterator.seekToFirst();
} else {
iterator.seek(fromKeyBytes);
}
while (iterator.isValid()) {
byte[] key = iterator.key();
if (toKey == null || !Arrays.equals(toKeyBytes, key)) {
subMap.put((K) unserialize(iterator.key()), (V) unserialize(iterator.value()));
} else {
subMap.put((K) unserialize(iterator.key()), (V) unserialize(iterator.value()));
break;
}
iterator.next();
}
return subMap;
}
}
@Override
public SortedMap<K,V> tailMap(K fromKey){
if(fromKey==null){
return null;
}
return subMap(fromKey, null);
}
@Override
public SortedMap<K,V> headMap(K toKey){
if(toKey == null){
return null;
}
return subMap(null, toKey);
}
@Override
public K firstKey() {
try (RocksIterator iterator = getIterator()) {
iterator.seekToFirst();
if (iterator.isValid()) {
return (K) unserialize(iterator.key());
}
return null;
}
}
@Override
public K lastKey() {
try (RocksIterator iterator = getIterator()) {
iterator.seekToLast();
if (iterator.isValid()) {
return (K) unserialize(iterator.key());
}
return null;
}
}
@Override
public int size() {
// try {
// return Integer.valueOf(rocksDB.getProperty(dataColumnFamilyHandle, "rocksdb.estimate-num-keys"));
// } catch (RocksDBException e) {
// e.printStackTrace();
int count = 0;
RocksIterator iterator = null;
try {
iterator = getIterator();
iterator.seekToFirst();
while (iterator.isValid()) {
iterator.next();
count++;
}
return count;
} finally {
if(iterator!=null){
iterator.close();
}
}
}
@Override
public boolean isEmpty() {
try (RocksIterator iterator = getIterator()){
iterator.seekToFirst();
return !iterator.isValid();
}
}
@Override
public boolean containsKey(Object key) {
byte[] values = null;
try {
Transaction transaction = threadLocalTransaction.get();
if(transaction!=null) {
values = transaction.get(dataColumnFamilyHandle, readOptions, serialize(key));
} else {
values = rocksDB.get(dataColumnFamilyHandle, readOptions, serialize(key));
}
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap containsKey " + key + " failed, " + e.getMessage(), e);
}
return values!=null;
}
@Override
public boolean containsValue(Object value) {
throw new UnsupportedOperationException();
}
/**
* ,
* @param key key
* @return key value
*/
public V lock(Object key){
return lock(key, true);
}
/**
*
* @param key key
*/
public void unlock(Object key) {
Transaction transaction = getTransaction();
transaction.undoGetForUpdate(serialize(key));
}
/**
*
* @param key key
* @param exclusive
* @return key value
*/
public V lock(Object key, boolean exclusive){
Transaction transaction = getTransaction();
try {
byte[] values = transaction.getForUpdate(readOptions, dataColumnFamilyHandle, serialize(key), exclusive);
return values==null ? null : (V) unserialize(values);
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap lock " + key + " failed, " + e.getMessage(), e);
}
}
private byte[] get(byte[] keyBytes) {
try {
byte[] values = null;
Transaction transaction = threadLocalTransaction.get();
if (transaction != null) {
values = transaction.getForUpdate(readOptions, dataColumnFamilyHandle, keyBytes, true);
} else {
values = rocksDB.get(dataColumnFamilyHandle, readOptions, keyBytes);
}
return values;
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap get failed, " + e.getMessage(), e);
}
}
@Override
public V get(Object key) {
if(key == null){
throw new NullPointerException();
}
byte[] values = get(serialize(key));
return values==null ? null : (V) unserialize(values);
}
public List<V> getAll(Collection<K> keys) {
ArrayList<V> values = new ArrayList<V>(keys.size());
Iterator<K> keysIterator = keys.iterator();
while (keysIterator.hasNext()) {
values.add(get(keysIterator.next()));
}
return values;
}
private byte[] put(byte[] keyBytes, byte[] valueBytes, boolean isRetVal) {
if(keyBytes == null || valueBytes == null){
throw new NullPointerException();
}
try {
byte[] oldValueBytes = null;
if(isRetVal) {
oldValueBytes = get(keyBytes);
}
Transaction transaction = threadLocalTransaction.get();
if (transaction != null) {
transaction.put(dataColumnFamilyHandle, keyBytes, valueBytes);
} else {
rocksDB.put(dataColumnFamilyHandle, writeOptions, keyBytes, valueBytes);
}
return oldValueBytes;
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap put failed, " + e.getMessage(), e);
}
}
public void empty(Object key) {
put(serialize(key), null);
}
public Object put(Object key, Object value, boolean isRetVal) {
return put(serialize(key), serialize(value), isRetVal);
}
@Override
public Object put(Object key, Object value) {
return put(serialize(key), serialize(value), true);
}
@Override
public V putIfAbsent(K key, V value) {
byte[] keyBytes = serialize(key);
byte[] valueBytes = serialize(value);
Transaction transaction = baseBeginTransaction(-1, true, false);
try {
byte[] oldValueBytes = transaction.getForUpdate(readOptions, dataColumnFamilyHandle, keyBytes, true);
if(oldValueBytes == null){
transaction.put(dataColumnFamilyHandle, keyBytes, valueBytes);
return null;
} else {
return (V) unserialize(oldValueBytes);
}
} catch (RocksDBException e) {
rollback();
throw new RocksMapException("RocksMap putIfAbsent error, " + e.getMessage(), e);
} finally {
commit();
}
}
/**
* key
* @param key key
* @return false key , true , key , boomfilter
*/
public boolean keyMayExists(K key) {
return keyMayExists(serialize(key));
}
private boolean keyMayExists(byte[] keyBytes) {
return rocksDB.keyMayExist(dataColumnFamilyHandle, keyBytes, null);
}
/**
* key
* @param key key
* @return false key , true , key
*/
public boolean isKeyExists(K key) {
return isKeyExists(serialize(key));
}
private boolean isKeyExists(byte[] keyBytes) {
boolean result = keyMayExists(keyBytes);
if(result) {
try {
return rocksDB.get(keyBytes) != null;
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap isKeyExists failed , " + e.getMessage(), e);
}
}
return result;
}
@Override
public boolean replace(K key, V oldValue, V newValue) {
byte[] keyBytes = serialize(key);
byte[] newValueBytes = serialize(newValue);
byte[] oldValueBytes = serialize(oldValue);
Transaction transaction = baseBeginTransaction(-1, true, false);
try {
byte[] oldDbValueBytes = transaction.getForUpdate(readOptions, dataColumnFamilyHandle, keyBytes, true);
if(oldDbValueBytes!=null && Arrays.equals(oldDbValueBytes, oldValueBytes)){
transaction.put(dataColumnFamilyHandle, keyBytes, newValueBytes);
return true;
} else {
return false;
}
} catch (RocksDBException e) {
rollback();
throw new RocksMapException("RocksMap replace failed , " + e.getMessage(), e);
} finally {
commit();
}
}
/**
* key
* @param keyBytes key
* @param isRetVal value
* @return , isRetVal=false , null
*/
private byte[] remove(byte[] keyBytes, boolean isRetVal) {
if(keyBytes == null){
throw new NullPointerException();
}
byte[] valueBytes = null;
if(isRetVal) {
valueBytes = get(keyBytes);
}
try {
if (!isRetVal || valueBytes != null) {
Transaction transaction = threadLocalTransaction.get();
if (transaction != null) {
transaction.delete(dataColumnFamilyHandle, keyBytes);
} else {
rocksDB.delete(dataColumnFamilyHandle, writeOptions, keyBytes);
}
}
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap remove failed , " + e.getMessage(), e);
}
return valueBytes;
}
/**
* key
* @param key key
* @param isRetVal value
* @return , isRetVal=false , null
*/
public V remove(Object key, boolean isRetVal) {
if(key == null){
throw new NullPointerException();
}
byte[] valuesByte = remove(serialize(key), isRetVal);
return (V) unserialize(valuesByte);
}
@Override
public V remove(Object key) {
return remove(key, true);
}
public void removeAll(Collection<K> keys) {
if(keys == null){
throw new NullPointerException();
}
try {
Transaction transaction = threadLocalTransaction.get();
WriteBatch writeBatch = null;
if (transaction == null) {
writeBatch = THREAD_LOCAL_WRITE_BATCH.get();
writeBatch.clear();
for(K key : keys) {
if(key == null){
continue;
}
try {
writeBatch.delete(dataColumnFamilyHandle, serialize(key));
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap removeAll " + key + " failed", e);
}
}
rocksDB.write(writeOptions, writeBatch);
} else {
for(K key : keys) {
if(key == null){
continue;
}
try {
transaction.delete(dataColumnFamilyHandle, serialize(key));
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap removeAll " + key + " failed", e);
}
}
}
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap removeAll write failed", e);
}
}
/**
* Removes the database entries in the range ["beginKey", "endKey"), i.e.,
* including "beginKey" and excluding "endKey". a non-OK status on error. It
* is not an error if no keys exist in the range ["beginKey", "endKey").
* @param fromKey key
* @param toKey key
*
*/
public void removeRange(K fromKey, K toKey){
removeRange(fromKey, toKey, true);
}
/**
* Removes the database entries in the range ["beginKey", "endKey"), i.e.,
* including "beginKey" and excluding "endKey". a non-OK status on error. It
* is not an error if no keys exist in the range ["beginKey", "endKey").
* @param fromKey key
* @param toKey key
* @param useTransaction
*
*/
public void removeRange(K fromKey, K toKey, boolean useTransaction) {
Transaction transaction = useTransaction ? threadLocalTransaction.get() : null;
byte[] fromKeyBytes = serialize(fromKey);
byte[] toKeyBytes = serialize(toKey);
try {
if(transaction==null) {
rocksDB.deleteRange(dataColumnFamilyHandle, writeOptions, fromKeyBytes, toKeyBytes);
} else {
try (RocksIterator iterator = getIterator()) {
iterator.seek(fromKeyBytes);
while (iterator.isValid()) {
if (!Arrays.equals(iterator.key(), toKeyBytes)) {
transaction.delete(dataColumnFamilyHandle, iterator.key());
iterator.next();
} else {
break;
}
}
}
}
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap removeAll failed", e);
}
}
public static ThreadLocal<WriteBatch> THREAD_LOCAL_WRITE_BATCH = ThreadLocal.withInitial(()->new WriteBatch());
@Override
public void putAll(Map m) {
try {
Transaction transaction = threadLocalTransaction.get();
WriteBatch writeBatch = null;
if (transaction == null) {
writeBatch = THREAD_LOCAL_WRITE_BATCH.get();
writeBatch.clear();
Iterator<Entry> iterator = m.entrySet().iterator();
while (iterator.hasNext()) {
Entry entry = iterator.next();
Object key = entry.getKey();
Object value = entry.getValue();
writeBatch.put(dataColumnFamilyHandle, serialize(key), serialize(value));
}
rocksDB.write(writeOptions, writeBatch);
} else {
Iterator<Entry> iterator = m.entrySet().iterator();
while (iterator.hasNext()) {
Entry entry = iterator.next();
Object key = entry.getKey();
Object value = entry.getValue();
transaction.put(dataColumnFamilyHandle, serialize(key), serialize(value));
}
}
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap putAll failed", e);
}
}
/**
*
* @param sync
* @param allowStall
*/
public void flush(boolean sync, boolean allowStall){
try {
FlushOptions flushOptions = new FlushOptions();
flushOptions.setWaitForFlush(sync);
flushOptions.setAllowWriteStall(allowStall);
rocksDB.flush(flushOptions, this.dataColumnFamilyHandle);
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap flush failed", e);
}
}
/**
*
* @param allowStall stall
*/
public void flush(boolean allowStall){
flush(true, allowStall);
}
/**
* , not stall
*/
public void flush(){
flush(true, false);
}
/**
*
* @param sync
* @param allowStall
*/
public void flushAll(boolean sync, boolean allowStall) {
try {
Map<String, ColumnFamilyHandle> columnFamilyHandleMap = RocksMap.COLUMN_FAMILY_HANDLE_MAP.get(rocksDB);
List<ColumnFamilyHandle> columnFamilyHandleList = new ArrayList(columnFamilyHandleMap.values());
FlushOptions flushOptions = new FlushOptions();
flushOptions.setWaitForFlush(sync);
flushOptions.setAllowWriteStall(allowStall);
rocksDB.flush(flushOptions, columnFamilyHandleList);
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap flush all failed", e);
}
}
/**
*
* @param sync
* @param allowStall
*/
public void flushAll(boolean allowStall) {
flushAll(true, allowStall);
}
/**
* , not stall
*/
public void flushAll() {
flushAll(true, false);
}
/**
* WAL
* @param sync
*/
public void flushWal(boolean sync){
try {
rocksDB.flushWal(sync);
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap flushWal failed", e);
}
}
public void flushWal() {
flushWal(true);
}
@Override
public void clear() {
if(readOnly){
Logger.error("Clear failed, ", new RocksDBException("Not supported operation in read only mode"));
return;
}
try {
drop();
ColumnFamilyDescriptor columnFamilyDescriptor = new ColumnFamilyDescriptor(columnFamilyName.getBytes(), columnFamilyOptions);
dataColumnFamilyHandle = rocksDB.createColumnFamily(columnFamilyDescriptor);
COLUMN_FAMILY_HANDLE_MAP.get(rocksDB).put(new String(dataColumnFamilyHandle.getName()), dataColumnFamilyHandle);
dataColumnFamilyHandle = getColumnFamilyHandler(rocksDB, this.columnFamilyName);
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap clear failed", e);
}
}
public void drop(){
try {
rocksDB.dropColumnFamily(dataColumnFamilyHandle);
COLUMN_FAMILY_HANDLE_MAP.get(rocksDB).remove(new String(dataColumnFamilyHandle.getName()));
dataColumnFamilyHandle.close();
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap drop failed", e);
}
}
/**
* , Set Rocksdb
* @return Key set
*/
@Override
public Set keySet() {
TreeSet<K> keySet = new TreeSet<K>();
try (RocksIterator iterator = getIterator()){
iterator.seekToFirst();
while (iterator.isValid()) {
K k = (K) unserialize(iterator.key());
keySet.add(k);
iterator.next();
}
return keySet;
}
}
@Override
public Collection values() {
ArrayList<V> values = new ArrayList<V>();
try (RocksIterator iterator = getIterator()){
iterator.seekToFirst();
while (iterator.isValid()) {
V value = (V) unserialize(iterator.value());
values.add(value);
iterator.next();
}
return values;
}
}
/**
* , Set Rocksdb
* @return Entry set
*/
@Override
public Set<Entry<K, V>> entrySet() {
TreeSet<Entry<K,V>> entrySet = new TreeSet<Entry<K,V>>();
try (RocksIterator iterator = getIterator()) {
iterator.seekToFirst();
while (iterator.isValid()) {
entrySet.add(new RocksMapEntry<K, V>(this, iterator.key(), iterator.value()));
iterator.next();
}
return entrySet;
}
}
/**
* key
* @param key key
* @return Map
*/
public Map<K,V> startWith(K key) {
return startWith(key, 0,0);
}
/**
* key
* @param key key
* @param skipSize
* @param size
* @return Map
*/
public Map<K,V> startWith(K key, int skipSize, int size) {
byte[] keyBytes = serialize(key);
TreeMap<K,V> entryMap = new TreeMap<K,V>();
try (RocksMapIterator iterator = new RocksMapIterator(this, key, null, skipSize, size)) {
while (iterator.directNext(true)) {
if (TByte.byteArrayStartWith(iterator.keyBytes(), keyBytes)) {
entryMap.put((K) iterator.key(), (V) iterator.value());
} else {
break;
}
}
return entryMap;
}
}
@Override
public void close() {
Transaction transaction = threadLocalTransaction.get();
if(transaction!=null){
try {
transaction.rollback();
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap rollback on close failed", e);
} finally {
closeTransaction();
}
}
dbOptions.close();
readOptions.close();
writeOptions.close();
columnFamilyOptions.close();
dbOptions = null;
readOptions = null;
writeOptions = null;
columnFamilyOptions = null;
if(!isDuplicate) {
RocksMap.closeRocksDB(rocksDB);
}
}
/**
*
* @param fromKey key
* @param toKey key
* @param size
* @param skipSize
* @param size
* @return
*/
public RocksMapIterator<K,V> iterator(K fromKey, K toKey, int skipSize, int size){
return new RocksMapIterator(this, fromKey, toKey, skipSize, size);
}
/**
*
* @param fromKey key
* @param toKey key
* @return
*/
public RocksMapIterator<K,V> iterator(K fromKey, K toKey){
return new RocksMapIterator(this, fromKey, toKey, 0, 0);
}
/**
*
* @param skipSize
* @param size
* @return
*/
public RocksMapIterator<K,V> iterator(int skipSize, int size){
return new RocksMapIterator(this, null, null, skipSize, size);
}
/**
*
* @param size
* @return
*/
public RocksMapIterator<K,V> iterator(int size){
return new RocksMapIterator(this, null, null, 0, size);
}
/**
*
* @return
*/
public RocksMapIterator<K,V> iterator(){
return new RocksMapIterator(this, null, null, 0, 0);
}
/**
*
* @param checker , true: , false:
*/
public void scan(Function<RocksMap<K,V>.RocksMapEntry<K,V>, Boolean> checker) {
scan(null, null, checker, false);
}
/**
*
* @param checker , true: , false:
* @param disableWal wal
*/
public void scan(Function<RocksMap<K,V>.RocksMapEntry<K,V>, Boolean> checker, boolean disableWal) {
scan(null, null, checker, disableWal);
}
/**
*
* @param fromKey key
* @param toKey key
* @param checker , true: , false:
*/
public void scan(K fromKey, K toKey, Function<RocksMap<K,V>.RocksMapEntry<K,V>, Boolean> checker) {
scan(fromKey, toKey, checker, false);
}
/**
*
* @param fromKey key
* @param toKey key
* @param checker , true: , false:
* @param disableWal wal
*/
public void scan(K fromKey, K toKey, Function<RocksMap<K,V>.RocksMapEntry<K,V>, Boolean> checker, boolean disableWal) {
RocksMap<K,V> innerRocksMap = this.duplicate(this.getColumnFamilyName(), false);
if(disableWal) {
innerRocksMap.writeOptions.setSync(false);
}
innerRocksMap.writeOptions.setDisableWAL(disableWal);
try(RocksMap<K,V>.RocksMapIterator<K,V> iterator = innerRocksMap.iterator(fromKey, toKey)) {
RocksMap<K, V>.RocksMapEntry<K, V> rocksMapEntry = null;
while ((rocksMapEntry = iterator.nextAndValid(true))!=null) {
if (checker.apply(rocksMapEntry)) {
continue;
} else {
break;
}
}
}
innerRocksMap.close();
}
public class RocksMapEntry<K, V> implements Map.Entry<K, V>, Comparable<RocksMapEntry> {
private RocksMap<K,V> rocksMap;
private byte[] keyBytes;
private K k;
private byte[] valueBytes;
private V v;
protected RocksMapEntry(RocksMap<K, V> rocksMap, byte[] keyBytes, byte[] valueBytes) {
this.rocksMap = rocksMap;
this.keyBytes = keyBytes;
this.valueBytes = valueBytes;
}
@Override
public K getKey() {
if(k==null){
this.k = (K) unserialize(keyBytes);
}
return k;
}
@Override
public V getValue() {
if(v==null) {
this.v = (V) unserialize(valueBytes);
}
return v;
}
public byte[] getKeyBytes() {
return keyBytes;
}
public byte[] getValueBytes() {
return valueBytes;
}
@Override
public V setValue(V value) {
rocksMap.put(keyBytes, serialize(value));
return value;
}
@Override
public int compareTo(RocksMapEntry o) {
return TByte.byteArrayCompare(this.keyBytes, o.keyBytes);
}
@Override
public String toString(){
return getKey() + "=" + getValue();
}
public RocksMap<K, V> getRocksMap() {
return rocksMap;
}
public void remove(){
rocksMap.remove(keyBytes, false);
}
}
public class RocksMapIterator<K,V> implements Iterator<RocksMapEntry<K,V>>, Closeable{
private RocksMap<K,V> rocksMap;
private RocksIterator iterator;
private byte[] fromKeyBytes;
private byte[] toKeyBytes;
private int skipSize;
private int size = 0;
private int count=0;
//["beginKey", "endKey")
protected RocksMapIterator(RocksMap rocksMap, K fromKey, K toKey, int skipSize, int size) {
this.rocksMap = rocksMap;
this.iterator = rocksMap.getIterator();
this.fromKeyBytes = serialize(fromKey);
this.toKeyBytes = serialize(toKey);
this.skipSize = skipSize;
this.size = size;
if(fromKeyBytes==null) {
iterator.seekToFirst();
} else {
iterator.seek(fromKeyBytes);
}
if(skipSize >0) {
for(int i=0;i<=this.skipSize;i++) {
if(!directNext(false)) {
break;
}
}
}
count = 0;
}
/**
* Entry
* @return RocksMapEntry
*/
public RocksMapEntry<K, V> getEntry() {
return new RocksMapEntry(rocksMap, iterator.key(), iterator.value());
}
@Override
public boolean hasNext() {
boolean ret = false;
if(count == 0 && isValid()) {
return true;
}
if(!iterator.isValid()) {
return false;
}
try {
iterator.next();
ret = isValid();
} finally {
iterator.prev();
if(size!=0 && count > size - 1){
ret = false;
}
}
return ret;
}
/**
*
* @return true: , false:
*/
public boolean isValid(){
boolean ret;
if (toKeyBytes == null) {
ret = iterator.isValid();
} else {
ret = iterator.isValid() && TByte.byteArrayCompare(toKeyBytes, iterator.key()) != 0;
}
return ret;
}
/**
* Key
* @return Key
*/
public K key(){
return (K)unserialize(iterator.key());
}
/**
* value
* @return value
*/
public V value(){
return (V)unserialize(iterator.value());
}
/**
* Key
* @return Key
*/
public byte[] keyBytes(){
return iterator.key();
}
/**
* value
* @return value
*/
public byte[] valueBytes(){
return iterator.value();
}
/**
* next
* @param valid
* @return true: , false:
*/
public boolean directNext(boolean valid) {
if(count != 0) {
iterator.next();
}
boolean flag = false;
if(valid) {
flag = isValid();
} else {
flag = iterator.isValid();
}
if(flag) {
count++;
return true;
} else {
return false;
}
}
public RocksMapEntry<K,V> nextAndValid(boolean valid) {
if(directNext(true)) {
return getEntry();
} else {
return null;
}
}
@Override
public RocksMapEntry<K,V> next() {
return nextAndValid(false);
}
@Override
public void remove() {
try {
rocksMap.rocksDB.delete(rocksMap.dataColumnFamilyHandle, rocksMap.writeOptions, iterator.key());
} catch (RocksDBException e) {
throw new RocksMapException("RocksMapIterator remove failed", e);
}
}
@Override
public void forEachRemaining(Consumer<? super RocksMapEntry<K, V>> action) {
throw new UnsupportedOperationException();
}
public void close(){
iterator.close();
}
}
public static class RocksWalRecord {
// WriteBatch::rep_ :=
// sequence: fixed64
// count: fixed32
// data: record[count]
// record :=
// kTypeValue varstring varstring
// kTypeDeletion varstring
// kTypeSingleDeletion varstring
// kTypeRangeDeletion varstring varstring
// kTypeMerge varstring varstring
// kTypeColumnFamilyValue varint32 varstring varstring
// kTypeColumnFamilyDeletion varint32 varstring
// kTypeColumnFamilySingleDeletion varint32 varstring
// kTypeColumnFamilyRangeDeletion varint32 varstring varstring
// kTypeColumnFamilyMerge varint32 varstring varstring
// kTypeBeginPrepareXID varstring
// kTypeEndPrepareXID
// kTypeCommitXID varstring
// kTypeRollbackXID varstring
// kTypeBeginPersistedPrepareXID varstring
// kTypeBeginUnprepareXID varstring
// kTypeNoop
// varstring :=
// len: varint32
// data: uint8[len]
public static int TYPE_DELETION = 0x0;
public static int TYPE_VALUE = 0x1;
public static int TYPE_MERGE = 0x2;
public static int TYPE_LOGDATA = 0x3; // WAL only.
public static int TYPE_COLUMNFAMILY_DELETION = 0x4;
public static int TYPE_COLUMNFAMILY_VALUE = 0x5;
public static int TYPE_COLUMNFAMILY_MERGE = 0x6; // WAL only.
public static int TYPE_SINGLE_DELETION = 0x7;
public static int TYPE_COLUMNFAMILY_SINGLE_DELETION = 0x8; // WAL only.
public static int TYPE_BEGIN_PREPARE_XID = 0x9; // WAL only.
public static int TYPE_END_PREPARE_XID = 0xA; // WAL only.
public static int TYPE_COMMIT_XID = 0xB; // WAL only.
public static int TYPE_ROLLBACK_XID = 0xC; // WAL only.
public static int TYPE_NOOP = 0xD; // WAL only.
public static int TYPE_COLUMNFAMILY_RANGE_DELETION = 0xE; // WAL only.
public static int TYPE_RANGE_DELETION = 0xF; // meta block
public static int TYPE_COLUMNFAMILY_BLOB_INDEX = 0x10; // Blob DB only
public static int TYPE_BLOB_INDEX = 0x11; // Blob DB only
public static int TYPE_BEGIN_PERSISTED_PREPARE_XID = 0x12; // WAL only
public static int TYPE_BEGIN_UNPREPARE_XID = 0x13; // WAL only.
public static int[] TYPE_ELEMENT_COUNT = new int[]{
1, //0 kTypeDeletion varstring
2, //1 kTypeValue varstring varstring
2, //2 kTypeMerge varstring varstring
0,
1, //4 kTypeColumnFamilyDeletion varint32 varstring
2, //5 kTypeColumnFamilyValue varint32 varstring varstring
2, //6 kTypeColumnFamilyMerge varint32 varstring varstring
1, //7 kTypeSingleDeletion varstring
1, //8 kTypeColumnFamilySingleDeletion varint32 varstring
1, //9 kTypeBeginPrepareXID varstring
0, //A kTypeEndPrepareXID
1, //B kTypeCommitXID varstring
1, //C kTypeRollbackXID varstring
0, //D kTypeNoop
2, //E kTypeColumnFamilyRangeDeletion varint32 varstring varstring
0, //F kTypeRangeDeletion varstring varstring
0, //10 kTypeColumnFamilyBlobIndex
2, //11 kTypeBlobIndex varstring varstring
1, //12 kTypeBeginPersistedPrepareXID varstring
1 //13 kTypeBeginUnprepareXID varstring
};
private long sequence;
private int type;
private int columnFamilyId = 0;
private ArrayList<Object> chunks;
private RocksWalRecord(long sequence, int type, int columnFamilyId) {
this.sequence = sequence;
this.type = type;
this.columnFamilyId = columnFamilyId;
chunks = new ArrayList<Object>();
}
public long getSequence() {
return sequence;
}
private void setSequence(long sequence) {
this.sequence = sequence;
}
public int getType() {
return type;
}
private void setType(int type) {
this.type = type;
}
public int getColumnFamilyId() {
return columnFamilyId;
}
private void setColumnFamilyId(int columnFamilyId) {
this.columnFamilyId = columnFamilyId;
}
public ArrayList<Object> getChunks() {
return chunks;
}
/**
*
* @param byteBuffer
* @param withSerial
* @return
*/
public static List<RocksWalRecord> parse(ByteBuffer byteBuffer, boolean withSerial) {
return parse(byteBuffer, null, withSerial);
}
/**
*
* @param byteBuffer
* @param filter ,
* @param withSerial
* @return
*/
public static List<RocksWalRecord> parse(ByteBuffer byteBuffer, BiFunction<Integer, Integer, Boolean> filter, boolean withSerial) {
ByteOrder originByteOrder = byteBuffer.order();
byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
if(byteBuffer.remaining() < 13) {
throw new ParseException("not a correct recorder");
}
Long sequence = byteBuffer.getLong();
//Wal
int recordCount = byteBuffer.getInt();
List<RocksWalRecord> rocksWalRecords = new ArrayList<RocksWalRecord>();
for(int count=0;
count < recordCount && byteBuffer.hasRemaining();
count++) {
RocksWalRecord rocksWalRecord = parseOperation(byteBuffer, sequence, filter, withSerial);
if (rocksWalRecord != null) {
rocksWalRecords.add(rocksWalRecord);
}
}
byteBuffer.order(originByteOrder);
return rocksWalRecords;
}
/**
*
* @param byteBuffer
* @param sequence
* @param withSerial
* @return
*/
public static RocksWalRecord parseOperation(ByteBuffer byteBuffer, long sequence, boolean withSerial){
return parseOperation(byteBuffer, sequence, withSerial);
}
/**
*
* @param byteBuffer
* @param sequence
* @param filter ,
* @param withSerial
* @return
*/
public static RocksWalRecord parseOperation(ByteBuffer byteBuffer, long sequence, BiFunction<Integer, Integer, Boolean> filter, boolean withSerial){
int type = byteBuffer.get();
if (type == TYPE_NOOP) {
if(byteBuffer.hasRemaining()) {
type = byteBuffer.get();
} else {
return null;
}
}
int columnFamilyId=0;
if (type == TYPE_COLUMNFAMILY_DELETION ||
type == TYPE_COLUMNFAMILY_VALUE ||
type == TYPE_COLUMNFAMILY_MERGE ||
type == TYPE_COLUMNFAMILY_SINGLE_DELETION ||
type == TYPE_COLUMNFAMILY_RANGE_DELETION) {
columnFamilyId = Varint.varintToInt(byteBuffer);
}
RocksWalRecord rocksWalRecord = null;
if (type < TYPE_ELEMENT_COUNT.length) {
boolean isEnable = filter==null || filter.apply(columnFamilyId, type);
if(isEnable) {
rocksWalRecord = new RocksWalRecord(sequence, type, columnFamilyId);
}
for (int i = 0; i < TYPE_ELEMENT_COUNT[type] && byteBuffer.hasRemaining(); i++) {
int chunkSize = Varint.varintToInt(byteBuffer);
if(isEnable) {
byte[] chunkBytes = new byte[chunkSize];
byteBuffer.get(chunkBytes);
Object chunk = chunkBytes;
if (withSerial) {
chunk = unserialize(chunkBytes);
} else {
chunk = chunkBytes;
}
rocksWalRecord.getChunks().add(chunk);
} else {
byteBuffer.position(byteBuffer.position() + chunkSize);
}
}
}
return rocksWalRecord;
}
}
/**
* Wal, wal
*/
public static class RocksWalReader {
private Object mark;
private RocksMap rocksMap;
private Long lastSequence;
private int batchSeqsize;
private List<Integer> columnFamilys;
private List<Integer> walTypes;
public RocksWalReader(Object mark, RocksMap rocksMap, int batchSeqsize) {
this.mark = mark;
this.rocksMap = rocksMap;
this.batchSeqsize = batchSeqsize;
this.rocksMap = rocksMap;
this.lastSequence = (Long) this.rocksMap.get(mark);
this.lastSequence = this.lastSequence==null ? 0 : this.lastSequence;
Logger.debug("Start sequence: " + this.lastSequence);
}
public long getLastSequence() {
return lastSequence;
}
public List<Integer> getColumnFamily() {
return columnFamilys;
}
public void setColumnFamily(List<Integer> columnFamilys) {
this.columnFamilys = columnFamilys;
}
public int getBatchSeqsize() {
return batchSeqsize;
}
public List<Integer> getWalTypes() {
return walTypes;
}
public void setWalTypes(List<Integer> walTypes) {
this.walTypes = walTypes;
}
public void processing(RocksWalProcessor rocksWalProcessor){
//wal
Long endSequence = rocksMap.getLastSequence();
if(lastSequence + batchSeqsize < endSequence){
endSequence = lastSequence + batchSeqsize;
}
List<RocksWalRecord> rocksWalRecords = rocksMap.getWalBetween(lastSequence, endSequence, (columnFamilyId, type)-> {
return (walTypes == null ? true : walTypes.contains(type)) &&
(columnFamilys==null ? true : columnFamilys.contains(columnFamilyId));
}, true);
if(rocksWalRecords.size() > 0) {
rocksWalProcessor.process(endSequence, rocksWalRecords);
}
rocksMap.put(mark, endSequence);
lastSequence = endSequence;
}
public static interface RocksWalProcessor {
public void process(Long endSequence, List<RocksWalRecord> rocksWalRecords);
}
}
} |
package org.voovan.tools.collection;
import org.rocksdb.*;
import org.voovan.Global;
import org.voovan.tools.TByte;
import org.voovan.tools.TFile;
import org.voovan.tools.Varint;
import org.voovan.tools.exception.ParseException;
import org.voovan.tools.exception.RocksMapException;
import org.voovan.tools.log.Logger;
import org.voovan.tools.serialize.TSerialize;
import java.io.Closeable;
import java.io.File;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.*;
import java.util.Comparator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
public class RocksMap<K, V> implements SortedMap<K, V>, Closeable {
static {
RocksDB.loadLibrary();
}
public final static String DEFAULT_DB_NAME = "Default";
private static byte[] DATA_BYTES = "data".getBytes();
// db TransactionDB
private static Map<String, RocksDB> ROCKSDB_MAP = new ConcurrentHashMap<String, RocksDB>();
// TransactionDB
private static Map<RocksDB, Map<String, ColumnFamilyHandle>> COLUMN_FAMILY_HANDLE_MAP = new ConcurrentHashMap<RocksDB, Map<String, ColumnFamilyHandle>>();
private static String DEFAULT_DB_PATH = ".rocksdb"+ File.separator;
private static String DEFAULT_WAL_PATH = DEFAULT_DB_PATH + ".wal"+ File.separator;
/**
*
* @return
*/
public static String getDefaultDbPath() {
return DEFAULT_DB_PATH;
}
/**
*
* @param defaultDbPath
*/
public static void setDefaultDbPath(String defaultDbPath) {
DEFAULT_DB_PATH = defaultDbPath.endsWith(File.separator) ? defaultDbPath : defaultDbPath + File.separator;
}
/**
* WAL
* @return WAL
*/
public static String getDefaultWalPath() {
return DEFAULT_WAL_PATH;
}
/**
* WAL
* @param defaultWalPath WAL
*/
public static void setDefaultWalPath(String defaultWalPath) {
DEFAULT_WAL_PATH = defaultWalPath.endsWith(File.separator) ? defaultWalPath : defaultWalPath + File.separator;;
}
/**
*
* @param rocksDB RocksDB
* @param columnFamilyName
* @return
*/
private static ColumnFamilyHandle getColumnFamilyHandler(RocksDB rocksDB, String columnFamilyName) {
return COLUMN_FAMILY_HANDLE_MAP.get(rocksDB).get(columnFamilyName);
}
/**
* RocksDB
* @param rocksDB RocksDB
*/
private static void closeRocksDB(RocksDB rocksDB) {
for (ColumnFamilyHandle columnFamilyHandle : COLUMN_FAMILY_HANDLE_MAP.get(rocksDB).values()) {
columnFamilyHandle.close();
}
try {
rocksDB.syncWal();
} catch (RocksDBException e) {
e.printStackTrace();
}
rocksDB.close();
COLUMN_FAMILY_HANDLE_MAP.remove(rocksDB);
}
public static byte[] serialize(Object obj) {
return obj == null ? new byte[0] : TSerialize.serialize(obj);
}
public static Object unserialize(byte[] obj) {
return obj==null || obj.length == 0 ? null : TSerialize.unserialize(obj);
}
public transient DBOptions dbOptions;
public transient ReadOptions readOptions;
public transient WriteOptions writeOptions;
public transient ColumnFamilyOptions columnFamilyOptions;
private transient RocksDB rocksDB;
private transient ColumnFamilyHandle dataColumnFamilyHandle;
private transient ThreadLocal<Transaction> threadLocalTransaction = new ThreadLocal<Transaction>();
private transient ThreadLocal<Integer> threadLocalSavePointCount = ThreadLocal.withInitial(()->new Integer(0));
private transient String dbname;
private transient String dataPath;
private transient String walPath;
private transient String columnFamilyName;
private transient Boolean readOnly;
private transient Boolean isDuplicate = false;
private transient int transactionLockTimeout = 5000;
public RocksMap() {
this(null, null, null, null, null, null, null);
}
/**
*
* @param columnFamilyName
*/
public RocksMap(String columnFamilyName) {
this(null, columnFamilyName, null, null, null, null, null);
}
/**
*
* @param dbname ,
* @param columnFamilyName
*/
public RocksMap(String dbname, String columnFamilyName) {
this(dbname, columnFamilyName, null, null, null, null, null);
}
/**
*
* @param readOnly
*/
public RocksMap(boolean readOnly) {
this(null, null, null, null, null, null, readOnly);
}
/**
*
* @param columnFamilyName
* @param readOnly
*/
public RocksMap(String columnFamilyName, boolean readOnly) {
this(null, columnFamilyName, null, null, null, null, readOnly);
}
/**
*
* @param dbname ,
* @param columnFamilyName
* @param readOnly
*/
public RocksMap(String dbname, String columnFamilyName, boolean readOnly) {
this(dbname, columnFamilyName, null, null, null, null, readOnly);
}
/**
*
* @param dbname ,
* @param columnFamilyName
* @param dbOptions DBOptions
* @param readOptions ReadOptions
* @param writeOptions WriteOptions
* @param columnFamilyOptions
* @param readOnly
*/
public RocksMap(String dbname, String columnFamilyName, ColumnFamilyOptions columnFamilyOptions, DBOptions dbOptions, ReadOptions readOptions, WriteOptions writeOptions, Boolean readOnly) {
this.dbname = dbname == null ? DEFAULT_DB_NAME : dbname;
this.columnFamilyName = columnFamilyName == null ? "voovan_default" : columnFamilyName;
this.readOptions = readOptions == null ? new ReadOptions() : readOptions;
this.writeOptions = writeOptions == null ? new WriteOptions() : writeOptions;
this.columnFamilyOptions = columnFamilyOptions == null ? new ColumnFamilyOptions() : columnFamilyOptions;
this.readOnly = readOnly == null ? false : readOnly;
Options options = new Options();
options.setCreateIfMissing(true);
options.setCreateMissingColumnFamilies(true);
if(dbOptions == null) {
//Rocksdb
this.dbOptions = new DBOptions(options);
} else {
this.dbOptions = dbOptions;
}
this.dataPath = DEFAULT_DB_PATH + this.dbname;
this.walPath = DEFAULT_WAL_PATH +this.dbname;
this.dbOptions.useDirectIoForFlushAndCompaction();
this.dbOptions.setWalDir(walPath);
TFile.mkdir(dataPath);
TFile.mkdir(this.dbOptions.walDir());
rocksDB = ROCKSDB_MAP.get(this.dbname);
try {
if (rocksDB == null || this.readOnly) {
List<ColumnFamilyDescriptor> DEFAULT_CF_DESCRIPTOR_LIST = new ArrayList<ColumnFamilyDescriptor>();
{
List<byte[]> columnFamilyNameBytes = RocksDB.listColumnFamilies(new Options(), DEFAULT_DB_PATH + this.dbname);
if (columnFamilyNameBytes.size() > 0) {
for (byte[] columnFamilyNameByte : columnFamilyNameBytes) {
ColumnFamilyDescriptor columnFamilyDescriptor = new ColumnFamilyDescriptor(columnFamilyNameByte, this.columnFamilyOptions);
DEFAULT_CF_DESCRIPTOR_LIST.add(columnFamilyDescriptor);
}
}
if (DEFAULT_CF_DESCRIPTOR_LIST.size() == 0) {
DEFAULT_CF_DESCRIPTOR_LIST.add( new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY, this.columnFamilyOptions));
}
}
//ColumnFamilyHandle
List<ColumnFamilyHandle> columnFamilyHandleList = new ArrayList<ColumnFamilyHandle>();
// Rocksdb
if (this.readOnly) {
rocksDB = TransactionDB.openReadOnly(this.dbOptions, DEFAULT_DB_PATH + this.dbname, DEFAULT_CF_DESCRIPTOR_LIST, columnFamilyHandleList);
} else {
rocksDB = TransactionDB.open(this.dbOptions, new TransactionDBOptions(), DEFAULT_DB_PATH + this.dbname, DEFAULT_CF_DESCRIPTOR_LIST, columnFamilyHandleList);
ROCKSDB_MAP.put(this.dbname, rocksDB);
}
Map<String, ColumnFamilyHandle> columnFamilyHandleMap = new ConcurrentHashMap<String, ColumnFamilyHandle>();
for(ColumnFamilyHandle columnFamilyHandle : columnFamilyHandleList) {
columnFamilyHandleMap.put(new String(columnFamilyHandle.getName()), columnFamilyHandle);
}
COLUMN_FAMILY_HANDLE_MAP.put(rocksDB, columnFamilyHandleMap);
}
choseColumnFamily(this.columnFamilyName);
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap initilize failed, " + e.getMessage(), e);
}
}
private RocksMap(RocksMap<K,V> rocksMap, String columnFamilyName, boolean shareTransaction){
this.dbOptions = new DBOptions(rocksMap.dbOptions);
this.readOptions = new ReadOptions(rocksMap.readOptions);
this.writeOptions = new WriteOptions(rocksMap.writeOptions);
this.columnFamilyOptions = new ColumnFamilyOptions(rocksMap.columnFamilyOptions);
this.rocksDB = rocksMap.rocksDB;
if(shareTransaction) {
this.threadLocalTransaction = rocksMap.threadLocalTransaction;
this.threadLocalSavePointCount = rocksMap.threadLocalSavePointCount;
} else {
this.threadLocalTransaction = ThreadLocal.withInitial(()->null);
this.threadLocalSavePointCount = ThreadLocal.withInitial(()->new Integer(0));
}
this.dbname = rocksMap.dbname;
this.columnFamilyName = columnFamilyName;
this.readOnly = rocksMap.readOnly;
this.transactionLockTimeout = rocksMap.transactionLockTimeout;
this.isDuplicate = true;
this.choseColumnFamily(columnFamilyName);
}
/**
* , RocksMap
* @param cfName
* @return RocksMap
*/
public RocksMap<K,V> duplicate(String cfName){
return new RocksMap<K, V>(this, cfName, true);
}
/**
* RocksMAp
* @param cfName
* @param shareTransaction true: , false:
* @return RocksMap
*/
public RocksMap<K,V> duplicate(String cfName, boolean shareTransaction){
return new RocksMap<K, V>(this, cfName, shareTransaction);
}
public String getDbname() {
return dbname;
}
public String getDataPath() {
return dataPath;
}
public String getWalPath() {
return walPath;
}
public String getColumnFamilyName() {
return columnFamilyName;
}
public Boolean getReadOnly() {
return readOnly;
}
public int savePointCount() {
return threadLocalSavePointCount.get();
}
public RocksDB getRocksDB(){
return rocksDB;
}
/**
*
* @param dbName db
* @param backupPath , null
* @return BackupableDBOptions
*/
public static BackupableDBOptions createBackupableOption(String dbName, String backupPath) {
String defaultBackPath = backupPath==null ? DEFAULT_DB_PATH+".backups"+File.separator+dbName+File.separator : backupPath;
TFile.mkdir(defaultBackPath);
return new BackupableDBOptions(defaultBackPath);
}
public static BackupableDBOptions createBackupableOption(String dbName) {
return createBackupableOption(dbName, null);
}
public static BackupableDBOptions createBackupableOption(RocksMap rocksMap) {
return createBackupableOption(rocksMap.getDbname(), null);
}
/**
*
* @param backupableDBOptions
* @param beforeFlush flush
* @return
*/
public String createBackup(BackupableDBOptions backupableDBOptions, boolean beforeFlush) {
if(backupableDBOptions==null) {
backupableDBOptions = createBackupableOption(this.dbname);
}
try {
BackupEngine backupEngine = BackupEngine.open(rocksDB.getEnv(), backupableDBOptions);
backupEngine.createNewBackup(this.rocksDB, beforeFlush);
return backupableDBOptions.backupDir();
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap createBackup failed , " + e.getMessage(), e);
}
}
public String createBackup(BackupableDBOptions backupableDBOptions) {
return createBackup(backupableDBOptions, false);
}
public String createBackup() {
return createBackup(null, false);
}
/**
*
* @param backupableDBOptions
* @return
*/
public List<BackupInfo> getBackupInfo(BackupableDBOptions backupableDBOptions) {
if(backupableDBOptions==null) {
backupableDBOptions = createBackupableOption(this.dbname);
}
try {
BackupEngine backupEngine = BackupEngine.open(RocksEnv.getDefault(), backupableDBOptions);
return backupEngine.getBackupInfo();
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap getBackupInfo failed , " + e.getMessage(), e);
}
}
public List<BackupInfo> getBackupInfo() {
return getBackupInfo(null);
}
/**
*
* @param dbName ,
* @param backupableDBOptions
* @param keepLogfile wal
*/
public static void restoreLatestBackup(String dbName, BackupableDBOptions backupableDBOptions, Boolean keepLogfile) {
if(backupableDBOptions==null) {
backupableDBOptions = createBackupableOption(dbName);
}
try {
String dataPath = DEFAULT_DB_PATH + dbName;
String walPath = DEFAULT_WAL_PATH + dbName;
RestoreOptions restoreOptions = new RestoreOptions(keepLogfile);
BackupEngine backupEngine = BackupEngine.open(RocksEnv.getDefault(), backupableDBOptions);
backupEngine.restoreDbFromLatestBackup(dataPath, walPath, restoreOptions);
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap restoreFromLatestBackup failed , " + e.getMessage(), e);
}
}
public static void restoreLatestBackup() {
restoreLatestBackup(DEFAULT_DB_NAME, null, true);
}
/**
*
* @param backupId id
* @param dbName ,
* @param backupableDBOptions
* @param keepLogfile wal
*/
public static void restore(int backupId, String dbName, BackupableDBOptions backupableDBOptions, Boolean keepLogfile) {
if(backupableDBOptions==null) {
backupableDBOptions = createBackupableOption(dbName);
}
try {
String dataPath = DEFAULT_DB_PATH + dbName;
String walPath = DEFAULT_WAL_PATH + dbName;
RestoreOptions restoreOptions = new RestoreOptions(keepLogfile);
BackupEngine backupEngine = BackupEngine.open(RocksEnv.getDefault(), backupableDBOptions);
backupEngine.restoreDbFromBackup(backupId, dataPath, walPath, restoreOptions);
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap restore failed , " + e.getMessage(), e);
}
}
public static void restore(int backupId) throws RocksDBException {
restoreLatestBackup(DEFAULT_DB_NAME, null, true);
}
/**
*
* @param dbName
* @param backupableDBOptions
* @param number
*/
public static void PurgeOldBackups(String dbName, BackupableDBOptions backupableDBOptions, int number) {
if(backupableDBOptions==null) {
backupableDBOptions = createBackupableOption(dbName);
}
try {
BackupEngine backupEngine = BackupEngine.open(RocksEnv.getDefault(), backupableDBOptions);
backupEngine.purgeOldBackups(number);
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap PurgeOldBackups failed , " + e.getMessage(), e);
}
}
public int getColumnFamilyId(){
return getColumnFamilyId(this.columnFamilyName);
}
public void compact(){
try {
rocksDB.compactRange(dataColumnFamilyHandle);
} catch (RocksDBException e) {
throw new RocksMapException("compact failed", e);
}
}
public void compactRange(K start, K end){
try {
rocksDB.compactRange(dataColumnFamilyHandle, serialize(start), serialize(end));
} catch (RocksDBException e) {
throw new RocksMapException("compact failed", e);
}
}
private String getProperty(ColumnFamilyHandle columnFamilyHandle, String name) {
try {
return rocksDB.getProperty(columnFamilyHandle, "rocksdb." + name);
} catch (RocksDBException e) {
throw new RocksMapException("getProperty failed", e);
}
}
public String getProperty(String columnFamilyName, String name) {
try {
ColumnFamilyHandle columnFamilyHandle = getColumnFamilyHandler(rocksDB, columnFamilyName);
if(columnFamilyHandle != null) {
return rocksDB.getProperty(columnFamilyHandle, "rocksdb." + name);
} else {
return "ColumnFamily: " + columnFamilyName + " not exists";
}
} catch (RocksDBException e) {
throw new RocksMapException("getProperty failed", e);
}
}
public String getProperty(String name) {
try {
return rocksDB.getProperty(this.dataColumnFamilyHandle, "rocksdb." + name);
} catch (RocksDBException e) {
throw new RocksMapException("getProperty failed", e);
}
}
/**
*
* @return
*/
public Long getLastSequence() {
return rocksDB.getLatestSequenceNumber();
}
/**
*
* @param sequenceNumber
* @param withSerial
* @return
*/
public List<RocksWalRecord> getWalSince(Long sequenceNumber, boolean withSerial) {
return getWalBetween(sequenceNumber, null, null, withSerial);
}
/**
*
* @param startSequence
* @param filter ,
* @param withSerial
* @return
*/
public List<RocksWalRecord> getWalSince(Long startSequence, BiFunction<Integer, Integer, Boolean> filter, boolean withSerial) {
return getWalBetween(startSequence, null, filter, withSerial);
}
/**
*
* @param startSequence
* @param endSequence
* @param withSerial
* @return
*/
public List<RocksWalRecord> getWalSince(Long startSequence, Long endSequence, boolean withSerial) {
return getWalBetween(startSequence, endSequence, null, withSerial);
}
/**
*
* start end
* @param startSequence
* @param endSequence
* @param filter ,
* @param withSerial
* @return
*/
public List<RocksWalRecord> getWalBetween(Long startSequence, Long endSequence, BiFunction<Integer, Integer, Boolean> filter, boolean withSerial) {
try (TransactionLogIterator transactionLogIterator = rocksDB.getUpdatesSince(startSequence)) {
ArrayList<RocksWalRecord> rocksWalRecords = new ArrayList<RocksWalRecord>();
if(startSequence > getLastSequence()) {
return rocksWalRecords;
}
if(endSequence!=null && startSequence > endSequence) {
throw new RocksMapException("startSequence is large than endSequence");
}
long seq = 0l;
while (transactionLogIterator.isValid()) {
TransactionLogIterator.BatchResult batchResult = transactionLogIterator.getBatch();
if (batchResult.sequenceNumber() < startSequence) {
transactionLogIterator.next();
continue;
}
if(endSequence!=null && batchResult.sequenceNumber() > endSequence) {
break;
}
seq = batchResult.sequenceNumber();
try (WriteBatch writeBatch = batchResult.writeBatch()) {
List<RocksWalRecord> rocksWalRecordBySeq = RocksWalRecord.parse(ByteBuffer.wrap(writeBatch.data()), filter, withSerial);
rocksWalRecords.addAll(rocksWalRecordBySeq);
writeBatch.clear();
}
transactionLogIterator.next();
}
if(rocksWalRecords.size() > 0)
Logger.debug("wal between: " + startSequence + "->" + endSequence + ", " + rocksWalRecords.get(0).getSequence() + "->" + rocksWalRecords.get(rocksWalRecords.size()-1).getSequence());
return rocksWalRecords;
} catch (RocksDBException e) {
throw new RocksMapException("getUpdatesSince failed, " + e.getMessage(), e);
}
}
public int getColumnFamilyId(String columnFamilyName){
ColumnFamilyHandle columnFamilyHandle = getColumnFamilyHandler(rocksDB, columnFamilyName);
if(columnFamilyHandle!=null){
return columnFamilyHandle.getID();
} else {
throw new RocksMapException("ColumnFamily [" + columnFamilyName +"] not found.");
}
}
/**
* Columnt
* @param cfName columnFamily
* @return RocksMap
*/
public RocksMap<K, V> choseColumnFamily(String cfName) {
try {
dataColumnFamilyHandle = getColumnFamilyHandler(rocksDB, cfName);
if (dataColumnFamilyHandle == null) {
ColumnFamilyDescriptor columnFamilyDescriptor = new ColumnFamilyDescriptor(cfName.getBytes(), columnFamilyOptions);
dataColumnFamilyHandle = rocksDB.createColumnFamily(columnFamilyDescriptor);
COLUMN_FAMILY_HANDLE_MAP.get(rocksDB).putIfAbsent(new String(dataColumnFamilyHandle.getName()), dataColumnFamilyHandle);
}
this.columnFamilyName = cfName;
return this;
} catch(RocksDBException e){
throw new RocksMapException("RocksMap initilize failed, " + e.getMessage(), e);
}
}
/**
*
* @return
*/
public int getTransactionLockTimeout() {
return transactionLockTimeout;
}
/**
*
* @param transactionLockTimeout
*/
public void setTransactionLockTimeout(int transactionLockTimeout) {
this.transactionLockTimeout = transactionLockTimeout;
}
/**
* (, ,)
*
* savepoint , , , savepont
* @param transFunction , Null ,
* @param <T>
* @return null: , null:
*/
public <T> T withTransaction(Function<RocksMap<K, V>, T> transFunction) {
return withTransaction(-1, true, false, transFunction);
}
/**
*
*
* savepoint , , , savepont
* @param expire
* @param deadlockDetect
* @param withSnapShot
* @param transFunction , Null ,
* @param <T>
* @return null: , null:
*/
public <T> T withTransaction(long expire, boolean deadlockDetect, boolean withSnapShot, Function<RocksMap<K, V>, T> transFunction) {
beginTransaction(expire, deadlockDetect, withSnapShot);
try {
T object = transFunction.apply(this);
if (object == null) {
rollback(false);
} else {
commit();
}
return object;
} catch (Throwable e) {
rollback(false);
throw e;
}
}
/**
*
*
* : -1, :true, : false
*/
public void beginTransaction() {
beginTransaction(-1, true, false);
}
/**
*
*
*
*
* snapshot
*
* snapshotsnapshot(head)()
* @param expire
* @param deadlockDetect
* @param withSnapShot
*/
public void beginTransaction(long expire, boolean deadlockDetect, boolean withSnapShot) {
baseBeginTransaction(expire, deadlockDetect, withSnapShot);
}
/**
*
*
*
*
* snapshot
*
* snapshotsnapshot(head)()
* @param expire
* @param deadlockDetect
* @param withSnapShot
* @return Transaction
*/
private Transaction baseBeginTransaction(long expire, boolean deadlockDetect, boolean withSnapShot) {
Transaction transaction = threadLocalTransaction.get();
if(transaction==null) {
transaction = createTransaction(expire, deadlockDetect, withSnapShot);
threadLocalTransaction.set(transaction);
} else {
savePoint();
}
return transaction;
}
private Transaction createTransaction(long expire, boolean deadlockDetect, boolean withSnapShot) {
if(readOnly){
throw new RocksMapException("RocksMap Not supported operation in read only mode");
}
TransactionOptions transactionOptions = new TransactionOptions();
transactionOptions.setExpiration(expire);
transactionOptions.setDeadlockDetect(deadlockDetect);
transactionOptions.setSetSnapshot(withSnapShot);
transactionOptions.setLockTimeout(transactionLockTimeout);
Transaction transaction = ((TransactionDB) rocksDB).beginTransaction(writeOptions, transactionOptions);
transactionOptions.close();
return transaction;
}
private void closeTransaction() {
Transaction transaction = threadLocalTransaction.get();
if(transaction!=null) {
transaction.close();
threadLocalTransaction.set(null);
}
}
private Transaction getTransaction(){
Transaction transaction = threadLocalTransaction.get();
if(transaction==null){
throw new RocksMapException("RocksMap is not in transaction model");
}
return transaction;
}
public void savePoint() {
Transaction transaction = getTransaction();
try {
transaction.setSavePoint();
threadLocalSavePointCount.set(threadLocalSavePointCount.get()+1);
} catch (RocksDBException e) {
throw new RocksMapException("commit failed, " + e.getMessage(), e);
}
}
public void rollbackSavePoint(){
Transaction transaction = getTransaction();
try {
transaction.rollbackToSavePoint();
threadLocalSavePointCount.set(threadLocalSavePointCount.get()-1);
} catch (RocksDBException e) {
throw new RocksMapException("commit failed, " + e.getMessage(), e);
}
}
public void commit() {
Transaction transaction = getTransaction();
if(threadLocalSavePointCount.get() == 0) {
commit(transaction);
} else {
threadLocalSavePointCount.set(threadLocalSavePointCount.get()-1);
}
}
private void commit(Transaction transaction) {
if (transaction != null) {
try {
transaction.commit();
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap commit failed, " + e.getMessage(), e);
} finally {
closeTransaction();
}
} else {
throw new RocksMapException("RocksMap is not in transaction model");
}
}
public void rollback() {
rollback(true);
}
/**
*
* @param all true: , false: savepoint
*/
public void rollback(boolean all) {
Transaction transaction = getTransaction();
if(all) {
rollback(transaction);
} else if(threadLocalSavePointCount.get()==0) {
rollback(transaction);
} else {
rollbackSavePoint();
}
}
private void rollback(Transaction transaction) {
if (transaction != null) {
try {
transaction.rollback();
} catch(RocksDBException e){
throw new RocksMapException("RocksMap rollback failed, " + e.getMessage(), e);
} finally{
closeTransaction();
}
} else {
throw new RocksMapException("RocksMap is not in transaction model");
}
}
@Override
public Comparator<? super K> comparator() {
return null;
}
private RocksIterator getIterator(){
Transaction transaction = threadLocalTransaction.get();
if(transaction!=null) {
return transaction.getIterator(readOptions, dataColumnFamilyHandle);
} else {
return rocksDB.newIterator(dataColumnFamilyHandle, readOptions);
}
}
@Override
public SortedMap<K,V> subMap(K fromKey, K toKey) {
TreeMap<K,V> subMap = new TreeMap<K,V>();
try (RocksIterator iterator = getIterator()){
byte[] fromKeyBytes = serialize(fromKey);
byte[] toKeyBytes = serialize(toKey);
if (fromKeyBytes == null) {
iterator.seekToFirst();
} else {
iterator.seek(fromKeyBytes);
}
while (iterator.isValid()) {
byte[] key = iterator.key();
if (toKey == null || !Arrays.equals(toKeyBytes, key)) {
subMap.put((K) unserialize(iterator.key()), (V) unserialize(iterator.value()));
} else {
subMap.put((K) unserialize(iterator.key()), (V) unserialize(iterator.value()));
break;
}
iterator.next();
}
return subMap;
}
}
@Override
public SortedMap<K,V> tailMap(K fromKey){
if(fromKey==null){
return null;
}
return subMap(fromKey, null);
}
@Override
public SortedMap<K,V> headMap(K toKey){
if(toKey == null){
return null;
}
return subMap(null, toKey);
}
@Override
public K firstKey() {
try (RocksIterator iterator = getIterator()) {
iterator.seekToFirst();
if (iterator.isValid()) {
return (K) unserialize(iterator.key());
}
return null;
}
}
@Override
public K lastKey() {
try (RocksIterator iterator = getIterator()) {
iterator.seekToLast();
if (iterator.isValid()) {
return (K) unserialize(iterator.key());
}
return null;
}
}
@Override
public int size() {
// try {
// return Integer.valueOf(rocksDB.getProperty(dataColumnFamilyHandle, "rocksdb.estimate-num-keys"));
// } catch (RocksDBException e) {
// e.printStackTrace();
int count = 0;
RocksIterator iterator = null;
try {
iterator = getIterator();
iterator.seekToFirst();
while (iterator.isValid()) {
iterator.next();
count++;
}
return count;
} finally {
if(iterator!=null){
iterator.close();
}
}
}
@Override
public boolean isEmpty() {
try (RocksIterator iterator = getIterator()){
iterator.seekToFirst();
return !iterator.isValid();
}
}
@Override
public boolean containsKey(Object key) {
byte[] values = null;
try {
Transaction transaction = threadLocalTransaction.get();
if(transaction!=null) {
values = transaction.get(dataColumnFamilyHandle, readOptions, serialize(key));
} else {
values = rocksDB.get(dataColumnFamilyHandle, readOptions, serialize(key));
}
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap containsKey " + key + " failed, " + e.getMessage(), e);
}
return values!=null;
}
@Override
public boolean containsValue(Object value) {
throw new UnsupportedOperationException();
}
/**
* ,
* @param key key
* @return key value
*/
public V lock(Object key){
return lock(key, true);
}
/**
*
* @param key key
*/
public void unlock(Object key) {
Transaction transaction = getTransaction();
transaction.undoGetForUpdate(serialize(key));
}
/**
*
* @param key key
* @param exclusive
* @return key value
*/
public V lock(Object key, boolean exclusive){
Transaction transaction = getTransaction();
try {
byte[] values = transaction.getForUpdate(readOptions, dataColumnFamilyHandle, serialize(key), exclusive);
return values==null ? null : (V) unserialize(values);
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap lock " + key + " failed, " + e.getMessage(), e);
}
}
private byte[] get(byte[] keyBytes) {
try {
byte[] values = null;
Transaction transaction = threadLocalTransaction.get();
if (transaction != null) {
values = transaction.getForUpdate(readOptions, dataColumnFamilyHandle, keyBytes, true);
} else {
values = rocksDB.get(dataColumnFamilyHandle, readOptions, keyBytes);
}
return values;
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap get failed, " + e.getMessage(), e);
}
}
@Override
public V get(Object key) {
if(key == null){
throw new NullPointerException();
}
byte[] values = get(serialize(key));
return values==null ? null : (V) unserialize(values);
}
public List<V> getAll(Collection<K> keys) {
ArrayList<V> values = new ArrayList<V>(keys.size());
Iterator<K> keysIterator = keys.iterator();
while (keysIterator.hasNext()) {
values.add(get(keysIterator.next()));
}
return values;
}
private byte[] put(byte[] keyBytes, byte[] valueBytes, boolean isRetVal) {
if(keyBytes == null || valueBytes == null){
throw new NullPointerException();
}
try {
byte[] oldValueBytes = null;
if(isRetVal) {
oldValueBytes = get(keyBytes);
}
Transaction transaction = threadLocalTransaction.get();
if (transaction != null) {
transaction.put(dataColumnFamilyHandle, keyBytes, valueBytes);
} else {
rocksDB.put(dataColumnFamilyHandle, writeOptions, keyBytes, valueBytes);
}
return oldValueBytes;
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap put failed, " + e.getMessage(), e);
}
}
public void empty(Object key) {
put(serialize(key), null);
}
public Object put(Object key, Object value, boolean isRetVal) {
return put(serialize(key), serialize(value), isRetVal);
}
@Override
public Object put(Object key, Object value) {
return put(serialize(key), serialize(value), true);
}
@Override
public V putIfAbsent(K key, V value) {
byte[] keyBytes = serialize(key);
byte[] valueBytes = serialize(value);
Transaction transaction = baseBeginTransaction(-1, true, false);
try {
byte[] oldValueBytes = transaction.getForUpdate(readOptions, dataColumnFamilyHandle, keyBytes, true);
if(oldValueBytes == null){
transaction.put(dataColumnFamilyHandle, keyBytes, valueBytes);
return null;
} else {
return (V) unserialize(oldValueBytes);
}
} catch (RocksDBException e) {
rollback();
throw new RocksMapException("RocksMap putIfAbsent error, " + e.getMessage(), e);
} finally {
commit();
}
}
/**
* key
* @param key key
* @return false key , true , key , boomfilter
*/
public boolean keyMayExists(K key) {
return keyMayExists(serialize(key));
}
private boolean keyMayExists(byte[] keyBytes) {
return rocksDB.keyMayExist(dataColumnFamilyHandle, keyBytes, null);
}
/**
* key
* @param key key
* @return false key , true , key
*/
public boolean isKeyExists(K key) {
return isKeyExists(serialize(key));
}
private boolean isKeyExists(byte[] keyBytes) {
boolean result = keyMayExists(keyBytes);
if(result) {
try {
return rocksDB.get(keyBytes) != null;
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap isKeyExists failed , " + e.getMessage(), e);
}
}
return result;
}
@Override
public boolean replace(K key, V oldValue, V newValue) {
byte[] keyBytes = serialize(key);
byte[] newValueBytes = serialize(newValue);
byte[] oldValueBytes = serialize(oldValue);
Transaction transaction = baseBeginTransaction(-1, true, false);
try {
byte[] oldDbValueBytes = transaction.getForUpdate(readOptions, dataColumnFamilyHandle, keyBytes, true);
if(oldDbValueBytes!=null && Arrays.equals(oldDbValueBytes, oldValueBytes)){
transaction.put(dataColumnFamilyHandle, keyBytes, newValueBytes);
return true;
} else {
return false;
}
} catch (RocksDBException e) {
rollback();
throw new RocksMapException("RocksMap replace failed , " + e.getMessage(), e);
} finally {
commit();
}
}
/**
* key
* @param keyBytes key
* @param isRetVal value
* @return , isRetVal=false , null
*/
private byte[] remove(byte[] keyBytes, boolean isRetVal) {
if(keyBytes == null){
throw new NullPointerException();
}
byte[] valueBytes = null;
if(isRetVal) {
valueBytes = get(keyBytes);
}
try {
if (!isRetVal || valueBytes != null) {
Transaction transaction = threadLocalTransaction.get();
if (transaction != null) {
transaction.delete(dataColumnFamilyHandle, keyBytes);
} else {
rocksDB.delete(dataColumnFamilyHandle, writeOptions, keyBytes);
}
}
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap remove failed , " + e.getMessage(), e);
}
return valueBytes;
}
/**
* key
* @param key key
* @param isRetVal value
* @return , isRetVal=false , null
*/
public V remove(Object key, boolean isRetVal) {
if(key == null){
throw new NullPointerException();
}
byte[] valuesByte = remove(serialize(key), isRetVal);
return (V) unserialize(valuesByte);
}
@Override
public V remove(Object key) {
return remove(key, true);
}
public void removeAll(Collection<K> keys) {
if(keys == null){
throw new NullPointerException();
}
try {
Transaction transaction = threadLocalTransaction.get();
WriteBatch writeBatch = null;
if (transaction == null) {
writeBatch = THREAD_LOCAL_WRITE_BATCH.get();
writeBatch.clear();
for(K key : keys) {
if(key == null){
continue;
}
try {
writeBatch.delete(dataColumnFamilyHandle, serialize(key));
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap removeAll " + key + " failed", e);
}
}
rocksDB.write(writeOptions, writeBatch);
} else {
for(K key : keys) {
if(key == null){
continue;
}
try {
transaction.delete(dataColumnFamilyHandle, serialize(key));
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap removeAll " + key + " failed", e);
}
}
}
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap removeAll write failed", e);
}
}
/**
* Removes the database entries in the range ["beginKey", "endKey"), i.e.,
* including "beginKey" and excluding "endKey". a non-OK status on error. It
* is not an error if no keys exist in the range ["beginKey", "endKey").
* @param fromKey key
* @param toKey key
*
*/
public void removeRange(K fromKey, K toKey){
removeRange(fromKey, toKey, true);
}
/**
* Removes the database entries in the range ["beginKey", "endKey"), i.e.,
* including "beginKey" and excluding "endKey". a non-OK status on error. It
* is not an error if no keys exist in the range ["beginKey", "endKey").
* @param fromKey key
* @param toKey key
* @param useTransaction
*
*/
public void removeRange(K fromKey, K toKey, boolean useTransaction) {
Transaction transaction = useTransaction ? threadLocalTransaction.get() : null;
byte[] fromKeyBytes = serialize(fromKey);
byte[] toKeyBytes = serialize(toKey);
try {
if(transaction==null) {
rocksDB.deleteRange(dataColumnFamilyHandle, writeOptions, fromKeyBytes, toKeyBytes);
} else {
try (RocksIterator iterator = getIterator()) {
iterator.seek(fromKeyBytes);
while (iterator.isValid()) {
if (!Arrays.equals(iterator.key(), toKeyBytes)) {
transaction.delete(dataColumnFamilyHandle, iterator.key());
iterator.next();
} else {
break;
}
}
}
}
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap removeAll failed", e);
}
}
public static ThreadLocal<WriteBatch> THREAD_LOCAL_WRITE_BATCH = ThreadLocal.withInitial(()->new WriteBatch());
@Override
public void putAll(Map m) {
try {
Transaction transaction = threadLocalTransaction.get();
WriteBatch writeBatch = null;
if (transaction == null) {
writeBatch = THREAD_LOCAL_WRITE_BATCH.get();
writeBatch.clear();
Iterator<Entry> iterator = m.entrySet().iterator();
while (iterator.hasNext()) {
Entry entry = iterator.next();
Object key = entry.getKey();
Object value = entry.getValue();
writeBatch.put(dataColumnFamilyHandle, serialize(key), serialize(value));
}
rocksDB.write(writeOptions, writeBatch);
} else {
Iterator<Entry> iterator = m.entrySet().iterator();
while (iterator.hasNext()) {
Entry entry = iterator.next();
Object key = entry.getKey();
Object value = entry.getValue();
transaction.put(dataColumnFamilyHandle, serialize(key), serialize(value));
}
}
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap putAll failed", e);
}
}
/**
*
* @param sync
* @param allowStall
*/
public void flush(boolean sync, boolean allowStall){
try {
FlushOptions flushOptions = new FlushOptions();
flushOptions.setWaitForFlush(sync);
flushOptions.setAllowWriteStall(allowStall);
rocksDB.flush(flushOptions, this.dataColumnFamilyHandle);
if(!sync) {
Global.getHashWheelTimer().addTask(()->{
flushOptions.waitForFlush();
}, 1, true);
}
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap flush failed", e);
}
}
/**
*
* @param sync
*/
public void flush(boolean sync){
flush(sync, true);
}
public void flush(){
flush(true, true);
}
/**
* WAL
* @param sync
*/
public void flushWal(boolean sync){
try {
rocksDB.flushWal(sync);
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap flushWal failed", e);
}
}
public void flushWal() {
flushWal(true);
}
@Override
public void clear() {
if(readOnly){
Logger.error("Clear failed, ", new RocksDBException("Not supported operation in read only mode"));
return;
}
try {
drop();
ColumnFamilyDescriptor columnFamilyDescriptor = new ColumnFamilyDescriptor(columnFamilyName.getBytes(), columnFamilyOptions);
dataColumnFamilyHandle = rocksDB.createColumnFamily(columnFamilyDescriptor);
COLUMN_FAMILY_HANDLE_MAP.get(rocksDB).put(new String(dataColumnFamilyHandle.getName()), dataColumnFamilyHandle);
dataColumnFamilyHandle = getColumnFamilyHandler(rocksDB, this.columnFamilyName);
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap clear failed", e);
}
}
public void drop(){
try {
rocksDB.dropColumnFamily(dataColumnFamilyHandle);
COLUMN_FAMILY_HANDLE_MAP.get(rocksDB).remove(new String(dataColumnFamilyHandle.getName()));
dataColumnFamilyHandle.close();
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap drop failed", e);
}
}
/**
* , Set Rocksdb
* @return Key set
*/
@Override
public Set keySet() {
TreeSet<K> keySet = new TreeSet<K>();
try (RocksIterator iterator = getIterator()){
iterator.seekToFirst();
while (iterator.isValid()) {
K k = (K) unserialize(iterator.key());
keySet.add(k);
iterator.next();
}
return keySet;
}
}
@Override
public Collection values() {
ArrayList<V> values = new ArrayList<V>();
try (RocksIterator iterator = getIterator()){
iterator.seekToFirst();
while (iterator.isValid()) {
V value = (V) unserialize(iterator.value());
values.add(value);
iterator.next();
}
return values;
}
}
/**
* , Set Rocksdb
* @return Entry set
*/
@Override
public Set<Entry<K, V>> entrySet() {
TreeSet<Entry<K,V>> entrySet = new TreeSet<Entry<K,V>>();
try (RocksIterator iterator = getIterator()) {
iterator.seekToFirst();
while (iterator.isValid()) {
entrySet.add(new RocksMapEntry<K, V>(this, iterator.key(), iterator.value()));
iterator.next();
}
return entrySet;
}
}
/**
* key
* @param key key
* @return Map
*/
public Map<K,V> startWith(K key) {
return startWith(key, 0,0);
}
/**
* key
* @param key key
* @param skipSize
* @param size
* @return Map
*/
public Map<K,V> startWith(K key, int skipSize, int size) {
byte[] keyBytes = serialize(key);
TreeMap<K,V> entryMap = new TreeMap<K,V>();
try (RocksMapIterator iterator = new RocksMapIterator(this, key, null, skipSize, size)) {
while (iterator.directNext(true)) {
if (TByte.byteArrayStartWith(iterator.keyBytes(), keyBytes)) {
entryMap.put((K) iterator.key(), (V) iterator.value());
} else {
break;
}
}
return entryMap;
}
}
@Override
public void close() {
Transaction transaction = threadLocalTransaction.get();
if(transaction!=null){
try {
transaction.rollback();
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap rollback on close failed", e);
} finally {
closeTransaction();
}
}
dbOptions.close();
readOptions.close();
writeOptions.close();
columnFamilyOptions.close();
dbOptions = null;
readOptions = null;
writeOptions = null;
columnFamilyOptions = null;
if(!isDuplicate) {
RocksMap.closeRocksDB(rocksDB);
}
}
/**
*
* @param fromKey key
* @param toKey key
* @param size
* @param skipSize
* @param size
* @return
*/
public RocksMapIterator<K,V> iterator(K fromKey, K toKey, int skipSize, int size){
return new RocksMapIterator(this, fromKey, toKey, skipSize, size);
}
/**
*
* @param fromKey key
* @param toKey key
* @return
*/
public RocksMapIterator<K,V> iterator(K fromKey, K toKey){
return new RocksMapIterator(this, fromKey, toKey, 0, 0);
}
/**
*
* @param skipSize
* @param size
* @return
*/
public RocksMapIterator<K,V> iterator(int skipSize, int size){
return new RocksMapIterator(this, null, null, skipSize, size);
}
/**
*
* @param size
* @return
*/
public RocksMapIterator<K,V> iterator(int size){
return new RocksMapIterator(this, null, null, 0, size);
}
/**
*
* @return
*/
public RocksMapIterator<K,V> iterator(){
return new RocksMapIterator(this, null, null, 0, 0);
}
/**
*
* @param checker , true: , false:
*/
public void scan(Function<RocksMap<K,V>.RocksMapEntry<K,V>, Boolean> checker) {
scan(null, null, checker, false);
}
/**
*
* @param checker , true: , false:
* @param disableWal wal
*/
public void scan(Function<RocksMap<K,V>.RocksMapEntry<K,V>, Boolean> checker, boolean disableWal) {
scan(null, null, checker, disableWal);
}
/**
*
* @param fromKey key
* @param toKey key
* @param checker , true: , false:
*/
public void scan(K fromKey, K toKey, Function<RocksMap<K,V>.RocksMapEntry<K,V>, Boolean> checker) {
scan(fromKey, toKey, checker, false);
}
/**
*
* @param fromKey key
* @param toKey key
* @param checker , true: , false:
* @param disableWal wal
*/
public void scan(K fromKey, K toKey, Function<RocksMap<K,V>.RocksMapEntry<K,V>, Boolean> checker, boolean disableWal) {
RocksMap<K,V> innerRocksMap = this.duplicate(this.getColumnFamilyName(), false);
if(disableWal) {
innerRocksMap.writeOptions.setSync(false);
}
innerRocksMap.writeOptions.setDisableWAL(disableWal);
try(RocksMap<K,V>.RocksMapIterator<K,V> iterator = innerRocksMap.iterator(fromKey, toKey)) {
RocksMap<K, V>.RocksMapEntry<K, V> rocksMapEntry = null;
while ((rocksMapEntry = iterator.nextAndValid(true))!=null) {
if (checker.apply(rocksMapEntry)) {
continue;
} else {
break;
}
}
}
innerRocksMap.close();
}
public class RocksMapEntry<K, V> implements Map.Entry<K, V>, Comparable<RocksMapEntry> {
private RocksMap<K,V> rocksMap;
private byte[] keyBytes;
private K k;
private byte[] valueBytes;
private V v;
protected RocksMapEntry(RocksMap<K, V> rocksMap, byte[] keyBytes, byte[] valueBytes) {
this.rocksMap = rocksMap;
this.keyBytes = keyBytes;
this.valueBytes = valueBytes;
}
@Override
public K getKey() {
if(k==null){
this.k = (K) unserialize(keyBytes);
}
return k;
}
@Override
public V getValue() {
if(v==null) {
this.v = (V) unserialize(valueBytes);
}
return v;
}
public byte[] getKeyBytes() {
return keyBytes;
}
public byte[] getValueBytes() {
return valueBytes;
}
@Override
public V setValue(V value) {
rocksMap.put(keyBytes, serialize(value));
return value;
}
@Override
public int compareTo(RocksMapEntry o) {
return TByte.byteArrayCompare(this.keyBytes, o.keyBytes);
}
@Override
public String toString(){
return getKey() + "=" + getValue();
}
public RocksMap<K, V> getRocksMap() {
return rocksMap;
}
public void remove(){
rocksMap.remove(keyBytes, false);
}
}
public class RocksMapIterator<K,V> implements Iterator<RocksMapEntry<K,V>>, Closeable{
private RocksMap<K,V> rocksMap;
private RocksIterator iterator;
private byte[] fromKeyBytes;
private byte[] toKeyBytes;
private int skipSize;
private int size = 0;
private int count=0;
//["beginKey", "endKey")
protected RocksMapIterator(RocksMap rocksMap, K fromKey, K toKey, int skipSize, int size) {
this.rocksMap = rocksMap;
this.iterator = rocksMap.getIterator();
this.fromKeyBytes = serialize(fromKey);
this.toKeyBytes = serialize(toKey);
this.skipSize = skipSize;
this.size = size;
if(fromKeyBytes==null) {
iterator.seekToFirst();
} else {
iterator.seek(fromKeyBytes);
}
if(skipSize >0) {
for(int i=0;i<=this.skipSize;i++) {
if(!directNext(false)) {
break;
}
}
}
count = 0;
}
/**
* Entry
* @return RocksMapEntry
*/
public RocksMapEntry<K, V> getEntry() {
return new RocksMapEntry(rocksMap, iterator.key(), iterator.value());
}
@Override
public boolean hasNext() {
boolean ret = false;
if(count == 0 && isValid()) {
return true;
}
if(!iterator.isValid()) {
return false;
}
try {
iterator.next();
ret = isValid();
} finally {
iterator.prev();
if(size!=0 && count > size - 1){
ret = false;
}
}
return ret;
}
/**
*
* @return true: , false:
*/
public boolean isValid(){
boolean ret;
if (toKeyBytes == null) {
ret = iterator.isValid();
} else {
ret = iterator.isValid() && TByte.byteArrayCompare(toKeyBytes, iterator.key()) != 0;
}
return ret;
}
/**
* Key
* @return Key
*/
public K key(){
return (K)unserialize(iterator.key());
}
/**
* value
* @return value
*/
public V value(){
return (V)unserialize(iterator.value());
}
/**
* Key
* @return Key
*/
public byte[] keyBytes(){
return iterator.key();
}
/**
* value
* @return value
*/
public byte[] valueBytes(){
return iterator.value();
}
/**
* next
* @param valid
* @return true: , false:
*/
public boolean directNext(boolean valid) {
if(count != 0) {
iterator.next();
}
boolean flag = false;
if(valid) {
flag = isValid();
} else {
flag = iterator.isValid();
}
if(flag) {
count++;
return true;
} else {
return false;
}
}
public RocksMapEntry<K,V> nextAndValid(boolean valid) {
if(directNext(true)) {
return getEntry();
} else {
return null;
}
}
@Override
public RocksMapEntry<K,V> next() {
return nextAndValid(false);
}
@Override
public void remove() {
try {
rocksMap.rocksDB.delete(rocksMap.dataColumnFamilyHandle, rocksMap.writeOptions, iterator.key());
} catch (RocksDBException e) {
throw new RocksMapException("RocksMapIterator remove failed", e);
}
}
@Override
public void forEachRemaining(Consumer<? super RocksMapEntry<K, V>> action) {
throw new UnsupportedOperationException();
}
public void close(){
iterator.close();
}
}
public static class RocksWalRecord {
// WriteBatch::rep_ :=
// sequence: fixed64
// count: fixed32
// data: record[count]
// record :=
// kTypeValue varstring varstring
// kTypeDeletion varstring
// kTypeSingleDeletion varstring
// kTypeRangeDeletion varstring varstring
// kTypeMerge varstring varstring
// kTypeColumnFamilyValue varint32 varstring varstring
// kTypeColumnFamilyDeletion varint32 varstring
// kTypeColumnFamilySingleDeletion varint32 varstring
// kTypeColumnFamilyRangeDeletion varint32 varstring varstring
// kTypeColumnFamilyMerge varint32 varstring varstring
// kTypeBeginPrepareXID varstring
// kTypeEndPrepareXID
// kTypeCommitXID varstring
// kTypeRollbackXID varstring
// kTypeBeginPersistedPrepareXID varstring
// kTypeBeginUnprepareXID varstring
// kTypeNoop
// varstring :=
// len: varint32
// data: uint8[len]
public static int TYPE_DELETION = 0x0;
public static int TYPE_VALUE = 0x1;
public static int TYPE_MERGE = 0x2;
public static int TYPE_LOGDATA = 0x3; // WAL only.
public static int TYPE_COLUMNFAMILY_DELETION = 0x4;
public static int TYPE_COLUMNFAMILY_VALUE = 0x5;
public static int TYPE_COLUMNFAMILY_MERGE = 0x6; // WAL only.
public static int TYPE_SINGLE_DELETION = 0x7;
public static int TYPE_COLUMNFAMILY_SINGLE_DELETION = 0x8; // WAL only.
public static int TYPE_BEGIN_PREPARE_XID = 0x9; // WAL only.
public static int TYPE_END_PREPARE_XID = 0xA; // WAL only.
public static int TYPE_COMMIT_XID = 0xB; // WAL only.
public static int TYPE_ROLLBACK_XID = 0xC; // WAL only.
public static int TYPE_NOOP = 0xD; // WAL only.
public static int TYPE_COLUMNFAMILY_RANGE_DELETION = 0xE; // WAL only.
public static int TYPE_RANGE_DELETION = 0xF; // meta block
public static int TYPE_COLUMNFAMILY_BLOB_INDEX = 0x10; // Blob DB only
public static int TYPE_BLOB_INDEX = 0x11; // Blob DB only
public static int TYPE_BEGIN_PERSISTED_PREPARE_XID = 0x12; // WAL only
public static int TYPE_BEGIN_UNPREPARE_XID = 0x13; // WAL only.
public static int[] TYPE_ELEMENT_COUNT = new int[]{
1, //0 kTypeDeletion varstring
2, //1 kTypeValue varstring varstring
2, //2 kTypeMerge varstring varstring
0,
1, //4 kTypeColumnFamilyDeletion varint32 varstring
2, //5 kTypeColumnFamilyValue varint32 varstring varstring
2, //6 kTypeColumnFamilyMerge varint32 varstring varstring
1, //7 kTypeSingleDeletion varstring
1, //8 kTypeColumnFamilySingleDeletion varint32 varstring
1, //9 kTypeBeginPrepareXID varstring
0, //A kTypeEndPrepareXID
1, //B kTypeCommitXID varstring
1, //C kTypeRollbackXID varstring
0, //D kTypeNoop
2, //E kTypeColumnFamilyRangeDeletion varint32 varstring varstring
0, //F kTypeRangeDeletion varstring varstring
0, //10 kTypeColumnFamilyBlobIndex
2, //11 kTypeBlobIndex varstring varstring
1, //12 kTypeBeginPersistedPrepareXID varstring
1 //13 kTypeBeginUnprepareXID varstring
};
private long sequence;
private int type;
private int columnFamilyId = 0;
private ArrayList<Object> chunks;
private RocksWalRecord(long sequence, int type, int columnFamilyId) {
this.sequence = sequence;
this.type = type;
this.columnFamilyId = columnFamilyId;
chunks = new ArrayList<Object>();
}
public long getSequence() {
return sequence;
}
private void setSequence(long sequence) {
this.sequence = sequence;
}
public int getType() {
return type;
}
private void setType(int type) {
this.type = type;
}
public int getColumnFamilyId() {
return columnFamilyId;
}
private void setColumnFamilyId(int columnFamilyId) {
this.columnFamilyId = columnFamilyId;
}
public ArrayList<Object> getChunks() {
return chunks;
}
/**
*
* @param byteBuffer
* @param withSerial
* @return
*/
public static List<RocksWalRecord> parse(ByteBuffer byteBuffer, boolean withSerial) {
return parse(byteBuffer, null, withSerial);
}
/**
*
* @param byteBuffer
* @param filter ,
* @param withSerial
* @return
*/
public static List<RocksWalRecord> parse(ByteBuffer byteBuffer, BiFunction<Integer, Integer, Boolean> filter, boolean withSerial) {
ByteOrder originByteOrder = byteBuffer.order();
byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
if(byteBuffer.remaining() < 13) {
throw new ParseException("not a correct recorder");
}
Long sequence = byteBuffer.getLong();
//Wal
int recordCount = byteBuffer.getInt();
List<RocksWalRecord> rocksWalRecords = new ArrayList<RocksWalRecord>();
for(int count=0;
count < recordCount && byteBuffer.hasRemaining();
count++) {
RocksWalRecord rocksWalRecord = parseOperation(byteBuffer, sequence, filter, withSerial);
if (rocksWalRecord != null) {
rocksWalRecords.add(rocksWalRecord);
}
}
byteBuffer.order(originByteOrder);
return rocksWalRecords;
}
/**
*
* @param byteBuffer
* @param sequence
* @param withSerial
* @return
*/
public static RocksWalRecord parseOperation(ByteBuffer byteBuffer, long sequence, boolean withSerial){
return parseOperation(byteBuffer, sequence, withSerial);
}
/**
*
* @param byteBuffer
* @param sequence
* @param filter ,
* @param withSerial
* @return
*/
public static RocksWalRecord parseOperation(ByteBuffer byteBuffer, long sequence, BiFunction<Integer, Integer, Boolean> filter, boolean withSerial){
int type = byteBuffer.get();
if (type == TYPE_NOOP) {
if(byteBuffer.hasRemaining()) {
type = byteBuffer.get();
} else {
return null;
}
}
int columnFamilyId=0;
if (type == TYPE_COLUMNFAMILY_DELETION ||
type == TYPE_COLUMNFAMILY_VALUE ||
type == TYPE_COLUMNFAMILY_MERGE ||
type == TYPE_COLUMNFAMILY_SINGLE_DELETION ||
type == TYPE_COLUMNFAMILY_RANGE_DELETION) {
columnFamilyId = Varint.varintToInt(byteBuffer);
}
RocksWalRecord rocksWalRecord = null;
if (type < TYPE_ELEMENT_COUNT.length) {
boolean isEnable = filter==null || filter.apply(columnFamilyId, type);
if(isEnable) {
rocksWalRecord = new RocksWalRecord(sequence, type, columnFamilyId);
}
for (int i = 0; i < TYPE_ELEMENT_COUNT[type] && byteBuffer.hasRemaining(); i++) {
int chunkSize = Varint.varintToInt(byteBuffer);
if(isEnable) {
byte[] chunkBytes = new byte[chunkSize];
byteBuffer.get(chunkBytes);
Object chunk = chunkBytes;
if (withSerial) {
chunk = unserialize(chunkBytes);
} else {
chunk = chunkBytes;
}
rocksWalRecord.getChunks().add(chunk);
} else {
byteBuffer.position(byteBuffer.position() + chunkSize);
}
}
}
return rocksWalRecord;
}
}
/**
* Wal, wal
*/
public static class RocksWalReader {
private Object mark;
private RocksMap rocksMap;
private Long lastSequence;
private int batchSeqsize;
private List<Integer> columnFamilys;
private List<Integer> walTypes;
public RocksWalReader(Object mark, RocksMap rocksMap, int batchSeqsize) {
this.mark = mark;
this.rocksMap = rocksMap;
this.batchSeqsize = batchSeqsize;
this.rocksMap = rocksMap;
this.lastSequence = (Long) this.rocksMap.get(mark);
this.lastSequence = this.lastSequence==null ? 0 : this.lastSequence;
Logger.debug("Start sequence: " + this.lastSequence);
}
public long getLastSequence() {
return lastSequence;
}
public List<Integer> getColumnFamily() {
return columnFamilys;
}
public void setColumnFamily(List<Integer> columnFamilys) {
this.columnFamilys = columnFamilys;
}
public int getBatchSeqsize() {
return batchSeqsize;
}
public List<Integer> getWalTypes() {
return walTypes;
}
public void setWalTypes(List<Integer> walTypes) {
this.walTypes = walTypes;
}
public void processing(RocksWalProcessor rocksWalProcessor){
//wal
Long endSequence = rocksMap.getLastSequence();
if(lastSequence + batchSeqsize < endSequence){
endSequence = lastSequence + batchSeqsize;
}
List<RocksWalRecord> rocksWalRecords = rocksMap.getWalBetween(lastSequence, endSequence, (columnFamilyId, type)-> {
return (walTypes == null ? true : walTypes.contains(type)) &&
(columnFamilys==null ? true : columnFamilys.contains(columnFamilyId));
}, true);
if(rocksWalRecords.size() > 0) {
rocksWalProcessor.process(endSequence, rocksWalRecords);
}
rocksMap.put(mark, endSequence);
lastSequence = endSequence;
}
public static interface RocksWalProcessor {
public void process(Long endSequence, List<RocksWalRecord> rocksWalRecords);
}
}
} |
package spacefront;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.util.Set;
public class Shot extends SpaceObject {
private static final long serialVersionUID = 1L;
/* Appearance */
private static final double SIZE = 8;
public static final Color COLOR = Color.RED;
public static final Shape SHAPE =
new Ellipse2D.Double(-SIZE / 2, -SIZE / 2, SIZE, SIZE);
private static final double OSCILLATION_RATE = 32;
private static final double OSCILLATION_SCALE = 3;
/* Behavior */
private static final double SPEED = 8;
public Shot(double destx, double desty) {
super(0, 0, 0);
double a = Math.atan2(desty, destx);
setSpeed(Math.cos(a) * SPEED, Math.sin(a) * SPEED, 0);
setShape(SHAPE);
}
public Meteoroid step(Set<Meteoroid> targets) {
super.step();
for (Meteoroid m : targets) {
if (m.get().contains(getX(), getY())) {
return m;
}
}
return null;
}
public void paint(Graphics2D g) {
g.setColor(COLOR);
Shape self = get();
long time = System.currentTimeMillis();
double scale = Math.sin(time / OSCILLATION_RATE) /
OSCILLATION_SCALE + 1d;
AffineTransform at = getTransform();
at.scale(scale, scale);
g.fill(at.createTransformedShape(getShape()));
}
} |
package io.spine.base;
import com.google.protobuf.DescriptorProtos.DescriptorProto;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Message;
import io.spine.protobuf.Messages;
import java.util.List;
import java.util.UUID;
import static com.google.common.base.Preconditions.checkState;
import static io.spine.base.UuidValue.FIELD_NAME;
import static io.spine.util.Exceptions.newIllegalArgumentException;
import static io.spine.util.Preconditions2.checkNotEmptyOrBlank;
/**
* A factory for creating UUID-based identifiers of the given {@link Message} type.
*
* <p>The passed message type must contain a single {@code string} field named 'uuid'.
*
* @param <I>
* the type of created messages
*/
class UuidFactory<I extends Message> {
private static final String ERROR_MESSAGE =
"A UUID message should have a single string field named %s.";
private static final String INVALID_STRING_MESSAGE = "Invalid UUID string: %s";
private final Class<I> idClass;
private final FieldDescriptor uuidField;
private UuidFactory(Class<I> idClass, FieldDescriptor uuidField) {
this.idClass = idClass;
this.uuidField = uuidField;
}
static <I extends Message> UuidFactory<I> forClass(Class<I> idClass) {
Descriptor message = Messages.newInstance(idClass)
.getDescriptorForType();
checkState(isUuidMessage(message), ERROR_MESSAGE, FIELD_NAME);
List<FieldDescriptor> fields = message.getFields();
FieldDescriptor uuidField = fields.get(0);
return new UuidFactory<>(idClass, uuidField);
}
/**
* Generates an instance of the UUID message using a random string.
*
* @return a message instance with the initialized {@code uuid} field
*/
I newUuid() {
return newUuidOf(Identifier.newUuid());
}
/**
* Creates an instance of the UUID message from the passed value.
*
* @param value
* a value to use
* @return a new message instance with the {@code uuid} field initialized to the given value
*/
@SuppressWarnings("unchecked") // It is OK as the builder is obtained by the specified class.
I newUuidOf(String value) {
checkIsUuid(value);
Message initializedId = Messages.builderFor(idClass)
.setField(uuidField, value)
.build();
return (I) initializedId;
}
private static boolean isUuidMessage(Descriptor message) {
DescriptorProto messageProto = message.toProto();
return new UuidValue.Matcher().test(messageProto);
}
@SuppressWarnings({"CheckReturnValue", "ResultOfMethodCallIgnored"})
// Just verify that the object is constructed without errors.
private static void checkIsUuid(String value) {
checkNotEmptyOrBlank(value);
try {
UUID.fromString(value);
} catch (NumberFormatException e) {
throw newIllegalArgumentException(e, INVALID_STRING_MESSAGE, value);
}
}
} |
package com.chiorichan.util;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.FileChannel;
import com.chiorichan.Loader;
import com.chiorichan.framework.Site;
/**
* Class containing file utilities
*/
public class FileUtil
{
public static byte[] inputStream2Bytes( InputStream is ) throws IOException
{
return inputStream2ByteArray( is ).toByteArray();
}
public static ByteArrayOutputStream inputStream2ByteArray( InputStream is ) throws IOException
{
int nRead;
byte[] data = new byte[16384];
ByteArrayOutputStream bs = new ByteArrayOutputStream();
while ( ( nRead = is.read( data, 0, data.length ) ) != -1 )
{
bs.write( data, 0, nRead );
}
bs.flush();
return bs;
}
/**
* This method copies one file to another location
*
* @param inFile
* the source filename
* @param outFile
* the target filename
* @return true on success
*/
@SuppressWarnings( "resource" )
public static boolean copy( File inFile, File outFile )
{
if ( !inFile.exists() )
return false;
FileChannel in = null;
FileChannel out = null;
try
{
in = new FileInputStream( inFile ).getChannel();
out = new FileOutputStream( outFile ).getChannel();
long pos = 0;
long size = in.size();
while ( pos < size )
{
pos += in.transferTo( pos, 10 * 1024 * 1024, out );
}
}
catch ( IOException ioe )
{
return false;
}
finally
{
try
{
if ( in != null )
in.close();
if ( out != null )
out.close();
}
catch ( IOException ioe )
{
return false;
}
}
return true;
}
/**
* Calculate a file location
*
* @param name
* @return
*/
public static File calculateFileBase( String path, Site site )
{
if ( path.startsWith( "[" ) )
{
path = path.replace( "[pwd]", new File( "" ).getAbsolutePath() );
path = path.replace( "[web]", Loader.webroot );
if ( site != null )
path = path.replace( "[site]", site.getAbsoluteRoot().getAbsolutePath() );
}
return new File( path );
}
public static File calculateFileBase( String path )
{
return calculateFileBase( path, null );
}
public static void directoryHealthCheck( File file )
{
if ( file.isFile() )
file.delete();
if ( !file.exists() )
file.mkdirs();
}
public static File fileHealthCheck( File file ) throws IOException
{
if ( file.exists() && file.isDirectory() )
file = new File( file, "default" );
if ( !file.exists() )
file.createNewFile();
return file;
}
} |
public class Node <T> {
public Node <T> next;
public T element;
public Node (T t) {
this.element = t;
}
}
/**
* EPI: 8.3
* Given a linked list:
* return true if a cycle exists.
* return false otherwise
*/
public boolean hasCycle(Node node) {
Node fast = node;
Node slow = node;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
return true;
}
}
return false;
}
/**
* EPI: 8.35 (Variant)
* Given a linked list, return the beginning node of the cycle.
* If a cycle does not exist then return null.
*/
public Node hasCycle(Node node) {
Node fast = node;
Node slow = node;
Node head = node;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
// Found intersection point, therefore cycle exists.
if (fast == slow) {
// The beginning of the cycle is equidistant
// from the head of the linked list and the intersection point.
while (head != fast) {
head = head.next;
fast = fast.next;
}
return head;
}
}
return null;
}
/**
* EPI: 8.4
* Given two linked lists, return true if there are any nodes that exist in both lists.
* Return false if no equal node exists in both.
*/
public boolean hasEqualNode(Node a, Node b) {
while (a.next != null || b.next != null) {data
a = a.next == null ? a : a.next;
b = b.next == null ? b : b.next;
}
return a == b;
}
/**
* EPI: 8.45 (Variant)
* Given two linked lists, return the first node that exists in both (where the merge occurs).
* If no node exists, then return null.
*/
public Node hasEqualNode(Node a, Node b) {
int sizeA = 1;
int sizeB = 1;
while (a.next != null || b.next != null) {
if (a.next != null) {
sizeA ++;
a = a.next;
}
if (b.next != null) {
sizeB ++;
b = b.next;
}
}
Node longer = a > b ? a : b;
Node shorter = a > b ? b : a;
int diff = Math.abs(sizeA - sizeB);
// Trash the first diff nodes in the longer list.
for (int i = 0; i < diff; i ++)
longer = longer.next;
// Now compare the two lists now that they are equal lengths.
while(longer.next != null) {
if (longer == shorter) return longer;
longer = longer.next;
shorter = shorter.next;
}
return null;
}
/**
* EPI: 8.6
* Given a linked list node, delete that node from the list.
* The given node may or may not be the head node, but you'll never be given the last node.
*/
public void deleteLinkedListNode(Node node){
node.element = node.next.element;
node.next = node.next.next;
} |
package datafu.test.pig.sampling;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import junit.framework.Assert;
import org.adrianwalker.multilinestring.Multiline;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.data.BagFactory;
import org.apache.pig.data.DataBag;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import org.apache.pig.pigunit.PigTest;
import org.testng.annotations.Test;
import datafu.pig.sampling.ReservoirSample;
import datafu.pig.sampling.WeightedSample;
import datafu.test.pig.PigTests;
public class SamplingTests extends PigTests
{
/**
register $JAR_PATH
define WeightedSample datafu.pig.sampling.WeightedSample('1');
data = LOAD 'input' AS (A: bag {T: tuple(v1:chararray,v2:INT)});
data2 = FOREACH data GENERATE WeightedSample(A,1);
--describe data2;
STORE data2 INTO 'output';
*/
@Multiline
private String weightedSampleTest;
@Test
public void weightedSampleTest() throws Exception
{
PigTest test = createPigTestFromString(weightedSampleTest);
writeLinesToFile("input",
"({(a, 100),(b, 1),(c, 5),(d, 2)})");
test.runScript();
assertOutput(test, "data2",
"({(a,100),(c,5),(b,1),(d,2)})");
}
/**
register $JAR_PATH
define WeightedSample datafu.pig.sampling.WeightedSample('1');
data = LOAD 'input' AS (A: bag {T: tuple(v1:chararray,v2:INT)});
data2 = FOREACH data GENERATE WeightedSample(A,1,3);
--describe data2;
STORE data2 INTO 'output';
*/
@Multiline
private String weightedSampleLimitTest;
@Test
public void weightedSampleLimitTest() throws Exception
{
PigTest test = createPigTestFromString(weightedSampleLimitTest);
writeLinesToFile("input",
"({(a, 100),(b, 1),(c, 5),(d, 2)})");
test.runScript();
assertOutput(test, "data2",
"({(a,100),(c,5),(b,1)})");
}
@Test
public void weightedSampleLimitExecTest() throws IOException
{
WeightedSample sampler = new WeightedSample();
DataBag bag = BagFactory.getInstance().newDefaultBag();
for (int i=0; i<100; i++)
{
Tuple t = TupleFactory.getInstance().newTuple(2);
t.set(0, i);
t.set(1, 1); // score is equal for all
bag.add(t);
}
Tuple input = TupleFactory.getInstance().newTuple(3);
input.set(0, bag);
input.set(1, 1); // use index 1 for score
input.set(2, 10); // get 10 items
DataBag result = sampler.exec(input);
Assert.assertEquals(10, result.size());
// all must be found, no repeats
Set<Integer> found = new HashSet<Integer>();
for (Tuple t : result)
{
Integer i = (Integer)t.get(0);
System.out.println(i);
Assert.assertTrue(i>=0 && i<100);
Assert.assertFalse(String.format("Found duplicate of %d",i), found.contains(i));
found.add(i);
}
}
/**
register $JAR_PATH
DEFINE SampleByKey datafu.pig.sampling.SampleByKey('salt2.5', '0.5');
data = LOAD 'input' AS (A_id:chararray, B_id:chararray, C:int);
sampled = FILTER data BY SampleByKey(A_id);
STORE sampled INTO 'output';
*/
@Multiline
private String sampleByKeyTest;
@Test
public void sampleByKeyTest() throws Exception
{
PigTest test = createPigTestFromString(sampleByKeyTest);
writeLinesToFile("input",
"A1\tB1\t1","A1\tB1\t4","A1\tB3\t4","A1\tB4\t4",
"A2\tB1\t4","A2\tB2\t4",
"A3\tB1\t3","A3\tB1\t1","A3\tB3\t77",
"A4\tB1\t3","A4\tB2\t3","A4\tB3\t59","A4\tB4\t29",
"A5\tB1\t4",
"A6\tB2\t3","A6\tB2\t55","A6\tB3\t1",
"A7\tB1\t39","A7\tB2\t27","A7\tB3\t85",
"A8\tB1\t4","A8\tB2\t45",
"A9\tB3\t92", "A9\tB1\t42","A9\tB2\t1","A9\tB3\t0",
"A10\tB1\t7","A10\tB2\t23","A10\tB3\t1","A10\tB4\t41","A10\tB5\t52");
test.runScript();
assertOutput(test, "sampled",
"(A4,B1,3)","(A4,B2,3)","(A4,B3,59)","(A4,B4,29)",
"(A5,B1,4)",
"(A6,B2,3)","(A6,B2,55)","(A6,B3,1)",
"(A7,B1,39)","(A7,B2,27)","(A7,B3,85)",
"(A10,B1,7)","(A10,B2,23)","(A10,B3,1)","(A10,B4,41)","(A10,B5,52)");
}
/**
register $JAR_PATH
DEFINE SampleByKey datafu.pig.sampling.SampleByKey('salt2.5', '0.5');
data = LOAD 'input' AS (A_id:chararray, B_id:chararray, C:int);
sampled = FILTER data BY SampleByKey(A_id, B_id);
STORE sampled INTO 'output';
*/
@Multiline
private String sampleByKeyMultipleKeyTest;
@Test
public void sampleByKeyMultipleKeyTest() throws Exception
{
PigTest test = createPigTestFromString(sampleByKeyMultipleKeyTest);
writeLinesToFile("input",
"A1\tB1\t1","A1\tB1\t4",
"A1\tB3\t4",
"A1\tB4\t4",
"A2\tB1\t4",
"A2\tB2\t4",
"A3\tB1\t3","A3\tB1\t1",
"A3\tB3\t77",
"A4\tB1\t3",
"A4\tB2\t3",
"A4\tB3\t59",
"A4\tB4\t29",
"A5\tB1\t4",
"A6\tB2\t3","A6\tB2\t55",
"A6\tB3\t1",
"A7\tB1\t39",
"A7\tB2\t27",
"A7\tB3\t85",
"A8\tB1\t4",
"A8\tB2\t45",
"A9\tB3\t92","A9\tB3\t0",
"A9\tB6\t42","A9\tB5\t1",
"A10\tB1\t7",
"A10\tB2\t23","A10\tB2\t1","A10\tB2\t31",
"A10\tB6\t41",
"A10\tB7\t52");
test.runScript();
assertOutput(test, "sampled",
"(A1,B1,1)","(A1,B1,4)",
"(A1,B4,4)",
"(A2,B1,4)",
"(A2,B2,4)",
"(A3,B1,3)","(A3,B1,1)",
"(A4,B4,29)",
"(A5,B1,4)",
"(A6,B3,1)",
"(A7,B1,39)",
"(A8,B1,4)",
"(A9,B3,92)","(A9,B3,0)",
"(A10,B2,23)","(A10,B2,1)","(A10,B2,31)"
);
}
/**
register $JAR_PATH
DEFINE ReservoirSample datafu.pig.sampling.ReservoirSample('$RESERVOIR_SIZE');
data = LOAD 'input' AS (A_id:chararray, B_id:chararray, C:int);
sampled = FOREACH (GROUP data ALL) GENERATE ReservoirSample(data) as sample_data;
sampled = FOREACH sampled GENERATE COUNT(sample_data) AS sample_count;
STORE sampled INTO 'output';
*/
@Multiline
private String reservoirSampleTest;
@Test
public void reservoirSampleTest() throws Exception
{
writeLinesToFile("input",
"A1\tB1\t1",
"A1\tB1\t4",
"A1\tB3\t4",
"A1\tB4\t4",
"A2\tB1\t4",
"A2\tB2\t4",
"A3\tB1\t3",
"A3\tB1\t1",
"A3\tB3\t77",
"A4\tB1\t3",
"A4\tB2\t3",
"A4\tB3\t59",
"A4\tB4\t29",
"A5\tB1\t4",
"A6\tB2\t3",
"A6\tB2\t55",
"A6\tB3\t1",
"A7\tB1\t39",
"A7\tB2\t27",
"A7\tB3\t85",
"A8\tB1\t4",
"A8\tB2\t45",
"A9\tB3\t92",
"A9\tB3\t0",
"A9\tB6\t42",
"A9\tB5\t1",
"A10\tB1\t7",
"A10\tB2\t23",
"A10\tB2\t1",
"A10\tB2\t31",
"A10\tB6\t41",
"A10\tB7\t52");
for(int i=10; i<=30; i=i+10){
int reservoirSize = i ;
PigTest test = createPigTestFromString(reservoirSampleTest, "RESERVOIR_SIZE="+reservoirSize);
test.runScript();
assertOutput(test, "sampled", "("+reservoirSize+")");
}
}
@Test
public void reservoirSampleExecTest() throws IOException
{
ReservoirSample sampler = new ReservoirSample("10");
DataBag bag = BagFactory.getInstance().newDefaultBag();
for (int i=0; i<100; i++)
{
Tuple t = TupleFactory.getInstance().newTuple(1);
t.set(0, i);
bag.add(t);
}
Tuple input = TupleFactory.getInstance().newTuple(bag);
DataBag result = sampler.exec(input);
Assert.assertEquals(10, result.size());
// all must be found, no repeats
Set<Integer> found = new HashSet<Integer>();
for (Tuple t : result)
{
Integer i = (Integer)t.get(0);
System.out.println(i);
Assert.assertTrue(i>=0 && i<100);
Assert.assertFalse(String.format("Found duplicate of %d",i), found.contains(i));
found.add(i);
}
}
@Test
public void reservoirSampleAccumulateTest() throws IOException
{
ReservoirSample sampler = new ReservoirSample("10");
for (int i=0; i<100; i++)
{
Tuple t = TupleFactory.getInstance().newTuple(1);
t.set(0, i);
DataBag bag = BagFactory.getInstance().newDefaultBag();
bag.add(t);
Tuple input = TupleFactory.getInstance().newTuple(bag);
sampler.accumulate(input);
}
DataBag result = sampler.getValue();
Assert.assertEquals(10, result.size());
// all must be found, no repeats
Set<Integer> found = new HashSet<Integer>();
for (Tuple t : result)
{
Integer i = (Integer)t.get(0);
System.out.println(i);
Assert.assertTrue(i>=0 && i<100);
Assert.assertFalse(String.format("Found duplicate of %d",i), found.contains(i));
found.add(i);
}
}
} |
package rr.meta;
import java.util.HashSet;
import java.util.Set;
import java.util.Vector;
import acme.util.Assert;
import acme.util.Util;
public class ClassInfo extends MetaDataInfo implements Comparable<ClassInfo> {
public static enum State { FRESH, IN_PRELOAD, PRELOADED, COMPLETE }
protected State state;
protected boolean isClass;
protected final boolean isSynthetic;
protected final String name;
protected ClassInfo superClass;
protected final Vector<FieldInfo> fields = new Vector<FieldInfo>();
protected final Vector<ClassInfo> interfaces = new Vector<ClassInfo>();
protected final Vector<MethodInfo> methods = new Vector<MethodInfo>();
protected volatile Vector<FieldInfo> instanceFields;
public ClassInfo(int id, SourceLocation loc, String name, boolean isSynthetic) {
super(id, loc);
Assert.assertTrue(!name.contains("."), "Bad Class: " + name);
this.name = name;
this.setState(State.FRESH);
this.isSynthetic = isSynthetic;
}
protected void assertStateAtLeast(State s, String info) {
if (!stateAtLeast(s)) {
Assert.fail("State for " + this + " is " + getState() + " but must be atleast " + (s) + ". " + info);
}
}
protected void assertStateAtMost(State s, String info) {
if (!stateAtMost(s)) {
Assert.fail("State for " + this + " is " + getState() + " but must be atmost " + (s) + ". " + info);
}
}
protected void assertStateIs(State s, String info) {
if (!stateIs(s)) {
Assert.fail("State for " + this + " is " + getState() + " but must be " + (s) + ". " + info);
}
}
protected void assertStateAtLeast(State s) {
assertStateAtLeast(s, "");
}
protected void assertStateAtMost(State s) {
assertStateAtMost(s, "");
}
protected void assertStateIs(State s) {
assertStateIs(s, "");
}
public boolean stateAtLeast(State s) {
return (this.getState().compareTo(s) >= 0);
}
public boolean stateAtMost(State s) {
return (this.getState().compareTo(s) <= 0);
}
public boolean stateIs(State s) {
return (this.getState().compareTo(s) == 0);
}
public void addField(FieldInfo x) {
if (superClass != null) {
superClass.assertStateAtLeast(State.PRELOADED);
}
if (!fields.contains(x)) {
fields.add(x);
}
}
public void setSuperClass(ClassInfo superClass) {
if (this.superClass != superClass) {
Assert.assertTrue(instanceFields == null);
assertStateAtMost(State.IN_PRELOAD, "add super " + superClass);
}
superClass.assertStateAtLeast(State.PRELOADED);
this.isClass = true;
this.superClass = superClass;
}
public ClassInfo getSuperClass() {
assertStateAtLeast(State.PRELOADED);
return superClass;
}
public Vector<FieldInfo> getFields() {
assertStateAtLeast(State.PRELOADED);
return fields;
}
@Override
protected String computeKey() {
return MetaDataInfoKeys.getClassKey(this.getName());
}
@Override
public void accept(MetaDataInfoVisitor v) {
assertStateIs(State.COMPLETE);
v.visit(this);
for (FieldInfo f : fields) {
f.accept(v);
}
for (MethodInfo m : methods) {
m.accept(v);
}
}
public void setIsClass(boolean isClass) {
assertStateAtMost(State.IN_PRELOAD);
this.isClass = isClass;
}
public boolean isClass() {
assertStateAtLeast(State.PRELOADED);
return isClass;
}
private void addAllSuperTypes(ClassInfo type, Set<ClassInfo> v) {
if (type == null) return;
v.add(type);
addAllSuperTypes(type.getSuperClass(), v);
for (ClassInfo c : type.getInterfaces()) {
addAllSuperTypes(c, v);
}
}
private Set<ClassInfo> supers;
public Set<ClassInfo> getSuperTypes() {
assertStateAtLeast(State.PRELOADED);
if (supers == null) {
supers = new HashSet<ClassInfo>();
addAllSuperTypes(this, supers);
}
return supers;
}
public State getState() {
return state;
}
protected String instanceLayout() {
String r = "";
for (FieldInfo x : getInstanceFields()) {
r += " " + x.getName();
}
return r;
}
public void setState(State state) {
this.state = state;
}
public void addInterface(ClassInfo i) {
if (!interfaces.contains(i)) {
assertStateAtMost(State.IN_PRELOAD);
interfaces.add(i);
}
}
public void addMethod(MethodInfo x) {
if (!methods.contains(x)) {
methods.add(x);
}
// else if (!x.isSynthetic() && stateAtLeast(State.PRELOADED)) {
// Util.log("Adding method " + x + " to " + this + " in state " + getState());
}
public Vector<ClassInfo> getInterfaces() {
assertStateAtLeast(State.PRELOADED);
return interfaces;
}
public Vector<MethodInfo> getMethods() {
assertStateAtLeast(State.PRELOADED);
return methods;
}
public String getName() {
return name;
}
public boolean isSynthetic() {
return this.isSynthetic;
}
public int compareTo(ClassInfo o) {
return getName().compareTo(((ClassInfo)o).getName());
}
protected void makeInstanceFieldList() {
if (instanceFields == null) {
synchronized(this) {
if (instanceFields == null) {
Vector<FieldInfo> tmpFields;
if (this.superClass != null) {
superClass.makeInstanceFieldList();
tmpFields = new Vector<FieldInfo>(superClass.instanceFields);
} else {
tmpFields = new Vector<FieldInfo>();
}
for (FieldInfo x : fields) {
if (!x.isStatic() && !x.isFinal()) {
tmpFields.add(x);
}
}
instanceFields = tmpFields;
}
}
}
}
public Vector<FieldInfo> getInstanceFields() {
assertStateAtLeast(State.PRELOADED);
makeInstanceFieldList();
return instanceFields;
}
public int offsetOfInstanceField(FieldInfo x) {
makeInstanceFieldList();
int i = instanceFields.indexOf(x);
Assert.assertTrue(i != -1 || x.isStatic() || x.isFinal(), x + " ? " + instanceFields);
return i;
}
} |
package smp;
/**
* Index values for the Hashtable in the ImageLoader class.
* When other objects need to access their respective images,
* use these keys to get the BufferedImage references.
* @author RehdBlob
* @since 2012.08.14
*/
public enum ImageIndex {
// SPLASHSCREEN,
/*
* Instruments grayed out.
*/
MARIO_GRAY, MUSHROOM_GRAY, YOSHI_GRAY, STAR_GRAY, FLOWER_GRAY,
GAMEBOY_GRAY, DOG_GRAY, CAT_GRAY, PIG_GRAY, SWAN_GRAY, FACE_GRAY,
PLANE_GRAY, BOAT_GRAY, CAR_GRAY, HEART_GRAY, PIRANHA_GRAY, COIN_GRAY,
SHYGUY_GRAY, BOO_GRAY, LUIGI_GRAY,
SHARP_GRAY, FLAT_GRAY, DOUBLESHARP_GRAY, DOUBLEFLAT_GRAY,
/*
* Silhouettes of images.
*/
MARIO_SIL, MUSHROOM_SIL, YOSHI_SIL, STAR_SIL, FLOWER_SIL,
GAMEBOY_SIL, DOG_SIL, CAT_SIL, PIG_SIL, SWAN_SIL, FACE_SIL,
PLANE_SIL, BOAT_SIL, CAR_SIL, HEART_SIL, PIRANHA_SIL, COIN_SIL,
SHYGUY_SIL, BOO_SIL, LUIGI_SIL,
SHARP_SIL, FLAT_SIL, DOUBLESHARP_SIL, DOUBLEFLAT_SIL,
/*
* Instruments.
*/
MARIO (MARIO_GRAY, MARIO_SIL),
MUSHROOM(MUSHROOM_GRAY, MUSHROOM_SIL),
YOSHI (YOSHI_GRAY, YOSHI_SIL),
STAR (STAR_GRAY, STAR_SIL),
FLOWER (FLOWER_GRAY, FLOWER_SIL),
GAMEBOY (GAMEBOY_GRAY, GAMEBOY_SIL),
DOG (DOG_GRAY, DOG_SIL),
CAT (CAT_GRAY, CAT_SIL),
PIG (PIG_GRAY, PIG_SIL),
SWAN (SWAN_GRAY, SWAN_SIL),
FACE (FACE_GRAY, FACE_SIL),
PLANE (PLANE_GRAY, PLANE_SIL),
BOAT (BOAT_GRAY, BOAT_SIL),
CAR (CAR_GRAY, CAR_SIL),
HEART (HEART_GRAY, HEART_SIL),
PIRANHA (PIRANHA_GRAY, PIRANHA_SIL),
COIN (COIN_GRAY, COIN_SIL),
SHYGUY (SHYGUY_GRAY, SHYGUY_SIL),
BOO (BOO_GRAY, BOO_SIL),
LUIGI (LUIGI_GRAY, LUIGI_SIL),
SHARP (SHARP_GRAY, SHARP_SIL),
FLAT (FLAT_GRAY, FLAT_SIL),
DOUBLESHARP (DOUBLESHARP_GRAY, DOUBLESHARP_SIL),
DOUBLEFLAT (DOUBLEFLAT_GRAY, DOUBLEFLAT_SIL),
/*
* Clefs.
*/
TREBLE_CLEF, BASS_CLEF,
/*
* Staff elements
*/
/**
* The frame that encloses the staff.
*/
STAFF_FRAME,
/**
* The background of the staff, which contains a treble clef.
*/
STAFF_BG,
/**
* Each one of these lines indicates a "beat"
*/
STAFF_LINE,
/**
* EAch one of these lines indicates a measure.
*/
STAFF_MLINE,
/**
* This is the bar that goes across the screen when one hits play.
*/
PLAY_BAR1,
/**
* This is a horizontal line that appears when someone tries to go
* above or below the middle five lines of the staff.
*/
STAFF_HLINE,
/*
* Controls elements
*/
CONTROLS_LEFT, CONTROLS_MID, CONTROLS_RIGHT,
/*
* Button elements
*/
STOP_PRESSED, STOP_RELEASED, STOP_LABEL,
PLAY_PRESSED, PLAY_RELEASED, PLAY_LABEL,
LOOP_PRESSED, LOOP_RELEASED, LOOP_LABEL,
/*
* Tempo stuff.
*/
TEMPO_PLUS, TEMPO_MINUS, TEMPO_LABEL;
/* Digits for the ImageViews of the measure lines.
* ZERO, ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE;
*/
/** The gray version of this sprite. It can be null. */
private ImageIndex gray = null;
/** The silhouette version of this sprite. It can be null. */
private ImageIndex silhouette = null;
/**
* @param gray The gray version of this sprite.
* @param sil The silhouette version of this sprite.
*/
private ImageIndex(ImageIndex gr, ImageIndex sil) {
gray = gr;
silhouette = sil;
}
/**
* Default constructor.
*/
private ImageIndex() {
}
/** @return The <code>ImageIndex</code> of the gray figure. */
public ImageIndex gray() {
return gray;
}
/** @return The <code>ImageIndex</code> of the silhouette figure. */
public ImageIndex silhouette() {
return silhouette;
}
} |
/**
* A (non-adaptive) 4th-order Runge-Kutta integrator.
*/
public class RK4 extends OdeInt {
public RK4(String system, double dt, double t0, double X0[]) {
super(system, dt, t0, X0);
}
private void step() {
int i;
double[] XInc = new double[X.length];
double[] XStep = new double[X.length];
// First increment
double[] K1 = system.evaluate(t, X);
for (i = 0; i < K1.length; i++)
K1[i] *= dt;
// Second increment
for (i = 0; i < XInc.length; i++)
XInc[i] = X[i] + K1[i] / 2.0;
double[] K2 = system.evaluate(t + dt / 2.0, XInc);
for (i = 0; i < K2.length; i++)
K2[i] *= dt;
// Third increment
for (i = 0; i < XInc.length; i++)
XInc[i] = X[i] + K2[i] / 2.0;
double[] K3 = system.evaluate(t + dt / 2.0, XInc);
for (i = 0; i < K3.length; i++)
K3[i] *= dt;
// Fourth increment
for (i = 0; i < XInc.length; i++)
XInc[i] = X[i] + K3[i];
double[] K4 = system.evaluate(t + dt, XInc);
for (i = 0; i < K4.length; i++)
K4[i] *= dt;
// Weighted average of increments
for (i = 0; i < XStep.length; i++)
X[i] += (K1[i] + 2.0 * K2[i] + 2.0 * K3[i] + K4[i]) / 6.0;
t += dt;
}
public void integrate(int nSteps) {
while (nSteps
step();
}
} |
package org.wikipathways;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import javax.xml.rpc.ServiceException;
import org.jibble.pircbot.IrcException;
import org.jibble.pircbot.PircBot;
import org.pathvisio.wikipathways.WikiPathwaysClient;
import org.pathvisio.wikipathways.webservice.WSHistoryRow;
import org.pathvisio.wikipathways.webservice.WSPathwayHistory;
import org.pathvisio.wikipathways.webservice.WSPathwayInfo;
public class WipaBot extends PircBot
{
Timer t;
Date last;
final static String channel = "#wikipathways";
Set<WSHistoryRow> reported = new HashSet<WSHistoryRow>();
class PollTask extends TimerTask
{
@Override
public void run()
{
System.out.println ("TIMER FIRED");
// TODO Auto-generated method stub
System.out.println ("Changes since " + last);
try
{
WSPathwayInfo infos[] = client.getRecentChanges(last);
last = new Date();
for (WSPathwayInfo info : infos)
{
WSHistoryRow history[] = client.getPathwayHistory(info.getId(), last).getHistory();
if (history != null) for (WSHistoryRow hist : history)
{
String msg = info.getName() + " - " + info.getSpecies() + " updated by " + hist.getUser() + " with comment " + hist.getComment();
System.out.println (msg);
if (reported.contains(hist))
{
System.out.println ("ERROR: already reported");
}
else
{
WipaBot.this.sendMessage(channel, msg);
reported.add(hist);
}
}
}
}
catch (RemoteException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (NullPointerException e)
{
e.printStackTrace();
}
}
}
WikiPathwaysClient client;
public WipaBot() throws ServiceException
{
this.setName("wipabot");
client = new WikiPathwaysClient();
}
public void run() throws IOException, IrcException
{
this.connect("irc.freenode.net");
// this.sendMessage("NickServ", "IDENTIFY password_here");
this.joinChannel("#wikipathways");
t = new Timer();
last = new Date();
t.schedule(new PollTask(), 0, 60000);
}
} |
package cn.cerc.mis.core;
import cn.cerc.core.IHandle;
import cn.cerc.db.core.IAppConfig;
import cn.cerc.db.core.ServerConfig;
import cn.cerc.mis.client.IServiceProxy;
import cn.cerc.mis.client.ServiceFactory;
import cn.cerc.mis.config.AppStaticFileDefault;
import cn.cerc.mis.config.ApplicationConfig;
import cn.cerc.mis.language.R;
import cn.cerc.mis.other.BufferType;
import cn.cerc.mis.other.MemoryBuffer;
import cn.cerc.mis.page.JsonPage;
import cn.cerc.mis.page.JspPage;
import cn.cerc.mis.page.RedirectPage;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
@Slf4j
public class StartForms implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
String uri = req.getRequestURI();
log.debug("uri {}", uri);
if (StringUtils.countMatches(uri, "/") < 2 && !uri.contains("favicon.ico")) {
IAppConfig conf = Application.getAppConfig();
String redirect = String.format("%s%s", ApplicationConfig.App_Path, conf.getFormWelcome());
resp.sendRedirect(redirect);
return;
}
if (AppStaticFileDefault.getInstance().isStaticFile(uri)) {
// TODO jar
if (uri.contains("imgZoom")) {
chain.doFilter(req, resp);
return;
}
/*
* 1 getPathForms forms AppConfig
* 2 3/ /131001/images/systeminstall-pc.png ->
* /forms/images/systeminstall-pc.png
*/
log.debug("before {}", uri);
IAppConfig conf = Application.getAppConfig();
int index = uri.indexOf("/", 2);
if (index < 0) {
request.getServletContext().getRequestDispatcher(uri).forward(request, response);
} else {
String source = "/" + conf.getPathForms() + uri.substring(index);
request.getServletContext().getRequestDispatcher(source).forward(request, response);
log.debug("after {}", source);
}
return;
}
if (uri.contains("service/")) {
chain.doFilter(req, resp);
return;
}
if (uri.contains("task/")) {
chain.doFilter(req, resp);
return;
}
if (uri.contains("docs/")) {
chain.doFilter(req, resp);
return;
}
// 2Url
String childCode = getRequestCode(req);
if (childCode == null) {
outputErrorPage(req, resp, new RuntimeException("" + req.getServletPath()));
return;
}
String[] params = childCode.split("\\.");
String formId = params[0];
String funcCode = params.length == 1 ? "execute" : params[1];
// TODO ???
req.setAttribute("logon", false);
// TODO ???
IFormFilter formFilter = Application.getBean(IFormFilter.class, "AppFormFilter");
if (formFilter != null) {
if (formFilter.doFilter(resp, formId, funcCode)) {
return;
}
}
IHandle handle = null;
try {
IForm form = Application.getForm(req, resp, formId);
if (form == null) {
outputErrorPage(req, resp, new RuntimeException("error servlet:" + req.getServletPath()));
return;
}
ClientDevice client = new ClientDevice();
client.setRequest(req);
req.setAttribute("_showMenu_", !ClientDevice.APP_DEVICE_EE.equals(client.getDevice()));
form.setClient(client);
handle = Application.getHandle();
handle.setProperty(Application.sessionId, req.getSession().getId());
handle.setProperty(Application.deviceLanguage, client.getLanguage());
req.setAttribute("myappHandle", handle);
form.setHandle(handle);
if (form.logon()) {
callForm(form, funcCode);
} else {
IAppLogin page = Application.getBean(IAppLogin.class, "appLogin", "appLoginDefault");
page.init(form);
String cmd = page.checkToken(client.getToken());
if (cmd != null) {
if (cmd.startsWith("redirect:")) {
resp.sendRedirect(cmd.substring(9));
} else {
String url = String.format("/WEB-INF/%s/%s", Application.getAppConfig().getPathForms(),
cmd);
request.getServletContext().getRequestDispatcher(url).forward(request, response);
}
} else {
callForm(form, funcCode);
}
}
} catch (Exception e) {
outputErrorPage(req, resp, e);
} finally {
if (handle != null) {
handle.close();
}
}
}
private void outputErrorPage(HttpServletRequest request, HttpServletResponse response, Throwable e)
throws ServletException, IOException {
Throwable err = e.getCause();
if (err == null) {
err = e;
}
IAppErrorPage errorPage = Application.getBean(IAppErrorPage.class, "appErrorPage", "appErrorPageDefault");
if (errorPage != null) {
String result = errorPage.getErrorPage(request, response, err);
if (result != null) {
String url = String.format("/WEB-INF/%s/%s", Application.getAppConfig().getPathForms(), result);
request.getServletContext().getRequestDispatcher(url).forward(request, response);
}
} else {
log.warn("not define bean: errorPage");
log.error(err.getMessage());
err.printStackTrace();
}
}
protected boolean passDevice(IForm form) {
// iPhone
if (isExperienceAccount(form)) {
return true;
}
String deviceId = form.getClient().getId();
// TODO
String verifyCode = form.getRequest().getParameter("verifyCode");
log.debug(String.format(", deviceId=%s", deviceId));
String userId = (String) form.getHandle().getProperty(Application.userId);
try (MemoryBuffer buff = new MemoryBuffer(BufferType.getSessionInfo, userId, deviceId)) {
if (!buff.isNull()) {
if (buff.getBoolean("VerifyMachine")) {
log.debug("");
return true;
}
}
boolean result = false;
IServiceProxy app = ServiceFactory.get(form.getHandle());
app.setService("SvrUserLogin.verifyMachine");
app.getDataIn().getHead().setField("deviceId", deviceId);
if (verifyCode != null && !"".equals(verifyCode)) {
app.getDataIn().getHead().setField("verifyCode", verifyCode);
}
if (app.exec()) {
result = true;
} else {
int used = app.getDataOut().getHead().getInt("Used_");
if (used == 1) {
result = true;
} else {
form.setParam("message", app.getMessage());
}
}
if (result) {
buff.setField("VerifyMachine", true);
}
return result;
}
}
protected void callForm(IForm form, String funcCode) throws ServletException, IOException {
HttpServletResponse response = form.getResponse();
HttpServletRequest request = form.getRequest();
if ("excel".equals(funcCode)) {
response.setContentType("application/vnd.ms-excel; charset=UTF-8");
response.addHeader("Content-Disposition", "attachment; filename=excel.csv");
} else {
response.setContentType("text/html;charset=UTF-8");
}
Object pageOutput;
Method method = null;
long startTime = System.currentTimeMillis();
try {
// FIXME: 2019/12/8 ??? CLIENTVER
String CLIENTVER = request.getParameter("CLIENTVER");
if (CLIENTVER != null) {
request.getSession().setAttribute("CLIENTVER", CLIENTVER);
}
if (!Application.getPassport(form.getHandle()).passForm(form)) {
log.warn(String.format(" %s", request.getRequestURL()));
throw new RuntimeException(R.asString(form.getHandle(), ""));
}
if (isExperienceAccount(form)) {
try {
if (form.getClient().isPhone()) {
try {
method = form.getClass().getMethod(funcCode + "_phone");
} catch (NoSuchMethodException e) {
method = form.getClass().getMethod(funcCode);
}
} else {
method = form.getClass().getMethod(funcCode);
}
pageOutput = method.invoke(form);
} catch (PageException e) {
form.setParam("message", e.getMessage());
pageOutput = e.getViewFile();
}
} else {
if (form.getHandle().getProperty(Application.userId) == null || form.passDevice() || passDevice(form)) {
try {
if (form.getClient().isPhone()) {
try {
method = form.getClass().getMethod(funcCode + "_phone");
} catch (NoSuchMethodException e) {
method = form.getClass().getMethod(funcCode);
}
} else {
method = form.getClass().getMethod(funcCode);
}
pageOutput = method.invoke(form);
} catch (PageException e) {
form.setParam("message", e.getMessage());
pageOutput = e.getViewFile();
}
} else {
log.debug("");
ServerConfig config = ServerConfig.getInstance();
String supCorpNo = config.getProperty("vine.mall.supCorpNo", "");
// APPiPhoneiPhone
if (!"".equals(supCorpNo) && form.getClient().getDevice().equals(ClientDevice.APP_DEVICE_IPHONE)) {
try {
method = form.getClass().getMethod(funcCode + "_phone");
} catch (NoSuchMethodException e) {
method = form.getClass().getMethod(funcCode);
}
form.getRequest().setAttribute("needVerify", "true");
pageOutput = method.invoke(form);
} else {
if (form instanceof IJSONForm) {
JsonPage output = new JsonPage(form);
output.setResultMessage(false, "");
pageOutput = output;
} else {
pageOutput = new RedirectPage(form, Application.getAppConfig().getFormVerifyDevice());
}
}
}
}
if (pageOutput != null) {
if (pageOutput instanceof IPage) {
IPage output = (IPage) pageOutput;
String cmd = output.execute();
if (cmd != null) {
if (cmd.startsWith("redirect:")) {
response.sendRedirect(cmd.substring(9));
} else {
String url = String.format("/WEB-INF/%s/%s", Application.getAppConfig().getPathForms(),
cmd);
request.getServletContext().getRequestDispatcher(url).forward(request, response);
}
} else if ("GET".equals(request.getMethod())) {
StringBuffer jumpUrl = new StringBuffer();
String[] zlass = form.getClass().getName().split("\\.");
if (zlass != null && zlass.length > 0) {
jumpUrl.append(zlass[zlass.length - 1]);
jumpUrl.append(".").append(funcCode);
} else {
jumpUrl.append(request.getRequestURL().toString());
}
if (request.getParameterMap().size() > 0) {
jumpUrl.append("?");
request.getParameterMap().forEach((key, value) -> {
jumpUrl.append(key).append("=").append(String.join(",", value)).append("&");
});
jumpUrl.delete(jumpUrl.length() - 1, jumpUrl.length());
}
response.setHeader("jumpURL", jumpUrl.toString());
}
} else {
log.warn(String.format("%s pageOutput is not IPage: %s", funcCode, pageOutput));
JspPage output = new JspPage(form);
output.setJspFile((String) pageOutput);
output.execute();
}
}
} catch (Exception e) {
outputErrorPage(request, response, e);
} finally {
if (method != null) {
long timeout = 1000;
Webpage webpage = method.getAnnotation(Webpage.class);
if (webpage != null) {
timeout = webpage.timeout();
}
checkTimeout(form, funcCode, startTime, timeout);
}
}
}
protected void checkTimeout(IForm form, String funcCode, long startTime, long timeout) {
long totalTime = System.currentTimeMillis() - startTime;
if (totalTime > timeout) {
String[] tmp = form.getClass().getName().split("\\.");
String pageCode = tmp[tmp.length - 1] + "." + funcCode;
String dataIn = new Gson().toJson(form.getRequest().getParameterMap());
if (dataIn.length() > 200) {
dataIn = dataIn.substring(0, 200);
}
log.warn("pageCode: {}, tickCount: {}, dataIn: {}", pageCode, totalTime, dataIn);
}
}
public static String getRequestCode(HttpServletRequest req) {
String url = null;
log.debug("servletPath {}", req.getServletPath());
String[] args = req.getServletPath().split("/");
if (args.length == 2 || args.length == 3) {
if ("".equals(args[0]) && !"".equals(args[1])) {
if (args.length == 3) {
url = args[2];
} else {
String token = (String) req.getAttribute(RequestData.TOKEN);
IAppConfig conf = Application.getAppConfig();
if (token != null && !"".equals(token)) {
url = conf.getFormDefault();
} else {
url = conf.getFormWelcome();
}
}
}
}
return url;
}
protected boolean isExperienceAccount(IForm form) {
String userCode = form.getHandle().getUserCode();
return LoginWhitelist.getInstance().contains(userCode);
}
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void destroy() {
}
} |
package org.srplib.support;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @author Q-APE
*/
public class BeanBuilder {
public static final String BUILD_METHOD = "build";
public static <T, B extends Builder<T>> B create(T object, Class<B> builderInterface) {
BeanBuilderInvocationHandler invocationHandler = new BeanBuilderInvocationHandler(object);
return (B)Proxy.newProxyInstance(
BeanBuilder.class.getClassLoader(), new Class[] {builderInterface }, invocationHandler);
}
private static class BeanBuilderInvocationHandler implements InvocationHandler {
private Object object;
private BeanBuilderInvocationHandler(Object object) {
this.object = object;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result;
if (BUILD_METHOD.equals(method.getName())) {
// Build method. Return final object.
result = object;
}
else {
// property set method.
Method originalMethod = getOriginalMethod(method);
originalMethod.invoke(object, args);
result = proxy;
}
return result;
}
private Method getOriginalMethod(Method method) {
String originalMethodName = "set" + firstCharToUpper(method.getName());
try {
return object.getClass().getDeclaredMethod(originalMethodName, method.getParameterTypes());
}
catch (NoSuchMethodException e) {
throw new IllegalStateException(String.format(
"Original method not found in class '%s'. Called builder's method: '%s', " +
"expected corresponding object's method: '%s'",
object.getClass().getName(), method.getName(), originalMethodName), e);
}
}
private String firstCharToUpper(String string) {
return Character.toUpperCase(string.charAt(0)) + string.substring(1);
}
}
} |
package soot;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.jimple.SpecialInvokeExpr;
import soot.util.ArraySet;
import soot.util.Chain;
/** Represents the class hierarchy. It is closely linked to a Scene,
* and must be recreated if the Scene changes.
*
* The general convention is that if a method name contains
* "Including", then it returns the non-strict result; otherwise,
* it does a strict query (e.g. strict superclass). */
public class Hierarchy
{
// These two maps are not filled in the constructor.
Map<SootClass, List<SootClass>> classToSubclasses;
Map<SootClass, List<SootClass>> interfaceToSubinterfaces;
Map<SootClass, List<SootClass>> interfaceToSuperinterfaces;
Map<SootClass, List<SootClass>> classToDirSubclasses;
Map<SootClass, List<SootClass>> interfaceToDirSubinterfaces;
Map<SootClass, List<SootClass>> interfaceToDirSuperinterfaces;
// This holds the direct implementers.
Map<SootClass, List<SootClass>> interfaceToDirImplementers;
int state;
Scene sc;
/** Constructs a hierarchy from the current scene. */
public Hierarchy()
{
this.sc = Scene.v();
state = sc.getState();
// Well, this used to be describable by 'Duh'.
// Construct the subclasses hierarchy and the subinterfaces hierarchy.
{
Chain<SootClass> allClasses = sc.getClasses();
classToSubclasses = new HashMap<SootClass, List<SootClass>>(allClasses.size() * 2 + 1, 0.7f);
interfaceToSubinterfaces = new HashMap<SootClass, List<SootClass>>(allClasses.size() * 2 + 1, 0.7f);
interfaceToSuperinterfaces = new HashMap<SootClass, List<SootClass>>(allClasses.size() * 2 + 1, 0.7f);
classToDirSubclasses = new HashMap<SootClass, List<SootClass>>
(allClasses.size() * 2 + 1, 0.7f);
interfaceToDirSubinterfaces = new HashMap<SootClass, List<SootClass>>
(allClasses.size() * 2 + 1, 0.7f);
interfaceToDirSuperinterfaces = new HashMap<SootClass, List<SootClass>>
(allClasses.size() * 2 + 1, 0.7f);
interfaceToDirImplementers = new HashMap<SootClass, List<SootClass>>
(allClasses.size() * 2 + 1, 0.7f);
for (SootClass c : allClasses) {
if( c.resolvingLevel() < SootClass.HIERARCHY ) continue;
if (c.isInterface())
{
interfaceToDirSubinterfaces.put(c, new ArrayList<SootClass>());
interfaceToDirSuperinterfaces.put(c, new ArrayList<SootClass>());
interfaceToDirImplementers.put(c, new ArrayList<SootClass>());
}
else
classToDirSubclasses.put(c, new ArrayList<SootClass>());
}
for (SootClass c : allClasses) {
if( c.resolvingLevel() < SootClass.HIERARCHY ) continue;
if (c.hasSuperclass()) {
if (c.isInterface()) {
List<SootClass> l2 = interfaceToDirSuperinterfaces.get(c);
for (SootClass i : c.getInterfaces()) {
if( c.resolvingLevel() < SootClass.HIERARCHY ) continue;
List<SootClass> l = interfaceToDirSubinterfaces.get(i);
if (l != null) l.add(c);
if (l2 != null) l2.add(i);
}
}
else {
List<SootClass> l = classToDirSubclasses.get(c.getSuperclass());
if (l != null) l.add(c);
for (SootClass i : c.getInterfaces()) {
if( c.resolvingLevel() < SootClass.HIERARCHY ) continue;
l = interfaceToDirImplementers.get(i);
if (l != null) l.add(c);
}
}
}
}
// Fill the directImplementers lists with subclasses.
for (SootClass c : allClasses) {
if( c.resolvingLevel() < SootClass.HIERARCHY ) continue;
if (c.isInterface()) {
List<SootClass> imp = interfaceToDirImplementers.get(c);
Set<SootClass> s = new ArraySet<SootClass>();
for (SootClass c0 : imp) {
if( c.resolvingLevel() < SootClass.HIERARCHY ) continue;
s.addAll(getSubclassesOfIncluding(c0));
}
imp.clear();
imp.addAll(s);
}
}
}
}
private void checkState()
{
if (state != sc.getState())
throw new ConcurrentModificationException("Scene changed for Hierarchy!");
}
// This includes c in the list of subclasses.
/** Returns a list of subclasses of c, including itself. */
public List<SootClass> getSubclassesOfIncluding(SootClass c)
{
c.checkLevel(SootClass.HIERARCHY);
if (c.isInterface())
throw new RuntimeException("class needed!");
List<SootClass> l = new ArrayList<SootClass>();
l.addAll(getSubclassesOf(c));
l.add(c);
return Collections.unmodifiableList(l);
}
/** Returns a list of subclasses of c, excluding itself. */
public List<SootClass> getSubclassesOf(SootClass c)
{
c.checkLevel(SootClass.HIERARCHY);
if (c.isInterface())
throw new RuntimeException("class needed!");
checkState();
// If already cached, return the value.
if (classToSubclasses.get(c) != null)
return classToSubclasses.get(c);
// Otherwise, build up the hashmap.
List<SootClass> l = new ArrayList<SootClass>();
for (SootClass cls : classToDirSubclasses.get(c)) {
if( cls.resolvingLevel() < SootClass.HIERARCHY ) continue;
l.addAll(getSubclassesOfIncluding(cls));
}
l = Collections.unmodifiableList(l);
classToSubclasses.put(c, l);
return l;
}
/** Returns a list of superclasses of c, including itself. */
public List<SootClass> getSuperclassesOfIncluding(SootClass c)
{
c.checkLevel(SootClass.HIERARCHY);
List<SootClass> l = getSuperclassesOf(c);
ArrayList<SootClass> al = new ArrayList<SootClass>(); al.add(c); al.addAll(l);
return Collections.unmodifiableList(al);
}
/** Returns a list of strict superclasses of c, starting with c's parent. */
public List<SootClass> getSuperclassesOf(SootClass c)
{
c.checkLevel(SootClass.HIERARCHY);
if (c.isInterface())
throw new RuntimeException("class needed!");
checkState();
ArrayList<SootClass> l = new ArrayList<SootClass>();
SootClass cl = c;
while (cl.hasSuperclass())
{
l.add(cl.getSuperclass());
cl = cl.getSuperclass();
}
return Collections.unmodifiableList(l);
}
/** Returns a list of subinterfaces of c, including itself. */
public List<SootClass> getSubinterfacesOfIncluding(SootClass c)
{
c.checkLevel(SootClass.HIERARCHY);
if (!c.isInterface())
throw new RuntimeException("interface needed!");
List<SootClass> l = new ArrayList<SootClass>();
l.addAll(getSubinterfacesOf(c));
l.add(c);
return Collections.unmodifiableList(l);
}
/** Returns a list of subinterfaces of c, excluding itself. */
public List<SootClass> getSubinterfacesOf(SootClass c)
{
c.checkLevel(SootClass.HIERARCHY);
if (!c.isInterface())
throw new RuntimeException("interface needed!");
checkState();
// If already cached, return the value.
if (interfaceToSubinterfaces.get(c) != null)
return interfaceToSubinterfaces.get(c);
// Otherwise, build up the hashmap.
List<SootClass> l = new ArrayList<SootClass>();
for (SootClass si : interfaceToDirSubinterfaces.get(c)) {
l.addAll(getSubinterfacesOfIncluding(si));
}
interfaceToSubinterfaces.put(c, Collections.unmodifiableList(l));
return Collections.unmodifiableList(l);
}
/** Returns a list of superinterfaces of c, including itself. */
public List<SootClass> getSuperinterfacesOfIncluding(SootClass c)
{
c.checkLevel(SootClass.HIERARCHY);
if (!c.isInterface())
throw new RuntimeException("interface needed!");
List<SootClass> l = new ArrayList<SootClass>();
l.addAll(getSuperinterfacesOf(c));
l.add(c);
return Collections.unmodifiableList(l);
}
/** Returns a list of superinterfaces of c, excluding itself. */
public List<SootClass> getSuperinterfacesOf(SootClass c)
{
c.checkLevel(SootClass.HIERARCHY);
if (!c.isInterface())
throw new RuntimeException("interface needed!");
checkState();
// If already cached, return the value.
if (interfaceToSuperinterfaces.get(c) != null)
return interfaceToSuperinterfaces.get(c);
// Otherwise, build up the hashmap.
List<SootClass> l = new ArrayList<SootClass>();
for (SootClass si : interfaceToDirSuperinterfaces.get(c)) {
l.addAll(getSuperinterfacesOfIncluding(si));
}
interfaceToSuperinterfaces.put(c, Collections.unmodifiableList(l));
return Collections.unmodifiableList(l);
}
/** Returns a list of direct superclasses of c, excluding c. */
public List<SootClass> getDirectSuperclassesOf(SootClass c)
{
throw new RuntimeException("Not implemented yet!");
}
/** Returns a list of direct subclasses of c, excluding c. */
public List<SootClass> getDirectSubclassesOf(SootClass c)
{
c.checkLevel(SootClass.HIERARCHY);
if (c.isInterface())
throw new RuntimeException("class needed!");
checkState();
return Collections.unmodifiableList(classToDirSubclasses.get(c));
}
// This includes c in the list of subclasses.
/** Returns a list of direct subclasses of c, including c. */
public List<SootClass> getDirectSubclassesOfIncluding(SootClass c)
{
c.checkLevel(SootClass.HIERARCHY);
if (c.isInterface())
throw new RuntimeException("class needed!");
checkState();
List<SootClass> l = new ArrayList<SootClass>();
l.addAll(classToDirSubclasses.get(c));
l.add(c);
return Collections.unmodifiableList(l);
}
/** Returns a list of direct superinterfaces of c. */
public List<SootClass> getDirectSuperinterfacesOf(SootClass c)
{
throw new RuntimeException("Not implemented yet!");
}
/** Returns a list of direct subinterfaces of c. */
public List<SootClass> getDirectSubinterfacesOf(SootClass c)
{
c.checkLevel(SootClass.HIERARCHY);
if (!c.isInterface())
throw new RuntimeException("interface needed!");
checkState();
return interfaceToDirSubinterfaces.get(c);
}
/** Returns a list of direct subinterfaces of c, including itself. */
public List<SootClass> getDirectSubinterfacesOfIncluding(SootClass c)
{
c.checkLevel(SootClass.HIERARCHY);
if (!c.isInterface())
throw new RuntimeException("interface needed!");
checkState();
List<SootClass> l = new ArrayList<SootClass>();
l.addAll(interfaceToDirSubinterfaces.get(c));
l.add(c);
return Collections.unmodifiableList(l);
}
/** Returns a list of direct implementers of c, excluding itself. */
public List<SootClass> getDirectImplementersOf(SootClass i)
{
i.checkLevel(SootClass.HIERARCHY);
if (!i.isInterface())
throw new RuntimeException("interface needed; got "+i);
checkState();
return Collections.unmodifiableList(interfaceToDirImplementers.get(i));
}
/** Returns a list of implementers of c, excluding itself. */
public List<SootClass> getImplementersOf(SootClass i)
{
i.checkLevel(SootClass.HIERARCHY);
if (!i.isInterface())
throw new RuntimeException("interface needed; got "+i);
checkState();
ArraySet<SootClass> set = new ArraySet<SootClass>();
for (SootClass c : getSubinterfacesOfIncluding(i)) {
set.addAll(getDirectImplementersOf(c));
}
ArrayList<SootClass> l = new ArrayList<SootClass>();
l.addAll(set);
return Collections.unmodifiableList(l);
}
/**
* Returns true if child is a subclass of possibleParent. If one of the
* known parent classes is phantom, we conservatively assume that the
* current class might be a child.
*/
public boolean isClassSubclassOf(SootClass child, SootClass possibleParent)
{
child.checkLevel(SootClass.HIERARCHY);
possibleParent.checkLevel(SootClass.HIERARCHY);
List<SootClass> parentClasses = getSuperclassesOf(child);
if (parentClasses.contains(possibleParent))
return true;
for (SootClass sc : parentClasses)
if (sc.isPhantom())
return true;
return false;
}
/**
* Returns true if child is, or is a subclass of, possibleParent. If one of
* the known parent classes is phantom, we conservatively assume that the
* current class might be a child.
*/
public boolean isClassSubclassOfIncluding(SootClass child, SootClass possibleParent)
{
child.checkLevel(SootClass.HIERARCHY);
possibleParent.checkLevel(SootClass.HIERARCHY);
List<SootClass> parentClasses = getSuperclassesOfIncluding(child);
if (parentClasses.contains(possibleParent))
return true;
for (SootClass sc : parentClasses)
if (sc.isPhantom())
return true;
return false;
}
/** Returns true if child is a direct subclass of possibleParent. */
public boolean isClassDirectSubclassOf(SootClass c, SootClass c2)
{
throw new RuntimeException("Not implemented yet!");
}
/** Returns true if child is a superclass of possibleParent. */
public boolean isClassSuperclassOf(SootClass parent, SootClass possibleChild)
{
parent.checkLevel(SootClass.HIERARCHY);
possibleChild.checkLevel(SootClass.HIERARCHY);
return getSubclassesOf(parent).contains(possibleChild);
}
/** Returns true if parent is, or is a superclass of, possibleChild. */
public boolean isClassSuperclassOfIncluding(SootClass parent, SootClass possibleChild)
{
parent.checkLevel(SootClass.HIERARCHY);
possibleChild.checkLevel(SootClass.HIERARCHY);
return getSubclassesOfIncluding(parent).contains(possibleChild);
}
/** Returns true if child is a subinterface of possibleParent. */
public boolean isInterfaceSubinterfaceOf(SootClass child, SootClass possibleParent)
{
child.checkLevel(SootClass.HIERARCHY);
possibleParent.checkLevel(SootClass.HIERARCHY);
return getSubinterfacesOf(possibleParent).contains(child);
}
/** Returns true if child is a direct subinterface of possibleParent. */
public boolean isInterfaceDirectSubinterfaceOf(SootClass child,
SootClass possibleParent)
{
child.checkLevel(SootClass.HIERARCHY);
possibleParent.checkLevel(SootClass.HIERARCHY);
return getDirectSubinterfacesOf(possibleParent).contains(child);
}
/** Returns true if parent is a superinterface of possibleChild. */
public boolean isInterfaceSuperinterfaceOf(SootClass parent, SootClass possibleChild)
{
parent.checkLevel(SootClass.HIERARCHY);
possibleChild.checkLevel(SootClass.HIERARCHY);
return getSuperinterfacesOf(possibleChild).contains(parent);
}
/** Returns true if parent is a direct superinterface of possibleChild. */
public boolean isInterfaceDirectSuperinterfaceOf(SootClass parent,
SootClass possibleChild)
{
parent.checkLevel(SootClass.HIERARCHY);
possibleChild.checkLevel(SootClass.HIERARCHY);
return getDirectSuperinterfacesOf(possibleChild).contains(parent);
}
/** Returns the most specific type which is an ancestor of both c1 and c2. */
public SootClass getLeastCommonSuperclassOf(SootClass c1,
SootClass c2)
{
c1.checkLevel(SootClass.HIERARCHY);
c2.checkLevel(SootClass.HIERARCHY);
throw new RuntimeException("Not implemented yet!");
}
// Questions about method invocation.
/** Checks whether check is a visible class in view of the from class.
* It assumes that protected and private classes do not exit.
* If they exist and check is either protected or private,
* the check will return false. */
public boolean isVisible( SootClass from, SootClass check) {
if (check.isPublic())
return true;
if( check.isProtected() || check.isPrivate())
return false;
//package visibility
return from.getJavaPackageName().equals(
check.getJavaPackageName() );
}
/** Returns true if the classmember m is visible from code in the class from. */
public boolean isVisible( SootClass from, ClassMember m ) {
from.checkLevel(SootClass.HIERARCHY);
m.getDeclaringClass().checkLevel(SootClass.HIERARCHY);
if (!isVisible(from, m.getDeclaringClass()))
return false;
if( m.isPublic() ) return true;
if( m.isPrivate() ) {
return from.equals( m.getDeclaringClass() );
}
if( m.isProtected() ) {
return isClassSubclassOfIncluding( from, m.getDeclaringClass() );
}
// m is package
return from.getJavaPackageName().equals(
m.getDeclaringClass().getJavaPackageName() );
//|| isClassSubclassOfIncluding( from, m.getDeclaringClass() );
}
/**
* Given an object of actual type C (o = new C()), returns the method which
* will be called on an o.f() invocation.
*/
public SootMethod resolveConcreteDispatch(SootClass concreteType,
SootMethod m) {
concreteType.checkLevel(SootClass.HIERARCHY);
m.getDeclaringClass().checkLevel(SootClass.HIERARCHY);
checkState();
if (concreteType.isInterface())
throw new RuntimeException("class needed!");
String methodSig = m.getSubSignature();
for (SootClass c : getSuperclassesOfIncluding(concreteType)) {
SootMethod sm = c.getMethodUnsafe(methodSig);
if (sm != null && isVisible(c, m)) {
return sm;
}
}
throw new RuntimeException(
"could not resolve concrete dispatch!\nType: " + concreteType
+ "\nMethod: " + m);
}
/** Given a set of definite receiver types, returns a list of possible targets. */
public List<SootMethod> resolveConcreteDispatch(List<Type> classes, SootMethod m)
{
m.getDeclaringClass().checkLevel(SootClass.HIERARCHY);
checkState();
Set<SootMethod> s = new ArraySet<SootMethod>();
for (Type cls : classes) {
if (cls instanceof RefType)
s.add(resolveConcreteDispatch(((RefType)cls).getSootClass(), m));
else if (cls instanceof ArrayType) {
s.add(resolveConcreteDispatch((RefType.v("java.lang.Object")).getSootClass(), m));
}
else throw new RuntimeException("Unable to resolve concrete dispatch of type "+ cls);
}
return Collections.unmodifiableList(new ArrayList<SootMethod>(s));
}
// what can get called for c & all its subclasses
/** Given an abstract dispatch to an object of type c and a method m, gives
* a list of possible receiver methods. */
public List<SootMethod> resolveAbstractDispatch(SootClass c, SootMethod m)
{
c.checkLevel(SootClass.HIERARCHY);
m.getDeclaringClass().checkLevel(SootClass.HIERARCHY);
checkState();
Set<SootMethod> s = new ArraySet<SootMethod>();
Collection<SootClass> classesIt;
if (c.isInterface()) {
Set<SootClass> classes = new HashSet<SootClass>();
for (SootClass sootClass : getImplementersOf(c)) {
classes.addAll(getSubclassesOfIncluding(sootClass));
}
classesIt = classes;
}
else
classesIt = getSubclassesOfIncluding(c);
for (SootClass cl : classesIt) {
if( !Modifier.isAbstract( cl.getModifiers() ) ) {
s.add(resolveConcreteDispatch(cl, m));
}
}
return Collections.unmodifiableList(new ArrayList<SootMethod>(s));
}
// what can get called if you have a set of possible receiver types
/** Returns a list of possible targets for the given method and set of receiver types. */
public List<SootMethod> resolveAbstractDispatch(List<SootClass> classes, SootMethod m)
{
m.getDeclaringClass().checkLevel(SootClass.HIERARCHY);
Set<SootMethod> s = new ArraySet<SootMethod>();
for (SootClass sootClass : classes ) {
s.addAll(resolveAbstractDispatch(sootClass, m));
}
return Collections.unmodifiableList(new ArrayList<SootMethod>(s));
}
/** Returns the target for the given SpecialInvokeExpr. */
public SootMethod resolveSpecialDispatch(SpecialInvokeExpr ie, SootMethod container)
{
container.getDeclaringClass().checkLevel(SootClass.HIERARCHY);
SootMethod target = ie.getMethod();
target.getDeclaringClass().checkLevel(SootClass.HIERARCHY);
/* This is a bizarre condition! Hopefully the implementation is correct.
See VM Spec, 2nd Edition, Chapter 6, in the definition of invokespecial. */
if ("<init>".equals(target.getName()) || target.isPrivate())
return target;
else if (isClassSubclassOf(target.getDeclaringClass(), container.getDeclaringClass()))
return resolveConcreteDispatch(container.getDeclaringClass(), target);
else
return target;
}
} |
package soot.coffi;
import soot.options.*;
import java.lang.*;
import java.util.*;
import soot.*;
import soot.jimple.*;
import soot.baf.*;
import soot.util.*;
import soot.tagkit.*;
/** A Control Flow Graph.
* @author Clark Verbrugge
*/
public class CFG {
/** Method for which this is a control flow graph.
* @see method_info
*/
private method_info method;
/** Ordered list of BasicBlocks comprising the code of this CFG.
*/
BasicBlock cfg;
Chain units;
JimpleBody listBody;
Map instructionToFirstStmt;
Map instructionToLastStmt;
SootMethod jmethod;
Scene cm;
Instruction firstInstruction;
Instruction lastInstruction;
private short wide; // convert indices when parsing jimple
private Instruction sentinel;
private Hashtable h2bb, t2bb;
private int bbcount; // statistics, number of BBs processed
/** Constructs a new control flow graph for the given method.
* @param m the method in question.
* @see method_info
*/
public CFG(method_info m)
{
this.method = m;
this.sentinel = new Instruction_Nop();
this.sentinel.next = m.instructions;
m.instructions.prev = this.sentinel;
// printInstructions();
// printExceptionTable();
eliminateJsrRets();
// printInstructions();
// printExceptionTable();
buildBBCFG();
// printBBs();
// printBBCFGSucc();
cfg.beginCode = true;
m.cfg = this;
if(cfg != null)
firstInstruction = cfg.head;
else
firstInstruction = null;
/*
if (m.code_attr != null)
{
for (int i=0; i<m.code_attr.attributes.length; i++)
{
if (m.code_attr.attributes[i]
instanceof LineNumberTable_attribute)
{
G.v().out.print(m.code_attr.attributes[i]);
}
}
}
*/
}
private void printBBCFGSucc()
{
BasicBlock b = this.cfg;
while ( b!= null )
{
G.v().out.print(b.id +" -> ");
for (int i=0; i<b.succ.size(); i++)
{
BasicBlock bs = (BasicBlock)b.succ.elementAt(i);
G.v().out.print(bs.id+" ");
}
G.v().out.println();
b = b.next;
}
}
private void printBBCFGPred()
{
BasicBlock b = this.cfg;
while ( b!= null )
{
G.v().out.print(b.id +" <- ");
for (int i=0; i<b.pred.size(); i++)
{
BasicBlock bs = (BasicBlock)b.pred.elementAt(i);
G.v().out.print(bs.id+" ");
}
G.v().out.println();
b = b.next;
}
}
private void printOneBasicBlock(BasicBlock b)
{
G.v().out.println("Block "+b.id);
Instruction insn = b.head;
G.v().out.println(insn);
while (insn != b.tail && insn != null)
{
insn = insn.next;
G.v().out.println(insn);
}
G.v().out.println();
}
private void printBBHeadTail(BasicBlock fb)
{
BasicBlock b = fb;
while (b != null)
{
G.v().out.println(b.head);
G.v().out.println(b.tail+"\n");
b = b.next;
}
}
private void printBBs()
{
BasicBlock bb = this.cfg;
while (bb != null)
{
printOneBasicBlock(bb);
bb = bb.next;
}
}
private void printInstructions()
{
Instruction insn = method.instructions;
while (insn != null)
{
G.v().out.println(insn);
insn = insn.next;
}
}
private void printExceptionTable()
{
Code_attribute ca = this.method.locate_code_attribute();
G.v().out.println("\nException table :");
G.v().out.println("start\tend\thandler");
for (int i=0; i<ca.exception_table.length; i++)
{
exception_table_entry ete = ca.exception_table[i];
G.v().out.println((ete.start_inst == null ? "null" :
Integer.toString(ete.start_inst.label)) + " \t " +
(ete.end_inst == null ? "null" :
Integer.toString(ete.end_inst.label)) + " \t " +
ete.handler_inst.label);
}
}
// Constructs the actual control flow graph. Assumes the hash table
// currently associates leaders with BasicBlocks, this function
// builds the next[] and prev[] pointer arrays.
private void buildBBCFG()
{
Object branches[], nextinsn;
Code_attribute ca = method.locate_code_attribute();
{
h2bb = new Hashtable(100,25);
t2bb = new Hashtable(100,25);
Instruction insn = this.sentinel.next;
BasicBlock blast = null;
if (insn != null)
{
Instruction tail = buildBasicBlock(insn);
cfg = new BasicBlock(insn, tail);
h2bb.put(insn, cfg);
t2bb.put(tail, cfg);
insn = tail.next;
blast = cfg;
}
while (insn != null)
{
Instruction tail = buildBasicBlock(insn);
BasicBlock block = new BasicBlock(insn, tail);
blast.next = block;
blast = block;
h2bb.put(insn, block);
t2bb.put(tail, block);
insn = tail.next;
}
}
BasicBlock block = cfg;
while (block != null)
{
Instruction insn = block.tail;
if (insn.branches)
{
if (insn instanceof Instruction_Athrow)
{
// see how many targets it can reach. Note that this is a
// subset of the exception_table.
HashSet ethandlers = new HashSet();
// exits this method, so start icount at 1
for (int i=0; i<ca.exception_table_length; i++)
{
exception_table_entry etentry =
ca.exception_table[i];
if (insn.label >= etentry.start_inst.label
&& (etentry.end_inst==null
|| insn.label < etentry.end_inst.label))
{
ethandlers.add(etentry.handler_inst);
}
}
branches = ethandlers.toArray();
}
else
{
branches = insn.branchpoints(insn.next);
}
if (branches != null)
{
block.succ.ensureCapacity(block.succ.size()+branches.length);
for (int i=0; i<branches.length; i++)
{
if ( branches[i]!=null ) {
BasicBlock bb = (BasicBlock)h2bb.get(branches[i]);
if (bb == null)
{
G.v().out.println("Warning: "
+"target of a branch is null");
G.v().out.println ( insn );
}
else
{
block.succ.addElement(bb);
bb.pred.addElement(block);
}
}
}
}
}
else
if (block.next!=null)
{ // BB ended not with a branch, so just go to next
block.succ.addElement(block.next);
block.next.pred.addElement(block);
}
block = block.next;
}
// One final step, run through exception handlers and mark which
// basic blocks begin their code
for (int i=0; i<ca.exception_table_length; i++)
{
BasicBlock bb = (BasicBlock)h2bb.get(
ca.exception_table[i].handler_inst);
if ( bb == null )
{
G.v().out.println("Warning: No basic block found for" +
" start of exception handler code.");
}
else
{
bb.beginException = true;
ca.exception_table[i].b = bb;
}
}
}
/* given the list of instructions head, this pulls off the front
* basic block, terminates it with a null, and returns the next
* instruction after.
*/
private static Instruction buildBasicBlock(Instruction head)
{
Instruction insn, next;
insn = head;
next = insn.next;
if (next == null)
return insn;
do
{
if (insn.branches || next.labelled)
break;
else
{
insn = next;
next = insn.next;
}
} while (next != null);
return insn;
}
/* get a set of reachable instructions from an astore to matching ret.
* it does not consider the exception handler as reachable now.
*/
private Set getReachableInsns(Instruction from, Instruction to)
{
Code_attribute codeAttribute = method.locate_code_attribute();
/* find all reachable blocks. */
Set reachableinsns = new HashSet();
LinkedList tovisit = new LinkedList();
reachableinsns.add(from);
tovisit.add(from);
while (!tovisit.isEmpty())
{
Instruction insn = (Instruction)tovisit.removeFirst();
if (insn == to)
continue;
Instruction[] bps = null;
if (insn.branches)
{
bps = insn.branchpoints(insn.next);
}
else
{
bps = new Instruction[1];
bps[0] = insn.next;
}
if (bps != null)
{
for (int i=0; i<bps.length; i++)
{
Instruction bp = bps[i];
if (bp != null
&& !reachableinsns.contains(bp))
{
reachableinsns.add(bp);
tovisit.add(bp);
}
}
}
}
return reachableinsns;
}
/* We only handle simple cases. */
Map jsr2astore = new HashMap();
Map astore2ret = new HashMap();
LinkedList jsrorder = new LinkedList();
/* Eliminate subroutines ( JSR/RET instructions ) by inlining the
routine bodies. */
private boolean eliminateJsrRets()
{
Instruction insn = this.sentinel;
// find the last instruction, for copying blocks.
while (insn.next != null) {
insn = insn.next;
}
this.lastInstruction = insn;
HashMap todoBlocks = new HashMap();
todoBlocks.put(this.sentinel.next, this.lastInstruction);
LinkedList todoList = new LinkedList();
todoList.add(this.sentinel.next);
while (!todoList.isEmpty()) {
Instruction firstInsn = (Instruction)todoList.removeFirst();
Instruction lastInsn = (Instruction)todoBlocks.get(firstInsn);
jsrorder.clear();
jsr2astore.clear();
astore2ret.clear();
if (findOutmostJsrs(firstInsn, lastInsn)) {
HashMap newblocks = inliningJsrTargets();
todoBlocks.putAll(newblocks);
todoList.addAll(newblocks.keySet());
}
}
/* patch exception table and others.*/
{
method.instructions = this.sentinel.next;
adjustExceptionTable();
adjustLineNumberTable();
adjustBranchTargets();
}
// we should prune the code and exception table here.
// remove any exception handler whose region is in a jsr/ret block.
// pruneExceptionTable();
return true;
}
// find outmost jsr/ret pairs in a code area, all information is
// saved in jsr2astore, and astore2ret
// start : start instruction, inclusively.
// end : the last instruction, inclusively.
// return the last instruction encounted ( before end )
// the caller cleans jsr2astore, astore2ret
private boolean findOutmostJsrs(Instruction start, Instruction end) {
// use to put innerJsrs.
HashSet innerJsrs = new HashSet();
boolean unusual = false;
Instruction insn = start;
do {
if (insn instanceof Instruction_Jsr
|| insn instanceof Instruction_Jsr_w)
{
if (innerJsrs.contains(insn)) {
// skip it
insn = insn.next;
continue;
}
Instruction astore = ((Instruction_branch)insn).target;
if (! (astore instanceof Interface_Astore))
{
unusual = true;
break;
}
Instruction ret = findMatchingRet(astore, insn, innerJsrs);
/*
if (ret == null)
{
unusual = true;
break;
}
*/
jsrorder.addLast(insn);
jsr2astore.put(insn, astore);
astore2ret.put(astore, ret);
}
insn = insn.next;
} while (insn != end.next);
if (unusual)
{
G.v().out.println("Sorry, I cannot handle this method.");
return false;
}
return true;
}
private Instruction findMatchingRet(Instruction astore,
Instruction jsr,
HashSet innerJsrs)
{
int astorenum = ((Interface_Astore)astore).getLocalNumber();
Instruction insn = astore.next;
while (insn != null)
{
if (insn instanceof Instruction_Ret
|| insn instanceof Instruction_Ret_w)
{
int retnum = ((Interface_OneIntArg)insn).getIntArg();
if (astorenum == retnum)
return insn;
}
else
/* adjust the jsr inlining order. */
if (insn instanceof Instruction_Jsr
|| insn instanceof Instruction_Jsr_w)
{
innerJsrs.add(insn);
}
insn = insn.next;
}
return null;
}
// make copies of jsr/ret blocks
// return new blocks
private HashMap inliningJsrTargets()
{
/*
for (int i=0, n=jsrorder.size(); i<n; i++) {
Instruction jsr = (Instruction)jsrorder.get(i);
Instruction astore = (Instruction)jsr2astore.get(jsr);
Instruction ret = (Instruction)astore2ret.get(astore);
G.v().out.println("jsr"+jsr.label+"\t"
+"as"+astore.label+"\t"
+"ret"+ret.label);
}
*/
HashMap newblocks = new HashMap();
while (!jsrorder.isEmpty())
{
Instruction jsr = (Instruction)jsrorder.removeFirst();
Instruction astore = (Instruction)jsr2astore.get(jsr);
Instruction ret = (Instruction)astore2ret.get(astore);
// make a copy of the code, append to the last instruction.
Instruction newhead = makeCopyOf(astore, ret, jsr.next);
// jsr is replaced by goto newhead
// astore has been removed
// ret is replaced by goto jsr.next
Instruction_Goto togo = new Instruction_Goto();
togo.target = newhead;
newhead.labelled = true;
togo.label = jsr.label;
togo.labelled = jsr.labelled;
togo.prev = jsr.prev;
togo.next = jsr.next;
togo.prev.next = togo;
togo.next.prev = togo;
replacedInsns.put(jsr, togo);
// just quick hack
if (ret != null) {
newblocks.put(newhead, this.lastInstruction);
}
}
return newblocks;
}
/* make a copy of code between from and to exclusively,
* fixup targets of branch instructions in the code.
*/
private Instruction makeCopyOf(Instruction astore,
Instruction ret,
Instruction target)
{
// do a quick hacker for ret == null
if (ret == null) {
return astore.next;
}
Instruction last = this.lastInstruction;
Instruction headbefore = last;
int curlabel = this.lastInstruction.label;
// mapping from original instructions to new instructions.
HashMap insnmap = new HashMap();
Instruction insn = astore.next;
while (insn != ret && insn != null)
{
try {
Instruction newone = (Instruction)insn.clone();
newone.label = ++curlabel;
newone.prev = last;
last.next = newone;
last = newone;
insnmap.put(insn, newone);
} catch (CloneNotSupportedException e)
{
G.v().out.println("Error !");
}
insn = insn.next;
}
// replace ret by a goto
Instruction_Goto togo = new Instruction_Goto();
togo.target = target;
target.labelled = true;
togo.label = ++curlabel;
last.next = togo;
togo.prev = last;
last = togo;
this.lastInstruction = last;
// The ret instruction is removed,
insnmap.put(astore, headbefore.next);
insnmap.put(ret, togo);
// fixup targets in new instruction (only in the scope of
// new instructions).
// do not forget set target labelled as TRUE
insn = headbefore.next;
while (insn != last)
{
if (insn instanceof Instruction_branch)
{
Instruction oldtgt = ((Instruction_branch)insn).target;
Instruction newtgt = (Instruction)insnmap.get(oldtgt);
if (newtgt != null)
{
((Instruction_branch)insn).target = newtgt;
newtgt.labelled = true;
}
}
else
if (insn instanceof Instruction_Lookupswitch)
{
Instruction_Lookupswitch switchinsn =
(Instruction_Lookupswitch)insn;
Instruction newdefault = (Instruction)insnmap.get(switchinsn.default_inst);
if (newdefault != null)
{
switchinsn.default_inst = newdefault;
newdefault.labelled = true;
}
for (int i=0; i<switchinsn.match_insts.length; i++)
{
Instruction newtgt = (Instruction)insnmap.get(switchinsn.match_insts[i]);
if (newtgt != null)
{
switchinsn.match_insts[i] = newtgt;
newtgt.labelled = true;
}
}
}
else
if (insn instanceof Instruction_Tableswitch)
{
Instruction_Tableswitch switchinsn =
(Instruction_Tableswitch)insn;
Instruction newdefault = (Instruction)insnmap.get(switchinsn.default_inst);
if (newdefault != null)
{
switchinsn.default_inst = newdefault;
newdefault.labelled = true;
}
for (int i=0; i<switchinsn.jump_insts.length; i++)
{
Instruction newtgt = (Instruction)insnmap.get(switchinsn.jump_insts[i]);
if (newtgt != null)
{
switchinsn.jump_insts[i] = newtgt;
newtgt.labelled = true;
}
}
}
insn = insn.next;
}
// do we need to copy a new exception table entry?
// new exception table has new exception range,
// and the new exception handler.
{
Code_attribute ca = method.locate_code_attribute();
LinkedList newentries = new LinkedList();
int orig_start_of_subr = astore.next.originalIndex; // inclusive
int orig_end_of_subr = ret.originalIndex; // again, inclusive
for (int i=0; i<ca.exception_table_length; i++)
{
exception_table_entry etentry =
ca.exception_table[i];
int orig_start_of_trap = etentry.start_pc; // inclusive
int orig_end_of_trap = etentry.end_pc; // exclusive
if ( orig_start_of_trap < orig_end_of_subr &&
orig_end_of_trap > orig_start_of_subr) {
// At least a portion of the cloned subroutine is trapped.
exception_table_entry newone =
new exception_table_entry();
if (orig_start_of_trap <= orig_start_of_subr) {
newone.start_inst = headbefore.next;
} else {
newone.start_inst = (Instruction)insnmap.get(etentry.start_inst);
}
if (orig_end_of_trap > orig_end_of_subr) {
newone.end_inst = null; // Representing the insn after
// the last instruction in the
// subr; we need to fix it if
// we inline another subr.
} else {
newone.end_inst = (Instruction)insnmap.get(etentry.end_inst);
}
newone.handler_inst = (Instruction)insnmap.get(etentry.handler_inst);
if (newone.handler_inst == null)
newone.handler_inst = etentry.handler_inst;
// We can leave newone.start_pc == 0 and newone.end_pc == 0.
// since that cannot overlap the range of any other
// subroutines that get inlined later.
newentries.add(newone);
}
// Finally, fix up the old entry if its protected area
// ran to the end of the method we have just lengthened:
// patch its end marker to be the first
// instruction in the subroutine we've just inlined.
if (etentry.end_inst == null) {
etentry.end_inst = headbefore.next;
}
}
if (newentries.size() > 0)
{
ca.exception_table_length += newentries.size();
exception_table_entry[] newtable = new exception_table_entry[ca.exception_table_length];
System.arraycopy(ca.exception_table, 0, newtable, 0, ca.exception_table.length);
for (int i=0, j=ca.exception_table.length; i<newentries.size(); i++, j++)
{
newtable[j] = (exception_table_entry)newentries.get(i);
}
ca.exception_table = newtable;
}
}
return headbefore.next;
}
private void pruneExceptionTable() {
HashSet invalidInsns = new HashSet();
Instruction insn = this.sentinel.next;
do {
if (insn instanceof Instruction_Jsr
|| insn instanceof Instruction_Jsr_w) {
Instruction astore = ((Instruction_branch)insn).target;
int astorenum = ((Interface_Astore)astore).getLocalNumber();
Instruction ret = astore.next;
do {
invalidInsns.add(ret);
if (ret instanceof Instruction_Ret
|| ret instanceof Instruction_Ret_w) {
int retnum = ((Interface_OneIntArg)ret).getIntArg();
if (astorenum == retnum) {
insn = ret;
break;
}
}
ret = ret.next;
} while (true);
}
insn = insn.next;
} while (insn != null);
Iterator it = invalidInsns.iterator();
while (it.hasNext()) {
G.v().out.println(it.next());
}
// pruning exception table
LinkedList validEntries = new LinkedList();
Code_attribute codeAttribute = method.locate_code_attribute();
for(int i = 0; i < codeAttribute.exception_table_length; i++)
{
exception_table_entry entry = codeAttribute.exception_table[i];
if (!invalidInsns.contains(entry.start_inst)) {
validEntries.add(entry);
}
}
if (validEntries.size() != codeAttribute.exception_table_length) {
exception_table_entry newtable[] =
new exception_table_entry[validEntries.size()];
for (int i=0; i<newtable.length; i++) {
newtable[i] =
(exception_table_entry)validEntries.get(i);
}
codeAttribute.exception_table = newtable;
codeAttribute.exception_table_length = newtable.length;
}
}
/* if a jsr/astore/ret is replaced by some other instruction, it will be put on this table. */
private Hashtable replacedInsns = new Hashtable();
private void dumpReplacedInsns()
{
G.v().out.println("replaced table:");
Set keys = replacedInsns.keySet();
Iterator keyIt = keys.iterator();
while (keyIt.hasNext())
{
Object key = keyIt.next();
Object value = replacedInsns.get(key);
G.v().out.println(key + " ==> "+ value);
}
}
/* do not forget set the target labelled as TRUE.*/
private void adjustBranchTargets()
{
Instruction insn = this.sentinel.next;
while (insn != null)
{
if (insn instanceof Instruction_branch)
{
Instruction_branch binsn = (Instruction_branch)insn;
Instruction newtgt = (Instruction)replacedInsns.get(binsn.target);
if (newtgt != null)
{
binsn.target = newtgt;
newtgt.labelled = true;
}
}
else
if (insn instanceof Instruction_Lookupswitch)
{
Instruction_Lookupswitch switchinsn =
(Instruction_Lookupswitch)insn;
Instruction newdefault =
(Instruction)replacedInsns.get(switchinsn.default_inst);
if (newdefault != null)
{
switchinsn.default_inst = newdefault;
newdefault.labelled = true;
}
for (int i=0; i<switchinsn.npairs; i++)
{
Instruction newtgt =
(Instruction)replacedInsns.get(switchinsn.match_insts[i]);
if (newtgt != null)
{
switchinsn.match_insts[i] = newtgt;
newtgt.labelled = true;
}
}
}
else
if (insn instanceof Instruction_Tableswitch)
{
Instruction_Tableswitch switchinsn =
(Instruction_Tableswitch)insn;
Instruction newdefault = (Instruction)replacedInsns.get(switchinsn.default_inst);
if (newdefault != null)
{
switchinsn.default_inst = newdefault;
newdefault.labelled = true;
}
for (int i=0; i<switchinsn.high-switchinsn.low; i++)
{
Instruction newtgt =
(Instruction)replacedInsns.get(switchinsn.jump_insts[i]);
if (newtgt != null)
{
switchinsn.jump_insts[i] = newtgt;
newtgt.labelled = true;
}
}
}
insn = insn.next;
}
}
private void adjustExceptionTable()
{
Code_attribute codeAttribute = method.locate_code_attribute();
for(int i = 0; i < codeAttribute.exception_table_length; i++)
{
exception_table_entry entry = codeAttribute.exception_table[i];
Instruction oldinsn = entry.start_inst;
Instruction newinsn = (Instruction)replacedInsns.get(oldinsn);
if (newinsn != null)
entry.start_inst = newinsn;
oldinsn = entry.end_inst;
if (entry.end_inst != null)
{
newinsn = (Instruction)replacedInsns.get(oldinsn);
if (newinsn != null)
entry.end_inst = newinsn;
}
oldinsn = entry.handler_inst;
newinsn = (Instruction)replacedInsns.get(oldinsn);
if (newinsn != null)
entry.handler_inst = newinsn;
}
}
private void adjustLineNumberTable()
{
if (!Options.v().keep_line_number())
return;
if (method.code_attr == null)
return;
attribute_info[] attributes = method.code_attr.attributes;
for (int i=0; i<attributes.length; i++)
{
if (attributes[i] instanceof LineNumberTable_attribute)
{
LineNumberTable_attribute lntattr =
(LineNumberTable_attribute)attributes[i];
for (int j=0; j<lntattr.line_number_table.length; j++)
{
Instruction oldinst =
lntattr.line_number_table[j].start_inst;
Instruction newinst =
(Instruction)replacedInsns.get(oldinst);
if (newinst != null)
lntattr.line_number_table[j].start_inst = newinst;
}
}
}
}
/** Reconstructs the instruction stream by appending the Instruction
* lists associated with each basic block.
* <p>
* Note that this joins up the basic block Instruction lists, and so
* they will no longer end with <i>null</i> after this.
* @return the head of the list of instructions.
*/
public Instruction reconstructInstructions()
{
if (cfg != null)
return cfg.head;
else
return null;
}
/** Main.v() entry point for converting list of Instructions to Jimple statements;
* performs flow analysis, constructs Jimple statements, and fixes jumps.
* @param constant_pool constant pool of ClassFile.
* @param this_class constant pool index of the CONSTANT_Class_info object for
* this' class.
* @return <i>true</i> if all ok, <i>false</i> if there was an error.
* @see Stmt
*/
public boolean jimplify(cp_info constant_pool[],int this_class, JimpleBody listBody)
{
Util.v().setClassNameToAbbreviation(new HashMap());
Chain units = listBody.getUnits();
this.listBody = listBody;
this.units = units;
instructionToFirstStmt = new HashMap();
instructionToLastStmt = new HashMap();
jmethod = listBody.getMethod();
cm = Scene.v();
//TypeArray.setClassManager(cm);
//TypeStack.setClassManager(cm);
Set initialLocals = new ArraySet();
List parameterTypes = jmethod.getParameterTypes();
// Initialize nameToLocal which is an index*Type->Local map, which is used
// to determine local in bytecode references.
{
Code_attribute ca = method.locate_code_attribute();
LocalVariableTable_attribute la = ca.findLocalVariableTable();
Util.v().activeVariableTable = la;
Util.v().activeConstantPool = constant_pool;
Type thisType = RefType.v(jmethod.getDeclaringClass().getName());
boolean isStatic = Modifier.isStatic(jmethod.getModifiers());
int currentLocalIndex = 0;
// Initialize the 'this' variable
{
if(!isStatic)
{
String name;
if(!Util.v().useFaithfulNaming || la == null)
name = "l0";
else
{
name = la.getLocalVariableName(constant_pool, currentLocalIndex);
if (!Util.v().isValidJimpleName(name))
name = "l0";
}
Local local = Jimple.v().newLocal(name, UnknownType.v());
listBody.getLocals().add(local);
currentLocalIndex++;
units.add(Jimple.v().newIdentityStmt(local, Jimple.v().newThisRef(jmethod.getDeclaringClass().getType())));
}
}
// Initialize parameters
{
Iterator typeIt = parameterTypes.iterator();
int argCount = 0;
while(typeIt.hasNext())
{
String name;
Type type = (Type) typeIt.next();
if(!Util.v().useFaithfulNaming || la == null)
name = "l" + currentLocalIndex;
else
{
name = la.getLocalVariableName(constant_pool, currentLocalIndex);
if (!Util.v().isValidJimpleName(name))
name = "l" + currentLocalIndex;
}
Local local = Jimple.v().newLocal(name, UnknownType.v());
initialLocals.add(local);
listBody.getLocals().add(local);
units.add(Jimple.v().newIdentityStmt(local, Jimple.v().newParameterRef(type, argCount)));
if(type.equals(DoubleType.v()) ||
type.equals(LongType.v()))
{
currentLocalIndex += 2;
}
else {
currentLocalIndex += 1;
}
argCount++;
}
}
Util.v().resetEasyNames();
}
jimplify(constant_pool,this_class);
return true;
}
private void buildInsnCFGfromBBCFG()
{
BasicBlock block = cfg;
while(block != null)
{
Instruction insn = block.head;
while (insn != block.tail)
{
Instruction[] succs = new Instruction[1];
succs[0] = insn.next;
insn.succs = succs;
insn = insn.next;
}
{
// The successors are the ones from the basic block.
Vector bsucc = block.succ;
int size = bsucc.size();
Instruction[] succs = new Instruction[size];
for(int i = 0; i<size; i++)
succs[i] = ((BasicBlock)bsucc.elementAt(i)).head;
insn.succs = succs;
}
block = block.next;
}
}
private void printInsnCFG()
{
Instruction insn = cfg.head;
while (insn != null)
{
G.v().out.println(insn + " --> " + makeString(insn.succs));
insn = insn.next;
}
}
private String makeString(Object[] objs)
{
String buf = "";
for (int i=0; i<objs.length; i++)
buf += " , "+objs[i];
return buf;
}
/** Main.v() entry point for converting list of Instructions to Jimple statements;
* performs flow analysis, constructs Jimple statements, and fixes jumps.
* @param constant_pool constant pool of ClassFile.
* @param this_class constant pool index of the CONSTANT_Class_info object for
* this' class.
* @param clearStacks if <i>true</i> semantic stacks will be deleted after
* the process is complete.
* @return <i>true</i> if all ok, <i>false</i> if there was an error.
* @see CFG#jimplify(cp_info[], int)
* @see Stmt
*/
void jimplify(cp_info constant_pool[],int this_class)
{
Code_attribute codeAttribute = method.locate_code_attribute();
Set handlerInstructions = new ArraySet();
Map handlerInstructionToException = new HashMap();
Map instructionToTypeStack;
Map instructionToPostTypeStack;
{
// build graph in
buildInsnCFGfromBBCFG();
// Put in successors due to exception handlers
{
for(int i = 0; i < codeAttribute.exception_table_length; i++)
{
Instruction startIns = codeAttribute.exception_table[i].start_inst;
Instruction endIns = codeAttribute.exception_table[i].end_inst;
Instruction handlerIns = codeAttribute.exception_table[i].handler_inst;
handlerInstructions.add(handlerIns);
// Determine exception to catch
{
int catchType = codeAttribute.exception_table[i].catch_type;
SootClass exception;
if(catchType != 0)
{
CONSTANT_Class_info classinfo = (CONSTANT_Class_info)
constant_pool[catchType];
String name = ((CONSTANT_Utf8_info) (constant_pool[classinfo.name_index])).
convert();
name = name.replace('/', '.');
exception = cm.getSootClass(name);
}
else
exception = cm.getSootClass("java.lang.Throwable");
handlerInstructionToException.put(handlerIns, exception);
}
if(startIns == endIns)
throw new RuntimeException("Empty catch range for exception handler");
Instruction ins = startIns;
for(;;)
{
Instruction[] succs = ins.succs;
Instruction[] newsuccs = new Instruction[succs.length+1];
System.arraycopy(succs, 0, newsuccs, 0, succs.length);
newsuccs[succs.length] = handlerIns;
ins.succs = newsuccs;
ins = ins.next;
if (ins == endIns || ins == null)
break;
}
}
}
}
Set reachableInstructions = new HashSet();
// Mark all the reachable instructions
{
LinkedList instructionsToVisit = new LinkedList();
reachableInstructions.add(firstInstruction);
instructionsToVisit.addLast(firstInstruction);
while( !instructionsToVisit.isEmpty())
{
Instruction ins = (Instruction) instructionsToVisit.removeFirst();
Instruction[] succs = ins.succs;
for (int i=0; i<succs.length; i++)
{
Instruction succ = succs[i];
if(!reachableInstructions.contains(succ))
{
reachableInstructions.add(succ);
instructionsToVisit.addLast(succ);
}
}
}
}
/*
// Check to see if any instruction is unmarked.
{
BasicBlock b = cfg;
while(b != null)
{
Instruction ins = b.head;
while(ins != null)
{
if(!reachableInstructions.contains(ins))
throw new RuntimeException("Method to jimplify contains unreachable code! (not handled for now)");
ins = ins.next;
}
b = b.next;
}
}
*/
// Perform the flow analysis, and build up instructionToTypeStack and instructionToLocalArray
{
instructionToTypeStack = new HashMap();
instructionToPostTypeStack = new HashMap();
Set visitedInstructions = new HashSet();
List changedInstructions = new ArrayList();
TypeStack initialTypeStack;
// Build up initial type stack and initial local array (for the first instruction)
{
initialTypeStack = TypeStack.v();
// the empty stack with nothing on it.
}
// Get the loop cranked up.
{
instructionToTypeStack.put(firstInstruction, initialTypeStack);
visitedInstructions.add(firstInstruction);
changedInstructions.add(firstInstruction);
}
{
while(!changedInstructions.isEmpty())
{
Instruction ins = (Instruction) changedInstructions.get(0);
changedInstructions.remove(0);
OutFlow ret = processFlow(ins, (TypeStack) instructionToTypeStack.get(ins),
constant_pool);
instructionToPostTypeStack.put(ins, ret.typeStack);
Instruction[] successors = ins.succs;
for(int i = 0; i < successors.length; i++)
{
Instruction s = successors[i];
if(!visitedInstructions.contains(s))
{
// Special case for the first time visiting.
if(handlerInstructions.contains(s))
{
TypeStack exceptionTypeStack = (TypeStack.v()).push(RefType.v(
((SootClass) handlerInstructionToException.get(s)).getName()));
instructionToTypeStack.put(s, exceptionTypeStack);
}
else {
instructionToTypeStack.put(s, ret.typeStack);
}
visitedInstructions.add(s);
changedInstructions.add(s);
// G.v().out.println("adding successor: " + s);
}
else {
// G.v().out.println("considering successor: " + s);
TypeStack newTypeStack,
oldTypeStack = (TypeStack) instructionToTypeStack.get(s);
if(handlerInstructions.contains(s))
{
// The type stack for an instruction handler should always be that of
// single object on the stack.
TypeStack exceptionTypeStack = (TypeStack.v()).push(RefType.v(
((SootClass) handlerInstructionToException.get(s)).getName()));
newTypeStack = exceptionTypeStack;
}
else
{
try {
newTypeStack = ret.typeStack.merge(oldTypeStack);
} catch (RuntimeException re)
{
G.v().out.println("Considering "+s);
throw re;
}
}
if(!newTypeStack.equals(oldTypeStack))
{
changedInstructions.add(s);
// G.v().out.println("requires a revisit: " + s);
}
instructionToTypeStack.put(s, newTypeStack);
}
}
}
}
}
// Print out instructions + their localArray + typeStack
{
Instruction ins = firstInstruction;
// G.v().out.println();
while(ins != null)
{
TypeStack typeStack = (TypeStack) instructionToTypeStack.get(ins);
// TypeArray typeArray = (TypeArray) instructionToLocalArray.get(ins);
/*
G.v().out.println("[TypeArray]");
typeArray.print(G.v().out);
G.v().out.println();
G.v().out.println("[TypeStack]");
typeStack.print(G.v().out);
G.v().out.println();
G.v().out.println(ins.toString());
*/
ins = ins.next;
/*
G.v().out.println();
G.v().out.println();
*/
}
}
// G.v().out.println("Producing Jimple code...");
// Jimplify each statement
{
BasicBlock b = cfg;
while(b != null)
{
Instruction ins = b.head;
b.statements = new ArrayList();
List blockStatements = b.statements;
for (;;)
{
List statementsForIns = new ArrayList();
if(reachableInstructions.contains(ins))
generateJimple(ins, (TypeStack) instructionToTypeStack.get(ins),
(TypeStack) instructionToPostTypeStack.get(ins), constant_pool,
statementsForIns, b);
else
statementsForIns.add(Jimple.v().newNopStmt());
if(!statementsForIns.isEmpty())
{
for(int i = 0; i < statementsForIns.size(); i++)
{
units.add(statementsForIns.get(i));
blockStatements.add(statementsForIns.get(i));
}
instructionToFirstStmt.put(ins, statementsForIns.get(0));
instructionToLastStmt.put(ins, statementsForIns.get(statementsForIns.size() - 1));
}
if (ins == b.tail)
break;
ins = ins.next;
}
b = b.next;
}
}
jimpleTargetFixup(); // fix up jump targets
/*
// Print out basic blocks
{
BasicBlock b = cfg;
G.v().out.println("Basic blocks for: " + jmethod.getName());
while(b != null)
{
Instruction ins = b.head;
G.v().out.println();
while(ins != null)
{
G.v().out.println(ins.toString());
ins = ins.next;
}
b = b.next;
}
}
*/
// Insert beginCatch/endCatch statements for exception handling
{
Map targetToHandler = new HashMap();
for(int i = 0; i < codeAttribute.exception_table_length; i++)
{
Instruction startIns =
codeAttribute.exception_table[i].start_inst;
Instruction endIns =
codeAttribute.exception_table[i].end_inst;
Instruction targetIns =
codeAttribute.exception_table[i].handler_inst;
if(!instructionToFirstStmt.containsKey(startIns) ||
(endIns != null && (!instructionToLastStmt.containsKey(endIns))))
{
throw new RuntimeException("Exception range does not coincide with jimple instructions");
}
if(!instructionToFirstStmt.containsKey(targetIns))
{
throw new RuntimeException
("Exception handler does not coincide with jimple instruction");
}
SootClass exception;
// Determine exception to catch
{
int catchType =
codeAttribute.exception_table[i].catch_type;
if(catchType != 0)
{
CONSTANT_Class_info classinfo = (CONSTANT_Class_info)
constant_pool[catchType];
String name = ((CONSTANT_Utf8_info)
(constant_pool[classinfo.name_index])).convert();
name = name.replace('/', '.');
exception = cm.getSootClass(name);
}
else
exception = cm.getSootClass("java.lang.Throwable");
}
Stmt newTarget;
// Insert assignment of exception
{
Stmt firstTargetStmt =
(Stmt) instructionToFirstStmt.get(targetIns);
if(targetToHandler.containsKey(firstTargetStmt))
newTarget =
(Stmt) targetToHandler.get(firstTargetStmt);
else
{
Local local =
Util.v().getLocalCreatingIfNecessary(listBody, "$stack0",UnknownType.v());
newTarget = Jimple.v().newIdentityStmt(local, Jimple.v().newCaughtExceptionRef());
units.insertBefore(newTarget, firstTargetStmt);
instructionToFirstStmt.put(targetIns, newTarget);
targetToHandler.put(firstTargetStmt, newTarget);
}
}
// Insert trap
{
Stmt firstStmt = (Stmt)instructionToFirstStmt.get(startIns);
Stmt afterEndStmt;
if (endIns == null) {
// A kludge which isn't really correct, but
// gets us closer to correctness (until we
// clean up the rest of Soot to properly
// represent Traps which extend to the end
// of a method): if the protected code extends
// to the end of the method, use the last Stmt
// as the endUnit of the Trap, even though
// that will leave the last unit outside
// the protected area.
afterEndStmt = (Stmt) units.getLast();
} else {
afterEndStmt = (Stmt) instructionToLastStmt.get(endIns);
IdentityStmt catchStart =
(IdentityStmt) targetToHandler.get(afterEndStmt);
// (Cast to IdentityStmt as an assertion check.)
if (catchStart != null) {
// The protected region extends to the beginning of an
// exception handler, so we need to reset afterEndStmt
// to the identity statement which we have inserted
// before the old afterEndStmt.
if (catchStart != units.getPredOf(afterEndStmt)) {
throw new IllegalStateException("Assertion failure: catchStart != pred of afterEndStmt");
}
afterEndStmt = catchStart;
}
}
Trap trap = Jimple.v().newTrap(exception,
firstStmt,
afterEndStmt,
newTarget);
listBody.getTraps().add(trap);
}
}
}
/* convert line number table to tags attached to statements */
if (Options.v().keep_line_number())
{
HashMap stmtstags = new HashMap();
LinkedList startstmts = new LinkedList();
attribute_info[] attrs = codeAttribute.attributes;
for (int i=0; i<attrs.length; i++)
{
if (attrs[i] instanceof LineNumberTable_attribute)
{
LineNumberTable_attribute lntattr =
(LineNumberTable_attribute)attrs[i];
for (int j=0; j<lntattr.line_number_table.length; j++)
{
Stmt start_stmt = (Stmt)instructionToFirstStmt.get(
lntattr.line_number_table[j].start_inst);
if (start_stmt != null)
{
LineNumberTag lntag= new LineNumberTag(
lntattr.line_number_table[j].line_number);
stmtstags.put(start_stmt, lntag);
startstmts.add(start_stmt);
}
}
}
}
/* attach line number tag to each statement. */
for (int i=0; i<startstmts.size(); i++)
{
Stmt stmt = (Stmt)startstmts.get(i);
Tag tag = (Tag)stmtstags.get(stmt);
stmt.addTag(tag);
stmt = (Stmt)units.getSuccOf(stmt);
while (stmt != null
&& !stmtstags.containsKey(stmt))
{
stmt.addTag(tag);
stmt = (Stmt)units.getSuccOf(stmt);
}
}
}
}
private Type byteCodeTypeOf(Type type)
{
if(type.equals(ShortType.v()) ||
type.equals(CharType.v()) ||
type.equals(ByteType.v()) ||
type.equals(BooleanType.v()))
{
return IntType.v();
}
else
return type;
}
OutFlow processFlow(Instruction ins, TypeStack typeStack,
cp_info[] constant_pool)
{
int x;
x = ((int)(ins.code))&0xff;
switch(x)
{
case ByteCode.BIPUSH:
typeStack = typeStack.push(IntType.v());
break;
case ByteCode.SIPUSH:
typeStack = typeStack.push(IntType.v());
break;
case ByteCode.LDC1:
return processCPEntry(constant_pool,
((Instruction_Ldc1)ins).arg_b, typeStack, jmethod);
case ByteCode.LDC2:
case ByteCode.LDC2W:
return processCPEntry(constant_pool,
((Instruction_intindex)ins).arg_i, typeStack, jmethod);
case ByteCode.ACONST_NULL:
typeStack = typeStack.push(RefType.v("java.lang.Object"));
break;
case ByteCode.ICONST_M1:
case ByteCode.ICONST_0:
case ByteCode.ICONST_1:
case ByteCode.ICONST_2:
case ByteCode.ICONST_3:
case ByteCode.ICONST_4:
case ByteCode.ICONST_5:
typeStack = typeStack.push(IntType.v());
break;
case ByteCode.LCONST_0:
case ByteCode.LCONST_1:
typeStack = typeStack.push(LongType.v());
typeStack = typeStack.push(Long2ndHalfType.v());
break;
case ByteCode.FCONST_0:
case ByteCode.FCONST_1:
case ByteCode.FCONST_2:
typeStack = typeStack.push(FloatType.v());
break;
case ByteCode.DCONST_0:
case ByteCode.DCONST_1:
typeStack = typeStack.push(DoubleType.v());
typeStack = typeStack.push(Double2ndHalfType.v());
break;
case ByteCode.ILOAD:
typeStack = typeStack.push(IntType.v());
break;
case ByteCode.FLOAD:
typeStack = typeStack.push(FloatType.v());
break;
case ByteCode.ALOAD:
typeStack = typeStack.push(RefType.v("java.lang.Object"));
// this is highly imprecise
break;
case ByteCode.DLOAD:
typeStack = typeStack.push(DoubleType.v());
typeStack = typeStack.push(Double2ndHalfType.v());
break;
case ByteCode.LLOAD:
typeStack = typeStack.push(LongType.v());
typeStack = typeStack.push(Long2ndHalfType.v());
break;
case ByteCode.ILOAD_0:
case ByteCode.ILOAD_1:
case ByteCode.ILOAD_2:
case ByteCode.ILOAD_3:
typeStack = typeStack.push(IntType.v());
break;
case ByteCode.FLOAD_0:
case ByteCode.FLOAD_1:
case ByteCode.FLOAD_2:
case ByteCode.FLOAD_3:
typeStack = typeStack.push(FloatType.v());
break;
case ByteCode.ALOAD_0:
case ByteCode.ALOAD_1:
case ByteCode.ALOAD_2:
case ByteCode.ALOAD_3:
typeStack = typeStack.push(RefType.v("java.lang.Object"));
// this is highly imprecise
break;
case ByteCode.LLOAD_0:
case ByteCode.LLOAD_1:
case ByteCode.LLOAD_2:
case ByteCode.LLOAD_3:
typeStack = typeStack.push(LongType.v());
typeStack = typeStack.push(Long2ndHalfType.v());
break;
case ByteCode.DLOAD_0:
case ByteCode.DLOAD_1:
case ByteCode.DLOAD_2:
case ByteCode.DLOAD_3:
typeStack = typeStack.push(DoubleType.v());
typeStack = typeStack.push(Double2ndHalfType.v());
break;
case ByteCode.ISTORE:
typeStack = popSafe(typeStack, IntType.v());
break;
case ByteCode.FSTORE:
typeStack = popSafe(typeStack, FloatType.v());
break;
case ByteCode.ASTORE:
typeStack = typeStack.pop();
break;
case ByteCode.LSTORE:
typeStack = popSafe(typeStack, Long2ndHalfType.v());
typeStack = popSafe(typeStack, LongType.v());
break;
case ByteCode.DSTORE:
typeStack = popSafe(typeStack, Double2ndHalfType.v());
typeStack = popSafe(typeStack, DoubleType.v());
break;
case ByteCode.ISTORE_0:
case ByteCode.ISTORE_1:
case ByteCode.ISTORE_2:
case ByteCode.ISTORE_3:
typeStack = popSafe(typeStack, IntType.v());
break;
case ByteCode.FSTORE_0:
case ByteCode.FSTORE_1:
case ByteCode.FSTORE_2:
case ByteCode.FSTORE_3:
typeStack = popSafe(typeStack, FloatType.v());
break;
case ByteCode.ASTORE_0:
case ByteCode.ASTORE_1:
case ByteCode.ASTORE_2:
case ByteCode.ASTORE_3:
if(!(typeStack.top() instanceof StmtAddressType) &&
!(typeStack.top() instanceof RefType) &&
!(typeStack.top() instanceof ArrayType))
{
throw new RuntimeException("Astore failed, invalid stack type: " + typeStack.top());
}
typeStack = typeStack.pop();
break;
case ByteCode.LSTORE_0:
case ByteCode.LSTORE_1:
case ByteCode.LSTORE_2:
case ByteCode.LSTORE_3:
typeStack = popSafe(typeStack, Long2ndHalfType.v());
typeStack = popSafe(typeStack, LongType.v());
break;
case ByteCode.DSTORE_0:
case ByteCode.DSTORE_1:
case ByteCode.DSTORE_2:
case ByteCode.DSTORE_3:
typeStack = popSafe(typeStack, Double2ndHalfType.v());
typeStack = popSafe(typeStack, DoubleType.v());
break;
case ByteCode.IINC:
break;
case ByteCode.WIDE:
throw new RuntimeException("Wide instruction should not be encountered");
// break;
case ByteCode.NEWARRAY:
{
typeStack = popSafe(typeStack, IntType.v());
Type baseType = (Type) jimpleTypeOfAtype(((Instruction_Newarray)ins).atype);
typeStack = typeStack.push(ArrayType.v(baseType, 1));
break;
}
case ByteCode.ANEWARRAY:
{
CONSTANT_Class_info c = (CONSTANT_Class_info) constant_pool[
((Instruction_Anewarray)ins).arg_i];
String name = ((CONSTANT_Utf8_info) (constant_pool[c.name_index])).convert();
name = name.replace('/', '.');
typeStack = popSafe(typeStack, IntType.v());
typeStack = typeStack.push(ArrayType.v(
RefType.v(name), 1));
break;
}
case ByteCode.MULTIANEWARRAY:
{
int bdims = (int)(((Instruction_Multianewarray)ins).dims);
CONSTANT_Class_info c = (CONSTANT_Class_info) constant_pool[
((Instruction_Multianewarray)ins).arg_i];
String arrayDescriptor = ((CONSTANT_Utf8_info) (constant_pool[c.name_index])).convert();
ArrayType arrayType = (ArrayType)
Util.v().jimpleTypeOfFieldDescriptor(arrayDescriptor);
for (int j=0;j<bdims;j++)
typeStack = popSafe(typeStack, IntType.v());
typeStack = typeStack.push(arrayType);
break;
}
case ByteCode.ARRAYLENGTH:
typeStack = popSafeRefType(typeStack);
typeStack = typeStack.push(IntType.v());
break;
case ByteCode.IALOAD:
case ByteCode.BALOAD:
case ByteCode.CALOAD:
case ByteCode.SALOAD:
typeStack = popSafe(typeStack, IntType.v());
typeStack = popSafeRefType(typeStack);
typeStack = typeStack.push(IntType.v());
break;
case ByteCode.FALOAD:
typeStack = popSafe(typeStack, FloatType.v());
typeStack = popSafeRefType(typeStack);
typeStack = typeStack.push(FloatType.v());
break;
case ByteCode.AALOAD:
{
typeStack = popSafe(typeStack, IntType.v());
if(typeStack.top() instanceof ArrayType)
{
ArrayType arrayType = (ArrayType) typeStack.top();
typeStack = popSafeRefType(typeStack);
if(arrayType.numDimensions == 1)
typeStack = typeStack.push(arrayType.baseType);
else
typeStack = typeStack.push(ArrayType.v(arrayType.baseType, arrayType.numDimensions - 1));
}
else {
// it's a null object
typeStack = popSafeRefType(typeStack);
typeStack = typeStack.push(RefType.v("java.lang.Object"));
}
break;
}
case ByteCode.LALOAD:
typeStack = popSafe(typeStack, IntType.v());
typeStack = popSafeRefType(typeStack);
typeStack = typeStack.push(LongType.v());
typeStack = typeStack.push(Long2ndHalfType.v());
break;
case ByteCode.DALOAD:
typeStack = popSafe(typeStack, IntType.v());
typeStack = popSafeRefType(typeStack);
typeStack = typeStack.push(DoubleType.v());
typeStack = typeStack.push(Double2ndHalfType.v());
break;
case ByteCode.IASTORE:
case ByteCode.BASTORE:
case ByteCode.CASTORE:
case ByteCode.SASTORE:
typeStack = popSafe(typeStack, IntType.v());
typeStack = popSafe(typeStack, IntType.v());
typeStack = popSafeRefType(typeStack);
break;
case ByteCode.AASTORE:
typeStack = popSafeRefType(typeStack);
typeStack = popSafe(typeStack, IntType.v());
typeStack = popSafeRefType(typeStack);
break;
case ByteCode.FASTORE:
typeStack = popSafe(typeStack, FloatType.v());
typeStack = popSafe(typeStack, IntType.v());
typeStack = popSafeRefType(typeStack);
break;
case ByteCode.LASTORE:
typeStack = popSafe(typeStack, Long2ndHalfType.v());
typeStack = popSafe(typeStack, LongType.v());
typeStack = popSafe(typeStack, IntType.v());
typeStack = popSafeRefType(typeStack);
break;
case ByteCode.DASTORE:
typeStack = popSafe(typeStack, Double2ndHalfType.v());
typeStack = popSafe(typeStack, DoubleType.v());
typeStack = popSafe(typeStack, IntType.v());
typeStack = popSafeRefType(typeStack);
break;
case ByteCode.NOP:
break;
case ByteCode.POP:
typeStack = typeStack.pop();
break;
case ByteCode.POP2:
typeStack = typeStack.pop();
typeStack = typeStack.pop();
break;
case ByteCode.DUP:
typeStack = typeStack.push(typeStack.top());
break;
case ByteCode.DUP2:
{
Type topType = typeStack.get(typeStack.topIndex()),
secondType = typeStack.get(typeStack.topIndex()-1);
typeStack = (typeStack.push(secondType)).push(topType);
break;
}
case ByteCode.DUP_X1:
{
Type topType = typeStack.get(typeStack.topIndex()),
secondType = typeStack.get(typeStack.topIndex()-1);
typeStack = typeStack.pop().pop();
typeStack = typeStack.push(topType).push(secondType).push(topType);
break;
}
case ByteCode.DUP_X2:
{
Type topType = typeStack.get(typeStack.topIndex()),
secondType = typeStack.get(typeStack.topIndex()-1),
thirdType = typeStack.get(typeStack.topIndex()-2);
typeStack = typeStack.pop().pop().pop();
typeStack = typeStack.push(topType).push(thirdType).push(secondType).push(topType);
break;
}
case ByteCode.DUP2_X1:
{
Type topType = typeStack.get(typeStack.topIndex()),
secondType = typeStack.get(typeStack.topIndex()-1),
thirdType = typeStack.get(typeStack.topIndex()-2);
typeStack = typeStack.pop().pop().pop();
typeStack = typeStack.push(secondType).push(topType).
push(thirdType).push(secondType).push(topType);
break;
}
case ByteCode.DUP2_X2:
{
Type topType = typeStack.get(typeStack.topIndex()),
secondType = typeStack.get(typeStack.topIndex()-1),
thirdType = typeStack.get(typeStack.topIndex()-2),
fourthType = typeStack.get(typeStack.topIndex()-3);
typeStack = typeStack.pop().pop().pop().pop();
typeStack = typeStack.push(secondType).push(topType).
push(fourthType).push(thirdType).push(secondType).push(topType);
break;
}
case ByteCode.SWAP:
{
Type topType = typeStack.top();
typeStack = typeStack.pop();
Type secondType = typeStack.top();
typeStack = typeStack.pop();
typeStack = typeStack.push(topType);
typeStack = typeStack.push(secondType);
break;
}
case ByteCode.IADD:
case ByteCode.ISUB:
case ByteCode.IMUL:
case ByteCode.IDIV:
case ByteCode.IREM:
case ByteCode.ISHL:
case ByteCode.ISHR:
case ByteCode.IUSHR:
case ByteCode.IAND:
case ByteCode.IOR:
case ByteCode.IXOR:
typeStack = popSafe(typeStack, IntType.v());
typeStack = popSafe(typeStack, IntType.v());
typeStack = typeStack.push(IntType.v());
break;
case ByteCode.LUSHR:
case ByteCode.LSHR:
case ByteCode.LSHL:
typeStack = popSafe(typeStack, IntType.v());
typeStack = popSafe(typeStack, Long2ndHalfType.v());
typeStack = popSafe(typeStack, LongType.v());
typeStack = typeStack.push(LongType.v());
typeStack = typeStack.push(Long2ndHalfType.v());
break;
case ByteCode.LREM:
case ByteCode.LDIV:
case ByteCode.LMUL:
case ByteCode.LSUB:
case ByteCode.LADD:
case ByteCode.LAND:
case ByteCode.LOR:
case ByteCode.LXOR:
typeStack = popSafe(typeStack, Long2ndHalfType.v());
typeStack = popSafe(typeStack, LongType.v());
typeStack = popSafe(typeStack, Long2ndHalfType.v());
typeStack = popSafe(typeStack, LongType.v());
typeStack = typeStack.push(LongType.v());
typeStack = typeStack.push(Long2ndHalfType.v());
break;
case ByteCode.FREM:
case ByteCode.FDIV:
case ByteCode.FMUL:
case ByteCode.FSUB:
case ByteCode.FADD:
typeStack = popSafe(typeStack, FloatType.v());
typeStack = popSafe(typeStack, FloatType.v());
typeStack = typeStack.push(FloatType.v());
break;
case ByteCode.DREM:
case ByteCode.DDIV:
case ByteCode.DMUL:
case ByteCode.DSUB:
case ByteCode.DADD:
typeStack = popSafe(typeStack, Double2ndHalfType.v());
typeStack = popSafe(typeStack, DoubleType.v());
typeStack = popSafe(typeStack, Double2ndHalfType.v());
typeStack = popSafe(typeStack, DoubleType.v());
typeStack = typeStack.push(DoubleType.v());
typeStack = typeStack.push(Double2ndHalfType.v());
break;
case ByteCode.INEG:
case ByteCode.LNEG:
case ByteCode.FNEG:
case ByteCode.DNEG:
// Doesn't check to see if the required types are on the stack, but it should
// if it wanted to be safe.
break;
case ByteCode.I2L:
typeStack = popSafe(typeStack, IntType.v());
typeStack = typeStack.push(LongType.v());
typeStack = typeStack.push(Long2ndHalfType.v());
break;
case ByteCode.I2F:
typeStack = popSafe(typeStack, IntType.v());
typeStack = typeStack.push(FloatType.v());
break;
case ByteCode.I2D:
typeStack = popSafe(typeStack, IntType.v());
typeStack = typeStack.push(DoubleType.v());
typeStack = typeStack.push(Double2ndHalfType.v());
break;
case ByteCode.L2I:
typeStack = popSafe(typeStack, Long2ndHalfType.v());
typeStack = popSafe(typeStack, LongType.v());
typeStack = typeStack.push(IntType.v());
break;
case ByteCode.L2F:
typeStack = popSafe(typeStack, Long2ndHalfType.v());
typeStack = popSafe(typeStack, LongType.v());
typeStack = typeStack.push(FloatType.v());
break;
case ByteCode.L2D:
typeStack = popSafe(typeStack, Long2ndHalfType.v());
typeStack = popSafe(typeStack, LongType.v());
typeStack = typeStack.push(DoubleType.v());
typeStack = typeStack.push(Double2ndHalfType.v());
break;
case ByteCode.F2I:
typeStack = popSafe(typeStack, FloatType.v());
typeStack = typeStack.push(IntType.v());
break;
case ByteCode.F2L:
typeStack = popSafe(typeStack, FloatType.v());
typeStack = typeStack.push(LongType.v());
typeStack = typeStack.push(Long2ndHalfType.v());
break;
case ByteCode.F2D:
typeStack = popSafe(typeStack, FloatType.v());
typeStack = typeStack.push(DoubleType.v());
typeStack = typeStack.push(Double2ndHalfType.v());
break;
case ByteCode.D2I:
typeStack = popSafe(typeStack, Double2ndHalfType.v());
typeStack = popSafe(typeStack, DoubleType.v());
typeStack = typeStack.push(IntType.v());
break;
case ByteCode.D2L:
typeStack = popSafe(typeStack, Double2ndHalfType.v());
typeStack = popSafe(typeStack, DoubleType.v());
typeStack = typeStack.push(LongType.v());
typeStack = typeStack.push(Long2ndHalfType.v());
break;
case ByteCode.D2F:
typeStack = popSafe(typeStack, Double2ndHalfType.v());
typeStack = popSafe(typeStack, DoubleType.v());
typeStack = typeStack.push(FloatType.v());
break;
case ByteCode.INT2BYTE:
break;
case ByteCode.INT2CHAR:
break;
case ByteCode.INT2SHORT:
break;
case ByteCode.IFEQ:
case ByteCode.IFGT:
case ByteCode.IFLT:
case ByteCode.IFLE:
case ByteCode.IFNE:
case ByteCode.IFGE:
typeStack = popSafe(typeStack, IntType.v());
break;
case ByteCode.IFNULL:
case ByteCode.IFNONNULL:
typeStack = popSafeRefType(typeStack);
break;
case ByteCode.IF_ICMPEQ:
case ByteCode.IF_ICMPLT:
case ByteCode.IF_ICMPLE:
case ByteCode.IF_ICMPNE:
case ByteCode.IF_ICMPGT:
case ByteCode.IF_ICMPGE:
typeStack = popSafe(typeStack, IntType.v());
typeStack = popSafe(typeStack, IntType.v());
break;
case ByteCode.LCMP:
typeStack = popSafe(typeStack, Long2ndHalfType.v());
typeStack = popSafe(typeStack, LongType.v());
typeStack = popSafe(typeStack, Long2ndHalfType.v());
typeStack = popSafe(typeStack, LongType.v());
typeStack = typeStack.push(IntType.v());
break;
case ByteCode.FCMPL:
case ByteCode.FCMPG:
typeStack = popSafe(typeStack, FloatType.v());
typeStack = popSafe(typeStack, FloatType.v());
typeStack = typeStack.push(IntType.v());
break;
case ByteCode.DCMPL:
case ByteCode.DCMPG:
typeStack = popSafe(typeStack, Double2ndHalfType.v());
typeStack = popSafe(typeStack, DoubleType.v());
typeStack = popSafe(typeStack, Double2ndHalfType.v());
typeStack = popSafe(typeStack, DoubleType.v());
typeStack = typeStack.push(IntType.v());
break;
case ByteCode.IF_ACMPEQ:
case ByteCode.IF_ACMPNE:
typeStack = popSafeRefType(typeStack);
typeStack = popSafeRefType(typeStack);
break;
case ByteCode.GOTO:
case ByteCode.GOTO_W:
break;
case ByteCode.JSR:
case ByteCode.JSR_W:
typeStack = typeStack.push(StmtAddressType.v());
break;
case ByteCode.RET:
break;
case ByteCode.RET_W:
break;
case ByteCode.RETURN:
break;
case ByteCode.IRETURN:
typeStack = popSafe(typeStack, IntType.v());
break;
case ByteCode.FRETURN:
typeStack = popSafe(typeStack, FloatType.v());
break;
case ByteCode.ARETURN:
typeStack = popSafeRefType(typeStack);
break;
case ByteCode.DRETURN:
typeStack = popSafe(typeStack, Double2ndHalfType.v());
typeStack = popSafe(typeStack, DoubleType.v());
break;
case ByteCode.LRETURN:
typeStack = popSafe(typeStack, Long2ndHalfType.v());
typeStack = popSafe(typeStack, LongType.v());
break;
case ByteCode.BREAKPOINT:
break;
case ByteCode.TABLESWITCH:
typeStack = popSafe(typeStack, IntType.v());
break;
case ByteCode.LOOKUPSWITCH:
typeStack = popSafe(typeStack, IntType.v());
break;
case ByteCode.PUTFIELD:
{
Type type = byteCodeTypeOf(jimpleTypeOfFieldInFieldRef(cm, constant_pool,
((Instruction_Putfield)ins).arg_i));
if(type.equals(DoubleType.v()))
{
typeStack = popSafe(typeStack, Double2ndHalfType.v());
typeStack = popSafe(typeStack, DoubleType.v());
}
else if(type.equals(LongType.v()))
{
typeStack = popSafe(typeStack, Long2ndHalfType.v());
typeStack = popSafe(typeStack, LongType.v());
}
else if(type instanceof RefType)
typeStack = popSafeRefType(typeStack);
else
typeStack = popSafe(typeStack, type);
typeStack = popSafeRefType(typeStack);
break;
}
case ByteCode.GETFIELD:
{
Type type = byteCodeTypeOf(jimpleTypeOfFieldInFieldRef(cm, constant_pool,
((Instruction_Getfield)ins).arg_i));
typeStack = popSafeRefType(typeStack);
if (type.equals(DoubleType.v()))
{
typeStack = typeStack.push(DoubleType.v());
typeStack = typeStack.push(Double2ndHalfType.v());
}
else if(type.equals(LongType.v()))
{
typeStack = typeStack.push(LongType.v());
typeStack = typeStack.push(Long2ndHalfType.v());
}
else
typeStack = typeStack.push(type);
break;
}
case ByteCode.PUTSTATIC:
{
Type type = byteCodeTypeOf(jimpleTypeOfFieldInFieldRef(cm, constant_pool,
((Instruction_Putstatic)ins).arg_i));
if(type.equals(DoubleType.v()))
{
typeStack = popSafe(typeStack, Double2ndHalfType.v());
typeStack = popSafe(typeStack, DoubleType.v());
}
else if(type.equals(LongType.v()))
{
typeStack = popSafe(typeStack, Long2ndHalfType.v());
typeStack = popSafe(typeStack, LongType.v());
}
else if(type instanceof RefType)
typeStack = popSafeRefType(typeStack);
else
typeStack = popSafe(typeStack, type);
break;
}
case ByteCode.GETSTATIC:
{
Type type = byteCodeTypeOf(jimpleTypeOfFieldInFieldRef(cm, constant_pool,
((Instruction_Getstatic)ins).arg_i));
if (type.equals(DoubleType.v()))
{
typeStack = typeStack.push(DoubleType.v());
typeStack = typeStack.push(Double2ndHalfType.v());
}
else if(type.equals(LongType.v()))
{
typeStack = typeStack.push(LongType.v());
typeStack = typeStack.push(Long2ndHalfType.v());
}
else
typeStack = typeStack.push(type);
break;
}
case ByteCode.INVOKEVIRTUAL:
{
Instruction_Invokevirtual iv = (Instruction_Invokevirtual)ins;
int args = cp_info.countParams(constant_pool,iv.arg_i);
Type returnType = byteCodeTypeOf(jimpleReturnTypeOfMethodRef(cm,
constant_pool, iv.arg_i));
// pop off parameters.
for (int j=args-1;j>=0;j
{
if(typeStack.top().equals(Long2ndHalfType.v()))
{
typeStack = popSafe(typeStack, Long2ndHalfType.v());
typeStack = popSafe(typeStack, LongType.v());
}
else if(typeStack.top().equals(Double2ndHalfType.v()))
{
typeStack = popSafe(typeStack, Double2ndHalfType.v());
typeStack = popSafe(typeStack, DoubleType.v());
}
else
typeStack = popSafe(typeStack, typeStack.top());
}
typeStack = popSafeRefType(typeStack);
if(!returnType.equals(VoidType.v()))
typeStack = smartPush(typeStack, returnType);
break;
}
case ByteCode.INVOKENONVIRTUAL:
{
Instruction_Invokenonvirtual iv = (Instruction_Invokenonvirtual)ins;
int args = cp_info.countParams(constant_pool,iv.arg_i);
Type returnType = byteCodeTypeOf(jimpleReturnTypeOfMethodRef(cm,
constant_pool, iv.arg_i));
// pop off parameters.
for (int j=args-1;j>=0;j
{
if(typeStack.top().equals(Long2ndHalfType.v()))
{
typeStack = popSafe(typeStack, Long2ndHalfType.v());
typeStack = popSafe(typeStack, LongType.v());
}
else if(typeStack.top().equals(Double2ndHalfType.v()))
{
typeStack = popSafe(typeStack, Double2ndHalfType.v());
typeStack = popSafe(typeStack, DoubleType.v());
}
else
typeStack = popSafe(typeStack, typeStack.top());
}
typeStack = popSafeRefType(typeStack);
if(!returnType.equals(VoidType.v()))
typeStack = smartPush(typeStack, returnType);
break;
}
case ByteCode.INVOKESTATIC:
{
Instruction_Invokestatic iv = (Instruction_Invokestatic)ins;
int args = cp_info.countParams(constant_pool,iv.arg_i);
Type returnType = byteCodeTypeOf(jimpleReturnTypeOfMethodRef(cm,
constant_pool, iv.arg_i));
// pop off parameters.
for (int j=args-1;j>=0;j
{
if(typeStack.top().equals(Long2ndHalfType.v()))
{
typeStack = popSafe(typeStack, Long2ndHalfType.v());
typeStack = popSafe(typeStack, LongType.v());
}
else if(typeStack.top().equals(Double2ndHalfType.v()))
{
typeStack = popSafe(typeStack, Double2ndHalfType.v());
typeStack = popSafe(typeStack, DoubleType.v());
}
else
typeStack = popSafe(typeStack, typeStack.top());
}
if(!returnType.equals(VoidType.v()))
typeStack = smartPush(typeStack, returnType);
break;
}
case ByteCode.INVOKEINTERFACE:
{
Instruction_Invokeinterface iv = (Instruction_Invokeinterface) ins;
int args = cp_info.countParams(constant_pool,iv.arg_i);
Type returnType = byteCodeTypeOf(jimpleReturnTypeOfInterfaceMethodRef(cm,
constant_pool, iv.arg_i));
// pop off parameters.
for (int j=args-1;j>=0;j
{
if(typeStack.top().equals(Long2ndHalfType.v()))
{
typeStack = popSafe(typeStack, Long2ndHalfType.v());
typeStack = popSafe(typeStack, LongType.v());
}
else if(typeStack.top().equals(Double2ndHalfType.v()))
{
typeStack = popSafe(typeStack, Double2ndHalfType.v());
typeStack = popSafe(typeStack, DoubleType.v());
}
else
typeStack = popSafe(typeStack, typeStack.top());
}
typeStack = popSafeRefType(typeStack);
if(!returnType.equals(VoidType.v()))
typeStack = smartPush(typeStack, returnType);
break;
}
case ByteCode.ATHROW:
// technically athrow leaves the stack in an undefined
// state. In fact, the top value is the one we actually
// throw, but it should stay on the stack since the exception
// handler expects to start that way, at least in the real JVM.
break;
case ByteCode.NEW:
{
Type type = RefType.v(getClassName(constant_pool, ((Instruction_New)ins).arg_i));
typeStack = typeStack.push(type);
break;
}
case ByteCode.CHECKCAST:
{
String className = getClassName(constant_pool, ((Instruction_Checkcast)ins).arg_i);
Type castType;
if(className.startsWith("["))
castType = Util.v().jimpleTypeOfFieldDescriptor(getClassName(constant_pool,
((Instruction_Checkcast)ins).arg_i));
else
castType = RefType.v(className);
typeStack = popSafeRefType(typeStack);
typeStack = typeStack.push(castType);
break;
}
case ByteCode.INSTANCEOF:
{
typeStack = popSafeRefType(typeStack);
typeStack = typeStack.push(IntType.v());
break;
}
case ByteCode.MONITORENTER:
typeStack = popSafeRefType(typeStack);
break;
case ByteCode.MONITOREXIT:
typeStack = popSafeRefType(typeStack);
break;
default:
throw new RuntimeException("processFlow failed: Unknown bytecode instruction: " + x);
}
return new OutFlow(typeStack);
}
private Type jimpleTypeOfFieldInFieldRef(Scene cm,
cp_info[] constant_pool, int index)
{
CONSTANT_Fieldref_info fr = (CONSTANT_Fieldref_info)
(constant_pool[index]);
CONSTANT_NameAndType_info nat = (CONSTANT_NameAndType_info)
(constant_pool[fr.name_and_type_index]);
String fieldDescriptor = ((CONSTANT_Utf8_info)
(constant_pool[nat.descriptor_index])).convert();
return Util.v().jimpleTypeOfFieldDescriptor(fieldDescriptor);
}
private Type jimpleReturnTypeOfMethodRef(Scene cm,
cp_info[] constant_pool, int index)
{
CONSTANT_Methodref_info mr = (CONSTANT_Methodref_info)
(constant_pool[index]);
CONSTANT_NameAndType_info nat = (CONSTANT_NameAndType_info)
(constant_pool[mr.name_and_type_index]);
String methodDescriptor = ((CONSTANT_Utf8_info)
(constant_pool[nat.descriptor_index])).convert();
return Util.v().jimpleReturnTypeOfMethodDescriptor(methodDescriptor);
}
private Type jimpleReturnTypeOfInterfaceMethodRef(Scene cm,
cp_info[] constant_pool, int index)
{
CONSTANT_InterfaceMethodref_info mr = (CONSTANT_InterfaceMethodref_info)
(constant_pool[index]);
CONSTANT_NameAndType_info nat = (CONSTANT_NameAndType_info)
(constant_pool[mr.name_and_type_index]);
String methodDescriptor = ((CONSTANT_Utf8_info)
(constant_pool[nat.descriptor_index])).convert();
return Util.v().jimpleReturnTypeOfMethodDescriptor(methodDescriptor);
}
private OutFlow processCPEntry(cp_info constant_pool[],int i,
TypeStack typeStack,
SootMethod jmethod)
{
cp_info c = constant_pool[i];
if (c instanceof CONSTANT_Integer_info)
typeStack = typeStack.push(IntType.v());
else if (c instanceof CONSTANT_Float_info)
typeStack = typeStack.push(FloatType.v());
else if (c instanceof CONSTANT_Long_info)
{
typeStack = typeStack.push(LongType.v());
typeStack = typeStack.push(Long2ndHalfType.v());
}
else if (c instanceof CONSTANT_Double_info)
{
typeStack = typeStack.push(DoubleType.v());
typeStack = typeStack.push(Double2ndHalfType.v());
}
else if (c instanceof CONSTANT_String_info)
typeStack = typeStack.push(RefType.v("java.lang.String"));
else if (c instanceof CONSTANT_Utf8_info)
typeStack = typeStack.push(RefType.v("java.lang.String"));
else
throw new RuntimeException("Attempting to push a non-constant cp entry");
return new OutFlow(typeStack);
}
TypeStack smartPush(TypeStack typeStack, Type type)
{
if(type.equals(LongType.v()))
{
typeStack = typeStack.push(LongType.v());
typeStack = typeStack.push(Long2ndHalfType.v());
}
else if(type.equals(DoubleType.v()))
{
typeStack = typeStack.push(DoubleType.v());
typeStack = typeStack.push(Double2ndHalfType.v());
}
else
typeStack = typeStack.push(type);
return typeStack;
}
TypeStack popSafeRefType(TypeStack typeStack)
{
/*
if(!(typeStack.top() instanceof RefType) &&
!(typeStack.top() instanceof ArrayType))
{
throw new RuntimeException("popSafe failed; top: " + typeStack.top() +
" required: RefType");
}
*/
return typeStack.pop();
}
TypeStack popSafeArrayType(TypeStack typeStack)
{
/*
if(!(typeStack.top() instanceof ArrayType) &&
!(RefType.v("null").equals(typeStack.top())))
{
throw new RuntimeException("popSafe failed; top: " + typeStack.top() +
" required: ArrayType");
}
*/
return typeStack.pop();
}
TypeStack popSafe(TypeStack typeStack, Type requiredType)
{
/*
if(!typeStack.top().equals(requiredType))
throw new RuntimeException("popSafe failed; top: " + typeStack.top() +
" required: " + requiredType);
*/
return typeStack.pop();
}
void confirmType(Type actualType, Type requiredType)
{
/*
if(!actualType.equals(requiredType))
throw new RuntimeException("confirmType failed; actualType: " + actualType +
" required: " + requiredType);*/
}
String getClassName(cp_info[] constant_pool, int index)
{
CONSTANT_Class_info c = (CONSTANT_Class_info) constant_pool[index];
String name = ((CONSTANT_Utf8_info) (constant_pool[c.name_index])).convert();
return name.replace('/', '.');
}
void confirmRefType(Type actualType)
{
/*
if(!(actualType instanceof RefType) &&
!(actualType instanceof ArrayType))
throw new RuntimeException("confirmRefType failed; actualType: " + actualType);*/
}
/** Runs through the given bbq contents performing the target fix-up pass;
* Requires all reachable blocks to have their done flags set to true, and
* this resets them all back to false;
* @param bbq queue of BasicBlocks to process.
* @see jimpleTargetFixup
*/
private void processTargetFixup(BBQ bbq)
{
BasicBlock b,p;
Stmt s;
while (!bbq.isEmpty()) {
try {
b = bbq.pull();
} catch(NoSuchElementException e)
{ break; }
s = b.getTailJStmt();
if (s instanceof GotoStmt)
{
if (b.succ.size() == 1)
{
// Regular goto
((GotoStmt)s).setTarget(((BasicBlock) b.succ.firstElement()).getHeadJStmt());
}
else
{
// Goto derived from a jsr bytecode
/*
if((BasicBlock)(b.succ.firstElement())==b.next)
((GotoStmt)s).setTarget(((BasicBlock) b.succ.elementAt(1)).getHeadJStmt());
else
((GotoStmt)s).setTarget(((BasicBlock) b.succ.firstElement()).getHeadJStmt());
*/
G.v().out.println("Error :");
for (int i=0; i<b.statements.size(); i++)
G.v().out.println(b.statements.get(i));
throw new RuntimeException(b +" has "+b.succ.size()+" successors.");
}
}
else if (s instanceof IfStmt)
{
if (b.succ.size()!=2)
G.v().out.println("How can an if not have 2 successors?");
if((BasicBlock)(b.succ.firstElement())==b.next)
{
((IfStmt)s).setTarget(((BasicBlock) b.succ.elementAt(1)).getHeadJStmt());
}
else
{
((IfStmt)s).setTarget(((BasicBlock) b.succ.firstElement()).getHeadJStmt());
}
}
else if (s instanceof TableSwitchStmt)
{
int count=0;
TableSwitchStmt sts = (TableSwitchStmt)s;
// Successors of the basic block ending with a switch statement
// are listed in the successor vector in order, with the
// default as the very first (0-th entry)
for (Enumeration e = b.succ.elements();e.hasMoreElements();) {
p = (BasicBlock)(e.nextElement());
if (count==0) {
sts.setDefaultTarget(p.getHeadJStmt());
} else {
sts.setTarget(count-1, p.getHeadJStmt());
}
count++;
}
} else if (s instanceof LookupSwitchStmt)
{
int count=0;
LookupSwitchStmt sls = (LookupSwitchStmt)s;
// Successors of the basic block ending with a switch statement
// are listed in the successor vector in order, with the
// default as the very first (0-th entry)
for (Enumeration e = b.succ.elements();e.hasMoreElements();) {
p = (BasicBlock)(e.nextElement());
if (count==0) {
sls.setDefaultTarget(p.getHeadJStmt());
} else {
sls.setTarget(count-1, p.getHeadJStmt());
}
count++;
}
}
b.done = false;
for (Enumeration e = b.succ.elements();e.hasMoreElements();) {
p = (BasicBlock)(e.nextElement());
if (p.done) bbq.push(p);
}
}
}
/** After the initial jimple construction, a second pass is made to fix up
* missing Stmt targets for <tt>goto</tt>s, <tt>if</tt>'s etc.
* @param c code attribute of this method.
* @see CFG#jimplify
*/
void jimpleTargetFixup()
{
BasicBlock b;
BBQ bbq = new BBQ();
Code_attribute c = method.locate_code_attribute();
if (c==null)
return;
// Reset all the dones to true
{
BasicBlock bb = cfg;
while(bb != null)
{
bb.done = true;
bb = bb.next;
}
}
// first process the main code
bbq.push(cfg);
processTargetFixup(bbq);
// then the exceptions
if (bbq.isEmpty())
{
int i;
for (i=0;i<c.exception_table_length;i++)
{
b = c.exception_table[i].b;
// if block hasn't yet been processed...
if (b!=null && b.done)
{
bbq.push(b);
processTargetFixup(bbq);
if (!bbq.isEmpty()) {
G.v().out.println("Error 2nd processing exception block.");
break;
}
}
}
}
}
private void generateJimpleForCPEntry(cp_info constant_pool[], int i,
TypeStack typeStack, TypeStack postTypeStack,
SootMethod jmethod, List statements)
{
Expr e;
Stmt stmt;
Value rvalue;
cp_info c = constant_pool[i];
if (c instanceof CONSTANT_Integer_info)
{
CONSTANT_Integer_info ci = (CONSTANT_Integer_info)c;
rvalue = IntConstant.v((int) ci.bytes);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rvalue);
}
else if (c instanceof CONSTANT_Float_info)
{
CONSTANT_Float_info cf = (CONSTANT_Float_info)c;
rvalue = FloatConstant.v(cf.convert());
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rvalue);
}
else if (c instanceof CONSTANT_Long_info)
{
CONSTANT_Long_info cl = (CONSTANT_Long_info)c;
rvalue = LongConstant.v(cl.convert());
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rvalue);
}
else if (c instanceof CONSTANT_Double_info)
{
CONSTANT_Double_info cd = (CONSTANT_Double_info)c;
rvalue = DoubleConstant.v(cd.convert());
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rvalue);
}
else if (c instanceof CONSTANT_String_info)
{
CONSTANT_String_info cs = (CONSTANT_String_info)c;
String constant = cs.toString(constant_pool);
if(constant.startsWith("\"") && constant.endsWith("\""))
constant = constant.substring(1, constant.length() - 1);
rvalue = StringConstant.v(constant);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rvalue);
}
else if (c instanceof CONSTANT_Utf8_info)
{
CONSTANT_Utf8_info cu = (CONSTANT_Utf8_info)c;
String constant = cu.convert();
if(constant.startsWith("\"") && constant.endsWith("\""))
constant = constant.substring(1, constant.length() - 1);
rvalue = StringConstant.v(constant);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rvalue);
}
else {
throw new RuntimeException("Attempting to push a non-constant cp entry");
}
statements.add(stmt);
}
void generateJimple(Instruction ins, TypeStack typeStack, TypeStack postTypeStack,
cp_info constant_pool[],
List statements, BasicBlock basicBlock)
{
Value[] params;
Value v1=null,v2=null,v3=null,v4=null;
Local l1 = null, l2 = null, l3 = null, l4 = null;
Expr e=null,rhs=null;
BinopExpr b=null;
ConditionExpr co = null;
ArrayRef a=null;
int args;
Value rvalue;
// int localIndex;
Stmt stmt = null;
int x = ((int)(ins.code))&0xff;
Util.v().activeOriginalIndex = ins.originalIndex;
Util.v().isLocalStore = false;
Util.v().isWideLocalStore = false;
switch(x)
{
case ByteCode.BIPUSH:
rvalue = IntConstant.v(((Instruction_Bipush)ins).arg_b);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rvalue);
break;
case ByteCode.SIPUSH:
rvalue = IntConstant.v(((Instruction_Sipush)ins).arg_i);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rvalue);
break;
case ByteCode.LDC1:
generateJimpleForCPEntry(constant_pool,((Instruction_Ldc1)ins).arg_b, typeStack, postTypeStack,
jmethod, statements);
break;
case ByteCode.LDC2:
case ByteCode.LDC2W:
generateJimpleForCPEntry(constant_pool, ((Instruction_intindex)ins).arg_i,
typeStack, postTypeStack, jmethod, statements);
break;
case ByteCode.ACONST_NULL:
rvalue = NullConstant.v();
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rvalue);
break;
case ByteCode.ICONST_M1:
case ByteCode.ICONST_0:
case ByteCode.ICONST_1:
case ByteCode.ICONST_2:
case ByteCode.ICONST_3:
case ByteCode.ICONST_4:
case ByteCode.ICONST_5:
rvalue = IntConstant.v(x-ByteCode.ICONST_0);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rvalue);
break;
case ByteCode.LCONST_0:
case ByteCode.LCONST_1:
rvalue = LongConstant.v(x-ByteCode.LCONST_0);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rvalue);
break;
case ByteCode.FCONST_0:
case ByteCode.FCONST_1:
case ByteCode.FCONST_2:
rvalue = FloatConstant.v((float)(x - ByteCode.FCONST_0));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rvalue);
break;
case ByteCode.DCONST_0:
case ByteCode.DCONST_1:
rvalue = DoubleConstant.v((double)(x-ByteCode.DCONST_0));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rvalue);
break;
case ByteCode.ILOAD:
{
Local local = (Local)
Util.v().getLocalForIndex(listBody, ((Instruction_bytevar) ins).arg_b);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), local);
break;
}
case ByteCode.FLOAD:
{
Local local = (Local)
Util.v().getLocalForIndex(listBody, ((Instruction_bytevar)ins).arg_b);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), local);
break;
}
case ByteCode.ALOAD:
{
Local local =
Util.v().getLocalForIndex(listBody, ((Instruction_bytevar)ins).arg_b);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), local);
break;
}
case ByteCode.DLOAD:
{
Local local =
Util.v().getLocalForIndex(listBody, ((Instruction_bytevar)ins).arg_b);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), local);
break;
}
case ByteCode.LLOAD:
{
Local local =
Util.v().getLocalForIndex(listBody, ((Instruction_bytevar)ins).arg_b);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), local);
break;
}
case ByteCode.ILOAD_0:
case ByteCode.ILOAD_1:
case ByteCode.ILOAD_2:
case ByteCode.ILOAD_3:
{
Local local =
Util.v().getLocalForIndex(listBody, (x - ByteCode.ILOAD_0));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), local);
break;
}
case ByteCode.FLOAD_0:
case ByteCode.FLOAD_1:
case ByteCode.FLOAD_2:
case ByteCode.FLOAD_3:
{
Local local =
Util.v().getLocalForIndex(listBody, (x - ByteCode.FLOAD_0));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), local);
break;
}
case ByteCode.ALOAD_0:
case ByteCode.ALOAD_1:
case ByteCode.ALOAD_2:
case ByteCode.ALOAD_3:
{
Local local =
Util.v().getLocalForIndex(listBody, (x - ByteCode.ALOAD_0));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), local);
break;
}
case ByteCode.LLOAD_0:
case ByteCode.LLOAD_1:
case ByteCode.LLOAD_2:
case ByteCode.LLOAD_3:
{
Local local =
Util.v().getLocalForIndex(listBody, (x - ByteCode.LLOAD_0));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), local);
break;
}
case ByteCode.DLOAD_0:
case ByteCode.DLOAD_1:
case ByteCode.DLOAD_2:
case ByteCode.DLOAD_3:
{
Local local =
Util.v().getLocalForIndex(listBody, (x - ByteCode.DLOAD_0));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), local);
break;
}
case ByteCode.ISTORE:
{
Util.v().isLocalStore = true;
Util.v().isWideLocalStore = true;
Local local =
Util.v().getLocalForIndex(listBody,
((Instruction_bytevar)ins).arg_b);
stmt = Jimple.v().newAssignStmt(local, Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()));
break;
}
case ByteCode.FSTORE:
{
Util.v().isLocalStore = true;
Util.v().isWideLocalStore = true;
Local local =
Util.v().getLocalForIndex(listBody,
((Instruction_bytevar)ins).arg_b);
stmt = Jimple.v().newAssignStmt(local, Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()));
break;
}
case ByteCode.ASTORE:
{
Util.v().isLocalStore = true;
Util.v().isWideLocalStore = true;
Local local =
Util.v().getLocalForIndex(listBody,
((Instruction_bytevar)ins).arg_b);
stmt = Jimple.v().newAssignStmt(local, Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()));
break;
}
case ByteCode.LSTORE:
{
Util.v().isLocalStore = true;
Util.v().isWideLocalStore = true;
Local local =
Util.v().getLocalForIndex(listBody,
((Instruction_bytevar)ins).arg_b);
stmt = Jimple.v().newAssignStmt(local, Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()));
break;
}
case ByteCode.DSTORE:
{
Util.v().isLocalStore = true;
Util.v().isWideLocalStore = true;
Local local =
Util.v().getLocalForIndex(listBody,
((Instruction_bytevar)ins).arg_b);
stmt = Jimple.v().newAssignStmt(local, Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()));
break;
}
case ByteCode.ISTORE_0:
case ByteCode.ISTORE_1:
case ByteCode.ISTORE_2:
case ByteCode.ISTORE_3:
{
Util.v().isLocalStore = true;
Local local =
Util.v().getLocalForIndex(listBody, (x - ByteCode.ISTORE_0));
stmt = Jimple.v().newAssignStmt(local, Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()));
break;
}
case ByteCode.FSTORE_0:
case ByteCode.FSTORE_1:
case ByteCode.FSTORE_2:
case ByteCode.FSTORE_3:
{
Util.v().isLocalStore = true;
Local local = (Local)
Util.v().getLocalForIndex(listBody, (x - ByteCode.FSTORE_0));
stmt = Jimple.v().newAssignStmt(local, Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()));
break;
}
case ByteCode.ASTORE_0:
case ByteCode.ASTORE_1:
case ByteCode.ASTORE_2:
case ByteCode.ASTORE_3:
{
Util.v().isLocalStore = true;
Local local = Util.v().getLocalForIndex(listBody, (x - ByteCode.ASTORE_0));
stmt = Jimple.v().newAssignStmt(local, Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()));
break;
}
case ByteCode.LSTORE_0:
case ByteCode.LSTORE_1:
case ByteCode.LSTORE_2:
case ByteCode.LSTORE_3:
{
Util.v().isLocalStore = true;
Local local =
Util.v().getLocalForIndex(listBody, (x - ByteCode.LSTORE_0));
stmt = Jimple.v().newAssignStmt(local, Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()));
break;
}
case ByteCode.DSTORE_0:
case ByteCode.DSTORE_1:
case ByteCode.DSTORE_2:
case ByteCode.DSTORE_3:
{
Util.v().isLocalStore = true;
Local local =
Util.v().getLocalForIndex(listBody, (x - ByteCode.DSTORE_0));
stmt = Jimple.v().newAssignStmt(local, Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()));
break;
}
case ByteCode.IINC:
{
Local local =
Util.v().getLocalForIndex(listBody,
((Instruction_Iinc)ins).arg_b);
int amt = (((Instruction_Iinc)ins).arg_c);
rhs = Jimple.v().newAddExpr(local, IntConstant.v(amt));
stmt = Jimple.v().newAssignStmt(local,rhs);
break;
}
case ByteCode.WIDE:
throw new RuntimeException("WIDE instruction should not be encountered anymore");
// break;
case ByteCode.NEWARRAY:
{
Type baseType = (Type) jimpleTypeOfAtype(((Instruction_Newarray)ins).atype);
rhs = Jimple.v().newNewArrayExpr(baseType,
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody,
postTypeStack, postTypeStack.topIndex()), rhs);
break;
}
case ByteCode.ANEWARRAY:
{
String baseName = getClassName(constant_pool, ((Instruction_Anewarray)ins).arg_i);
Type baseType;
if(baseName.startsWith("["))
baseType = Util.v().jimpleTypeOfFieldDescriptor(getClassName(constant_pool, ((Instruction_Anewarray)ins).arg_i));
else
baseType = RefType.v(baseName);
rhs = Jimple.v().newNewArrayExpr(baseType, Util.v().getLocalForStackOp(listBody,
typeStack, typeStack.topIndex()));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody,
postTypeStack, postTypeStack.topIndex()),rhs);
break;
}
case ByteCode.MULTIANEWARRAY:
{
int bdims = (int)(((Instruction_Multianewarray)ins).dims);
List dims = new ArrayList();
for (int j=0; j < bdims; j++)
dims.add(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - bdims + j + 1));
String mstype = constant_pool[((Instruction_Multianewarray)ins).arg_i].
toString(constant_pool);
ArrayType jimpleType = (ArrayType) Util.v().jimpleTypeOfFieldDescriptor(mstype);
rhs = Jimple.v().newNewMultiArrayExpr(jimpleType, dims);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()),rhs);
break;
}
case ByteCode.ARRAYLENGTH:
rhs = Jimple.v().newLengthExpr(
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()),rhs);
break;
case ByteCode.IALOAD:
case ByteCode.BALOAD:
case ByteCode.CALOAD:
case ByteCode.SALOAD:
case ByteCode.FALOAD:
case ByteCode.LALOAD:
case ByteCode.DALOAD:
case ByteCode.AALOAD:
a = Jimple.v().newArrayRef(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 1),
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody,
postTypeStack, postTypeStack.topIndex()), a);
break;
case ByteCode.IASTORE:
case ByteCode.FASTORE:
case ByteCode.AASTORE:
case ByteCode.BASTORE:
case ByteCode.CASTORE:
case ByteCode.SASTORE:
a = Jimple.v().newArrayRef(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 2), Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 1));
stmt = Jimple.v().newAssignStmt(a, Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()));
break;
case ByteCode.LASTORE:
case ByteCode.DASTORE:
a = Jimple.v().newArrayRef(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 3), Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 2));
stmt = Jimple.v().newAssignStmt(a, Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()));
break;
case ByteCode.NOP:
stmt = Jimple.v().newNopStmt();
break;
case ByteCode.POP:
case ByteCode.POP2:
stmt = Jimple.v().newNopStmt();
break;
case ByteCode.DUP:
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()));
break;
case ByteCode.DUP2:
if(typeSize(typeStack.top()) == 2)
{
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex() - 1),
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1));
}
else {
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex() - 1),
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1));
statements.add(stmt);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), Util.v().getLocalForStackOp(listBody,
typeStack, typeStack.topIndex()));
statements.add(stmt);
stmt = null;
}
break;
case ByteCode.DUP_X1:
l1 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex());
l2 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-1);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), l1);
statements.add(stmt);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex() - 1), l2);
statements.add(stmt);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex() - 2), Util.v().getLocalForStackOp(listBody,
postTypeStack, postTypeStack.topIndex()));
statements.add(stmt);
stmt = null;
break;
case ByteCode.DUP_X2:
if(typeSize(typeStack.get(typeStack.topIndex() - 2)) == 2)
{
l3 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 2);
l1 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex());
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex() - 2), l3);
statements.add(stmt);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex() - 3), l1);
statements.add(stmt);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), l1);
statements.add(stmt);
stmt = null;
}
else {
l3 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 2);
l2 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1);
l1 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex());
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), l1);
statements.add(stmt);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex() - 1), l2);
statements.add(stmt);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex() - 2), l3);
statements.add(stmt);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex() - 3), Util.v().getLocalForStackOp(
listBody, postTypeStack, postTypeStack.topIndex()));
statements.add(stmt);
stmt = null;
}
break;
case ByteCode.DUP2_X1:
if(typeSize(typeStack.get(typeStack.topIndex() - 1)) == 2)
{
l2 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1);
l3 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 2);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex() -1), l2);
statements.add(stmt);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex() - 2), l3);
statements.add(stmt);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex() - 4),
Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex() - 1));
statements.add(stmt);
stmt = null;
}
else {
l3 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 2);
l2 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1);
l1 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex());
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), l1);
statements.add(stmt);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex() - 1), l2);
statements.add(stmt);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex() - 2), l3);
statements.add(stmt);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex() - 3), Util.v().getLocalForStackOp(
listBody, postTypeStack, postTypeStack.topIndex()));
statements.add(stmt);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex() - 4), Util.v().getLocalForStackOp(
listBody, postTypeStack, postTypeStack.topIndex() - 1));
statements.add(stmt);
stmt = null;
}
break;
case ByteCode.DUP2_X2:
if(typeSize(typeStack.get(typeStack.topIndex() - 1)) == 2)
{
l2 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex() - 1), l2);
statements.add(stmt);
}
else {
l1 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex());
l2 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex() - 1), l2);
statements.add(stmt);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), l1);
statements.add(stmt);
}
if(typeSize(typeStack.get(typeStack.topIndex() - 3)) == 2)
{
l4 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 3);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex() - 3), l4);
statements.add(stmt);
}
else {
l4 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 3);
l3 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 2);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex() - 3), l4);
statements.add(stmt);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex() - 2), l3);
statements.add(stmt);
}
if(typeSize(typeStack.get(typeStack.topIndex() - 1)) == 2)
{
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex() - 5), Util.v().getLocalForStackOp(
listBody, postTypeStack, postTypeStack.topIndex() - 1));
statements.add(stmt);
}
else {
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex() - 5), Util.v().getLocalForStackOp(
listBody, postTypeStack, postTypeStack.topIndex() - 1));
statements.add(stmt);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex() - 4), Util.v().getLocalForStackOp(
listBody, postTypeStack, postTypeStack.topIndex()));
statements.add(stmt);
}
stmt = null;
break;
case ByteCode.SWAP:
{
Local first;
typeStack = typeStack.push(typeStack.top());
first = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex());
typeStack = typeStack.pop();
// generation of a free temporary
Local second = Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex());
Local third = Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex() - 1);
stmt = Jimple.v().newAssignStmt(first, second);
statements.add(stmt);
stmt = Jimple.v().newAssignStmt(second, third);
statements.add(stmt);
stmt = Jimple.v().newAssignStmt(third, first);
statements.add(stmt);
stmt = null;
break;
}
case ByteCode.FADD:
case ByteCode.IADD:
rhs = Jimple.v().newAddExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 1), Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rhs);
break;
case ByteCode.DADD:
case ByteCode.LADD:
rhs = Jimple.v().newAddExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 3), Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 1));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rhs);
break;
case ByteCode.FSUB:
case ByteCode.ISUB:
rhs = Jimple.v().newSubExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 1), Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rhs);
break;
case ByteCode.DSUB:
case ByteCode.LSUB:
rhs = Jimple.v().newSubExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 3), Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 1));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rhs);
break;
case ByteCode.FMUL:
case ByteCode.IMUL:
rhs = Jimple.v().newMulExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 1), Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rhs);
break;
case ByteCode.DMUL:
case ByteCode.LMUL:
rhs = Jimple.v().newMulExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 3), Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 1));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rhs);
break;
case ByteCode.FDIV:
case ByteCode.IDIV:
rhs = Jimple.v().newDivExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 1), Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rhs);
break;
case ByteCode.DDIV:
case ByteCode.LDIV:
rhs = Jimple.v().newDivExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 3), Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 1));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rhs);
break;
case ByteCode.FREM:
case ByteCode.IREM:
rhs = Jimple.v().newRemExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 1), Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rhs);
break;
case ByteCode.DREM:
case ByteCode.LREM:
rhs = Jimple.v().newRemExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 3), Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 1));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rhs);
break;
case ByteCode.INEG:
case ByteCode.LNEG:
case ByteCode.FNEG:
case ByteCode.DNEG:
rhs = Jimple.v().newNegExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()),rhs);
break;
case ByteCode.ISHL:
rhs = Jimple.v().newShlExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 1), Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rhs);
break;
case ByteCode.ISHR:
rhs = Jimple.v().newShrExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 1), Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rhs);
break;
case ByteCode.IUSHR:
rhs = Jimple.v().newUshrExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 1), Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rhs);
break;
case ByteCode.LSHL:
rhs = Jimple.v().newShlExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 2), Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rhs);
break;
case ByteCode.LSHR:
rhs = Jimple.v().newShrExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 2), Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rhs);
break;
case ByteCode.LUSHR:
rhs = Jimple.v().newUshrExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 2), Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rhs);
break;
case ByteCode.IAND:
rhs = Jimple.v().newAndExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 1), Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rhs);
break;
case ByteCode.LAND:
rhs = Jimple.v().newAndExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 3), Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 1));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rhs);
break;
case ByteCode.IOR:
rhs = Jimple.v().newOrExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 1), Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rhs);
break;
case ByteCode.LOR:
rhs = Jimple.v().newOrExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 3), Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 1));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rhs);
break;
case ByteCode.IXOR:
rhs = Jimple.v().newXorExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 1), Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rhs);
break;
case ByteCode.LXOR:
rhs = Jimple.v().newXorExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 3), Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex() - 1));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rhs);
break;
case ByteCode.D2L:
case ByteCode.F2L:
case ByteCode.I2L:
rhs = Jimple.v().newCastExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()), LongType.v());
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rhs);
break;
case ByteCode.D2F:
case ByteCode.L2F:
case ByteCode.I2F:
rhs = Jimple.v().newCastExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()), FloatType.v());
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rhs);
break;
case ByteCode.I2D:
case ByteCode.L2D:
case ByteCode.F2D:
rhs = Jimple.v().newCastExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()), DoubleType.v());
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rhs);
break;
case ByteCode.L2I:
case ByteCode.F2I:
case ByteCode.D2I:
rhs = Jimple.v().newCastExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()), IntType.v());
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rhs);
break;
case ByteCode.INT2BYTE:
rhs = Jimple.v().newCastExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()), ByteType.v());
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rhs);
break;
case ByteCode.INT2CHAR:
rhs = Jimple.v().newCastExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()), CharType.v());
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rhs);
break;
case ByteCode.INT2SHORT:
rhs = Jimple.v().newCastExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()), ShortType.v());
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rhs);
break;
case ByteCode.IFEQ:
co = Jimple.v().newEqExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()),
IntConstant.v(0));
stmt = Jimple.v().newIfStmt(co, new FutureStmt());
break;
case ByteCode.IFNULL:
co = Jimple.v().newEqExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()),
NullConstant.v());
stmt = Jimple.v().newIfStmt(co, new FutureStmt());
break;
case ByteCode.IFLT:
co = Jimple.v().newLtExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()),
IntConstant.v(0));
stmt = Jimple.v().newIfStmt(co, new FutureStmt());
break;
case ByteCode.IFLE:
co = Jimple.v().newLeExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()),
IntConstant.v(0));
stmt = Jimple.v().newIfStmt(co, new FutureStmt());
break;
case ByteCode.IFNE:
co = Jimple.v().newNeExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()),
IntConstant.v(0));
stmt = Jimple.v().newIfStmt(co, new FutureStmt());
break;
case ByteCode.IFNONNULL:
co = Jimple.v().newNeExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()),
NullConstant.v());
stmt = Jimple.v().newIfStmt(co, new FutureStmt());
break;
case ByteCode.IFGT:
co = Jimple.v().newGtExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()),
IntConstant.v(0));
stmt = Jimple.v().newIfStmt(co, new FutureStmt());
break;
case ByteCode.IFGE:
co = Jimple.v().newGeExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()),
IntConstant.v(0));
stmt = Jimple.v().newIfStmt(co, new FutureStmt());
break;
case ByteCode.IF_ICMPEQ:
co = Jimple.v().newEqExpr(
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-1),
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()));
stmt = Jimple.v().newIfStmt(co, new FutureStmt());
break;
case ByteCode.IF_ICMPLT:
co = Jimple.v().newLtExpr(
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-1),
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()));
stmt = Jimple.v().newIfStmt(co, new FutureStmt());
break;
case ByteCode.IF_ICMPLE:
co = Jimple.v().newLeExpr(
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-1),
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()));
stmt = Jimple.v().newIfStmt(co, new FutureStmt());
break;
case ByteCode.IF_ICMPNE:
co = Jimple.v().newNeExpr(
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-1),
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()));
stmt = Jimple.v().newIfStmt(co, new FutureStmt());
break;
case ByteCode.IF_ICMPGT:
co = Jimple.v().newGtExpr(
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-1),
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()));
stmt = Jimple.v().newIfStmt(co, new FutureStmt());
break;
case ByteCode.IF_ICMPGE:
co = Jimple.v().newGeExpr(
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-1),
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()));
stmt = Jimple.v().newIfStmt(co, new FutureStmt());
break;
case ByteCode.LCMP:
rhs = Jimple.v().newCmpExpr(
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-3),
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-1));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rhs);
break;
case ByteCode.FCMPL:
rhs = Jimple.v().newCmplExpr(
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-1),
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody,
postTypeStack, postTypeStack.topIndex()),rhs);
break;
case ByteCode.FCMPG:
rhs = Jimple.v().newCmpgExpr(
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-1),
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody,
postTypeStack, postTypeStack.topIndex()),rhs);
break;
case ByteCode.DCMPL:
rhs = Jimple.v().newCmplExpr(
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-3),
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-1));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody,
postTypeStack, postTypeStack.topIndex()),rhs);
break;
case ByteCode.DCMPG:
rhs = Jimple.v().newCmpgExpr(
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-3),
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-1));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody,
postTypeStack, postTypeStack.topIndex()),rhs);
break;
case ByteCode.IF_ACMPEQ:
co = Jimple.v().newEqExpr(
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-1),
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()));
stmt = Jimple.v().newIfStmt(co, new FutureStmt());
break;
case ByteCode.IF_ACMPNE:
co = Jimple.v().newNeExpr(
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-1),
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()));
stmt = Jimple.v().newIfStmt(co, new FutureStmt());
break;
case ByteCode.GOTO:
stmt = Jimple.v().newGotoStmt(new FutureStmt());
break;
case ByteCode.GOTO_W:
stmt = Jimple.v().newGotoStmt(new FutureStmt());
break;
/*
case ByteCode.JSR:
case ByteCode.JSR_W:
{
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), Jimple.v().newNextNextStmtRef());
statements.add(stmt);
stmt = Jimple.v().newGotoStmt(new FutureStmt());
statements.add(stmt);
stmt = null;
break;
}
*/
case ByteCode.RET:
{
Local local =
Util.v().getLocalForIndex(listBody, ((Instruction_Ret)ins).arg_b);
stmt = Jimple.v().newRetStmt(local);
break;
}
case ByteCode.RET_W:
{
Local local =
Util.v().getLocalForIndex(listBody, ((Instruction_Ret_w)ins).arg_i);
stmt = Jimple.v().newRetStmt(local);
break;
}
case ByteCode.RETURN:
stmt = Jimple.v().newReturnVoidStmt();
break;
case ByteCode.LRETURN:
case ByteCode.DRETURN:
case ByteCode.IRETURN:
case ByteCode.FRETURN:
case ByteCode.ARETURN:
stmt = Jimple.v().newReturnStmt(Util.v().getLocalForStackOp(listBody,
typeStack, typeStack.topIndex()));
break;
case ByteCode.BREAKPOINT:
stmt = Jimple.v().newBreakpointStmt();
break;
case ByteCode.TABLESWITCH:
{
int lowIndex = ((Instruction_Tableswitch)ins).low,
highIndex = ((Instruction_Tableswitch)ins).high;
stmt = Jimple.v().newTableSwitchStmt(
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()),
lowIndex,
highIndex,
Arrays.asList(new FutureStmt[highIndex - lowIndex + 1]),
new FutureStmt());
break;
}
case ByteCode.LOOKUPSWITCH:
{
List matches = new ArrayList();
int npairs = ((Instruction_Lookupswitch)ins).npairs;
for (int j = 0; j < npairs; j++)
matches.add(IntConstant.v( ((Instruction_Lookupswitch)ins).match_offsets[j*2]));
stmt = Jimple.v().newLookupSwitchStmt(
Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()),
matches,
Arrays.asList(new FutureStmt[npairs]),
new FutureStmt());
break;
}
case ByteCode.PUTFIELD:
{
CONSTANT_Fieldref_info fieldInfo =
(CONSTANT_Fieldref_info) constant_pool[((Instruction_Putfield)ins).arg_i];
CONSTANT_Class_info c =
(CONSTANT_Class_info) constant_pool[fieldInfo.class_index];
String className = ((CONSTANT_Utf8_info) (constant_pool[c.name_index])).convert();
className = className.replace('/', '.');
CONSTANT_NameAndType_info i =
(CONSTANT_NameAndType_info) constant_pool[fieldInfo.name_and_type_index];
String fieldName = ((CONSTANT_Utf8_info) (constant_pool[i.name_index])).convert();
String fieldDescriptor = ((CONSTANT_Utf8_info) (constant_pool[i.descriptor_index])).
convert();
Type fieldType = Util.v().jimpleTypeOfFieldDescriptor(fieldDescriptor);
SootClass bclass = cm.getSootClass(className);
SootFieldRef fieldRef = Scene.v().makeFieldRef(bclass, fieldName, fieldType, false);
InstanceFieldRef fr =
Jimple.v().newInstanceFieldRef(Util.v().getLocalForStackOp(listBody,
typeStack, typeStack.topIndex() - typeSize(typeStack.top())), fieldRef);
rvalue = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex());
stmt = Jimple.v().newAssignStmt(fr,rvalue);
break;
}
case ByteCode.GETFIELD:
{
InstanceFieldRef fr = null;
CONSTANT_Fieldref_info fieldInfo =
(CONSTANT_Fieldref_info) constant_pool[((Instruction_Getfield)ins).arg_i];
CONSTANT_Class_info c =
(CONSTANT_Class_info) constant_pool[fieldInfo.class_index];
String className = ((CONSTANT_Utf8_info) (constant_pool[c.name_index])).convert();
className = className.replace('/', '.');
CONSTANT_NameAndType_info i =
(CONSTANT_NameAndType_info) constant_pool[fieldInfo.name_and_type_index];
String fieldName = ((CONSTANT_Utf8_info) (constant_pool[i.name_index])).convert();
String fieldDescriptor = ((CONSTANT_Utf8_info) (constant_pool[i.descriptor_index])).
convert();
if (className.charAt(0) == '[')
className = "java.lang.Object";
SootClass bclass = cm.getSootClass(className);
Type fieldType = Util.v().jimpleTypeOfFieldDescriptor(fieldDescriptor);
SootFieldRef fieldRef = Scene.v().makeFieldRef(bclass, fieldName, fieldType, false);
fr = Jimple.v().newInstanceFieldRef(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()), fieldRef);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), fr);
break;
}
case ByteCode.PUTSTATIC:
{
StaticFieldRef fr = null;
CONSTANT_Fieldref_info fieldInfo =
(CONSTANT_Fieldref_info) constant_pool[((Instruction_Putstatic)ins).arg_i];
CONSTANT_Class_info c =
(CONSTANT_Class_info) constant_pool[fieldInfo.class_index];
String className = ((CONSTANT_Utf8_info) (constant_pool[c.name_index])).convert();
className = className.replace('/', '.');
CONSTANT_NameAndType_info i =
(CONSTANT_NameAndType_info) constant_pool[fieldInfo.name_and_type_index];
String fieldName = ((CONSTANT_Utf8_info) (constant_pool[i.name_index])).convert();
String fieldDescriptor = ((CONSTANT_Utf8_info) (constant_pool[i.descriptor_index])).
convert();
Type fieldType = Util.v().jimpleTypeOfFieldDescriptor(fieldDescriptor);
SootClass bclass = cm.getSootClass(className);
SootFieldRef fieldRef = Scene.v().makeFieldRef(bclass, fieldName, fieldType, true);
fr = Jimple.v().newStaticFieldRef(fieldRef);
stmt = Jimple.v().newAssignStmt(fr, Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()));
break;
}
case ByteCode.GETSTATIC:
{
StaticFieldRef fr = null;
CONSTANT_Fieldref_info fieldInfo =
(CONSTANT_Fieldref_info) constant_pool[((Instruction_Getstatic)ins).arg_i];
CONSTANT_Class_info c =
(CONSTANT_Class_info) constant_pool[fieldInfo.class_index];
String className = ((CONSTANT_Utf8_info) (constant_pool[c.name_index])).convert();
className = className.replace('/', '.');
CONSTANT_NameAndType_info i =
(CONSTANT_NameAndType_info) constant_pool[fieldInfo.name_and_type_index];
String fieldName = ((CONSTANT_Utf8_info) (constant_pool[i.name_index])).convert();
String fieldDescriptor = ((CONSTANT_Utf8_info) (constant_pool[i.descriptor_index])).
convert();
Type fieldType = Util.v().jimpleTypeOfFieldDescriptor(fieldDescriptor);
SootClass bclass = cm.getSootClass(className);
SootFieldRef fieldRef = Scene.v().makeFieldRef(bclass, fieldName, fieldType, true);
fr = Jimple.v().newStaticFieldRef(fieldRef);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), fr);
break;
}
case ByteCode.INVOKEVIRTUAL:
{
Instruction_Invokevirtual iv = (Instruction_Invokevirtual)ins;
args = cp_info.countParams(constant_pool,iv.arg_i);
SootMethodRef methodRef = null;
CONSTANT_Methodref_info methodInfo =
(CONSTANT_Methodref_info) constant_pool[iv.arg_i];
CONSTANT_Class_info c =
(CONSTANT_Class_info) constant_pool[methodInfo.class_index];
String className = ((CONSTANT_Utf8_info) (constant_pool[c.name_index])).convert();
className = className.replace('/', '.');
CONSTANT_NameAndType_info i =
(CONSTANT_NameAndType_info) constant_pool[methodInfo.name_and_type_index];
String methodName = ((CONSTANT_Utf8_info) (constant_pool[i.name_index])).convert();
String methodDescriptor = ((CONSTANT_Utf8_info) (constant_pool[i.descriptor_index])).
convert();
if (className.charAt(0) == '[')
className = "java.lang.Object";
SootClass bclass = cm.getSootClass(className);
Local[] parameters;
List parameterTypes;
Type returnType;
// Generate parameters & returnType & parameterTypes
{
Type[] types = Util.v().jimpleTypesOfFieldOrMethodDescriptor(methodDescriptor);
parameterTypes = new ArrayList();
for(int k = 0; k < types.length - 1; k++)
{
parameterTypes.add(types[k]);
}
returnType = types[types.length - 1];
}
methodRef = Scene.v().makeMethodRef(bclass, methodName, parameterTypes, returnType, false);
// build array of parameters
params = new Value[args];
for (int j=args-1;j>=0;j
{
params[j] = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex());
if(typeSize(typeStack.top()) == 2)
{
typeStack = typeStack.pop();
typeStack = typeStack.pop();
}
else
typeStack = typeStack.pop();
}
rvalue = Jimple.v().newVirtualInvokeExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()), methodRef, Arrays.asList(params));
if(!returnType.equals(VoidType.v()))
{
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()),rvalue);
}
else
stmt = Jimple.v().newInvokeStmt((InvokeExpr) rvalue);
break;
}
case ByteCode.INVOKENONVIRTUAL:
{
Instruction_Invokenonvirtual iv = (Instruction_Invokenonvirtual)ins;
args = cp_info.countParams(constant_pool,iv.arg_i);
SootMethodRef methodRef = null;
CONSTANT_Methodref_info methodInfo =
(CONSTANT_Methodref_info) constant_pool[iv.arg_i];
CONSTANT_Class_info c =
(CONSTANT_Class_info) constant_pool[methodInfo.class_index];
String className = ((CONSTANT_Utf8_info) (constant_pool[c.name_index])).convert();
className = className.replace('/', '.');
CONSTANT_NameAndType_info i =
(CONSTANT_NameAndType_info) constant_pool[methodInfo.name_and_type_index];
String methodName = ((CONSTANT_Utf8_info) (constant_pool[i.name_index])).convert();
String methodDescriptor = ((CONSTANT_Utf8_info) (constant_pool[i.descriptor_index])).
convert();
SootClass bclass = cm.getSootClass(className);
Local[] parameters;
List parameterTypes;
Type returnType;
// Generate parameters & returnType & parameterTypes
{
Type[] types = Util.v().jimpleTypesOfFieldOrMethodDescriptor(methodDescriptor);
parameterTypes = new ArrayList();
for(int k = 0; k < types.length - 1; k++)
{
parameterTypes.add(types[k]);
}
returnType = types[types.length - 1];
}
methodRef = Scene.v().makeMethodRef( bclass, methodName, parameterTypes, returnType, false);
// build array of parameters
params = new Value[args];
for (int j=args-1;j>=0;j
{
params[j] = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex());
if(typeSize(typeStack.top()) == 2)
{
typeStack = typeStack.pop();
typeStack = typeStack.pop();
}
else
typeStack = typeStack.pop();
}
rvalue = Jimple.v().newSpecialInvokeExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()), methodRef, Arrays.asList(params));
if(!returnType.equals(VoidType.v()))
{
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rvalue);
}
else
stmt = Jimple.v().newInvokeStmt((InvokeExpr) rvalue);
break;
}
case ByteCode.INVOKESTATIC:
{
Instruction_Invokestatic is = (Instruction_Invokestatic)ins;
args = cp_info.countParams(constant_pool,is.arg_i);
SootMethodRef methodRef = null;
CONSTANT_Methodref_info methodInfo =
(CONSTANT_Methodref_info) constant_pool[is.arg_i];
CONSTANT_Class_info c =
(CONSTANT_Class_info) constant_pool[methodInfo.class_index];
String className = ((CONSTANT_Utf8_info) (constant_pool[c.name_index])).convert();
className = className.replace('/', '.');
CONSTANT_NameAndType_info i =
(CONSTANT_NameAndType_info) constant_pool[methodInfo.name_and_type_index];
String methodName = ((CONSTANT_Utf8_info) (constant_pool[i.name_index])).convert();
String methodDescriptor = ((CONSTANT_Utf8_info) (constant_pool[i.descriptor_index])).
convert();
if (className.charAt(0) == '[')
className = "java.lang.Object";
SootClass bclass = cm.getSootClass(className);
Local[] parameters;
List parameterTypes;
Type returnType;
// Generate parameters & returnType & parameterTypes
{
Type[] types = Util.v().jimpleTypesOfFieldOrMethodDescriptor(methodDescriptor);
parameterTypes = new ArrayList();
for(int k = 0; k < types.length - 1; k++)
{
parameterTypes.add(types[k]);
}
returnType = types[types.length - 1];
}
methodRef = Scene.v().makeMethodRef(bclass, methodName, parameterTypes, returnType, true);
// build Vector of parameters
params = new Value[args];
for (int j=args-1;j>=0;j
{
/* G.v().out.println("BeforeTypeStack");
typeStack.print(G.v().out);
G.v().out.println("AfterTypeStack");
postTypeStack.print(G.v().out);
*/
params[j] = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex());
if(typeSize(typeStack.top()) == 2)
{
typeStack = typeStack.pop();
typeStack = typeStack.pop();
}
else
typeStack = typeStack.pop();
}
rvalue = Jimple.v().newStaticInvokeExpr(methodRef, Arrays.asList(params));
if(!returnType.equals(VoidType.v()))
{
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()),rvalue);
}
else
stmt = Jimple.v().newInvokeStmt((InvokeExpr) rvalue);
break;
}
case ByteCode.INVOKEINTERFACE:
{
Instruction_Invokeinterface ii = (Instruction_Invokeinterface)ins;
args = cp_info.countParams(constant_pool,ii.arg_i);
SootMethodRef methodRef = null;
CONSTANT_InterfaceMethodref_info methodInfo =
(CONSTANT_InterfaceMethodref_info) constant_pool[ii.arg_i];
CONSTANT_Class_info c =
(CONSTANT_Class_info) constant_pool[methodInfo.class_index];
String className = ((CONSTANT_Utf8_info) (constant_pool[c.name_index])).convert();
className = className.replace('/', '.');
CONSTANT_NameAndType_info i =
(CONSTANT_NameAndType_info) constant_pool[methodInfo.name_and_type_index];
String methodName = ((CONSTANT_Utf8_info) (constant_pool[i.name_index])).convert();
String methodDescriptor = ((CONSTANT_Utf8_info) (constant_pool[i.descriptor_index])).
convert();
if (className.charAt(0) == '[')
className = "java.lang.Object";
SootClass bclass = cm.getSootClass(className);
Local[] parameters;
List parameterTypes;
Type returnType;
// Generate parameters & returnType & parameterTypes
{
Type[] types = Util.v().jimpleTypesOfFieldOrMethodDescriptor(methodDescriptor);
parameterTypes = new ArrayList();
for(int k = 0; k < types.length - 1; k++)
{
parameterTypes.add(types[k]);
}
returnType = types[types.length - 1];
}
methodRef = Scene.v().makeMethodRef(bclass, methodName, parameterTypes, returnType, false);
// build Vector of parameters
params = new Value[args];
for (int j=args-1;j>=0;j
{
params[j] = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex());
if(typeSize(typeStack.top()) == 2)
{
typeStack = typeStack.pop();
typeStack = typeStack.pop();
}
else
typeStack = typeStack.pop();
}
rvalue = Jimple.v().newInterfaceInvokeExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()), methodRef, Arrays.asList(params));
if(!returnType.equals(VoidType.v()))
{
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), rvalue);
}
else
stmt = Jimple.v().newInvokeStmt((InvokeExpr) rvalue);
break;
}
case ByteCode.ATHROW:
stmt = Jimple.v().newThrowStmt(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()));
break;
case ByteCode.NEW:
{
SootClass bclass = cm.getSootClass(getClassName(constant_pool,
((Instruction_New)ins).arg_i));
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()), Jimple.v().newNewExpr(RefType.v(bclass.getName())));
break;
}
case ByteCode.CHECKCAST:
{
String className = getClassName(constant_pool, ((Instruction_Checkcast)ins).arg_i);
Type castType;
if(className.startsWith("["))
castType = Util.v().jimpleTypeOfFieldDescriptor(getClassName(constant_pool,
((Instruction_Checkcast)ins).arg_i));
else
castType = RefType.v(className);
rhs = Jimple.v().newCastExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()), castType);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()),rhs);
break;
}
case ByteCode.INSTANCEOF:
{
Type checkType;
String className = getClassName(constant_pool, ((Instruction_Instanceof)ins).arg_i);
if(className.startsWith("["))
checkType = Util.v().jimpleTypeOfFieldDescriptor(getClassName(constant_pool,
((Instruction_Instanceof)ins).arg_i));
else
checkType = RefType.v(className);
rhs = Jimple.v().newInstanceOfExpr(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()), checkType);
stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack,
postTypeStack.topIndex()),rhs);
break;
}
case ByteCode.MONITORENTER:
stmt = Jimple.v().newEnterMonitorStmt(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()));
break;
case ByteCode.MONITOREXIT:
stmt = Jimple.v().newExitMonitorStmt(Util.v().getLocalForStackOp(listBody, typeStack,
typeStack.topIndex()));
break;
default:
throw new RuntimeException("Unrecognized bytecode instruction: " + x);
}
if(stmt != null) {
if (Options.v().keep_offset()) {
stmt.addTag(new BytecodeOffsetTag(ins.label));
}
statements.add(stmt);
}
}
Type jimpleTypeOfAtype(int atype)
{
switch(atype)
{
case 4:
return BooleanType.v();
case 5:
return CharType.v();
case 6:
return FloatType.v();
case 7:
return DoubleType.v();
case 8:
return ByteType.v();
case 9:
return ShortType.v();
case 10:
return IntType.v();
case 11:
return LongType.v();
default:
throw new RuntimeException("Undefined 'atype' in NEWARRAY byte instruction");
}
}
int typeSize(Type type)
{
if (type.equals(LongType.v()) || type.equals(DoubleType.v()) ||
type.equals(Long2ndHalfType.v()) || type.equals(Double2ndHalfType.v()))
{
return 2;
}
else
return 1;
}
}
class OutFlow
{
TypeStack typeStack;
OutFlow(TypeStack typeStack)
{
this.typeStack = typeStack;
}
} |
package ons.solubility.rdf;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
public class BO {
private static Model model = ModelFactory.createDefaultModel();
public static final String NS = "http://blueobelisk.sourceforge.net/chemistryblogs/";
public static String getURI() {
return NS;
}
public static final Resource NAMESPACE = model.createResource(NS);
public static final Property smiles = model.createProperty(NS + "smiles");
public static final Property inchi = model.createProperty(NS + "inchi");
} |
package nl.mpi.arbil;
import java.awt.BorderLayout;
import nl.mpi.arbil.ui.menu.ArbilMenuBar;
import nl.mpi.arbil.util.ApplicationVersionManager;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import nl.mpi.arbil.data.ArbilTreeHelper;
import nl.mpi.arbil.ui.ArbilTaskStatusBar;
import nl.mpi.arbil.ui.ArbilTreePanels;
import nl.mpi.arbil.ui.ArbilWindowManager;
import nl.mpi.arbil.ui.PreviewSplitPanel;
import nl.mpi.arbil.util.ArbilMimeHashQueue;
import nl.mpi.arbil.util.BugCatcherManager;
public final class ArbilMain extends javax.swing.JFrame {
private javax.swing.JSplitPane mainSplitPane;
private ArbilMenuBar arbilMenuBar;
private ArbilTaskStatusBar statusBar;
private final ArbilTreeHelper treeHelper;
private final ArbilWindowManager windowManager;
private final ApplicationVersionManager versionManager;
private final ArbilMimeHashQueue mimeHashQueue;
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
System.setProperty("sun.swing.enableImprovedDragGesture", "true");
System.setProperty("apple.awt.graphics.UseQuartz", "true");
System.setProperty("apple.laf.useScreenMenuBar", "true");
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
final ApplicationVersionManager versionManager = new ApplicationVersionManager(new ArbilVersion());
try {
new ArbilMain(versionManager);
} catch (Exception ex) {
BugCatcherManager.getBugCatcher().logError(ex);
}
}
});
}
public ArbilMain(ApplicationVersionManager versionManager) {
this.versionManager = versionManager;
final ArbilDesktopInjector injector = new ArbilDesktopInjector();
injector.injectHandlers(versionManager);
this.treeHelper = injector.getTreeHelper();
this.windowManager = injector.getWindowManager();
this.mimeHashQueue = injector.getMimeHashQueue();
initApplication();
initUI();
checkFirstRun();
}
private void initApplication() {
treeHelper.init();
mimeHashQueue.init();
}
private void initUI() {
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
arbilMenuBar.performCleanExit();
//super.windowClosing(e);
}
});
initComponents();
windowManager.addTaskListener(statusBar);
PreviewSplitPanel previewSplitPanel = PreviewSplitPanel.getInstance();
mainSplitPane.setRightComponent(previewSplitPanel);
ArbilTreePanels arbilTreePanels = new ArbilTreePanels(treeHelper);
mainSplitPane.setLeftComponent(arbilTreePanels);
arbilMenuBar = new ArbilMenuBar(previewSplitPanel, null);
setJMenuBar(arbilMenuBar);
mainSplitPane.setDividerLocation(0.25);
windowManager.loadGuiState(this, statusBar);
setTitle(versionManager.getApplicationVersion().applicationTitle + " " + versionManager.getApplicationVersion().compileDate);
setIconImage(ArbilIcons.getSingleInstance().linorgIcon.getImage());
// load the templates and populate the templates menu
setVisible(true);
if (arbilMenuBar.checkNewVersionAtStartCheckBoxMenuItem.isSelected()) {
versionManager.checkForUpdate();
}
initMacApplicationHandlers(windowManager);
}
private void checkFirstRun() {
windowManager.showSetupWizardIfFirstRun();
windowManager.openIntroductionPage();
}
private void initComponents() {
mainSplitPane = new javax.swing.JSplitPane();
statusBar = new ArbilTaskStatusBar();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
setTitle("Arbil");
mainSplitPane.setDividerLocation(100);
mainSplitPane.setDividerSize(5);
mainSplitPane.setName("mainSplitPane");
getContentPane().setLayout(new BorderLayout());
getContentPane().add(mainSplitPane, java.awt.BorderLayout.CENTER);
getContentPane().add(statusBar, BorderLayout.SOUTH);
pack();
}
/**
* Initializes handlers for 'Quit' and 'About' options on MacOS (application menu + CMD-Q)
* This is done using reflection so that no compile or run time errors occur on systems that are not Mac
* and do not have the required classes available...
*/
private void initMacApplicationHandlers(ArbilWindowManager windowManager) {
try {
// Get application class
Class applicationClass = Class.forName("com.apple.eawt.Application");
Exception exception = null;
try {
// Get application object
Object application = applicationClass.getMethod("getApplication").invoke(null);
// Init quit handler
initMacQuitHandler(applicationClass, application);
// Init about handler
initMacAboutHandler(windowManager, applicationClass, application);
// Successfully set handlers, now remove redundant options from menu bar
arbilMenuBar.setMacOsMenu(true);
return;
} catch (IllegalAccessException ex) {
exception = ex;
} catch (IllegalArgumentException ex) {
exception = ex;
} catch (InvocationTargetException ex) {
exception = ex;
} catch (NoSuchMethodException ex) {
exception = ex;
} catch (SecurityException ex) {
exception = ex;
} catch (ClassNotFoundException ex) {
exception = ex;
}
System.err.println("Could not configure MacOS application handlers");
if (exception != null) {
System.err.println(exception);
}
} catch (ClassNotFoundException ex) {
// Application class not found - not on a Mac or not supported for some other reason. Fail silently.
}
}
private void initMacQuitHandler(Class applicationClass, Object application) throws IllegalArgumentException, IllegalAccessException, ClassNotFoundException, SecurityException, NoSuchMethodException, InvocationTargetException {
initMacHandler(applicationClass, application, "com.apple.eawt.QuitHandler", "setQuitHandler", new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("handleQuitRequestWith")) {
if (!arbilMenuBar.performCleanExit()) {
// Quit canceled. Tell MacOS...
if (args.length >= 2) {
// Second argument should be QuitResponse object
Object quitResponse = args[1];
Class quitResponseClass = Class.forName("com.apple.eawt.QuitResponse");
if (quitResponse.getClass().equals(quitResponseClass)) {
// Tell MacOS that quit should be canceled
quitResponseClass.getMethod("cancelQuit").invoke(quitResponse);
}
}
}
}
return null;
}
});
}
private void initMacAboutHandler(final ArbilWindowManager windowManager, Class applicationClass, Object application) throws IllegalArgumentException, IllegalAccessException, ClassNotFoundException, SecurityException, NoSuchMethodException, InvocationTargetException {
initMacHandler(applicationClass, application, "com.apple.eawt.AboutHandler", "setAboutHandler", new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
windowManager.openAboutPage();
return null;
}
});
}
/**
* Sets a MacOS application handler
* @param applicationClass Application class (com.apple.eawt.Application)
* @param application Application instance
* @param interfaceName Name of handler interface
* @param setMethodName Name of method on application that sets the handler
* @param invocationHandler Invocation handler that does the work for application handler
*/
private static void initMacHandler(Class applicationClass, Object application, String interfaceName, String setMethodName, InvocationHandler invocationHandler) throws IllegalArgumentException, IllegalAccessException, ClassNotFoundException, SecurityException, NoSuchMethodException, InvocationTargetException {
// Get class for named interface
Class handlerInterface = Class.forName(interfaceName);
// Create dynamic proxy using specified invocation handler
Object handler = Proxy.newProxyInstance(handlerInterface.getClassLoader(), new Class[]{handlerInterface}, invocationHandler);
// Set on specified application using specified method
applicationClass.getMethod(setMethodName, handlerInterface).invoke(application, handler);
}
} |
package com.nicoletfear.Robot2015;
import edu.wpi.first.wpilibj.*;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.CANTalon;
import java.util.Vector;
/**
* The RobotMap is a mapping from the ports sensors and actuators are wired into
* to a variable name. This provides flexibility changing wiring, makes checking
* the wiring easier and significantly reduces the number of magic numbers
* floating around.
*/
public class RobotMap {
//public static SpeedController dogMotor;
public static SpeedController dogMotor = new CANTalon(Subsystems.rioCheck.getPortNumber(12));
public static DigitalInput dogLimitSwitchTop;
public static void init() {
dogLimitSwitchTop = new DigitalInput(5);
CANTalon TalonTwelve = new CANTalon(12);
LiveWindow.addSensor("dog", "LimitSwitchTop", dogLimitSwitchTop);
// dogMotor = new Talon(0);
//LiveWindow.addActuator("dog", "Motor", (Talon) dogMotor);
}
// For example to map the left and right motors, you could define the
// following variables to use with your drivetrain subsystem.
// public static int leftMotor = 1;
// public static int rightMotor = 2;
// If you are using multiple modules, make sure to define both the port
// number and the module. For example you with a rangefinder:
// public static int rangefinderPort = 1;
// public static int rangefinderModule = 1;
public static final int pressureSwitchChannel = 1;
public static final int compressorRelayChannel = 8;
} |
package example;
//-*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
//@homepage@
import java.awt.*;
import java.awt.event.*;
import java.nio.charset.*;
//import java.util.Objects;
//import java.util.regex.*;
import javax.swing.*;
import javax.swing.text.*;
public final class MainPanel extends JPanel {
private static final Font FONT = new Font(Font.MONOSPACED, Font.PLAIN, 12);
private MainPanel() {
super(new GridLayout(4, 1, 0, 2));
JPasswordField pf1 = makePasswordField();
AbstractButton b1 = new JCheckBox("show passwords");
b1.addActionListener(e -> {
AbstractButton c = (AbstractButton) e.getSource();
pf1.setEchoChar(c.isSelected() ? '\u0000' : (Character) UIManager.get("PasswordField.echoChar"));
});
JPanel p1 = new JPanel(new BorderLayout());
p1.add(pf1);
p1.add(b1, BorderLayout.SOUTH);
add(makeTitlePanel(p1, "BorderLayout + JCheckBox"));
JPasswordField pf2 = makePasswordField();
//AbstractDocument doc = (AbstractDocument) pf2.getDocument();
//doc.setDocumentFilter(new ASCIIOnlyDocumentFilter());
AbstractButton b2 = new JToggleButton();
b2.addActionListener(e -> {
AbstractButton c = (AbstractButton) e.getSource();
pf2.setEchoChar(c.isSelected() ? '\u0000' : (Character) UIManager.get("PasswordField.echoChar"));
});
initEyeButton(b2);
JPanel p2 = makeOverlayLayoutPanel();
p2.add(b2);
p2.add(pf2);
add(makeTitlePanel(p2, "OverlayLayout + JToggleButton"));
JPasswordField pf3 = makePasswordField();
AbstractDocument doc = (AbstractDocument) pf3.getDocument();
JTextField tf3 = new JTextField(24);
tf3.setFont(FONT);
tf3.enableInputMethods(false);
tf3.setDocument(doc);
CardLayout cardLayout = new CardLayout();
JPanel p3 = new JPanel(cardLayout);
p3.setAlignmentX(Component.RIGHT_ALIGNMENT);
p3.add(pf3, PasswordField.HIDE.toString());
p3.add(tf3, PasswordField.SHOW.toString());
AbstractButton b3 = new JToggleButton();
b3.addActionListener(e -> {
AbstractButton c = (AbstractButton) e.getSource();
PasswordField s = c.isSelected() ? PasswordField.SHOW : PasswordField.HIDE;
cardLayout.show(p3, s.toString());
});
initEyeButton(b3);
JPanel pp3 = makeOverlayLayoutPanel();
pp3.add(b3);
pp3.add(p3);
add(makeTitlePanel(pp3, "CardLayout + JTextField(can copy) + ..."));
JPasswordField pf4 = makePasswordField();
AbstractButton b4 = new JButton();
b4.addMouseListener(new MouseAdapter() {
@Override public void mousePressed(MouseEvent e) {
pf4.setEchoChar('\u0000');
}
@Override public void mouseReleased(MouseEvent e) {
pf4.setEchoChar((Character) UIManager.get("PasswordField.echoChar"));
}
});
initEyeButton(b4);
JPanel p4 = makeOverlayLayoutPanel();
p4.add(b4);
p4.add(pf4);
add(makeTitlePanel(p4, "press and hold down the mouse button"));
setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 5));
setPreferredSize(new Dimension(320, 240));
}
private static void initEyeButton(AbstractButton b) {
b.setFocusable(false);
b.setOpaque(false);
b.setContentAreaFilled(false);
b.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 4));
b.setAlignmentX(Component.RIGHT_ALIGNMENT);
b.setAlignmentY(Component.CENTER_ALIGNMENT);
b.setIcon(new ColorIcon(Color.GREEN));
b.setRolloverIcon(new ColorIcon(Color.BLUE));
b.setSelectedIcon(new ColorIcon(Color.RED));
b.setRolloverSelectedIcon(new ColorIcon(Color.ORANGE));
b.setToolTipText("show/hide passwords");
}
private static JPanel makeOverlayLayoutPanel() {
JPanel p = new JPanel() {
@Override public boolean isOptimizedDrawingEnabled() {
return false;
}
};
p.setLayout(new OverlayLayout(p));
return p;
}
private static JPasswordField makePasswordField() {
JPasswordField pf = new JPasswordField(24);
pf.setText("abcdefghijklmn");
pf.setAlignmentX(Component.RIGHT_ALIGNMENT);
return pf;
}
private static JComponent makeTitlePanel(JComponent cmp, String title) {
JPanel p = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1d;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(5, 5, 5, 5);
p.add(cmp, c);
p.setBorder(BorderFactory.createTitledBorder(title));
return p;
}
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
enum PasswordField {
SHOW, HIDE;
}
// class ASCIIOnlyDocumentFilter extends DocumentFilter {
// //private static Pattern pattern = Pattern.compile("\\A\\p{ASCII}*\\z");
// private static CharsetEncoder asciiEncoder = Charset.forName("US-ASCII").newEncoder();
// @Override public void insertString(DocumentFilter.FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
// if (Objects.isNull(string)) {
// return;
// } else {
// replace(fb, offset, 0, string, attr);
// @Override public void remove(DocumentFilter.FilterBypass fb, int offset, int length) throws BadLocationException {
// replace(fb, offset, length, "", null);
// @Override public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
// Document doc = fb.getDocument();
// int currentLength = doc.getLength();
// String currentContent = doc.getText(0, currentLength);
// String before = currentContent.substring(0, offset);
// String after = currentContent.substring(length + offset, currentLength);
// String newValue = before + Objects.toString(text, "") + after;
// checkInput(newValue, offset);
// fb.replace(offset, length, text, attrs);
// //In Java, is it possible to check if a String is only ASCII? - Stack Overflow
// private static void checkInput(String proposedValue, int offset) throws BadLocationException {
// if (!proposedValue.isEmpty() && !asciiEncoder.canEncode(proposedValue)) {
// throw new BadLocationException(proposedValue, offset);
// // for (char c: proposedValue.toCharArray()) {
// // if (((int) c) > 127) {
// // throw new BadLocationException(proposedValue, offset);
// // //if (!proposedValue.isEmpty() && !proposedValue.chars().allMatch(c -> c < 128)) { //JDK 8
// // Matcher m = pattern.matcher(proposedValue);
// // if (!proposedValue.isEmpty() && !m.find()) {
// // throw new BadLocationException(proposedValue, offset);
class ColorIcon implements Icon {
private final Dimension d = new Dimension(12, 12);
private final Color color;
protected ColorIcon(Color color) {
this.color = color;
}
@Override public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2 = (Graphics2D) g.create();
g2.translate(x, y);
g2.setPaint(color);
g2.fillRect(1, 1, d.width - 1, d.height - 1);
g2.dispose();
}
@Override public int getIconWidth() {
return d.width;
}
@Override public int getIconHeight() {
return d.height;
}
} |
package ifc.container;
import com.sun.star.uno.XInterface;
import lib.MultiMethodTest;
import com.sun.star.container.XIndexAccess;
import com.sun.star.lang.IndexOutOfBoundsException;
import com.sun.star.lang.WrappedTargetException;
/**
* Testing <code>com.sun.star.container.XIndexAccess</code>
* interface methods :
* <ul>
* <li><code> getCount()</code></li>
* <li><code> getByIndex()</code></li>
* </ul> <p>
* Test seems to work properly in multithreaded environment.
* @see com.sun.star.container.XIndexAccess
*/
public class _XIndexAccess extends MultiMethodTest {
public XIndexAccess oObj = null;
/**
* Number of elements in the container.
*/
public int count = 0;
/**
* Get number of element in the container. <p>
* Has <b> OK </b> status if method returns number lager than -1.
*/
public void _getCount() {
boolean result = true;
log.println("getting the number of the elements");
// hope we haven't a count lower than zerro ;-)
count = -1;
count = oObj.getCount();
result = (count != -1);
tRes.tested("getCount()", result);
} //end getCount()
/**
* This method tests the IndexAccess from the first element,
* the middle element and the last element. Finaly it test
* Exceptions which throws by a not available index. <p>
* Has <b> OK </b> status if first, middle and last elements
* successfully returned and has non null value; and if on
* invalid index parameter <code>IndexOutOfBoundException</code>
* is thrown.<p>
* The following method tests are to be completed successfully before :
* <ul>
* <li> <code> getCount() </code> : to have number of elements
* in container. </li>
* </ul>
*/
public void _getByIndex() {
requiredMethod("getCount()");
// get count from holder
try {
Thread.sleep(200);
}
catch(java.lang.InterruptedException e) {}
boolean result = true;
boolean loc_result = true;
Object o = null;
log.println("Testing getByIndex()");
if (count > 0) {
// Check the first element
log.println("Check the first element");
result &= checkGetByIndex(0);
// Check the middle element
log.println("Check the middle element");
result &= checkGetByIndex(count /2);
// Check the last element
log.println("Check the last element");
result &= checkGetByIndex(count -1);
// Testing getByIndex with wrong params.
log.println("Testing getByIndex with wrong params.");
try {
log.println("getByIndex(" + count + ")");
loc_result = oObj.getByIndex(count) == null;
log.println("no exception thrown - FAILED");
result = false;
} catch (IndexOutOfBoundsException e) {
log.println("Expected exception cought! " + e + " OK");
} catch (WrappedTargetException e) {
log.println("Wrong exception! " + e + " FAILED");
result = false;
}
}
tRes.tested("getByIndex()", result);
} // end getByIndex
private boolean checkGetByIndex(int index){
Object o = null;
boolean result = true;
try {
log.println("getByIndex(" + index + ")");
o = oObj.getByIndex(index);
if ( tEnv.getObjRelation("XIndexAccess.getByIndex.mustBeNull") != null){
result = (o == null);
if (result) log.println("OK"); else log.println("FAILED -> not null");
} else {
result = (o != null);
if (result) log.println("OK"); else log.println("FAILED -> null");
}
} catch (WrappedTargetException e) {
log.println("Exception! " + e);
result = false;
} catch (IndexOutOfBoundsException e) {
log.println("Exception! " + e);
result = false;
}
return result;
}
} // end XIndexAccess |
package org.kaazing.test.util;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.concurrent.TimeUnit;
import org.junit.rules.DisableOnDebug;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.rules.Timeout;
import org.kaazing.k3po.junit.rules.K3poRule;
public final class ITUtil {
/**
* Creates a rule (chain) out of a k3po rule and gateway rule, adding extra rules as follows:<ol>
* <li> a timeout rule to have tests time out if they run for more than 10 seconds
* <li> a rule to print console messages at the start and end of each test method and print trace level
* log messages on test failure.
* </ol>
* @param gateway Rule to start up and shut down the gateway
* @param robot Rule to startup and stop k3po
* @return A TestRule which should be the only public @Rule in our robot tests
*/
public static RuleChain createRuleChain(TestRule gateway, K3poRule robot) {
return createRuleChain(gateway, robot, 10, SECONDS);
}
/**
* Creates a rule (chain) out of a k3po rule and gateway rule, adding extra rules as follows:<ol>
* <li> a timeout rule
* <li> a rule to print console messages at the start and end of each test method and print trace level
* log messages on test failure.
* </ol>
* @param gateway Rule to start up and shut down the gateway (or acceptor or etc)
* @param robot Rule to startup and stop k3po
* @param timeout The maximum allowed time duration of each test (including Gateway and robot startup and shutdown)
* @param timeUnit The unit for the timeout
* @return A TestRule which should be the only public @Rule in our robot tests
*/
public static RuleChain createRuleChain(TestRule gateway, K3poRule robot, long timeout, TimeUnit timeUnit) {
return createRuleChain(robot, timeout, timeUnit).around(gateway);
}
/**
* Creates a rule (chain) out of a k3po or other rule, adding extra rules as follows:<ol>
* <li> a timeout rule
* <li> a rule to print console messages at the start and end of each test method and print trace level
* log messages on test failure.
* </ol>
* @param rule Rule to startup and stop k3po
* @param timeout The maximum allowed time duration of each test (including Gateway and robot startup and shutdown)
* @param timeUnit The unit for the timeout
* @return A TestRule which should be the only public @Rule in our robot tests
*/
public static RuleChain createRuleChain(TestRule rule, long timeout, TimeUnit timeUnit) {
return createRuleChain(timeout, timeUnit).around(rule);
}
/**
* Creates a rule chain containing the following rules:<ol>
* <li> a timeout rule
* <li> a rule to print console messages at the start and end of each test method and print trace level
* log messages on test failure.
* </ol>
* @param timeout The maximum allowed time duration of the test
* @param timeUnit The unit for the timeout
* @return
*/
public static RuleChain createRuleChain(long timeout, TimeUnit timeUnit) {
TestRule timeoutRule = new DisableOnDebug(Timeout.builder().withTimeout(timeout, timeUnit)
.withLookingForStuckThread(true).build());
TestRule trace = new MethodExecutionTrace();
return RuleChain.outerRule(trace).around(timeoutRule);
}
private ITUtil() {
}
} |
package start;
import model.Proof;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
public class ExportLatex {
private static final HashMap<Character, String> unicodeToLaTeX;
static {
unicodeToLaTeX = new HashMap<Character, String>();
unicodeToLaTeX.put('∧', "\\land ");
unicodeToLaTeX.put('∨', "\\lor ");
unicodeToLaTeX.put('¬', "\\neg ");
unicodeToLaTeX.put('→', "\\to ");
unicodeToLaTeX.put('∃', "\\exists ");
unicodeToLaTeX.put('∀', "\\forall ");
unicodeToLaTeX.put('⊥', "\\bot ");
unicodeToLaTeX.put('₀', "0");
unicodeToLaTeX.put('₁', "1");
unicodeToLaTeX.put('₂', "2");
unicodeToLaTeX.put('₃', "3");
unicodeToLaTeX.put('₄', "4");
unicodeToLaTeX.put('₅', "5");
unicodeToLaTeX.put('₆', "6");
unicodeToLaTeX.put('₇', "7");
unicodeToLaTeX.put('₈', "8");
unicodeToLaTeX.put('₈', "9");
}
public static void export(Proof proof, String file) throws IOException {
String[] lines = proof.getProofString().split("\\r?\\n");
String output = "% For use with https:
output += "% Note that ending a box in a box is not valid and will not give the desired results.\n";
int maxDepth = -1;
int curDepth = 1;
for (String line : lines) {
String[] info = line.split("::");
int depth = Integer.parseInt(info[0]);
if (maxDepth < depth) {
maxDepth = depth;
}
if (curDepth == depth && Integer.parseInt(info[4])==1) { // Edge case same depth box after box
// Need to remove backslashes and both end and start a new environment
output = trimEnd(output);
output += "\\end{subproof}\n";
output += "\\begin{subproof}\n";
} else if (curDepth < depth) { // Regular depth increase
output += "\\begin{subproof}\n";
++curDepth;
} else while (curDepth > depth) {
output = trimEnd(output);
output += "\\end{subproof}\n";
--curDepth;
}
output += attachIndex(replaceAllUnicode(info[1])).replaceAll("null", "");
// Everything before the &, is in a math environment.
output += "&";
// We surround the crucial part in $ in the rule and references.
output += replaceAllUnicode(info[2]).replaceAll(
"(\\\\land |\\\\lor |\\\\to |\\\\forall |\\\\exists |\\\\bot |\\\\neg )(i|e)(_\\{(\\d)\\})?","\\$$1\\\\mathrm\\{$2\\}$3\\$").replaceAll("null", "");
output += "\\\\\n";
}
while (curDepth > 1) {
output = trimEnd(output);
output += "\\end{subproof}\n";
--curDepth;
}
output = trimEnd(output);
output = "\\begin{logicproof}{" + maxDepth + "}\n" + output + "\\end{logicproof}";
Files.write(Paths.get(file), output.getBytes());
}
private static String attachIndex(String s) {
return s.replaceAll("(\\d+)","_\\{$1\\}");
}
private static String replaceAllUnicode(String s) {
String ret = "";
for (int i = 0; i < s.length(); i++) {
String next = unicodeToLaTeX.getOrDefault(s.charAt(i), null);
if (next == null)
ret += s.charAt(i);
else
ret += next;
}
return ret;
}
private static String trimEnd(String s) {
if (s.endsWith("\\\\\n")) // Might need \r for cross platform
return s.substring(0, s.length() - 3) + '\n';
return s;
}
} |
package org.jgrapes.net;
import java.io.IOException;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayDeque;
import java.util.HashSet;
import java.util.Queue;
import java.util.Set;
import org.jgrapes.core.Channel;
import org.jgrapes.core.Component;
import org.jgrapes.core.Components;
import org.jgrapes.core.EventPipeline;
import org.jgrapes.core.NamedChannel;
import org.jgrapes.core.Self;
import org.jgrapes.core.annotation.Handler;
import org.jgrapes.core.events.Error;
import org.jgrapes.core.events.Start;
import org.jgrapes.core.events.Stop;
import org.jgrapes.core.internal.Common;
import org.jgrapes.io.IOSubchannel;
import org.jgrapes.io.NioHandler;
import org.jgrapes.io.events.Close;
import org.jgrapes.io.events.Closed;
import org.jgrapes.io.events.IOError;
import org.jgrapes.io.events.Input;
import org.jgrapes.io.events.NioRegistration;
import org.jgrapes.io.events.NioRegistration.Registration;
import org.jgrapes.io.events.Output;
import org.jgrapes.io.util.ManagedBufferQueue;
import org.jgrapes.io.util.ManagedByteBuffer;
import org.jgrapes.net.events.Accepted;
import org.jgrapes.net.events.Ready;
/**
* Provides a TCP server. The server binds to the given address. If the
* address is {@code null}, address and port are automatically assigned.
* <P>
* The end of record flag is not used by the server.
*
* @author Michael N. Lipp
*/
public class TcpServer extends Component implements NioHandler {
public static final NamedChannel
DEFAULT_CHANNEL = new NamedChannel("server");
private SocketAddress serverAddress;
private ServerSocketChannel serverSocketChannel;
private int bufferSize;
private Set<Connection> connections = new HashSet<>();
private boolean closing = false;
/**
* Creates a new server listening on the given address.
* The channel is set to the {@link NamedChannel} "server". The size of
* the send and receive buffers is set to the platform defaults.
*
* @param serverAddress the address to bind to
*/
public TcpServer(SocketAddress serverAddress) {
this(DEFAULT_CHANNEL, serverAddress);
}
/**
* Creates a new server using the given channel and address.
*
* @param componentChannel the component's channel
* @param serverAddress the address to bind to
*/
public TcpServer(Channel componentChannel, SocketAddress serverAddress) {
this(componentChannel, serverAddress, 0);
}
/**
* Creates a new server listening on the given address.
* The channel is set to the {@link NamedChannel} "server".
*
* @param serverAddress the address to bind to
* @param bufferSize the size to use for the send and receive buffers
*/
public TcpServer(SocketAddress serverAddress, int bufferSize) {
this(DEFAULT_CHANNEL, serverAddress, bufferSize);
}
/**
* Creates a new server using the given channel and address.
*
* @param componentChannel the component's channel
* @param serverAddress the address to bind to
* @param bufferSize the size to use for the send and receive buffers
*/
public TcpServer(Channel componentChannel,
SocketAddress serverAddress, int bufferSize) {
super(componentChannel);
this.serverAddress = serverAddress;
this.bufferSize = bufferSize;
}
/**
* Starts the server.
*
* @param event the start event
* @throws IOException if an I/O exception occurred
*/
@Handler
public void onStart(Start event) throws IOException {
closing = false;
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(serverAddress);
fire(new NioRegistration(this, serverSocketChannel,
SelectionKey.OP_ACCEPT, this), Channel.BROADCAST);
}
@Handler(channels=Self.class)
public void onRegistered(NioRegistration.Completed event)
throws InterruptedException, IOException {
NioHandler handler = event.event().handler();
if (handler == this) {
if (event.event().get() == null) {
fire(new Error(event,
"Registration failed, no NioDispatcher?"));
return;
}
fire(new Ready(serverSocketChannel.getLocalAddress()));
return;
}
if (handler instanceof Connection) {
((Connection)handler)
.registrationComplete(event.event());
}
}
/* (non-Javadoc)
* @see org.jgrapes.io.NioSelectable#handleOps(int)
*/
@Override
public void handleOps(int ops) {
synchronized (connections) {
if ((ops & SelectionKey.OP_ACCEPT) != 0 && !closing) {
try {
SocketChannel socketChannel = serverSocketChannel.accept();
connections.add(new Connection(socketChannel));
} catch (IOException e) {
fire(new IOError(null, e));
}
}
}
}
/**
* Writes the data passed in the event to the client. The end of record
* flag is ignored.
*
* @param event the event
* @throws IOException if an error occurs
*/
@Handler
public void onOutput(Output<ManagedByteBuffer> event) throws IOException {
for (Connection connection: event.channels(Connection.class)) {
if (connections.contains(connection)) {
connection.write(event);
}
}
}
/**
* Shuts down the server or one of the connections to the server
*
* @param event the event
* @throws IOException if an I/O exception occurred
* @throws InterruptedException if the execution was interrupted
*/
@Handler
public void onClose(Close event) throws IOException, InterruptedException {
boolean subOnly = true;
for (Channel channel: event.channels()) {
if (channel instanceof Connection) {
if (connections.contains(channel)) {
((Connection)channel).close();
}
} else {
subOnly = false;
}
}
if (subOnly || !serverSocketChannel.isOpen()) {
return;
}
synchronized (connections) {
closing = true;
// Copy to avoid concurrent modification exception
Set<Connection> conns = new HashSet<>(connections);
for (Connection conn : conns) {
conn.close();
}
while (connections.size() > 0) {
connections.wait();
}
}
serverSocketChannel.close();
closing = false;
fire(new Closed());
}
/**
* Shuts down the server.
*
* @param event the event
*/
@Handler
public void onStop(Stop event) {
if (closing || !serverSocketChannel.isOpen()) {
return;
}
newSyncEventPipeline().fire(new Close(), channel());
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return Components.objectName(this);
}
/**
* The internal representation of a connected client.
*
* @author Michael N. Lipp
*
*/
public class Connection implements NioHandler, IOSubchannel {
private SocketChannel nioChannel;
private EventPipeline downPipeline;
private EventPipeline upPipeline;
private ManagedBufferQueue<ManagedByteBuffer, ByteBuffer> readBuffers;
private ManagedBufferQueue<ManagedByteBuffer, ByteBuffer> writeBuffers;
private Registration registration = null;
private Queue<ManagedByteBuffer> pendingWrites = new ArrayDeque<>();
private boolean pendingClose = false;
/**
* @param nioChannel the channel
* @throws SocketException if an error occurred
*/
public Connection(SocketChannel nioChannel) throws SocketException {
this.nioChannel = nioChannel;
downPipeline = newEventPipeline();
upPipeline = newEventPipeline();
int writeBufferSize = bufferSize == 0
? nioChannel.socket().getSendBufferSize() : bufferSize;
writeBuffers = new ManagedBufferQueue<>(ManagedByteBuffer.class,
ByteBuffer.allocate(writeBufferSize),
ByteBuffer.allocate(writeBufferSize));
int readBufferSize = bufferSize == 0
? nioChannel.socket().getReceiveBufferSize() : bufferSize;
readBuffers = new ManagedBufferQueue<>(ManagedByteBuffer.class,
ByteBuffer.allocate(readBufferSize),
ByteBuffer.allocate(readBufferSize));
// Register with dispatcher
TcpServer.this.fire(
new NioRegistration(this, nioChannel, 0, TcpServer.this),
Channel.BROADCAST);
}
/* (non-Javadoc)
* @see org.jgrapes.io.IOSubchannel#getMainChannel()
*/
@Override
public Channel mainChannel() {
return TcpServer.this.channel();
}
/* (non-Javadoc)
* @see org.jgrapes.io.Connection#bufferPool()
*/
@Override
public ManagedBufferQueue<ManagedByteBuffer, ByteBuffer> bufferPool() {
return writeBuffers;
}
/* (non-Javadoc)
* @see org.jgrapes.io.DataConnection#getPipeline()
*/
@Override
public EventPipeline responsePipeline() {
return upPipeline;
}
/**
* Invoked when registration has completed.
*
* @param event the completed event
* @throws InterruptedException if the execution was interrupted
* @throws IOException if an I/O error occurred
*/
public void registrationComplete(NioRegistration event)
throws InterruptedException, IOException {
registration = event.get();
downPipeline.fire(new Accepted(nioChannel.getLocalAddress(),
nioChannel.getRemoteAddress()), this);
registration.updateInterested(SelectionKey.OP_READ);
}
/**
* Write the data on this connection.
*
* @param event the event
* @throws IOException if an error occurred
*/
public void write(Output<ManagedByteBuffer> event) throws IOException {
if (!nioChannel.isOpen()) {
return;
}
ManagedByteBuffer buffer = event.buffer();
synchronized(pendingWrites) {
if (!pendingWrites.isEmpty()) {
buffer.lockBuffer();
pendingWrites.add(buffer);
return;
}
}
nioChannel.write(buffer.backingBuffer());
if (!buffer.hasRemaining()) {
buffer.clear();
return;
}
synchronized(pendingWrites) {
buffer.lockBuffer();
pendingWrites.add(buffer);
if (pendingWrites.size() == 1) {
registration.updateInterested(
SelectionKey.OP_READ | SelectionKey.OP_WRITE);
}
}
}
@Override
public void handleOps(int ops) {
try {
if ((ops & SelectionKey.OP_READ) != 0) {
handleReadOp();
}
if ((ops & SelectionKey.OP_WRITE) != 0) {
handleWriteOp();
}
} catch (InterruptedException | IOException e) {
downPipeline.fire(new IOError(null, e));
}
}
/**
* Gets a buffer from the pool and reads available data into it.
* Sends the result as event.
*
* @throws InterruptedException
* @throws IOException
*/
private void handleReadOp() throws InterruptedException, IOException {
ManagedByteBuffer buffer;
buffer = readBuffers.acquire();
int bytes = nioChannel.read(buffer.backingBuffer());
if (bytes == 0) {
buffer.unlockBuffer();
return;
}
if (bytes > 0) {
buffer.flip();
downPipeline.fire(
new Input<ManagedByteBuffer>(buffer, false), this);
return;
}
// EOF (-1) from client
synchronized (nioChannel) {
if (nioChannel.socket().isOutputShutdown()) {
// Client confirms our close, complete close
nioChannel.close();
return;
}
}
// Client initiates close
removeConnection();
synchronized (pendingWrites) {
synchronized (nioChannel) {
if (!pendingWrites.isEmpty()) {
// Pending writes, delay close
pendingClose = true;
// Mark as client initiated close
nioChannel.shutdownInput();
return;
}
// Nothing left to do, close
nioChannel.close();
}
}
}
/**
* Checks if there is still data to be written. This may be
* a left over in an incompletely written buffer or a complete
* pending buffer.
*
* @throws IOException
* @throws InterruptedException
*/
private void handleWriteOp()
throws IOException, InterruptedException {
while (true) {
ManagedByteBuffer head = null;
synchronized (pendingWrites) {
if (pendingWrites.isEmpty()) {
// Nothing left to write, stop getting ops
registration.updateInterested(
SelectionKey.OP_READ);
// Was the connection closed while we were writing?
if (pendingClose) {
synchronized (nioChannel) {
if (nioChannel.socket().isInputShutdown()) {
// Delayed close from client, complete
nioChannel.close();
} else {
// Delayed close from server, initiate
nioChannel.shutdownOutput();
}
}
pendingClose = false;
}
break; // Nothing left to do
}
head = pendingWrites.peek();
if (!head.hasRemaining()) {
// Nothing left in head buffer, try next
head.clear();
head.unlockBuffer();
pendingWrites.remove();
continue;
}
}
nioChannel.write(head.backingBuffer()); // write...
break; // ... and wait for next op
}
}
/**
* Closes this connection.
*
* @throws IOException if an error occurs
* @throws InterruptedException if the execution was interrupted
*/
public void close() throws IOException, InterruptedException {
removeConnection();
synchronized (pendingWrites) {
if (!pendingWrites.isEmpty()) {
// Pending writes, delay close until done
pendingClose = true;
return;
}
// Nothing left to do, proceed
synchronized (nioChannel) {
if (nioChannel.isOpen()) {
// Initiate close, must be confirmed by client
nioChannel.shutdownOutput();
}
}
}
}
private void removeConnection() throws InterruptedException {
synchronized (connections) {
if(!connections.remove(this)) {
// Closed already
return;
}
// In case the server is shutting down
connections.notifyAll();
}
Closed evt = new Closed();
downPipeline.fire(evt, this);
evt.get();
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(Components.objectName(this));
builder.append("(");
builder.append(Common.channelToString(mainChannel()));
builder.append(")");
return builder.toString();
}
}
} |
package com.gallatinsystems.surveyal.dao;
import com.gallatinsystems.common.Constants;
import com.gallatinsystems.survey.dao.QuestionDao;
import com.gallatinsystems.survey.dao.QuestionGroupDao;
import com.gallatinsystems.survey.dao.SurveyDAO;
import com.gallatinsystems.survey.dao.SurveyGroupDAO;
import com.gallatinsystems.survey.dao.SurveyUtils;
import com.gallatinsystems.survey.domain.Question;
import com.gallatinsystems.survey.domain.QuestionGroup;
import com.gallatinsystems.survey.domain.Survey;
import com.gallatinsystems.survey.domain.SurveyGroup;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import org.akvo.flow.api.app.DataStoreTestUtil;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.BeanUtils;
import org.waterforpeople.mapping.app.gwt.client.survey.SurveyDto;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class SurveyUtilsTest {
private final LocalServiceTestHelper helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
private DataStoreTestUtil dataStoreTestUtil;
@BeforeEach
public void setUp() {
helper.setUp();
dataStoreTestUtil = new DataStoreTestUtil();
}
@AfterEach
public void tearDown() {
helper.tearDown();
}
@Test
public void testCopyTemplateSurvey() throws Exception {
Survey sourceSurvey = createSurvey();
Survey copiedSurvey = copySurvey(sourceSurvey);
SurveyUtils.copySurvey(copiedSurvey.getKey().getId(), sourceSurvey.getKey().getId(), true);
List<QuestionGroup> qgs = new QuestionGroupDao().listQuestionGroupBySurvey(copiedSurvey.getKey().getId());
assertEquals(1, qgs.size());
assertTrue(qgs.get(0).getImmutable());
List<Question> questions = new QuestionDao().listQuestionsBySurvey(copiedSurvey.getKey().getId());
assertEquals(1, questions.size());
assertTrue(questions.get(0).getImmutable());
}
private Survey copySurvey(Survey sourceSurvey) {
SurveyDto dto = new SurveyDto();
dto.setName(sourceSurvey.getName());
dto.setSurveyGroupId(sourceSurvey.getSurveyGroupId());
final Survey tmp = new Survey();
BeanUtils.copyProperties(sourceSurvey, tmp, Constants.EXCLUDED_PROPERTIES);
tmp.setName(dto.getName());
tmp.setSurveyGroupId(dto.getSurveyGroupId());
return new SurveyDAO().save(tmp);
}
private Survey createSurvey() {
SurveyGroup sg = new SurveyGroup();
SurveyGroup newSg = new SurveyGroupDAO().save(sg);
Survey survey = new Survey();
survey.setName("Simple survey");
survey.setSurveyGroupId(newSg.getKey().getId());
Survey newSurvey = new SurveyDAO().save(survey);
QuestionGroup qg = new QuestionGroup();
qg.setName("quesitongroup");
qg.setSurveyId(newSurvey.getKey().getId());
QuestionGroup newQg = new QuestionGroupDao().save(qg);
Question q = new Question();
q.setType(Question.Type.FREE_TEXT);
q.setQuestionGroupId(newQg.getKey().getId());
q.setSurveyId(newSurvey.getKey().getId());
new QuestionDao().save(q);
return newSurvey;
}
} |
package de.uka.ipd.sdq.beagle.gui;
import de.uka.ipd.sdq.beagle.core.facade.BeagleConfiguration;
import de.uka.ipd.sdq.beagle.core.facade.BeagleController;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.progress.UIJob;
import java.awt.event.ActionListener;
import java.lang.Thread.UncaughtExceptionHandler;
/*
* This class is involved in creating a Graphical User Interface. Its funtionality cannot
* reasonably be tested by automated unit tests.
*
* COVERAGE:OFF
*/
/**
* Controls the Graphical User Interface (GUI). One {@code GuiController} corresponds to
* exactly one instance of the GUI. Opening it several times is not possible. Note that
* it's possible for a GUI instance to exist while not being open.
*
* @author Christoph Michelbach
* @author Roman Langrehr
*/
public class GuiController {
private enum GuiControllerState {
unopened, wizardOpen, dialogOpen, terminated
};
private GuiControllerState state;
/**
* {@code true} if the wizard finished successfully (user pressed "finish"};
* {@code false} otherwise.
*/
private boolean wizardFinishedSuccessfully;
/**
* The shell the GUI plugin will use.
*/
private final Shell shell;
/**
* The {@link BeagleConfiguration} this {@link GuiController} and therefore everything
* linked to it uses.
*/
private final BeagleConfiguration beagleConfiguration;
private BeagleAnalysisWizard beagleAnalysisWizard;
/**
* Is used to display the actions "pause", "continue", and "abort" to the user. These
* actions are regarding the analysis.
*/
private MessageDialog messageDialog;
/**
* The {@link BeagleController} connected to this GUI.
*/
private BeagleController beagleController;
/**
* Constructs a new {@link GuiController} using {@code components} as the default
* components to be measured.
*
* @param beagleConfiguration The {@link BeagleConfiguration} to use.
*/
public GuiController(final BeagleConfiguration beagleConfiguration) {
this.beagleConfiguration = beagleConfiguration;
this.state = GuiControllerState.unopened;
this.shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
}
/**
* Opens the GUI, meaning that from the point of time this method is called, the user
* can see and interact with it. Calls after the first call of this function (per
* {@link GuiController} object) are ignored. Returns after the user closed the
* wizard. This includes finished the wizard as well as aborting it in any way.
*/
public void open() {
this.engageWizard();
}
private void engageWizard() {
this.wizardFinishedSuccessfully = false;
if (this.state == GuiControllerState.unopened) {
this.state = GuiControllerState.wizardOpen;
final ActionListener wizardFinished = event -> {
GuiController.this.beagleController = new BeagleController(GuiController.this.beagleConfiguration);
GuiController.this.wizardFinishedSuccessfully = true;
};
this.beagleAnalysisWizard = new BeagleAnalysisWizard(this.beagleConfiguration, wizardFinished);
final WizardDialog wizardDialog = new WizardDialog(this.shell, this.beagleAnalysisWizard);
this.state = GuiControllerState.wizardOpen;
wizardDialog.open();
if (this.wizardFinishedSuccessfully) {
// If the wizard finished successfully, indicate to the user that the
// analysis will start ...
this.state = GuiControllerState.dialogOpen;
// ... and let it actually start.
this.startAnalysis();
this.engageDialog();
} else {
this.state = GuiControllerState.terminated;
}
}
}
/**
* Opens up the dialog displaying the actions "pause", "continue", and "abort" to the
* user. These actions are regarding the analysis.
*/
private void engageDialog() {
final String dialogTitleRunning = "Beagle Analysis is Running";
final String dialogMessageRunning = "Beagle Analysis is running.";
final String[] buttonLabelsRunning = {
"Abort", "Pause"
};
final String dialogTitlePaused = "Beagle Analysis is Paused";
final String dialogMessagePaused = "Beagle Analysis is paused.";
final String[] buttonLabelsPaused = {
"Abort", "Continue"
};
boolean analysisRunning = false;
// equals a click on button "Continue" (continuing and starting the analysis
// always have the same behaviour regarding the dialog)
int buttonClick = 1;
while (buttonClick != 0) {
switch (buttonClick) {
case 1:
if (analysisRunning) {
// analysis is being paused by the user
analysisRunning = false;
GuiController.this.beagleController.pauseAnalysis();
this.messageDialog = new MessageDialog(this.shell, dialogTitlePaused, null, dialogMessagePaused,
MessageDialog.INFORMATION, buttonLabelsPaused, 0);
} else {
// analysis is being continued by the user
analysisRunning = true;
GuiController.this.beagleController.continueAnalysis();
this.messageDialog = new MessageDialog(this.shell, dialogTitleRunning, null,
dialogMessageRunning, MessageDialog.INFORMATION, buttonLabelsRunning, 0);
}
break;
default:
// what is done when no button has been clicked but the dialog has
// been closed in any different way
// just open the dialog again, so do nothing here
break;
}
buttonClick = this.messageDialog.open();
}
}
/**
* Calls {@link BeagleController} to start the analysis. This happens in a different
* thread so the GUI remains responsive.
*/
private void startAnalysis() {
final UncaughtExceptionHandler uncaughtExceptionHandler = Thread.currentThread().getUncaughtExceptionHandler();
/*
* Calls {@link BeagleController} to start the analysis. This happens in a
* different thread so the GUI remains responsive.
*/
new Thread(new Runnable() {
@Override
public void run() {
GuiController.this.guiJob(uncaughtExceptionHandler);
}
}).start();
}
/**
* Runs the tasks that should be done asynchrony to the GUI progress dialog.
*
* @param uncaughtExceptionHandler The {@link UncaughtExceptionHandler} to notify,
* when an exception occurs.
*/
private void guiJob(final UncaughtExceptionHandler uncaughtExceptionHandler) {
try {
GuiController.this.beagleController.startAnalysis();
} catch (final Exception exception) {
uncaughtExceptionHandler.uncaughtException(Thread.currentThread(), exception);
new UIJob(Display.getDefault(), "Close Beagle Dialog") {
@Override
public IStatus runInUIThread(final IProgressMonitor monitor) {
GuiController.this.messageDialog.close();
return Status.OK_STATUS;
}
}.schedule();
}
// when {@code beagleController.startAnalysis()} returns, close the
// dialog
GuiController.this.state = GuiControllerState.terminated;
new UIJob(Display.getDefault(), "Close Beagle Dialog") {
@Override
public IStatus runInUIThread(final IProgressMonitor monitor) {
GuiController.this.messageDialog.close();
return Status.OK_STATUS;
}
}.schedule();
}
} |
package layout;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import com.example.miss.temp.R;
import java.util.ArrayList;
import java.util.List;
import models.Category;
/**
* A simple {@link Fragment} subclass.
*/
public class AddNewWord extends Fragment {
private String[] categoriesNames;
private List<Category> categories;
private ArrayAdapter<String> spinnerAdapter;
public int pos;
Spinner categoryName;
public AddNewWord() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_add_new_word, container, false);
// this is only for reference how to get the id of a drawable resource by name;
// Button objectBtn = (Button) view.findViewById(R.id.object_btn);
// int backgroundReId = Utils.getResId("animal_category");
// objectBtn.setBackgroundResource(backgroundReId);
Bundle args = this.getArguments();
categories = new ArrayList<Category>((List<Category>) args.getSerializable("categories_array"));
categoryName = (Spinner) view.findViewById(R.id.category_spinner);
categoryName.setSelection(pos);
categoriesNames = new String[categories.size() + 1];
categoriesNames[0] = "Choose category";
for (int i = 0; i < categories.size(); i++) {
categoriesNames[i + 1] = categories.get(i).getName();
}
spinnerAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, categoriesNames);
categoryName.setOnItemSelectedListener(new CustomOnItemSelectedListener());
categoryName.setAdapter(spinnerAdapter);
return view;
}
public class CustomOnItemSelectedListener implements AdapterView.OnItemSelectedListener {
@Override
public void onItemSelected (AdapterView<?> main, View view, int position,
long Id) {
if(position > 0){
// Toast.makeText(getContext(), position,
// Toast.LENGTH_SHORT).show();
}else{
// Toast.makeText(getContext(), "Select category",
// Toast.LENGTH_SHORT).show();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// Toast.makeText(getContext(), "Select category (on nothing selected)",
// Toast.LENGTH_SHORT).show();
}
}
} |
package cx2x.decompiler;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import xcodeml.util.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
/**
* Wrapper class to call the Fortran decompiler of OMNI Compiler directly
* from Java instead of calling it as a separated program.
*
* @author clementval
*/
public class FortranDecompiler {
private BufferedReader _reader;
private XmToolFactory _toolFactory;
/**
* Constructs a new FortranDecompiler object.
*
* @throws XmException If instantiation of the XmToolFactory fails.
*/
public FortranDecompiler()
throws XmException
{
_toolFactory = new XmToolFactory("F");
}
private boolean openXcodeMLFile(String inputFilepath)
{
if(_reader != null) {
try {
_reader.close();
} catch(IOException e) {
e.printStackTrace();
return false;
}
}
try {
_reader = new BufferedReader(new FileReader(inputFilepath));
return true;
} catch(IOException e) {
return false;
}
}
/**
* Decompile the XcodeML file into Fortran code.
*
* @param outputFilepath Fortran output file path.
* @param inputFilepath XcodeML input file path.
* @param maxColumns Maximum number of column for the output file.
* @param lineDirectives If true, preprocessor line directives are added.
* @return True if the decompilation succeeded. False otherwise.
*/
public boolean decompile(String outputFilepath, String inputFilepath,
int maxColumns, boolean lineDirectives)
{
if(!lineDirectives) {
XmOption.setIsSuppressLineDirective(true);
}
XmOption.setCoarrayNoUseStatement(true);
XmOption.setDebugOutput(false);
if(!openXcodeMLFile(inputFilepath)) {
return false;
}
PrintWriter writer = null;
try {
writer = new PrintWriter(new BufferedWriter(new FileWriter(outputFilepath)));
} catch(IOException e) {
e.printStackTrace();
}
try {
XmDecompiler decompiler = _toolFactory.createDecompiler();
XmDecompilerContext context = _toolFactory.createDecompilerContext();
if(maxColumns > 0) {
context.setProperty(XmDecompilerContext.KEY_MAX_COLUMNS, "" + maxColumns);
}
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = docFactory.newDocumentBuilder();
Document xcodeDoc;
xcodeDoc = builder.parse(inputFilepath);
decompiler.decompile(context, xcodeDoc, writer);
} catch(ParserConfigurationException | SAXException | IOException e) {
return false;
}
if(writer != null) {
writer.flush();
} else {
return false;
}
return true;
} catch(Exception ex) {
if(_reader != null) {
try {
_reader.close();
} catch(IOException ignored) {
}
}
if(writer != null) {
writer.close();
}
}
return false;
}
} |
package info.xiaomo.redis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableAutoConfiguration
@ComponentScan("info.xiaomo")
@EnableCaching
@EnableScheduling
public class RedisMain {
public static void main(String[] args) throws Exception {
SpringApplication.run(RedisMain.class, args);
}
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
return new RedisCacheManager(redisTemplate);
}
} |
// Main Game Panel
package ui;
import javax.swing.SwingConstants;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javafx.scene.media.AudioClip;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.event.MouseEvent;
import input.Mouse;
import input.Keyboard;
import input.Key;
import utils.SoundUtils;
import utils.GameUtils;
import game.SaveFile;
import game.LevelResources;
import game.GameElement;
import game.gameelement.GameBackground;
import game.gameelement.GameScore;
import ui.AdBlockerFrame;
public class GamePanel extends JPanel implements Mouse.Listener, Keyboard.Listener
{
// Panel Constants
private SaveFile save;
private LevelResources res;
private int width;
private int height;
private AdBlockerFrame frame;
// Input Devices
private Mouse mouse;
private Keyboard keyboard;
// GUI Items
private BufferedImage buffer;
private GameScore score;
private GameBackground bg;
// Sound Items
private AudioClip music;
public GamePanel(SaveFile s, int w, int h, AdBlockerFrame f)
{
super(null);
save = s;
res = new LevelResources(s.getLevel());
width = w;
height = h;
frame = f;
mouse = new Mouse(this);
keyboard = new Keyboard(this);
addMouseListener(mouse);
addMouseMotionListener(mouse);
addMouseWheelListener(mouse);
addKeyListener(keyboard);
// Virtual Graphics Buffer
buffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// Score
score = new GameScore(save);
score.setSize(width, height/12);
score.setFont(new Font("Arial", Font.BOLD, height/24));
score.setForeground(Color.BLACK);
score.setHorizontalAlignment(SwingConstants.CENTER);
// Background
bg = new GameBackground(res.path()+res.bg(), width, height);
playBackgroundMusic();
setBounds(0, 0, width, height);
setFocusable(true);
setVisible(true);
}
public void paint(Graphics g)
{
super.paint(g);
Graphics vg = buffer.getGraphics();
bg.paint(vg);
score.paint(vg);
vg.dispose();
g.drawImage(buffer, 0, 0, null);
}
public void mousePressed(int x, int y, int button)
{
}
public void mouseReleased(int x, int y, int button)
{
}
public void mouseClicked(int x, int y, int button)
{
}
public void mouseMoved(int x, int y, int button)
{
save.changeScore(50);
repaint();
}
public void mouseDragged(int x, int y, int button)
{
}
public void mouseEntered(int x, int y, int button)
{
}
public void mouseExited(int x, int y, int button)
{
}
public void mouseWheeled(int dist)
{
}
public void keyPressed(Key k)
{
save.changeScore(-200);
if (k.equals(Key.KEY_ESCAPE))
{
frame.closed();
}
repaint();
}
public void keyReleased(Key k)
{
}
public void keyTyped(Key k)
{
}
private void playBackgroundMusic()
{
music = SoundUtils.getAudioClip(res.path() + res.music());
music.setCycleCount(AudioClip.INDEFINITE);
music.play();
}
private void stopBackgroundMusic()
{
music.stop();
}
public static void main(String[] args)
{
int level = 1;
int score = 0;
AdBlockerFrame f = new AdBlockerFrame();
f.getContentPane().removeAll();
f.startGame(new SaveFile(level, score));
}
} |
package com.dwarfartisan.parsec;
import java.io.EOFException;
public class Between<T, E, O, C> implements Parsec<T, E> {
private Parsec<O, E> open;
private Parsec<C, E> close;
private Parsec<T, E> parsec;
@Override
public T parse(State<E> s) throws EOFException, ParsecException {
open.parse(s);
T re = parsec.parse(s);
close.parse(s);
return re;
}
public Between(Parsec<O, E> open, Parsec<C, E> close, Parsec<T, E> parsec) {
this.open = open;
this.close = close;
this.parsec = parsec;
}
static public class In<T, E, O, C> {
private Parsec<O, E> open;
private Parsec<C, E> close;
public In(Parsec<O, E> open, Parsec<C, E> close) {
this.open = open;
this.close = close;
}
public Parsec<T, E> pack(Parsec<T, E> parser) {
return new Between<>(this.open, this.close, parser);
}
}
} |
package org.osmdroid.util;
import java.io.Serializable;
import org.osmdroid.api.IGeoPoint;
import org.osmdroid.util.constants.GeoConstants;
import org.osmdroid.views.util.constants.MathConstants;
import android.location.Location;
import android.os.Parcel;
import android.os.Parcelable;
/**
*
* @author Nicolas Gramlich
* @author Theodore Hong
*
*/
public class GeoPoint implements IGeoPoint, MathConstants, GeoConstants, Parcelable, Serializable, Cloneable {
// Constants
static final long serialVersionUID = 1L;
// Fields
private int mLongitudeE6;
private int mLatitudeE6;
private int mAltitude;
// Constructors
public GeoPoint(final int aLatitudeE6, final int aLongitudeE6) {
this.mLatitudeE6 = aLatitudeE6;
this.mLongitudeE6 = aLongitudeE6;
}
public GeoPoint(final int aLatitudeE6, final int aLongitudeE6, final int aAltitude) {
this.mLatitudeE6 = aLatitudeE6;
this.mLongitudeE6 = aLongitudeE6;
this.mAltitude = aAltitude;
}
public GeoPoint(final double aLatitude, final double aLongitude) {
this.mLatitudeE6 = (int) (aLatitude * 1E6);
this.mLongitudeE6 = (int) (aLongitude * 1E6);
}
public GeoPoint(final double aLatitude, final double aLongitude, final double aAltitude) {
this.mLatitudeE6 = (int) (aLatitude * 1E6);
this.mLongitudeE6 = (int) (aLongitude * 1E6);
this.mAltitude = (int) aAltitude;
}
public GeoPoint(final Location aLocation) {
this(aLocation.getLatitude(), aLocation.getLongitude(), aLocation.getAltitude());
}
public GeoPoint(final GeoPoint aGeopoint) {
this.mLatitudeE6 = aGeopoint.mLatitudeE6;
this.mLongitudeE6 = aGeopoint.mLongitudeE6;
this.mAltitude = aGeopoint.mAltitude;
}
public static GeoPoint fromDoubleString(final String s, final char spacer) {
final int spacerPos1 = s.indexOf(spacer);
final int spacerPos2 = s.indexOf(spacer, spacerPos1 + 1);
if (spacerPos2 == -1) {
return new GeoPoint(
(int) (Double.parseDouble(s.substring(0, spacerPos1)) * 1E6),
(int) (Double.parseDouble(s.substring(spacerPos1 + 1, s.length())) * 1E6));
} else {
return new GeoPoint(
(int) (Double.parseDouble(s.substring(0, spacerPos1)) * 1E6),
(int) (Double.parseDouble(s.substring(spacerPos1 + 1, spacerPos2)) * 1E6),
(int) Double.parseDouble(s.substring(spacerPos2 + 1, s.length())));
}
}
public static GeoPoint fromInvertedDoubleString(final String s, final char spacer) {
final int spacerPos1 = s.indexOf(spacer);
final int spacerPos2 = s.indexOf(spacer, spacerPos1 + 1);
if (spacerPos2 == -1) {
return new GeoPoint(
(int) (Double.parseDouble(s.substring(spacerPos1 + 1, s.length())) * 1E6),
(int) (Double.parseDouble(s.substring(0, spacerPos1)) * 1E6));
} else {
return new GeoPoint(
(int) (Double.parseDouble(s.substring(spacerPos1 + 1, spacerPos2)) * 1E6),
(int) (Double.parseDouble(s.substring(0, spacerPos1)) * 1E6),
(int) Double.parseDouble(s.substring(spacerPos2 + 1, s.length())));
}
}
public static GeoPoint fromIntString(final String s) {
final int commaPos1 = s.indexOf(',');
final int commaPos2 = s.indexOf(',', commaPos1 + 1);
if (commaPos2 == -1) {
return new GeoPoint(
Integer.parseInt(s.substring(0, commaPos1)),
Integer.parseInt(s.substring(commaPos1 + 1, s.length())));
} else {
return new GeoPoint(
Integer.parseInt(s.substring(0, commaPos1)),
Integer.parseInt(s.substring(commaPos1 + 1, commaPos2)),
Integer.parseInt(s.substring(commaPos2 + 1, s.length()))
);
}
}
// Getter & Setter
@Override
public int getLongitudeE6() {
return this.mLongitudeE6;
}
@Override
public int getLatitudeE6() {
return this.mLatitudeE6;
}
public int getAltitude() {
return this.mAltitude;
}
public void setLongitudeE6(final int aLongitudeE6) {
this.mLongitudeE6 = aLongitudeE6;
}
public void setLatitudeE6(final int aLatitudeE6) {
this.mLatitudeE6 = aLatitudeE6;
}
public void setAltitude(final int aAltitude) {
this.mAltitude = aAltitude;
}
public void setCoordsE6(final int aLatitudeE6, final int aLongitudeE6) {
this.mLatitudeE6 = aLatitudeE6;
this.mLongitudeE6 = aLongitudeE6;
}
// Methods from SuperClass/Interfaces
@Override
public Object clone() {
return new GeoPoint(this.mLatitudeE6, this.mLongitudeE6);
}
@Override
public String toString() {
return new StringBuilder().append(this.mLatitudeE6).append(",").append(this.mLongitudeE6).append(",").append(this.mAltitude)
.toString();
}
@Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj.getClass() != getClass()) {
return false;
}
final GeoPoint rhs = (GeoPoint) obj;
return rhs.mLatitudeE6 == this.mLatitudeE6 && rhs.mLongitudeE6 == this.mLongitudeE6 && rhs.mAltitude == this.mAltitude;
}
@Override
public int hashCode() {
return 37 * (17 * mLatitudeE6 + mLongitudeE6) + mAltitude;
}
// Parcelable
private GeoPoint(final Parcel in) {
this.mLatitudeE6 = in.readInt();
this.mLongitudeE6 = in.readInt();
this.mAltitude = in.readInt();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(final Parcel out, final int flags) {
out.writeInt(mLatitudeE6);
out.writeInt(mLongitudeE6);
out.writeInt(mAltitude);
}
public static final Parcelable.Creator<GeoPoint> CREATOR = new Parcelable.Creator<GeoPoint>() {
@Override
public GeoPoint createFromParcel(final Parcel in) {
return new GeoPoint(in);
}
@Override
public GeoPoint[] newArray(final int size) {
return new GeoPoint[size];
}
};
// Methods
public int distanceTo(final GeoPoint other) {
final double a1 = DEG2RAD * this.mLatitudeE6 / 1E6;
final double a2 = DEG2RAD * this.mLongitudeE6 / 1E6;
final double b1 = DEG2RAD * other.mLatitudeE6 / 1E6;
final double b2 = DEG2RAD * other.mLongitudeE6 / 1E6;
final double cosa1 = Math.cos(a1);
final double cosb1 = Math.cos(b1);
final double t1 = cosa1 * Math.cos(a2) * cosb1 * Math.cos(b2);
final double t2 = cosa1 * Math.sin(a2) * cosb1 * Math.sin(b2);
final double t3 = Math.sin(a1) * Math.sin(b1);
final double tt = Math.acos(t1 + t2 + t3);
return (int) (RADIUS_EARTH_METERS * tt);
}
public double bearingTo(final GeoPoint other) {
final double lat1 = Math.toRadians(this.mLatitudeE6 / 1E6);
final double long1 = Math.toRadians(this.mLongitudeE6 / 1E6);
final double lat2 = Math.toRadians(other.mLatitudeE6 / 1E6);
final double long2 = Math.toRadians(other.mLongitudeE6 / 1E6);
final double delta_long = long2 - long1;
final double a = Math.sin(delta_long) * Math.cos(lat2);
final double b = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2)
* Math.cos(delta_long);
final double bearing = Math.toDegrees(Math.atan2(a, b));
final double bearing_normalized = (bearing + 360) % 360;
return bearing_normalized;
}
public GeoPoint destinationPoint(final double aDistanceInMeters, final float aBearingInDegrees) {
// convert distance to angular distance
final double dist = aDistanceInMeters / RADIUS_EARTH_METERS;
// convert bearing to radians
final float brng = DEG2RAD * aBearingInDegrees;
// get current location in radians
final double lat1 = DEG2RAD * getLatitudeE6() / 1E6;
final double lon1 = DEG2RAD * getLongitudeE6() / 1E6;
final double lat2 = Math.asin(Math.sin(lat1) * Math.cos(dist) + Math.cos(lat1)
* Math.sin(dist) * Math.cos(brng));
final double lon2 = lon1
+ Math.atan2(Math.sin(brng) * Math.sin(dist) * Math.cos(lat1), Math.cos(dist)
- Math.sin(lat1) * Math.sin(lat2));
final double lat2deg = lat2 / DEG2RAD;
final double lon2deg = lon2 / DEG2RAD;
return new GeoPoint(lat2deg, lon2deg);
}
public static GeoPoint fromCenterBetween(final GeoPoint geoPointA, final GeoPoint geoPointB) {
return new GeoPoint((geoPointA.getLatitudeE6() + geoPointB.getLatitudeE6()) / 2,
(geoPointA.getLongitudeE6() + geoPointB.getLongitudeE6()) / 2);
}
public String toDoubleString() {
return new StringBuilder().append(this.mLatitudeE6 / 1E6).append(",")
.append(this.mLongitudeE6 / 1E6).append(",").append(this.mAltitude).toString();
}
public String toInvertedDoubleString() {
return new StringBuilder().append(this.mLongitudeE6 / 1E6).append(",")
.append(this.mLatitudeE6 / 1E6).append(",").append(this.mAltitude).toString();
}
// Inner and Anonymous Classes
} |
package com.example.ex_templete;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
public class BaofengActivity6 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_baofeng_activity6);
// 2014.01.02
//12.2 17:42
LayoutInflater inflater = getLayoutInflater();
View layout1 = inflater.inflate(R.layout.bao_pager1, null);
View layout2 = inflater.inflate(R.layout.bao_pager2, null);
View layout3 = inflater.inflate(R.layout.bao_pager3, null);
//12.2 20:19 viewpageritem
final ArrayList<View> viewArray=new ArrayList<View>();
viewArray.add(layout1);
viewArray.add(layout2);
viewArray.add(layout3);
final ViewPager viewPager=(ViewPager) findViewById(R.id.pager_icon);
viewPager.setAdapter(new PagerAdapter() {
@Override
public Object instantiateItem(View container, int position) {
View layout = viewArray.get(position);
viewPager.addView(layout);
return layout;
}
@Override
public void destroyItem(View container, int position, Object object) {
View layout = viewArray.get(position);
viewPager.removeView(layout);
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0==arg1;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return viewArray.size();
}
});
}
public void btnNextPage(View v) {
startActivity(new Intent(BaofengActivity6.this,ChenJiaLiang7Activity.class));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.baofeng_activity6, menu);
return true;
}
} |
package org.neo4j.helpers;
/**
* Utility to handle pairs of objects.
*/
public final class Pair<T1, T2>
{
private final T1 first;
private final T2 other;
public Pair( T1 first, T2 other )
{
this.first = first;
this.other = other;
}
public T1 first()
{
return first;
}
public T2 other()
{
return other;
}
@Override
public String toString()
{
return "(" + first + ", " + other + ")";
}
} |
// RMG - Reaction Mechanism Generator
// RMG Team (rmg_dev@mit.edu)
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
package jing.rxnSys;
import java.util.AbstractSequentialList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.StringTokenizer;
import jing.chem.Species;
import jing.param.Temperature;
import jing.rxn.PDepException;
import jing.rxn.PDepIsomer;
import jing.rxn.PDepKineticsEstimator;
import jing.rxn.PDepNetwork;
import jing.rxn.PDepReaction;
import jing.rxn.Reaction;
import jing.rxn.Structure;
/**
* A rate-based reaction model enlarger for use when pressure-dependent
* kinetics estimation is desired. In addition to checking the species fluxes,
* this class contains a piece of the activated species algorithm (ASA), a
* method for ensuring that pressure-dependent networks are being explored in
* sufficient detail.
* @author jwallen
*/
public class RateBasedPDepRME implements ReactionModelEnlarger {
/**
* The pressure-dependent kinetics estimator to use. Currently this will
* only hold a FastMasterEqn object, as the Chemdis class has been
* depreciated. This is the object called when a pressure-dependent
* calculation is run.
*/
private PDepKineticsEstimator pDepKineticsEstimator;
// Constructors
/**
* Default constructor. Does not set the pressure-dependent kinetics
* estimator.
*/
public RateBasedPDepRME() {
pDepKineticsEstimator = null;
}
// Accessors
/**
* Returns the current pressure-dependent kinetics estimator.
* @return The current pressure-dependent kinetics estimator
*/
public PDepKineticsEstimator getPDepKineticsEstimator() {
return pDepKineticsEstimator;
}
/**
* Sets the pressure-dependent kinetics estimator.
* @param pdke The new pressure-dependent kinetics estimator
*/
public void setPDepKineticsEstimator(PDepKineticsEstimator pdke) {
pDepKineticsEstimator = pdke;
}
/**
* Enlarges the reaction model by either adding a species to the core or
* making a unimolecular isomer included in a PDepNetwork. The action taken
* is based on the fluxes of species.
* @param rxnSystemList The reaction systems in the simulation
* @param rm The current reaction model in the simulation
* @param validList A boolean list of the validity status of each reaction system
*/
public void enlargeReactionModel(LinkedList rxnSystemList, ReactionModel rm, LinkedList validList) {
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel) rm;
// Iterate over reaction systems, enlarging each individually
LinkedList updateList = new LinkedList();
for (int i = 0; i < rxnSystemList.size(); i++) {
// Don't need to enlarge if the system is already valid
if ((Boolean) validList.get(i))
continue;
ReactionSystem rxnSystem = (ReactionSystem) rxnSystemList.get(i);
PresentStatus ps = rxnSystem.getPresentStatus();
// Get Rmin
double Rmin = rxnSystem.getRmin();
// Determine flux of all species (combining both pDep and non-pDep systems)
int len = cerm.getMaxSpeciesID() + 1;
double[] flux = new double[len];
for (int n = 0; n < len; n++)
flux[n] = 0.0;
// Flux from non-pDep and P-dep reactions
double[] unreactedSpeciesFlux = ps.getUnreactedSpeciesFlux();//unreacted species flux includes flux from both p-dep and non-pdep rxns: cf. appendUnreactedSpeciesStatus in ReactionSystem
for (Iterator iter = cerm.getUnreactedSpeciesSet().iterator(); iter.hasNext(); ) {
Species us = (Species) iter.next();
if (us.getID() < unreactedSpeciesFlux.length)
flux[us.getID()] = unreactedSpeciesFlux[us.getID()];
else
System.out.println("Warning: Attempted to read unreacted species flux for " +
us.getName() + "(" + us.getID() + "), but there are only " +
unreactedSpeciesFlux.length + " fluxes.");
}
// Flux from pDep reactions //gmagoon 61709: ...is already taken into account above (the unreactedSpeciesFlux is also used by the validityTester
// for (Iterator iter = PDepNetwork.getNetworks().iterator(); iter.hasNext(); ) {
// PDepNetwork pdn = (PDepNetwork) iter.next();
// for (Iterator iter2 = pdn.getNetReactions().iterator(); iter2.hasNext(); ) {
// PDepReaction rxn = (PDepReaction) iter2.next();
// double forwardFlux = rxn.calculateForwardFlux(ps);
// double reverseFlux = rxn.calculateReverseFlux(ps);
// //System.out.println(rxn.toString() + ": " + forwardFlux + " " + reverseFlux);
// for (int j = 0; j < rxn.getReactantNumber(); j++) {
// Species species = (Species) rxn.getReactantList().get(j);
// if (cerm.containsAsUnreactedSpecies(species))
// flux[species.getID()] += reverseFlux;
// for (int j = 0; j < rxn.getProductNumber(); j++) {
// Species species = (Species) rxn.getProductList().get(j);
// if (cerm.containsAsUnreactedSpecies(species))
// flux[species.getID()] += forwardFlux;
// Determine species with maximum flux and its flux
Species maxSpecies = null;
double maxFlux = 0;
for (Iterator iter = cerm.getUnreactedSpeciesSet().iterator(); iter.hasNext(); ) {
Species us = (Species) iter.next();
if (Math.abs(flux[us.getID()]) >= maxFlux) {
maxFlux = Math.abs(flux[us.getID()]);
maxSpecies = us;
}
}
if (maxSpecies == null) throw new NullPointerException();
// Determine network with maximum leak flux and its flux
PDepNetwork maxNetwork = null;
double maxLeak = 0;
for (Iterator iter = PDepNetwork.getNetworks().iterator(); iter.hasNext(); ) {
PDepNetwork pdn = (PDepNetwork) iter.next();
if (Math.abs(pdn.getLeakFlux(ps)) >= maxLeak) {
maxLeak = Math.abs(pdn.getLeakFlux(ps));
maxNetwork = pdn;
}
}
if (maxNetwork == null) throw new NullPointerException();
// Output results of above calculations to console
System.out.print("Time: ");
System.out.println(ps.getTime());
System.out.println("Rmin: " + String.valueOf(Rmin));
System.out.println("Unreacted species " + maxSpecies.getName() + " has highest flux: " + String.valueOf(maxFlux));
System.out.println("Network " + maxNetwork.getID() + " has highest leak flux: " + String.valueOf(maxLeak));
//if (maxFlux > Rmin)
if (maxFlux > maxLeak && maxFlux > Rmin) {
if (!updateList.contains(maxSpecies))
updateList.add(maxSpecies);
else
updateList.add(null);
}
else if (maxLeak > Rmin) {
if (!updateList.contains(maxNetwork))
updateList.add(maxNetwork);
else
updateList.add(null);
}
else
updateList.add(null);
}
for (int i = 0; i < updateList.size(); i++) {
Object object = updateList.get(i);
ReactionSystem rxnSystem = (ReactionSystem) rxnSystemList.get(i);
PresentStatus ps = rxnSystem.getPresentStatus();
if (object == null)
continue;
else if (object instanceof Species) {
Species maxSpecies = (Species) object;
// Add a species to the core
System.out.print("\nAdd a new reacted Species: ");
System.out.println(maxSpecies.getChemkinName());
System.out.println(maxSpecies.toStringWithoutH());
Temperature temp = new Temperature(715, "K");
double H = maxSpecies.calculateH(temp);
double S = maxSpecies.calculateS(temp);
double G = maxSpecies.calculateG(temp);
double Cp = maxSpecies.calculateCp(temp);
System.out.println("Thermo of species at 715K (H, S, G, Cp, respectively)\t" + String.valueOf(H) + '\t' + String.valueOf(S) + '\t' + String.valueOf(G) + '\t' + String.valueOf(Cp));
if (cerm.containsAsReactedSpecies(maxSpecies))
System.out.println("Species " + maxSpecies.getName() + "(" +
Integer.toString(maxSpecies.getID()) +
") is already present in reaction model");
else {
// Move the species and appropriate reactions from the edge to the core
cerm.moveFromUnreactedToReactedSpecies(maxSpecies);
cerm.moveFromUnreactedToReactedReaction();
// Adding a species to the core automatically makes it
// included in all networks it is contained in
// Therefore we need to merge all networks containing that
// species as a unimolecular isomer together
PDepNetwork network = null;
LinkedList<PDepNetwork> networksToRemove = new LinkedList<PDepNetwork>();
for (Iterator iter = PDepNetwork.getNetworks().iterator(); iter.hasNext(); ) {
PDepNetwork pdn = (PDepNetwork) iter.next();
if (pdn.contains(maxSpecies)) {
if (network == null)
network = pdn;
else {
for (int j = 0; j < pdn.getIsomers().size(); j++)
network.addIsomer(pdn.getIsomers().get(j));
for (int j = 0; j < pdn.getPathReactions().size(); j++)
network.addReaction(pdn.getPathReactions().get(j),false);
networksToRemove.add(pdn);
}
}
}
if (network != null) {
network.getIsomer(maxSpecies).setIncluded(true);
try {
network.updateReactionLists(cerm);
} catch (PDepException e) {
e.printStackTrace();
System.out.println(e.getMessage());
System.err.println("WARNING: Attempt to update reaction list failed " +
"for the following network:\n" + network.toString());
System.exit(0);
}
}
// Generate new reaction set; partition into core and edge
LinkedHashSet newReactionSet_nodup;
if(rxnSystem.getLibraryReactionGenerator().getReactionLibrary() != null){
// Iterate through the Reaction Library and find all reactions which include the species being considered
LinkedHashSet newReactionSet = rxnSystem.getLibraryReactionGenerator().react(cerm.getReactedSpeciesSet(),maxSpecies,"All");
System.out.println("Reaction Set Found from Reaction Library "+newReactionSet);
// Iterate through the reaction template
newReactionSet.addAll(rxnSystem.getReactionGenerator().react(cerm.getReactedSpeciesSet(),maxSpecies,"All"));
// To remove the duplicates that are found in Reaction Library and Reaction Template
// Preference given to Reaction Library over Template Reaction
newReactionSet_nodup = RemoveDuplicateReac(newReactionSet);
}
else{
// When no Reaction Library is present
newReactionSet_nodup = rxnSystem.getReactionGenerator().react(cerm.getReactedSpeciesSet(),maxSpecies,"All");
}
// shamel 6/22/2010 Suppressed output , line is only for debugging
// System.out.println("Reaction Set For Pdep PdepRME "+newReactionSet_nodup);
Iterator rxnIter = newReactionSet_nodup.iterator();
while (rxnIter.hasNext()){
Reaction r = (Reaction) rxnIter.next();
if (r.getReactantNumber() > 1 && r.getProductNumber() > 1)
cerm.addReaction(r);
else {
cerm.categorizeReaction(r.getStructure());
PDepNetwork.addReactionToNetworks(r);
}
}
}
}
else if (object instanceof PDepNetwork) {
PDepNetwork maxNetwork = (PDepNetwork) object;
if ( maxNetwork.getAltered() ) {
System.out.println("\nNetwork " + maxNetwork.getID() + " has been altered already this step, so will not be expanded until next step.");
}
else {
try {
PDepIsomer isomer = maxNetwork.getMaxLeakIsomer(ps);
System.out.println("\nAdd a new included Species: " + isomer.toString() +
" to network " + maxNetwork.getID());
// Making a species included in one network automatically
// makes it included in all networks it is contained in
// Therefore we need to merge all networks containing that
// species as a unimolecular isomer together
LinkedList<PDepNetwork> networksToRemove = new LinkedList<PDepNetwork>();
for (Iterator iter = PDepNetwork.getNetworks().iterator(); iter.hasNext(); ) {
PDepNetwork pdn = (PDepNetwork) iter.next();
if (pdn.contains(isomer.getSpecies(0)) && pdn != maxNetwork) {
for (int j = 0; j < pdn.getIsomers().size(); j++)
maxNetwork.addIsomer(pdn.getIsomers().get(j));
for (int j = 0; j < pdn.getPathReactions().size(); j++)
maxNetwork.addReaction(pdn.getPathReactions().get(j),false);
networksToRemove.add(pdn);
}
}
for (Iterator iter = networksToRemove.iterator(); iter.hasNext(); ) {
PDepNetwork pdn = (PDepNetwork) iter.next();
PDepNetwork.getNetworks().remove(pdn);
}
// Make the isomer included
// This will cause any other reactions of the form
// isomer -> products that don't yet exist to be created
maxNetwork.makeIsomerIncluded(isomer);
maxNetwork.updateReactionLists(cerm);
}
catch (PDepException e) {
e.printStackTrace();
System.out.println(e.getMessage());
System.out.println(maxNetwork.toString());
System.exit(0);
}
}
}
else
continue;
System.out.println("");
}
}
public LinkedHashSet RemoveDuplicateReac(LinkedHashSet reaction_set){
// Get the reactants and products of a reaction and check with other reaction if both reactants and products
// match - delete duplicate entry, give preference to Seed Mechanism > Reaction Library > Reaction Template
// this information might be available from the comments
LinkedHashSet newreaction_set = new LinkedHashSet();
Iterator iter_reaction =reaction_set.iterator();
Reaction current_reaction;
while(iter_reaction.hasNext()){
// Cast it into a Reaction ( i.e pick the reaction )
current_reaction = (Reaction)iter_reaction.next();
// To remove current reaction from reaction_set
reaction_set.remove(current_reaction);
// Match Current Reaction with the reaction set and if a duplicate reaction is found remove that reaction
LinkedHashSet dupreaction_set = dupreaction(reaction_set,current_reaction);
// Remove the duplicate reaction from reaction set
reaction_set.removeAll(dupreaction_set);
// If duplicate reaction set was not empty
if(!dupreaction_set.isEmpty()){
// Add current reaction to duplicate set and from among this choose reaction according to
// following hierarchy Seed > Reaction Library > Template. Add that reaction to the newreaction_set
// Add current_reaction to duplicate set
dupreaction_set.add(current_reaction);
// Get Reaction according to hierarchy
LinkedHashSet reaction_toadd = reaction_add(dupreaction_set);
// Add all the Reactions to be kept to new_reaction set
newreaction_set.addAll(reaction_toadd);
}
else{
// If no duplicate reaction was found add the current reaction to the newreaction set
newreaction_set.add(current_reaction);
}
// Need to change iterate over counter here
iter_reaction =reaction_set.iterator();
}
return newreaction_set;
}
public LinkedHashSet reaction_add(LinkedHashSet reaction_set){
Reaction current_reaction;
Iterator iter_reaction = reaction_set.iterator();
LinkedHashSet reaction_seedset = new LinkedHashSet();
LinkedHashSet reaction_rlset = new LinkedHashSet();
LinkedHashSet reaction_trset = new LinkedHashSet();
while(iter_reaction.hasNext()){
// Cast it into a Reaction ( i.e pick the reaction )
current_reaction = (Reaction)iter_reaction.next();
// As I cant call the instance test as I have casted my reaction as a Reaction
// I will use the source (comments) to find whether a reaction is from Seed Mechanism
// Reaction Library or Template Reaction
String source = current_reaction.getKineticsSource(0);
//System.out.println("Source"+source);
if (source == null){
// If source is null I am assuming that its not a Reaction from Reaction Library or Seed Mechanism
source = "TemplateReaction:";
}
// To grab the First word from the source of the comment
// As we have Reaction_Type:, we will use : as our string tokenizer
StringTokenizer st = new StringTokenizer(source,":");
String reaction_type = st.nextToken();
// shamel: Cant think of more elegant way for now
// Splitting the set into Reactions from Seed Mechanism/Reaction Library and otherwise Template Reaction
if (reaction_type.equals( "SeedMechanism")){
// Add to seed mechanism set
reaction_seedset.add(current_reaction);
}
else if (reaction_type.equals("ReactionLibrary") ){
// Add to reaction library set
reaction_rlset.add(current_reaction);
}
else{
// Add to template reaction set
reaction_trset.add(current_reaction);
}
}
if(!reaction_seedset.isEmpty()){
// shamel: 6/10/2010 Debug lines
//System.out.println("Reaction Set Being Returned"+reaction_seedset);
return reaction_seedset;
}
else if(!reaction_rlset.isEmpty()){
//System.out.println("Reaction Set Being Returned in RatbasedPDepRME"+reaction_rlset);
return reaction_rlset;
}
else{
//System.out.println("Reaction Set Being Returned"+reaction_trset);
return reaction_trset;
}
}
public LinkedHashSet dupreaction(LinkedHashSet reaction_set, Reaction test_reaction){
// Iterate over the reaction set and find if a duplicate reaction exist for the the test reaction
LinkedHashSet dupreaction_set = new LinkedHashSet();
Iterator iter_reaction =reaction_set.iterator();
Reaction current_reaction;
// we will test if reaction are equal by structure test here, structure dosent require kinetics
// Get Structure of test reaction
Structure test_reactionstructure = test_reaction.getStructure();
// Get reverse structure of test reaction
Structure test_reactionstructure_rev = test_reactionstructure.generateReverseStructure();
while(iter_reaction.hasNext()){
// Cast it into a Reaction ( i.e pick the reaction )
current_reaction = (Reaction)iter_reaction.next();
// Get Structure of current reaction to be tested for equality to test reaction
Structure current_reactionstructure = current_reaction.getStructure();
// Check if Current Reaction Structure matches the Fwd Structure of Test Reaction
if(current_reactionstructure.equals(test_reactionstructure)){
dupreaction_set.add(current_reaction);
}
// Check if Current Reaction Structure matches the Reverse Structure of Test Reaction
if(current_reactionstructure.equals(test_reactionstructure_rev)){
dupreaction_set.add(current_reaction);
}
}
// Print out the dupreaction set if not empty
if(!dupreaction_set.isEmpty()){
System.out.println("dupreaction_set" + dupreaction_set);
}
// Return the duplicate reaction set
return dupreaction_set;
}
} |
package org.vinodkd.jnv;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.util.HashMap;
import java.util.List;
class JNV{
public static void main(String[] args) {
JNV jnv = new JNV();
Models logicalModels = jnv.createModels();
// Models viewModels = jnv.createViewModels(logicalModels);
HashMap<String,Component> ui = jnv.createUI(logicalModels); // call getInitialState to build ui.
// ignoring the urge to overengineer with state machines for now.
jnv.addBehaviors(ui,logicalModels);
ui.get("window").setVisible(true);
}
public JNV(){}
public Models createModels(){
Notes notes = new Notes();
Models models = new Models();
models.add("notes",notes);
return models;
}
// public Models createViewModels(Models logicalModels){
// ViewModels models = new ViewModels();
// Model logicalNotes = logicalModels.get("notes");
// models.add("notetitle", new NoteTitle(logicalNotes));
// models.add("searchresults", new SearchResults(logicalNotes));
// models.add("notecontents", new NoteContents(logicalNotes));
public HashMap<String,Component> createUI(Models models){
HashMap<String,Component> controls = new HashMap<String,Component>();
JTextField noteName = new JTextField();
noteName.setPreferredSize(new Dimension(500,25));
controls.put("noteName", noteName);
// should createUI know about model data? no. kludge for now.
@SuppressWarnings("unchecked")
HashMap<String,Note> notes = (HashMap<String,Note>)(models.get("notes").getInitialValue());
DefaultListModel<String> foundNotesModel = new DefaultListModel<String>();
for(String title:notes.keySet()){
foundNotesModel.addElement(title);
}
JList<String> foundNotes = new JList<String>(foundNotesModel);
foundNotes.setLayoutOrientation(JList.VERTICAL);
JScrollPane foundNotesScroller = new JScrollPane(foundNotes);
foundNotesScroller.setPreferredSize(new Dimension(500,150));
controls.put("foundNotes", foundNotes);
JTextArea noteContent = new JTextArea();
noteContent.setLineWrap(true);
noteContent.setWrapStyleWord(true);
JScrollPane noteContentScroller = new JScrollPane(noteContent);
noteContentScroller.setPreferredSize(new Dimension(500,400));
controls.put("noteContent", noteContent);
Box vbox = Box.createVerticalBox();
vbox.add(noteName);
vbox.add(foundNotesScroller);
vbox.add(noteContentScroller);
JFrame ui = new JFrame("jNV");
ui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ui.setPreferredSize(new Dimension(520,600));
ui.add(vbox);
ui.pack();
controls.put("window", ui);
return controls;
}
private boolean SEARCHING = false;
public void addBehaviors(HashMap<String,Component> ui, final Models models){
final JTextField noteName = (JTextField)ui.get("noteName");
final JList foundNotes = (JList)ui.get("foundNotes");
final JTextArea noteContent = (JTextArea)ui.get("noteContent");
final JFrame window = (JFrame)ui.get("window");
final Notes notes = (Notes) models.get("notes");
noteName.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e){
SEARCHING = true;
String nName = noteName.getText();
List<String> searchResult = notes.search(nName);
// clear out list's model first regardless of search outcome.
@SuppressWarnings("unchecked")
DefaultListModel<String> fnModel = (DefaultListModel<String>)foundNotes.getModel();
fnModel.removeAllElements();
if(searchResult.isEmpty()){
noteContent.requestFocus();
}
else{
for(String title:searchResult){
fnModel.addElement(title);
}
}
SEARCHING = false;
}
}
);
foundNotes.addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent e){
// when still in search mode, this event is triggered by elements being added/removed
// from the model. the title should not updated then.
if(!SEARCHING){
// set the note title to the selected value
String selectedNote = (String)foundNotes.getSelectedValue();
noteName.setText(selectedNote);
// now set the content to reflect the selection as well
setNoteContent(noteContent, notes, selectedNote);
}
}
});
noteContent.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_TAB && e.isShiftDown()){
e.consume();
// fix for issue
saveIncremental();
KeyboardFocusManager.getCurrentKeyboardFocusManager().focusPreviousComponent();
}
}
});
window.addWindowListener( new WindowAdapter(){
public void windowClosing(WindowEvent e){
saveIncremental();
}
}
);
}
private void setNoteContent(JTextArea noteContent, Notes notes,String selectedNote){
noteContent.selectAll();
noteContent.replaceSelection(notes.get(selectedNote).getContents());
}
private void saveIncremental(){
System.out.println("saved!");
}
} |
package com.namelessmc.spigot;
import java.util.Arrays;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Statistic;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.namelessmc.java_api.ApiError;
import com.namelessmc.java_api.NamelessException;
public class ServerDataSender extends BukkitRunnable {
@Override
public void run() {
final int serverId = Config.MAIN.getConfig().getInt("server-id");
if (serverId < 1) {
return;
}
final JsonObject data = new JsonObject();
data.addProperty("tps", 20); // TODO Send real TPS
data.addProperty("time", System.currentTimeMillis());
data.addProperty("free-memory", Runtime.getRuntime().freeMemory());
data.addProperty("max-memory", Runtime.getRuntime().maxMemory());
data.addProperty("allocated-memory", Runtime.getRuntime().totalMemory());
data.addProperty("server-id", serverId);
try {
if (NamelessPlugin.permissions != null) {
final String[] gArray = NamelessPlugin.permissions.getGroups();
final JsonArray groups = new JsonArray(gArray.length);
Arrays.stream(gArray).map(JsonPrimitive::new).forEach(groups::add);
data.add("groups", groups);
}
} catch (final UnsupportedOperationException e) {}
final JsonObject players = new JsonObject();
for (final Player player : Bukkit.getOnlinePlayers()) {
final JsonObject playerInfo = new JsonObject();
playerInfo.addProperty("name", player.getName());
final JsonObject location = new JsonObject();
final Location loc = player.getLocation();
location.addProperty("world", loc.getWorld().getName());
location.addProperty("x", loc.getBlockX());
location.addProperty("y", loc.getBlockY());
location.addProperty("z", loc.getBlockZ());
playerInfo.add("location", location);
playerInfo.addProperty("ip", player.getAddress().getAddress().getHostAddress());
playerInfo.addProperty("playtime", player.getStatistic(Statistic.PLAY_ONE_TICK) / 120);
try {
if (NamelessPlugin.permissions != null) {
final String[] gArray = NamelessPlugin.permissions.getPlayerGroups(player);
final JsonArray groups = new JsonArray(gArray.length);
Arrays.stream(gArray).map(JsonPrimitive::new).forEach(groups::add);
playerInfo.add("groups", groups);
}
} catch (final UnsupportedOperationException e) {}
try {
if (NamelessPlugin.economy != null) {
playerInfo.addProperty("balance", NamelessPlugin.economy.getBalance(player));
}
} catch (final UnsupportedOperationException e) {}
final JsonObject placeholders = new JsonObject();
Config.MAIN.getConfig().getStringList("upload-placeholders")
.forEach(placeholder ->
placeholders.addProperty(placeholder, NamelessPlugin.getInstance().papiParser.parse(player, placeholder)));
playerInfo.add("placeholders", placeholders);
playerInfo.addProperty("login-time", NamelessPlugin.LOGIN_TIME.get(player.getUniqueId()));
players.add(player.getUniqueId().toString().replace("-", ""), playerInfo);
}
data.add("players", players);
Bukkit.getScheduler().runTaskAsynchronously(NamelessPlugin.getInstance(), () -> {
try {
NamelessPlugin.getApi().submitServerInfo(data);
} catch (final ApiError e) {
if (e.getError() == ApiError.INVALID_SERVER_ID) {
NamelessPlugin.getInstance().getLogger().warning("Server ID is incorrect. Please enter a correct server ID or disable the server data uploader.");
} else {
e.printStackTrace();
}
} catch (final NamelessException e) {
e.printStackTrace();
}
});
}
} |
package com.huettermann.all;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Message extends HttpServlet {
private String userName; // As this field is shared by all users, it's obvious that this piece of information should be managed differently
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String param = request.getParameter("param");
ServletContext context = getServletContext( );
if (param == null || param.equals("")) {
context.log("No message received:",
new IllegalStateException("Missing parameter"));
} else {
context.log("Here the paramater: " + param);
}
PrintWriter out = null;
try {
out = response.getWriter();
out.println("Hello: " + param);
out.flush();
out.close();
} catch (IOException io) {
io.printStackTrace();
}
}
} |
package com.eegeo.location;
import java.util.ArrayDeque;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.view.Surface;
import android.view.WindowManager;
public class HeadingService implements SensorEventListener
{
private SensorManager m_sensorManager;
private Activity m_activity;
private boolean m_hasAzimuthAngle = false;
private boolean m_listeningForUpdates = false;
// The results from SensorManager.getOrientation appear to be worse than the results of
// the deprecated Sensor.TYPE_ORIENTATION on the test device. To enable SensorManager.getOrientation
// using the results of the Sensor.TYPE_GRAVITY and Sensor.TYPE_MAGNETIC_FIELD sensors, set
// this field to false. The results of this have high jitter, so a low-pass filter is used. Even
// then, the results appear to be inferior to Sensor.TYPE_ORIENTATION.
private final boolean m_useDeprecatedOrientationMethod = true;
// Used if m_useDeprecatedOrientationMethod == true.
private float m_azimuthDegrees = 0.f;
// Used if m_useDeprecatedOrientationMethod == false.
private final int NumBufferedResults = 16;
private float m_sumSin, m_sumCos;
private ArrayDeque<Float> m_resultsBuffer = new ArrayDeque<Float>();
private float[] m_gravity = new float[3];
private float[] m_geomagnetic = new float[3];
public boolean hasHeading()
{
return m_hasAzimuthAngle;
}
public double heading()
{
if(m_useDeprecatedOrientationMethod)
{
return m_azimuthDegrees;
}
else
{
return filteredResultDegrees();
}
}
public HeadingService(Activity activity)
{
m_activity = activity;
}
public void startListening()
{
if (m_listeningForUpdates)
{
return;
}
m_listeningForUpdates = true;
m_sensorManager = (SensorManager)m_activity.getSystemService(Context.SENSOR_SERVICE);
if(m_useDeprecatedOrientationMethod)
{
@SuppressWarnings("deprecation")
Sensor orientation = m_sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
m_sensorManager.registerListener(this, orientation, SensorManager.SENSOR_DELAY_GAME);
}
else
{
Sensor accelerometer = m_sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
Sensor magnetometer = m_sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
m_sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME);
m_sensorManager.registerListener(this, magnetometer, SensorManager.SENSOR_DELAY_GAME);
}
}
public void stopListening()
{
if(m_listeningForUpdates)
{
m_sensorManager.unregisterListener(this);
}
m_listeningForUpdates = false;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
@SuppressWarnings("deprecation")
@Override
public void onSensorChanged(SensorEvent event)
{
if(m_useDeprecatedOrientationMethod)
{
if (event.sensor.getType() == Sensor.TYPE_ORIENTATION)
{
float smoothing = 0.6f;
float heading = event.values[0];
if (Float.isNaN(heading)) // Fix MPLY-4888
{
return;
}
float newAzimuth = adjustHeadingForDeviceOrientation(heading);
if(Math.abs(newAzimuth - m_azimuthDegrees) >= 180)
{
if(newAzimuth > m_azimuthDegrees)
{
m_azimuthDegrees += 360.0f;
}
else
{
newAzimuth += 360.0f;
}
}
m_azimuthDegrees = (float) ((newAzimuth * smoothing) + (m_azimuthDegrees * (1.0 - smoothing)));
m_azimuthDegrees %= 360.0f;
m_hasAzimuthAngle = true;
return;
}
}
else
{
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
{
m_gravity = event.values.clone();
}
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
{
m_geomagnetic = event.values.clone();
}
if (m_gravity != null && m_geomagnetic != null)
{
float R[] = new float[9];
float I[] = new float[9];
boolean success = SensorManager.getRotationMatrix(R, I, m_gravity, m_geomagnetic);
if(success)
{
float remap[] = new float[9];
SensorManager.remapCoordinateSystem(R, SensorManager.AXIS_X, SensorManager.AXIS_Z, remap);
float orientation[] = new float[3];
SensorManager.getOrientation(remap, orientation);
m_hasAzimuthAngle = true;
addResultForFiltering(adjustHeadingForDeviceOrientation(orientation[0]));
}
}
}
}
private void addResultForFiltering(float radians)
{
m_sumSin += (float) Math.sin(radians);
m_sumCos += (float) Math.cos(radians);
m_resultsBuffer.add(radians);
if(m_resultsBuffer.size() > NumBufferedResults)
{
float old = m_resultsBuffer.poll();
m_sumSin -= Math.sin(old);
m_sumCos -= Math.cos(old);
}
}
private float filteredResultDegrees()
{
int size = m_resultsBuffer.size();
if(size == 0)
{
return 0.f;
}
float resultRadians = (float) Math.atan2(m_sumSin / size, m_sumCos / size);
float resultDegrees = (float) Math.toDegrees(resultRadians);
return (resultDegrees + 360.f) % 360.f;
}
private float adjustHeadingForDeviceOrientation(float heading)
{
final int rotation = ((WindowManager) this.m_activity.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation();
switch (rotation)
{
case Surface.ROTATION_0:
heading += 0.f;
break;
case Surface.ROTATION_90:
heading += 90.f;
break;
case Surface.ROTATION_180:
heading += 180.f;
break;
default:
heading += 270.f;
break;
}
heading = (heading + 360.f)%360.f;
return heading;
}
} |
package com.eegeo.navwidget;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.location.Location;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewPropertyAnimator;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.eegeo.entrypointinfrastructure.MainActivity;
import com.eegeo.helpers.IBackButtonListener;
import com.eegeo.mobileexampleapp.R;
import com.eegeo.searchmenu.SearchWidgetResult;
import com.eegeo.searchproviders.MyTestSearchProvider;
import com.wrld.widgets.navigation.model.WrldNavEvent;
import com.wrld.widgets.navigation.model.WrldNavLocation;
import com.wrld.widgets.navigation.model.WrldNavMode;
import com.wrld.widgets.navigation.model.WrldNavModel;
import com.wrld.widgets.navigation.model.WrldNavModelObserver;
import com.wrld.widgets.navigation.model.WrldNavModelObserverListener;
import com.wrld.widgets.navigation.model.WrldNavRoute;
import com.wrld.widgets.navigation.model.WrldNavDirection;
import com.wrld.widgets.navigation.search.WrldNavSearchLocationView;
import com.wrld.widgets.navigation.widget.WrldNavWidget;
import com.wrld.widgets.navigation.widget.WrldNavWidgetViewObserver;
import com.wrld.widgets.navigation.widget.WrldNavWidgetViewVisibilityListener;
import com.wrld.widgets.navigation.widget.WrldNavWidgetViewSizeListener;
import com.wrld.widgets.search.WrldSearchWidget;
import com.wrld.widgets.search.model.SearchProvider;
import com.wrld.widgets.search.model.SearchProviderQueryResult;
import com.wrld.widgets.search.model.SearchQuery;
import com.wrld.widgets.search.model.SearchResult;
import com.wrld.widgets.search.model.SearchResultsListener;
import com.wrld.widgets.search.model.SuggestionProvider;
import java.util.List;
public class NavWidgetView implements IBackButtonListener, WrldNavModelObserverListener
{
protected MainActivity m_activity = null;
protected long m_nativeCallerPointer;
private View m_view = null;
private RelativeLayout m_uiRoot = null;
private AlertDialog m_calculatingSpinner = null;
private View m_navSearchHintView = null;
private boolean m_hasShownHint;
private WrldNavWidget m_navWidget = null;
private WrldNavModelObserver m_observer;
private WrldNavWidgetViewObserver m_viewObserver;
private WrldNavModel m_model;
private boolean m_isNavWidgetVisible = false;
private boolean m_isTopPanelVisible = false;
private boolean m_isBottomPanelVisible = false;
private float m_topPanelHeight = 0.0f;
private float m_bottomPanelHeight = 0.0f;
private WrldSearchWidget m_searchWidget;
private WrldNavSearchLocationView m_searchLocationView;
private boolean m_searchingForLocation;
private boolean m_searchingForStartLocation;
private ViewPropertyAnimator m_searchLocationViewAnimation;
private SearchResultsListener m_autocompleteListener;
private SearchResultsListener m_searchResultListener;
private MyTestSearchProvider m_locationSearchProvider;
private final int m_searchNavTopMargin;
public NavWidgetView(MainActivity activity, long nativeCallerPointer)
{
m_activity = activity;
m_nativeCallerPointer = nativeCallerPointer;
m_uiRoot = (RelativeLayout)m_activity.findViewById(R.id.ui_container);
m_view = m_activity.getLayoutInflater().inflate(R.layout.nav_widget_layout, m_uiRoot, false);
m_searchNavTopMargin = (int)activity.getResources().getDimension(R.dimen.nav_search_top_margin);
m_uiRoot.addView(m_view);
m_activity.addBackButtonPressedListener(this);
m_model = new WrldNavModel();
m_navWidget = (WrldNavWidget) m_view.findViewById(R.id.wrld_nav_widget_view);
m_navWidget.getObserver().setNavModel(m_model);
m_viewObserver = m_navWidget.getViewObserver();
m_searchLocationView = m_uiRoot.findViewById(R.id.wrld_nav_search_widget_view);
m_searchLocationView.getBackButton().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
endSearchForLocation();
}
});
m_searchLocationView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
m_searchLocationView.removeOnLayoutChangeListener(this);
setSearchLocationVisibility(false, false);
}
});
m_navSearchHintView = m_uiRoot.findViewById(R.id.wrld_nav_search_hint_container);
m_navSearchHintView.setVisibility(View.GONE);
m_hasShownHint = false;
if(m_searchWidget == null) {
m_searchWidget = m_searchLocationView.getSearchWidget();
}
m_autocompleteListener = new SearchResultsListener() {
@Override
public void onSearchResultsReceived(SearchQuery searchQuery, List<SearchProviderQueryResult> list)
{
dismissSearchHint();
}
@Override
public void onSearchResultsCleared() { }
@Override
public void onSearchResultsSelected(SearchResult searchResult) {
}
};
m_searchResultListener = new SearchResultsListener() {
@Override
public void onSearchResultsReceived(SearchQuery searchQuery, List<SearchProviderQueryResult> list) { }
@Override
public void onSearchResultsCleared() { }
@Override
public void onSearchResultsSelected(SearchResult searchResult) {
SearchWidgetResult widgetResult = (SearchWidgetResult) searchResult;
if(m_searchingForStartLocation) {
NavWidgetViewJniMethods.SetNavigationStartPointFromSuggestion(
m_nativeCallerPointer,
widgetResult.getIndex());
}
else {
NavWidgetViewJniMethods.SetNavigationEndPointFromSuggestion(
m_nativeCallerPointer,
widgetResult.getIndex());
}
endSearchForLocation();
}
};
m_observer = new WrldNavModelObserver();
m_observer.observeProperty(WrldNavModel.WrldNavModelProperty.SelectedDirectionIndex);
m_observer.observeProperty(WrldNavModel.WrldNavModelProperty.CurrentNavMode);
m_observer.observeProperty(WrldNavModel.WrldNavModelProperty.StartLocation);
m_observer.observeProperty(WrldNavModel.WrldNavModelProperty.EndLocation);
m_observer.setListener(this);
m_observer.setNavModel(m_model);
m_viewObserver.addSizeChangedListener(new WrldNavWidgetViewSizeListener(){
public void onTopPanelHeightChanged(float height)
{
m_topPanelHeight = height;
NavWidgetViewJniMethods.SetTopViewHeight(m_nativeCallerPointer, calculateVisibleTopHeight());
}
public void onBottomPanelHeightChanged(float height)
{
m_bottomPanelHeight = height;
NavWidgetViewJniMethods.SetBottomViewHeight(m_nativeCallerPointer, calculateVisibleBottomHeight());
}
public void onLeftPanelWidthChanged(float width)
{
}
});
m_viewObserver.addVisibilityListener(new WrldNavWidgetViewVisibilityListener(){
public void onTopPanelVisible(boolean isVisible) {
m_isTopPanelVisible = isVisible;
NavWidgetViewJniMethods.SetTopViewHeight(m_nativeCallerPointer, calculateVisibleTopHeight());
}
public void onBottomPanelVisible(boolean isVisible) {
m_isBottomPanelVisible = isVisible;
NavWidgetViewJniMethods.SetBottomViewHeight(m_nativeCallerPointer, calculateVisibleBottomHeight());
}
public void onLeftPanelVisible(boolean isVisible){}
});
NavWidgetViewJniMethods.SetTopViewHeight(m_nativeCallerPointer, (int) m_viewObserver.getTopPanelHeight());
NavWidgetViewJniMethods.SetBottomViewHeight(m_nativeCallerPointer, (int) m_viewObserver.getBottomPanelHeight());
}
public void addLocationSuggestionProvider(SuggestionProvider locationSuggestionProvider) {
m_searchWidget.addSuggestionProvider(locationSuggestionProvider);
}
public void removeLocationSuggestionProvider(SuggestionProvider locationSuggestionProvider) {
m_searchWidget.removeSuggestionProvider(locationSuggestionProvider);
}
public void setLocationSearchProvider(MyTestSearchProvider locationSearchProvider) {
if(m_locationSearchProvider != null)
{
m_searchWidget.removeSearchProvider(m_locationSearchProvider);
m_locationSearchProvider = null;
}
m_locationSearchProvider = locationSearchProvider;
if(m_locationSearchProvider != null) {
m_searchWidget.addSearchProvider(locationSearchProvider);
}
}
private int calculateVisibleTopHeight()
{
if(m_isTopPanelVisible){
return (int) m_topPanelHeight;
}
return 0;
}
private int calculateVisibleBottomHeight()
{
if(m_isBottomPanelVisible){
return (int) m_bottomPanelHeight;
}
return 0;
}
private void handleCloseClicked()
{
NavWidgetViewJniMethods.CloseButtonClicked(m_nativeCallerPointer);
}
private WrldNavLocation createNavLocation(String name, double lat, double lon, boolean isIndoors, String indoorMapId, int floorMapFloorId)
{
Location loc = new Location("Wrld");
loc.setLatitude(lat);
loc.setLongitude(lon);
WrldNavLocation location;
if (isIndoors)
{
location = new WrldNavLocation(name, loc, indoorMapId, floorMapFloorId);
}
else
{
location = new WrldNavLocation(name, loc);
}
return location;
}
public void setStartLocation(String name, double lat, double lon, boolean isIndoors, String indoorMapId, int floorMapFloorId)
{
m_model.setStartLocation(createNavLocation(name, lat, lon, isIndoors, indoorMapId, floorMapFloorId));
}
public void clearStartLocation()
{
m_model.setStartLocation(null);
}
public void setEndLocation(String name, double lat, double lon, boolean isIndoors, String indoorMapId, int floorMapFloorId)
{
m_model.setEndLocation(createNavLocation(name, lat, lon, isIndoors, indoorMapId, floorMapFloorId));
}
public void clearEndLocation()
{
m_model.setEndLocation(null);
}
public void setRoute(WrldNavRoute route, boolean isNewRoute)
{
if (isNewRoute)
{
m_model.setRoute(route);
}
else
{
List<WrldNavDirection> directions = route.directions;
for (int i = 0; i < directions.size(); i++)
{
m_model.setDirection(i, directions.get(i));
}
m_model.sendNavEvent(WrldNavEvent.RouteUpdated);
}
}
public void clearRoute()
{
m_model.setRoute(null);
}
public void setCurrentDirectionIndex(int directionIndex)
{
m_model.setCurrentDirectionIndex(directionIndex);
}
public void setCurrentDirection(WrldNavDirection currentDirection)
{
m_model.setCurrentDirection(currentDirection);
}
public void setSelectedDirectionIndex(int directionIndex)
{
m_model.setSelectedDirectionIndex(directionIndex);
}
public void setRemainingRouteDurationSeconds(double remainingRouteDurationSeconds)
{
m_model.setRemainingRouteDurationSeconds(remainingRouteDurationSeconds);
}
public void setCurrentNavMode(WrldNavMode navMode)
{
m_model.setCurrentNavMode(navMode);
}
public void showNavWidgetView()
{
m_model.sendNavEvent(WrldNavEvent.WidgetAnimateIn);
m_isNavWidgetVisible = true;
}
public void dismissNavWidgetView()
{
m_model.sendNavEvent(WrldNavEvent.WidgetAnimateOut);
m_isNavWidgetVisible = false;
}
public void showRerouteDialog(String message)
{
final AlertDialog dialog = new AlertDialog.Builder(m_activity).create();
LayoutInflater layoutInflater = m_activity.getLayoutInflater();
View rerouteDialog = layoutInflater.inflate(R.layout.nav_widget_reroute_dialog_layout, null);
rerouteDialog.findViewById(R.id.nav_reroute_dialog_btn_yes).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NavWidgetViewJniMethods.RerouteDialogClosed(m_nativeCallerPointer, false);
dialog.dismiss();
}
});
rerouteDialog.findViewById(R.id.nav_reroute_dialog_btn_no).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NavWidgetViewJniMethods.RerouteDialogClosed(m_nativeCallerPointer, true);
dialog.dismiss();
}
});
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
NavWidgetViewJniMethods.RerouteDialogClosed(m_nativeCallerPointer, true);
}
});
TextView messageText = rerouteDialog.findViewById(R.id.nav_reroute_dialog_msg);
messageText.setText(message);
dialog.setCancelable(false);
dialog.setView(rerouteDialog);
dialog.show();
}
public void showCalculatingRouteSpinner()
{
m_calculatingSpinner = new AlertDialog.Builder(m_activity).create();
LayoutInflater layoutInflater = m_activity.getLayoutInflater();
View calculatingSpinnerView = layoutInflater.inflate(R.layout.nav_widget_calculating_route_layout, null);
ImageView calculatingSpinnerImageView = calculatingSpinnerView.findViewById(R.id.calculating_spinner_image_view);
//Animate
RotateAnimation rotate = new RotateAnimation(0,360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
rotate.setDuration(2000);
rotate.setInterpolator(new LinearInterpolator());
rotate.setRepeatCount(Animation.INFINITE);
calculatingSpinnerImageView.setAnimation(rotate);
m_calculatingSpinner.setCancelable(false);
m_calculatingSpinner.setView(calculatingSpinnerView);
m_calculatingSpinner.show();
}
public void hideCalculatingRouteSpinner()
{
if(m_calculatingSpinner != null)
{
m_calculatingSpinner.dismiss();
m_calculatingSpinner = null;
}
}
public void destroy()
{
m_uiRoot.removeView(m_view);
m_activity.removeBackButtonPressedListener(this);
}
@Override
public boolean onBackButtonPressed()
{
if (m_isNavWidgetVisible)
{
WrldNavMode currentNavMode = m_model.getCurrentNavMode();
if (currentNavMode == WrldNavMode.NotReady || currentNavMode == WrldNavMode.Ready)
{
handleCloseClicked();
}
else
{
m_model.sendNavEvent(WrldNavEvent.StartEndButtonClicked);
}
return true;
}
return false;
}
@Override
public void onModelSet()
{
}
@Override
public void onPropertyChanged(WrldNavModel.WrldNavModelProperty wrldNavModelProperty)
{
switch (wrldNavModelProperty)
{
case StartLocation:
case EndLocation:
m_model.setRoute(null);
if(m_searchingForLocation) {
endSearchForLocation();
}
break;
case SelectedDirectionIndex:
NavWidgetViewJniMethods.SelectedDirectionIndexChanged(m_nativeCallerPointer, m_model.getSelectedDirectionIndex());
break;
case CurrentNavMode:
final boolean shouldDisableScreenTimeout = (m_model.getCurrentNavMode() == WrldNavMode.Active);
if (shouldDisableScreenTimeout)
{
m_activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
else
{
m_activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
break;
}
}
@Override
public void onEventReceived(WrldNavEvent wrldNavEvent)
{
switch (wrldNavEvent)
{
case CloseSetupJourneyClicked:
handleCloseClicked();
break;
case SelectStartLocationClicked:
NavWidgetViewJniMethods.SelectStartLocationClicked(m_nativeCallerPointer);
{
boolean isStartLocation = true;
searchForLocation(isStartLocation);
}
break;
case SelectEndLocationClicked:
NavWidgetViewJniMethods.SelectEndLocationClicked(m_nativeCallerPointer);
{
boolean isStartLocation = false;
searchForLocation(isStartLocation);
}
break;
case StartLocationClearButtonClicked:
NavWidgetViewJniMethods.StartLocationClearButtonClicked(m_nativeCallerPointer);
break;
case EndLocationClearButtonClicked:
NavWidgetViewJniMethods.EndLocationClearButtonClicked(m_nativeCallerPointer);
break;
case StartEndLocationsSwapped:
NavWidgetViewJniMethods.StartEndLocationsSwapped(m_nativeCallerPointer);
break;
case StartEndButtonClicked:
NavWidgetViewJniMethods.StartEndButtonClicked(m_nativeCallerPointer);
break;
}
}
public void searchForLocation(boolean startLocation) {
m_searchingForLocation = true;
m_searchingForStartLocation = startLocation;
setSearchLocationVisibility(true, true);
m_model.sendNavEvent(WrldNavEvent.WidgetAnimateOut);
m_searchWidget.getSuggestionResultsModel().addResultListener(m_autocompleteListener);
m_searchWidget.getSearchResultsModel().addResultListener(m_searchResultListener);
m_searchWidget.clearSearch();
NavWidgetViewJniMethods.SetSearchingForLocation(m_nativeCallerPointer, true, m_searchingForStartLocation);
if(!m_hasShownHint)
{
m_hasShownHint = true;
showSearchHint();
}
m_locationSearchProvider.showNavButtons(false);
}
public void endSearchForLocation() {
m_searchingForLocation = false;
m_searchWidget.getSearchResultsModel().removeResultListener(m_searchResultListener);
m_searchWidget.getSuggestionResultsModel().removeResultListener(m_autocompleteListener);
setSearchLocationVisibility(false, true);
m_model.sendNavEvent(WrldNavEvent.WidgetAnimateIn);
NavWidgetViewJniMethods.SetSearchingForLocation(m_nativeCallerPointer, false, m_searchingForStartLocation);
dismissSearchHint();
m_locationSearchProvider.showNavButtons(true);
}
private void setSearchLocationVisibility(final boolean visible, boolean animate) {
if(m_searchLocationViewAnimation != null) {
m_searchLocationViewAnimation.cancel();
m_searchLocationViewAnimation=null;
}
int panelHeight = m_searchLocationView.getHeight();
float targetY = visible ? m_searchNavTopMargin : -panelHeight;
if(animate) {
m_searchLocationViewAnimation = m_searchLocationView.animate()
.y(targetY)
.withEndAction(new Runnable() {
@Override
public void run() {
if(visible) {
// Try focus on the searchbox and show keyboard
View searchBoxView = m_searchWidget.getView().findViewById(R.id.searchbox_search_searchview);
if (searchBoxView != null) {
searchBoxView.requestFocus();
InputMethodManager imm = (InputMethodManager) m_activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
}
}
else
{
m_searchWidget.getView().clearFocus();
}
}
})
.setDuration(300);
}
else {
m_searchLocationView.setY(targetY);
}
}
private void showSearchHint() {
m_navSearchHintView.setVisibility(View.VISIBLE);
m_navSearchHintView.setAlpha(0.0f);
m_navSearchHintView.animate()
.alpha(1.0f)
.setStartDelay(300)
.setDuration(200)
.withEndAction(new Runnable() {
@Override
public void run() {
if(m_searchingForLocation) {
m_navSearchHintView.animate()
.alpha(0.0f)
.setStartDelay(5000)
.setDuration(200)
.withEndAction(new Runnable() {
@Override
public void run() {
m_navSearchHintView.setVisibility(View.GONE);
}
});
}
}
});
}
private void dismissSearchHint() {
if(m_navSearchHintView.getVisibility() != View.GONE) {
m_navSearchHintView.setAnimation(null);
m_navSearchHintView.animate()
.alpha(0.0f)
.setDuration(200)
.setStartDelay(0)
.withEndAction(new Runnable() {
@Override
public void run() {
m_navSearchHintView.setVisibility(View.GONE);
}
});
}
}
} |
package VASSAL.build.module;
import VASSAL.tools.ProblemDialog;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.KeyEvent;
import java.io.IOException;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;
import VASSAL.build.Buildable;
import VASSAL.build.GameModule;
import VASSAL.command.Command;
import VASSAL.command.CommandEncoder;
import VASSAL.configure.ColorConfigurer;
import VASSAL.configure.FontConfigurer;
import VASSAL.i18n.Resources;
import VASSAL.preferences.Prefs;
import VASSAL.tools.ErrorDialog;
import VASSAL.tools.KeyStrokeSource;
import VASSAL.tools.QuickColors;
import VASSAL.tools.ScrollPane;
import VASSAL.tools.swing.DataArchiveHTMLEditorKit;
/**
* The chat window component. Displays text messages and accepts input. Also
* acts as a {@link CommandEncoder}, encoding/decoding commands that display
* message in the text area
*/
public class Chatter extends JPanel implements CommandEncoder, Buildable {
private static final long serialVersionUID = 1L;
protected JTextPane conversationPane;
protected HTMLDocument doc;
protected HTMLEditorKit kit;
protected StyleSheet style;
protected JTextField input;
protected JScrollPane scroll = new ScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
protected JScrollPane scroll2 = new ScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
protected static final String MY_CHAT_COLOR = "HTMLChatColor"; //$NON-NLS-1$ // Different tags to "restart" w/ new default scheme
protected static final String OTHER_CHAT_COLOR = "HTMLotherChatColor"; //$NON-NLS-1$
protected static final String GAME_MSG1_COLOR = "HTMLgameMessage1Color"; //$NON-NLS-1$
protected static final String GAME_MSG2_COLOR = "HTMLgameMessage2Color"; //$NON-NLS-1$
protected static final String GAME_MSG3_COLOR = "HTMLgameMessage3Color"; //$NON-NLS-1$
protected static final String GAME_MSG4_COLOR = "HTMLgameMessage4Color"; //$NON-NLS-1$
protected static final String GAME_MSG5_COLOR = "HTMLgameMessage5Color"; //$NON-NLS-1$
protected static final String SYS_MSG_COLOR = "HTMLsystemMessageColor"; //$NON-NLS-1$
@Deprecated(since = "2020-08-06", forRemoval = true)
protected static final String GAME_MSG_COLOR = "gameMessageColor"; //NON-NLS
protected Font myFont;
protected Color gameMsg, gameMsg2, gameMsg3, gameMsg4, gameMsg5;
protected Color systemMsg, myChat, otherChat;
protected boolean needUpdate;
protected JTextArea conversation; // Backward compatibility for overridden classes. Needs something to suppress.
public static String getAnonymousUserName() {
return Resources.getString("Chat.anonymous"); //$NON-NLS-1$
}
public Chatter() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
conversation = new JTextArea(); // For backward override compatibility only.
//BR// Conversation is now a JTextPane w/ HTMLEditorKit to process HTML, which gives us HTML support "for free".
conversationPane = new JTextPane();
conversationPane.setContentType("text/html"); //NON-NLS
kit = new DataArchiveHTMLEditorKit(GameModule.getGameModule().getDataArchive());
conversationPane.setEditorKit(kit);
doc = (HTMLDocument) conversationPane.getDocument();
style = kit.getStyleSheet();
myFont = new Font("SansSerif", Font.PLAIN, 12); //NON-NLS // Will be overridden by the font from Chat preferences
try {
for (int i = 0; i < 30; ++i) { // Scroll past some arbitrary number of empty lines so that first text will start appearing on the bottom line
kit.insertHTML(doc, doc.getLength(), "<br>", 0, 0, null); //NON-NLS
}
}
catch (BadLocationException | IOException ble) {
ErrorDialog.bug(ble);
}
conversationPane.setEditable(false);
conversationPane.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
scroll.getVerticalScrollBar().setValue(scroll.getVerticalScrollBar().getMaximum());
}
});
input = new JTextField(60);
input.setFocusTraversalKeysEnabled(false);
input.addActionListener(e -> {
send(formatChat(e.getActionCommand()), e.getActionCommand());
input.setText(""); //$NON-NLS-1$
});
input.setMaximumSize(new Dimension(input.getMaximumSize().width, input.getPreferredSize().height));
final FontMetrics fm = getFontMetrics(myFont);
final int fontHeight = fm.getHeight();
conversationPane.setPreferredSize(new Dimension(input.getMaximumSize().width, fontHeight * 10));
scroll.setViewportView(conversationPane);
scroll.getVerticalScrollBar().setUnitIncrement(input.getPreferredSize().height); //Scroll this faster
add(scroll);
add(input);
setPreferredSize(new Dimension(input.getMaximumSize().width, input.getPreferredSize().height + conversationPane.getPreferredSize().height));
}
/**
* Because our Chatters make themselves visible in their constructor, providing a way for an overriding class to
* "turn this chatter off" is friendlier than What Went Before.
*
* @param vis - whether this chatter should be visible
*/
protected void setChatterVisible(boolean vis) {
conversationPane.setVisible(vis);
input.setVisible(vis);
scroll.setVisible(vis);
}
protected String formatChat(String text) {
final String id = GlobalOptions.getInstance().getPlayerId();
return String.format("<%s> - %s", id.isEmpty() ? "(" + getAnonymousUserName() + ")" : id, text); //HTML-friendly angle brackets //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
public JTextField getInputField() {
return input;
}
/**
* Styles a chat message based on the player who sent it. Presently just distinguishes a chat message "from me" from a chat message "from anyone else".
*
* To make the player colors easy to override in a custom class
* (my modules have logic to assign individual player colors -- beyond the scope of the present effort but a perhaps a fun future addition)
* @param s - chat message from a player
* @return - an entry in our CSS style sheet to use for this chat message
*/
protected String getChatStyle(String s) {
return s.startsWith(formatChat("").trim()) ? "mychat" : "other"; //NON-NLS
}
/**
* A hook for inserting a console class that accepts commands
* @param s - chat message
* @param style - current style name (contains information that might be useful)
* @param html_allowed - flag if html_processing is enabled for this message (allows console to apply security considerations)
* @return true - if was accepted as a console command
*/
@SuppressWarnings("unused")
public boolean consoleHook(String s, String style, boolean html_allowed) {
return GameModule.getGameModule().getConsole().exec(s, style, html_allowed);
}
/**
* Display a message in the text area. Ensures we execute in the EDT
*/
public void show(String s) {
if (SwingUtilities.isEventDispatchThread()) {
doShow(s);
}
else {
SwingUtilities.invokeLater(() -> doShow(s));
}
}
/**
* Display a message in the text area - use show() from outside the class - MUST run on EventDispatchThread
*/
private void doShow(String s) {
final String style;
final boolean html_allowed;
// Choose an appropriate style to display this message in
s = s.trim();
if (!s.isEmpty()) {
if (s.startsWith("*")) {
html_allowed = (QuickColors.getQuickColor(s, "*") >= 0) || GlobalOptions.getInstance().chatterHTMLSupport();
style = QuickColors.getQuickColorHTMLStyle(s, "*");
s = QuickColors.stripQuickColorTag(s, "*");
}
else if (s.startsWith("-")) {
html_allowed = true;
style = (QuickColors.getQuickColor(s, "-") >= 0) ? QuickColors.getQuickColorHTMLStyle(s, "-") : "sys"; //NON-NLS
s = QuickColors.stripQuickColorTag(s, "-");
}
else {
style = getChatStyle(s);
html_allowed = false;
}
}
else {
style = "msg"; //NON-NLS
html_allowed = false;
}
// Disable unwanted HTML tags in contexts where it shouldn't be allowed:
// (1) Anything received from chat channel, for security reasons
// (2) Legacy module "report" text when not explicitly opted in w/ first character or preference setting
if (!html_allowed) {
s = s.replaceAll("<", "<") //NON-NLS // This prevents any unwanted tag from functioning
.replaceAll(">", ">"); //NON-NLS // This makes sure > doesn't break any of our legit <div> tags
}
// Now we have to fix up any legacy angle brackets around the word <observer>
final String keystring = Resources.getString("PlayerRoster.observer");
final String replace = keystring.replace("<", "<").replace(">", ">"); //NON-NLS
if (!replace.equals(keystring)) {
s = s.replace(keystring, replace);
}
// Insert a div of the correct style for our line of text. Module designer
// still free to insert <span> tags and <img> tags and the like in Report
// messages.
try {
kit.insertHTML(doc, doc.getLength(), "\n<div class=" + style + ">" + s + "</div>", 0, 0, null); //NON-NLS
}
catch (BadLocationException | IOException ble) {
ErrorDialog.bug(ble);
}
conversationPane.repaint();
//consoleHook(s, style, html_allowed);
}
/**
* Adds or updates a CSS stylesheet entry. Styles in the color, font type, and font size.
* @param s Style name
* @param f Font to use
* @param c Color for text
* @param font_weight Bold? Italic?
* @param size Font size
*/
protected void addStyle(String s, Font f, Color c, String font_weight, int size) {
if ((style == null) || (c == null)) return;
style.addRule(s +
" {color:" + //NON-NLS
String.format("#%02x%02x%02x", c.getRed(), c.getGreen(), c.getBlue()) + //NON-NLS
"; font-family:" + //NON-NLS
f.getFamily() +
"; font-size:" + //NON-NLS
(size > 0 ? size : f.getSize()) +
"; " + //NON-NLS
((!font_weight.isBlank()) ? "font-weight:" + font_weight + "; " : "") + //NON-NLS
"}"); //NON-NLS
style.addRule(s + "color {color:" + String.format("#%02x%02x%02x", c.getRed(), c.getGreen(), c.getBlue()) + "; }"); //NON-NLS
}
/**
* Build ourselves a CSS stylesheet from our preference font/color settings.
* @param f - Font to use for this stylesheet
*/
protected void makeStyleSheet(Font f) {
if (style == null) {
return;
}
if (f == null) {
if (myFont == null) {
f = new Font("SansSerif", Font.PLAIN, 12); //NON-NLS
myFont = f;
}
else {
f = myFont;
}
}
addStyle(".msg", f, gameMsg, "", 0); //NON-NLS
addStyle(".msg2", f, gameMsg2, "", 0); //NON-NLS
addStyle(".msg3", f, gameMsg3, "", 0); //NON-NLS
addStyle(".msg4", f, gameMsg4, "", 0); //NON-NLS
addStyle(".msg5", f, gameMsg5, "", 0); //NON-NLS
addStyle(".mychat", f, myChat, "bold", 0); //NON-NLS
addStyle(".other ", f, otherChat, "bold", 0); //NON-NLS
addStyle(".sys", f, systemMsg, "", 0); //NON-NLS
// A fun extension would be letting the module designer provide extra class styles.
}
/**
* Set the Font used by the text area
*/
@Override
public void setFont(Font f) {
myFont = f;
if (input != null) {
if (input.getText().isEmpty()) {
input.setText("XXX"); //$NON-NLS-1$
input.setFont(f);
input.setText(""); //$NON-NLS-1$
}
else {
input.setFont(f);
}
}
if (conversationPane != null) {
conversationPane.setFont(f);
}
makeStyleSheet(f); // When font changes, rebuild our stylesheet
}
@Override
public void build(org.w3c.dom.Element e) {
}
@Override
public org.w3c.dom.Element getBuildElement(org.w3c.dom.Document doc) {
return doc.createElement(getClass().getName());
}
/**
* Expects to be added to a GameModule. Adds itself to the controls window and
* registers itself as a {@link CommandEncoder}
*/
@Override
public void addTo(Buildable b) {
final GameModule mod = (GameModule) b;
mod.setChatter(this);
mod.addCommandEncoder(this);
mod.addKeyStrokeSource(new KeyStrokeSource(this, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT));
final FontConfigurer chatFont = new FontConfigurer("ChatFont", //NON-NLS
Resources.getString("Chatter.chat_font_preference"));
chatFont.addPropertyChangeListener(evt -> setFont((Font) evt.getNewValue()));
mod.getPlayerWindow().addChatter(this);
chatFont.fireUpdate();
mod.getPrefs().addOption(Resources.getString("Chatter.chat_window"), chatFont); //$NON-NLS-1$
// Bug 10179 - Do not re-read Chat colors each time the Chat Window is
// repainted.
final Prefs globalPrefs = Prefs.getGlobalPrefs();
// game message color
final ColorConfigurer gameMsgColor = new ColorConfigurer(GAME_MSG1_COLOR,
Resources.getString("Chatter.game_messages_preference"), Color.black);
gameMsgColor.addPropertyChangeListener(e -> {
gameMsg = (Color) e.getNewValue();
makeStyleSheet(null);
});
globalPrefs.addOption(Resources.getString("Chatter.chat_window"), gameMsgColor);
gameMsg = (Color) globalPrefs.getValue(GAME_MSG1_COLOR);
// game message color #2 (messages starting with "!")
final ColorConfigurer gameMsg2Color = new ColorConfigurer(GAME_MSG2_COLOR,
Resources.getString("Chatter.game_messages_preference_2"), new Color(0, 153, 51));
gameMsg2Color.addPropertyChangeListener(e -> {
gameMsg2 = (Color) e.getNewValue();
makeStyleSheet(null);
});
globalPrefs.addOption(Resources.getString("Chatter.chat_window"), gameMsg2Color);
gameMsg2 = (Color) globalPrefs.getValue(GAME_MSG2_COLOR);
// game message color #3 (messages starting with "?")
final ColorConfigurer gameMsg3Color = new ColorConfigurer(GAME_MSG3_COLOR,
Resources.getString("Chatter.game_messages_preference_3"), new Color(255, 102, 102));
gameMsg3Color.addPropertyChangeListener(e -> {
gameMsg3 = (Color) e.getNewValue();
makeStyleSheet(null);
});
globalPrefs.addOption(Resources.getString("Chatter.chat_window"), gameMsg3Color);
gameMsg3 = (Color) globalPrefs.getValue(GAME_MSG3_COLOR);
// game message color #4 (messages starting with "~")
final ColorConfigurer gameMsg4Color = new ColorConfigurer(GAME_MSG4_COLOR,
Resources.getString("Chatter.game_messages_preference_4"), new Color(255, 0, 0));
gameMsg4Color.addPropertyChangeListener(e -> {
gameMsg4 = (Color) e.getNewValue();
makeStyleSheet(null);
});
globalPrefs.addOption(Resources.getString("Chatter.chat_window"), gameMsg4Color);
gameMsg4 = (Color) globalPrefs.getValue(GAME_MSG4_COLOR);
// game message color #5 (messages starting with "`")
final ColorConfigurer gameMsg5Color = new ColorConfigurer(GAME_MSG5_COLOR,
Resources.getString("Chatter.game_messages_preference_5"), new Color(153, 0, 153));
gameMsg5Color.addPropertyChangeListener(e -> {
gameMsg5 = (Color) e.getNewValue();
makeStyleSheet(null);
});
globalPrefs.addOption(Resources.getString("Chatter.chat_window"), gameMsg5Color);
gameMsg5 = (Color) globalPrefs.getValue(GAME_MSG5_COLOR);
final ColorConfigurer systemMsgColor = new ColorConfigurer(SYS_MSG_COLOR,
Resources.getString("Chatter.system_message_preference"), new Color(160, 160, 160));
systemMsgColor.addPropertyChangeListener(e -> {
systemMsg = (Color) e.getNewValue();
makeStyleSheet(null);
});
globalPrefs.addOption(Resources.getString("Chatter.chat_window"), systemMsgColor);
systemMsg = (Color) globalPrefs.getValue(SYS_MSG_COLOR);
final ColorConfigurer myChatColor = new ColorConfigurer(
MY_CHAT_COLOR,
Resources.getString("Chatter.my_text_preference"),
new Color(9, 32, 229));
myChatColor.addPropertyChangeListener(e -> {
myChat = (Color) e.getNewValue();
makeStyleSheet(null);
});
globalPrefs.addOption(Resources.getString("Chatter.chat_window"), myChatColor);
myChat = (Color) globalPrefs.getValue(MY_CHAT_COLOR);
final ColorConfigurer otherChatColor = new ColorConfigurer(
OTHER_CHAT_COLOR,
Resources.getString("Chatter.other_text_preference"),
new Color(0, 153, 255)
);
otherChatColor.addPropertyChangeListener(e -> {
otherChat = (Color) e.getNewValue();
makeStyleSheet(null);
});
globalPrefs.addOption(Resources.getString("Chatter.chat_window"), otherChatColor);
otherChat = (Color) globalPrefs.getValue(OTHER_CHAT_COLOR);
makeStyleSheet(myFont);
}
@Override
public void add(Buildable b) {
}
@Override
public Command decode(String s) {
if (!s.startsWith(DisplayText.PREFIX)) {
return null;
}
return new DisplayText(this, s.substring(DisplayText.PREFIX.length()));
}
@Override
public String encode(Command c) {
if (!(c instanceof DisplayText)) {
return null;
}
return DisplayText.PREFIX + ((DisplayText) c).getMessage();
}
/**
* Displays the message, Also logs and sends to the server a {@link Command}
* that displays this message.
*/
public void send(String msg) {
if (msg != null && !msg.isEmpty()) {
show(msg);
GameModule.getGameModule().sendAndLog(new DisplayText(this, msg));
}
}
/**
* Checks first for an intercepted console command; otherwise displays the message
* @param msg message to display if not a console command
* @param console potential console command (without any chat livery added to it)
*/
public void send(String msg, String console) {
if (!consoleHook(console, "", false)) {
send(msg);
}
}
/**
* Warning message method -- same as send, but accepts messages from static methods. For reporting soft-fail problems in modules.
*/
public static void warning(String msg) {
final Chatter chatter = GameModule.getGameModule().getChatter();
chatter.send(msg);
}
/**
* Classes other than the Chatter itself may forward KeyEvents to the Chatter by
* using this method
*/
public void keyCommand(KeyStroke e) {
if ((e.getKeyCode() == 0 || e.getKeyCode() == KeyEvent.CHAR_UNDEFINED)
&& !Character.isISOControl(e.getKeyChar())) {
if ((e.getModifiers() & KeyEvent.ALT_DOWN_MASK) != 0) {
return; // This catches occasional Alt+Key events that should not be forwarded to Chatter
}
input.setText(input.getText() + e.getKeyChar());
}
else if (e.isOnKeyRelease()) {
switch (e.getKeyCode()) {
case KeyEvent.VK_ENTER:
if (!input.getText().isEmpty())
send(formatChat(input.getText()), input.getText());
input.setText(""); //$NON-NLS-1$
break;
case KeyEvent.VK_BACK_SPACE:
case KeyEvent.VK_DELETE:
final String s = input.getText();
if (!s.isEmpty())
input.setText(s.substring(0, s.length() - 1));
break;
}
}
}
/**
* This is a {@link Command} object that, when executed, displays
* a text message in the Chatter's text area */
public static class DisplayText extends Command {
public static final String PREFIX = "CHAT"; //$NON-NLS-1$
private String msg;
private final Chatter c;
public DisplayText(Chatter c, String s) {
this.c = c;
msg = s;
if (msg.startsWith("<>")) { //NON-NLS
msg = "<(" + Chatter.getAnonymousUserName() + ")>" + s.substring(2); // HTML-friendly //NON-NLS
// angle brackets
}
else {
msg = s;
}
}
@Override
public void executeCommand() {
c.show(msg);
}
@Override
public Command myUndoCommand() {
return new DisplayText(c, Resources.getString("Chatter.undo_message", msg)); //$NON-NLS-1$
}
public String getMessage() {
return msg;
}
@Override
public String getDetails() {
return msg;
}
}
public static void main(String[] args) {
final Chatter chat = new Chatter();
final JFrame f = new JFrame();
f.add(chat);
f.pack();
f.setVisible(true);
}
/** @deprecated No Replacement */
@Deprecated(since = "2020-08-06", forRemoval = true)
public void setHandle(@SuppressWarnings("unused") String s) {
ProblemDialog.showDeprecated("2020-08-06"); //NON-NLS
}
/** @deprecated use {@link GlobalOptions#getPlayerId()} */
@Deprecated(since = "2020-08-06", forRemoval = true)
public String getHandle() {
ProblemDialog.showDeprecated("2020-08-06"); //NON-NLS
return GlobalOptions.getInstance().getPlayerId();
}
} |
package gradlebuild;
import com.google.common.collect.ImmutableList;
import groovy.util.Node;
import org.gradle.api.Action;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.artifacts.DependencySubstitutions;
import org.gradle.api.artifacts.component.ComponentSelector;
import org.gradle.api.artifacts.component.ProjectComponentSelector;
import org.gradle.api.file.ConfigurableFileCollection;
import org.gradle.api.internal.project.ProjectInternal;
import org.gradle.api.logging.StandardOutputListener;
import org.gradle.api.plugins.ExtensionContainer;
import org.gradle.api.plugins.JavaPluginConvention;
import org.gradle.api.provider.ProviderFactory;
import org.gradle.api.publish.PublishingExtension;
import org.gradle.api.publish.maven.MavenPublication;
import org.gradle.api.tasks.SourceSet;
import org.gradle.api.tasks.TaskContainer;
import org.gradle.api.tasks.TaskProvider;
import org.gradle.api.tasks.bundling.Jar;
import org.gradle.api.tasks.compile.JavaCompile;
import org.gradle.api.tasks.testing.Test;
import org.gradle.api.tasks.testing.TestDescriptor;
import org.gradle.api.tasks.testing.TestListener;
import org.gradle.api.tasks.testing.TestResult;
import org.gradle.internal.jvm.Jvm;
import org.gradle.internal.service.ServiceRegistry;
import org.gradle.language.cpp.CppSourceSet;
import org.gradle.language.cpp.tasks.CppCompile;
import org.gradle.model.Each;
import org.gradle.model.ModelMap;
import org.gradle.model.Mutate;
import org.gradle.model.RuleSource;
import org.gradle.model.internal.registry.ModelRegistry;
import org.gradle.nativeplatform.NativeBinarySpec;
import org.gradle.nativeplatform.PreprocessingTool;
import org.gradle.nativeplatform.SharedLibraryBinarySpec;
import org.gradle.nativeplatform.Tool;
import org.gradle.nativeplatform.internal.NativeBinarySpecInternal;
import org.gradle.nativeplatform.platform.Architecture;
import org.gradle.nativeplatform.platform.NativePlatform;
import org.gradle.nativeplatform.platform.OperatingSystem;
import org.gradle.nativeplatform.platform.internal.DefaultNativePlatform;
import org.gradle.nativeplatform.tasks.LinkSharedLibrary;
import org.gradle.nativeplatform.toolchain.Clang;
import org.gradle.nativeplatform.toolchain.Gcc;
import org.gradle.nativeplatform.toolchain.NativeToolChainRegistry;
import org.gradle.nativeplatform.toolchain.VisualCpp;
import org.gradle.platform.base.BinarySpec;
import org.gradle.platform.base.PlatformContainer;
import org.gradle.platform.base.SourceComponentSpec;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import static gradlebuild.NativeRulesUtils.addPlatform;
@SuppressWarnings("UnstableApiUsage")
public abstract class JniPlugin implements Plugin<Project> {
private static String binaryToVariantName(NativeBinarySpec binary) {
return binary.getTargetPlatform().getName().replace('_', '-');
}
@Override
public void apply(Project project) {
project.getPluginManager().apply(NativePlatformComponentPlugin.class);
VariantsExtension variants = project.getExtensions().getByType(VariantsExtension.class);
project.getPluginManager().apply(JniRules.class);
configureCppTasks(project);
configureNativeVersionGeneration(project);
configureJniTest(project);
configurePomOfMainJar(project, variants);
// Enabling this property means that the tests will try to resolve an external dependency for native platform
// and test that instead of building native platform for the current machine.
// The external dependency can live in the file repository `incoming-repo`.
boolean testVersionFromLocalRepository = project.getProviders().gradleProperty("testVersionFromLocalRepository").forUseAtConfigurationTime().isPresent();
if (testVersionFromLocalRepository) {
setupDependencySubstitutionForTestTask(project);
}
configureNativeJars(project, variants, testVersionFromLocalRepository);
}
private void configureJniTest(Project project) {
TaskProvider<Test> testJni = project.getTasks().register("testJni", Test.class, task -> {
task.jvmArgs("-Xcheck:jni");
// Only run tests that have the category
task.useJUnit(jUnitOptions ->
jUnitOptions.includeCategories("net.rubygrapefruit.platform.testfixture.JniChecksEnabled")
);
// Check standard output for JNI warnings and fail if we find anything
DetectJniWarnings detectJniWarnings = new DetectJniWarnings();
task.addTestListener(detectJniWarnings);
task.getLogging().addStandardOutputListener(detectJniWarnings);
task.doLast(new Action<Task>() {
@Override
public void execute(Task task) {
List<String> detectedWarnings = detectJniWarnings.getDetectedWarnings();
if (!detectedWarnings.isEmpty()) {
throw new RuntimeException(String.format(
"Detected JNI check warnings on standard output while executing tests:\n - %s",
String.join("\n - ", detectedWarnings)
));
}
}
});
});
project.getTasks().named("check", check -> check.dependsOn(testJni));
}
private void configureNativeVersionGeneration(Project project) {
NativePlatformVersionExtension nativeVersion = project.getExtensions().create("nativeVersion", NativePlatformVersionExtension.class);
File generatedFilesDir = new File(project.getBuildDir(), "generated");
TaskProvider<WriteNativeVersionSources> writeNativeVersionSources = project.getTasks().register("writeNativeVersionSources", WriteNativeVersionSources.class, task -> {
task.getGeneratedNativeHeaderDirectory().set(new File(generatedFilesDir, "version/header"));
task.getGeneratedJavaSourcesDir().set(new File(generatedFilesDir, "version/java"));
task.getVersionClassPackageName().set(nativeVersion.getVersionClassPackageName());
task.getVersionClassName().set(nativeVersion.getVersionClassName());
});
project.getTasks().withType(CppCompile.class).configureEach(task ->
task.includes(writeNativeVersionSources.flatMap(WriteNativeVersionSources::getGeneratedNativeHeaderDirectory)
));
JavaPluginConvention javaPluginConvention = project.getConvention().getPlugin(JavaPluginConvention.class);
javaPluginConvention.getSourceSets().getByName(SourceSet.MAIN_SOURCE_SET_NAME).java(javaSources ->
javaSources.srcDir(writeNativeVersionSources.flatMap(WriteNativeVersionSources::getGeneratedJavaSourcesDir))
);
}
@SuppressWarnings("unchecked")
private void configureNativeJars(Project project, VariantsExtension variants, boolean testVersionFromLocalRepository) {
TaskProvider<Jar> emptyZip = project.getTasks().register("emptyZip", Jar.class, jar -> jar.getArchiveClassifier().set("empty"));
// We register the publications here, so they are available when the project is used as a composite build.
// When we don't use the software model plugins anymore, then this can move out of the afterEvaluate block.
project.afterEvaluate(ignored -> {
String artifactId = project.getTasks().named("jar", Jar.class).get().getArchiveBaseName().get();
ModelRegistry modelRegistry = ((ProjectInternal) project).getModelRegistry();
// Realize the software model components, so we can create the corresponding publications.
modelRegistry.realize("components", ModelMap.class)
.forEach(spec -> getBinaries(spec).withType(NativeBinarySpec.class)
.forEach(binary -> {
if (variants.getVariantNames().get().contains(binaryToVariantName(binary)) && binary.isBuildable()) {
String variantName = binaryToVariantName(binary);
String taskName = "jar-" + variantName;
Jar foundNativeJar = (Jar) project.getTasks().findByName(taskName);
Jar nativeJar = foundNativeJar == null
? project.getTasks().create(taskName, Jar.class, jar -> jar.getArchiveBaseName().set(artifactId + "-" + variantName))
: foundNativeJar;
if (foundNativeJar == null) {
project.getArtifacts().add("runtimeElements", nativeJar);
project.getExtensions().configure(PublishingExtension.class, publishingExtension -> publishingExtension.publications(publications -> publications.create(variantName, MavenPublication.class, publication -> {
publication.artifact(nativeJar);
publication.artifact(emptyZip.get(), it -> it.setClassifier("sources"));
publication.artifact(emptyZip.get(), it -> it.setClassifier("javadoc"));
publication.setArtifactId(nativeJar.getArchiveBaseName().get());
})));
}
binary.getTasks().withType(LinkSharedLibrary.class, builderTask ->
nativeJar.into(String.join(
"/",
project.getGroup().toString().replace(".", "/"),
"platform",
variantName
), it -> it.from(builderTask.getLinkedFile()))
);
if (!testVersionFromLocalRepository) {
project.getTasks().withType(Test.class).configureEach(it -> ((ConfigurableFileCollection) it.getClasspath()).from(nativeJar));
}
}
}));
});
}
private void setupDependencySubstitutionForTestTask(Project project) {
// We need to change the group here, since dependency substitution will not replace
// a project artifact with an external artifact with the same GAV coordinates.
project.setGroup("new-group-for-root-project");
project.getConfigurations().all(configuration ->
{
DependencySubstitutions dependencySubstitution = configuration.getResolutionStrategy().getDependencySubstitution();
dependencySubstitution.all(spec -> {
ComponentSelector requested = spec.getRequested();
if (requested instanceof ProjectComponentSelector) {
Project projectDependency = project.project(((ProjectComponentSelector) requested).getProjectPath());
// Exclude test fixtures by excluding requested dependencies with capabilities.
if (requested.getRequestedCapabilities().isEmpty()) {
spec.useTarget(dependencySubstitution.module(String.join(":", NativePlatformComponentPlugin.GROUP_ID, projectDependency.getName(), projectDependency.getVersion().toString())));
}
}
});
});
project.getRepositories().maven(maven -> {
maven.setName("IncomingLocalRepository");
maven.setUrl(project.getRootProject().file("incoming-repo"));
});
}
private void configurePomOfMainJar(Project project, VariantsExtension variants) {
project.getExtensions().configure(
PublishingExtension.class,
extension -> extension.getPublications().named("main", MavenPublication.class, main ->
main.getPom().withXml(xmlProvider -> {
Node node = xmlProvider.asNode();
Node deps = node.appendNode("dependencies");
variants.getVariantNames().get().forEach(variantName -> {
Node dep = deps.appendNode("dependency");
dep.appendNode("groupId", project.getGroup());
dep.appendNode("artifactId", main.getArtifactId() + "-" + variantName);
dep.appendNode("version", project.getVersion());
dep.appendNode("scope", "runtime");
});
})));
}
private void configureCppTasks(Project project) {
TaskContainer tasks = project.getTasks();
TaskProvider<JavaCompile> compileJavaProvider = tasks.named("compileJava", JavaCompile.class);
tasks.withType(CppCompile.class)
.configureEach(task -> task.includes(
compileJavaProvider.flatMap(it -> it.getOptions().getHeaderOutputDirectory())
));
}
@SuppressWarnings("unchecked")
private static ModelMap<BinarySpec> getBinaries(Object modelSpec) {
try {
return (ModelMap<BinarySpec>) modelSpec.getClass().getMethod("getBinaries").invoke(modelSpec);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
public static class JniRules extends RuleSource {
@Mutate
void createPlatforms(PlatformContainer platformContainer) {
addPlatform(platformContainer, "osx_amd64", "osx", "amd64");
addPlatform(platformContainer, "osx_aarch64", "osx", "aarch64");
addPlatform(platformContainer, "linux_amd64", "linux", "amd64");
addPlatform(platformContainer, "linux_aarch64", "linux", "aarch64");
addPlatform(platformContainer, "windows_i386", "windows", "i386");
addPlatform(platformContainer, "windows_amd64", "windows", "amd64");
addPlatform(platformContainer, "windows_i386_min", "windows", "i386");
addPlatform(platformContainer, "windows_amd64_min", "windows", "amd64");
}
@Mutate void createToolChains(NativeToolChainRegistry toolChainRegistry) {
toolChainRegistry.create("gcc", Gcc.class, toolChain -> {
// The core Gradle toolchain for gcc only targets x86 and x86_64 out of the box.
toolChain.target("linux_aarch64");
});
toolChainRegistry.create("clang", Clang.class, toolChain -> {
// The core Gradle toolchain for Clang only targets x86 and x86_64 out of the box.
OperatingSystem os = new DefaultNativePlatform("current").getOperatingSystem();
if (os.isMacOsX()) {
toolChain.target("osx_aarch64");
}
});
toolChainRegistry.create("visualCpp", VisualCpp.class);
}
@Mutate
void addComponentSourcesSetsToProjectSourceSet(ModelMap<Task> tasks, ModelMap<SourceComponentSpec> sourceContainer) {
sourceContainer.forEach(sources -> sources.getSources().withType(CppSourceSet.class).forEach(sourceSet ->
tasks.withType(WriteNativeVersionSources.class, task -> {
task.getNativeSources().from(sourceSet.getSource().getSourceDirectories());
task.getNativeSources().from(sourceSet.getExportedHeaders().getSourceDirectories());
})));
}
@Mutate void configureBinaries(@Each NativeBinarySpecInternal binarySpec) {
DefaultNativePlatform currentPlatform = new DefaultNativePlatform("current");
Architecture currentArch = currentPlatform.getArchitecture();
NativePlatform targetPlatform = binarySpec.getTargetPlatform();
Architecture targetArch = targetPlatform.getArchitecture();
OperatingSystem targetOs = targetPlatform.getOperatingSystem();
if (ImmutableList.of("linux", "freebsd").contains(targetOs.getName()) && !targetArch.equals(currentArch)) {
// Native plugins don't detect whether multilib support is available or not. Assume not for now
binarySpec.setBuildable(false);
}
PreprocessingTool cppCompiler = binarySpec.getCppCompiler();
Tool linker = binarySpec.getLinker();
if (targetOs.isMacOsX()) {
cppCompiler.getArgs().addAll(determineJniIncludes("darwin"));
cppCompiler.args("-mmacosx-version-min=10.9");
linker.args("-mmacosx-version-min=10.9");
linker.args("-framework", "CoreServices");
} else if (targetOs.isLinux()) {
cppCompiler.getArgs().addAll(determineJniIncludes("linux"));
cppCompiler.args("-D_FILE_OFFSET_BITS=64");
} else if (targetOs.isWindows()) {
if (binarySpec.getName().contains("_min")) {
cppCompiler.define("WINDOWS_MIN");
}
cppCompiler.getArgs().addAll(determineWindowsJniIncludes());
linker.args("Shlwapi.lib", "Advapi32.lib");
} else if (targetOs.isFreeBSD()) {
cppCompiler.getArgs().addAll(determineJniIncludes("freebsd"));
}
}
@Mutate void configureSharedLibraryBinaries(@Each SharedLibraryBinarySpec binarySpec, ExtensionContainer extensions, ServiceRegistry serviceRegistry) {
// Only depend on variants which can be built on the current machine
boolean onlyLocalVariants = serviceRegistry.get(ProviderFactory.class).gradleProperty("onlyLocalVariants").forUseAtConfigurationTime().isPresent();
if (onlyLocalVariants && !binarySpec.isBuildable()) {
return;
}
String variantName = binaryToVariantName(binarySpec);
extensions.getByType(VariantsExtension.class).getVariantNames().add(variantName);
}
private List<String> determineJniIncludes(String osSpecificInclude) {
Jvm currentJvm = Jvm.current();
File jvmIncludePath = new File(currentJvm.getJavaHome(), "include");
return ImmutableList.of(
"-I", jvmIncludePath.getAbsolutePath(),
"-I", new File(jvmIncludePath, osSpecificInclude).getAbsolutePath()
);
}
private List<String> determineWindowsJniIncludes() {
Jvm currentJvm = Jvm.current();
File jvmIncludePath = new File(currentJvm.getJavaHome(), "include");
return ImmutableList.of(
"-I" + jvmIncludePath.getAbsolutePath(),
"-I" + new File(jvmIncludePath, "win32").getAbsolutePath()
);
}
}
private static class DetectJniWarnings implements TestListener, StandardOutputListener {
private String currentTest;
private List<String> detectedWarnings = new ArrayList<>();
@Override
public void beforeSuite(TestDescriptor testDescriptor) {}
@Override
public void afterSuite(TestDescriptor testDescriptor, TestResult testResult) {}
@Override
public void beforeTest(TestDescriptor testDescriptor) {
currentTest = testDescriptor.getClassName() + "." + testDescriptor.getDisplayName();
}
@Override
public void afterTest(TestDescriptor testDescriptor, TestResult testResult) {
currentTest = null;
}
@Override
public void onOutput(CharSequence message) {
if (currentTest != null && message.toString().startsWith("WARNING")) {
detectedWarnings.add(String.format("%s (test: %s)", message, currentTest));
}
}
public List<String> getDetectedWarnings() {
return detectedWarnings;
}
}
} |
package com.runescape.api;
import com.runescape.api.bestiary.Bestiary;
import com.runescape.api.ge.GrandExchange;
import com.runescape.api.hiscores.Hiscores;
/**
* Represents an instance of the RuneScape web-services API.
*/
public final class RuneScapeAPI {
/**
* Creates a new {@link RuneScapeAPI} backed by specific {@link Client} implementation.
* @param client The {@link Client} implementation.
* @return The {@link RuneScapeAPI}.
*/
public static RuneScapeAPI create(Client client) {
return new RuneScapeAPI(client);
}
/**
* Creates a new {@link RuneScapeAPI} backed by a {@link HttpClient}.
* @return The {@link RuneScapeAPI}.
*/
public static RuneScapeAPI createHttp() {
return create(new HttpClient());
}
/**
* The {@link Bestiary}.
*/
private final Bestiary bestiary;
/**
* The {@link GrandExchange}.
*/
private final GrandExchange grandExchange;
/**
* The {@link Hiscores}.
*/
private final Hiscores hiscores;
/**
* Creates a new {@link RuneScapeAPI}.
*/
private RuneScapeAPI(Client client) {
this.bestiary = new Bestiary(client);
this.grandExchange = new GrandExchange(client);
this.hiscores = new Hiscores(client);
}
/**
* Gets the {@link Bestiary}.
* @return The {@link Bestiary}.
*/
public Bestiary getBestiary() {
return bestiary;
}
/**
* Gets the {@link GrandExchange}.
* @return The {@link GrandExchange}.
*/
public GrandExchange getGrandExchange() {
return grandExchange;
}
/**
* Gets the {@link Hiscores}.
* @return The {@link Hiscores}.
*/
public Hiscores getHiscores() {
return hiscores;
}
} |
package org.jfree.chart.util;
/**
* A utility class for checking parameters.
*
* @since 1.0.14
*/
public class ParamChecks {
public static void nullNotPermitted(Object param, String name) {
if (param == null) {
throw new IllegalArgumentException("Null '" + name + "' argument");
}
}
} |
package jolie.net;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import jolie.Interpreter;
import jolie.JolieThread;
import jolie.lang.Constants;
import jolie.net.ext.CommChannelFactory;
import jolie.net.ext.CommListenerFactory;
import jolie.net.ext.CommProtocolFactory;
import jolie.net.ports.InputPort;
import jolie.net.ports.OutputPort;
import jolie.net.protocols.CommProtocol;
import jolie.process.Process;
import jolie.runtime.FaultException;
import jolie.runtime.InputOperation;
import jolie.runtime.InvalidIdException;
import jolie.runtime.OneWayOperation;
import jolie.runtime.TimeoutHandler;
import jolie.runtime.Value;
import jolie.runtime.VariablePath;
import jolie.runtime.correlation.CorrelationError;
import jolie.runtime.typing.TypeCheckingException;
/**
* Handles the communications mechanisms for an Interpreter instance.
*
* Each CommCore is related to an Interpreter, and each Interpreter owns one and only CommCore instance.
*
* @author Fabrizio Montesi
*/
public class CommCore
{
private final Map< String, CommListener > listenersMap = new HashMap< String, CommListener >();
private final static int CHANNEL_HANDLER_TIMEOUT = 5;
private final ThreadGroup threadGroup;
private static final Logger logger = Logger.getLogger( "JOLIE" );
private final int connectionsLimit;
// private final int connectionCacheSize;
private final Interpreter interpreter;
private final ReadWriteLock channelHandlersLock = new ReentrantReadWriteLock( true );
// Location URI -> Protocol name -> Persistent CommChannel object
private final Map< URI, Map< String, CommChannel > > persistentChannels =
new HashMap< URI, Map< String, CommChannel > >();
private void removePersistentChannel( URI location, String protocol, Map< String, CommChannel > protocolChannels )
{
protocolChannels.remove( protocol );
if ( protocolChannels.isEmpty() ) {
persistentChannels.remove( location );
}
}
private void removePersistentChannel( URI location, String protocol, CommChannel channel )
{
if ( persistentChannels.containsKey( location ) ) {
if ( persistentChannels.get( location ).get( protocol ) == channel ) {
removePersistentChannel( location, protocol, persistentChannels.get( location ) );
}
}
}
public CommChannel getPersistentChannel( URI location, String protocol )
{
CommChannel ret = null;
synchronized( persistentChannels ) {
Map< String, CommChannel > protocolChannels = persistentChannels.get( location );
if ( protocolChannels != null ) {
ret = protocolChannels.get( protocol );
if ( ret != null ) {
if ( ret.lock.tryLock() ) {
if ( ret.isOpen() ) {
/*
* We are going to return this channel, but first
* check if it supports concurrent use.
* If not, then others should not access this until
* the caller is finished using it.
*/
//if ( ret.isThreadSafe() == false ) {
removePersistentChannel( location, protocol, protocolChannels );
//} else {
// If we return a channel, make sure it will not timeout!
ret.setTimeoutHandler( null );
//if ( ret.timeoutHandler() != null ) {
//interpreter.removeTimeoutHandler( ret.timeoutHandler() );
// ret.setTimeoutHandler( null );
ret.lock.unlock();
} else { // Channel is closed
removePersistentChannel( location, protocol, protocolChannels );
ret.lock.unlock();
ret = null;
}
} else { // Channel is busy
removePersistentChannel( location, protocol, protocolChannels );
ret = null;
}
}
}
}
return ret;
}
private void setTimeoutHandler( final CommChannel channel, final URI location, final String protocol )
{
/*if ( channel.timeoutHandler() != null ) {
interpreter.removeTimeoutHandler( channel.timeoutHandler() );
}*/
final TimeoutHandler handler = new TimeoutHandler( interpreter.persistentConnectionTimeout() ) {
@Override
public void onTimeout()
{
try {
synchronized( persistentChannels ) {
if ( channel.timeoutHandler() == this ) {
removePersistentChannel( location, protocol, channel );
channel.close();
channel.setTimeoutHandler( null );
}
}
} catch( IOException e ) {
interpreter.logSevere( e );
}
}
};
channel.setTimeoutHandler( handler );
interpreter.addTimeoutHandler( handler );
}
public void putPersistentChannel( URI location, String protocol, final CommChannel channel )
{
synchronized( persistentChannels ) {
Map< String, CommChannel > protocolChannels = persistentChannels.get( location );
if ( protocolChannels == null ) {
protocolChannels = new HashMap< String, CommChannel >();
persistentChannels.put( location, protocolChannels );
}
// Set the timeout
setTimeoutHandler( channel, location, protocol );
// Put the protocol in the cache (may overwrite another one)
protocolChannels.put( protocol, channel );
/*if ( protocolChannels.size() <= connectionCacheSize && protocolChannels.containsKey( protocol ) == false ) {
// Set the timeout
setTimeoutHandler( channel );
// Put the protocol in the cache
protocolChannels.put( protocol, channel );
} else {
try {
if ( protocolChannels.get( protocol ) != channel ) {
channel.close();
} else {
setTimeoutHandler( channel );
}
} catch( IOException e ) {
interpreter.logWarning( e );
}
}*/
}
}
/**
* Returns the Interpreter instance this CommCore refers to.
* @return the Interpreter instance this CommCore refers to
*/
public Interpreter interpreter()
{
return interpreter;
}
/**
* Constructor.
* @param interpreter the Interpreter to refer to for this CommCore operations
* @param connectionsLimit if more than zero, specifies an upper bound to the connections handled in parallel.
* @throws java.io.IOException
*/
public CommCore( Interpreter interpreter, int connectionsLimit /*, int connectionsCacheSize */ )
throws IOException
{
this.interpreter = interpreter;
this.localListener = LocalListener.create( interpreter );
this.connectionsLimit = connectionsLimit;
// this.connectionCacheSize = connectionsCacheSize;
this.threadGroup = new ThreadGroup( "CommCore-" + interpreter.hashCode() );
if ( connectionsLimit > 0 ) {
executorService = Executors.newFixedThreadPool( connectionsLimit, new CommThreadFactory() );
} else {
executorService = Executors.newCachedThreadPool( new CommThreadFactory() );
}
//TODO make socket an extension, too?
CommListenerFactory listenerFactory = new SocketListenerFactory( this );
listenerFactories.put( "socket", listenerFactory );
CommChannelFactory channelFactory = new SocketCommChannelFactory( this );
channelFactories.put( "socket", channelFactory );
}
/**
* Returns the Logger used by this CommCore.
* @return the Logger used by this CommCore
*/
public Logger logger()
{
return logger;
}
/**
* Returns the connectionsLimit of this CommCore.
* @return the connectionsLimit of this CommCore
*/
public int connectionsLimit()
{
return connectionsLimit;
}
public ThreadGroup threadGroup()
{
return threadGroup;
}
private final Collection< Process > protocolConfigurations = new LinkedList< Process > ();
public Collection< Process > protocolConfigurations()
{
return protocolConfigurations;
}
public CommListener getListenerByInputPortName( String serviceName )
{
return listenersMap.get( serviceName );
}
private final Map< String, CommChannelFactory > channelFactories =
new HashMap< String, CommChannelFactory > ();
private CommChannelFactory getCommChannelFactory( String name )
throws IOException
{
CommChannelFactory factory = channelFactories.get( name );
if ( factory == null ) {
factory = interpreter.getClassLoader().createCommChannelFactory( name, this );
if ( factory != null ) {
channelFactories.put( name, factory );
}
}
return factory;
}
public CommChannel createCommChannel( URI uri, OutputPort port )
throws IOException
{
String medium = uri.getScheme();
CommChannelFactory factory = getCommChannelFactory( medium );
if ( factory == null ) {
throw new UnsupportedCommMediumException( medium );
}
return factory.createChannel( uri, port );
}
private final Map< String, CommProtocolFactory > protocolFactories =
new HashMap< String, CommProtocolFactory > ();
public CommProtocolFactory getCommProtocolFactory( String name )
throws IOException
{
CommProtocolFactory factory = protocolFactories.get( name );
if ( factory == null ) {
factory = interpreter.getClassLoader().createCommProtocolFactory( name, this );
if ( factory != null ) {
protocolFactories.put( name, factory );
}
}
return factory;
}
public CommProtocol createOutputCommProtocol( String protocolId, VariablePath configurationPath, URI uri )
throws IOException
{
CommProtocolFactory factory = getCommProtocolFactory( protocolId );
if ( factory == null ) {
throw new UnsupportedCommProtocolException( protocolId );
}
return factory.createOutputProtocol( configurationPath, uri );
}
public CommProtocol createInputCommProtocol( String protocolId, VariablePath configurationPath, URI uri )
throws IOException
{
CommProtocolFactory factory = getCommProtocolFactory( protocolId );
if ( factory == null ) {
throw new UnsupportedCommProtocolException( protocolId );
}
return factory.createInputProtocol( configurationPath, uri );
}
private final Map< String, CommListenerFactory > listenerFactories =
new HashMap< String, CommListenerFactory > ();
private final LocalListener localListener;
public LocalCommChannel getLocalCommChannel()
{
return new LocalCommChannel( interpreter, localListener );
}
public LocalCommChannel getLocalCommChannel( CommListener listener )
{
return new LocalCommChannel( interpreter, listener );
}
public CommListenerFactory getCommListenerFactory( String name )
throws IOException
{
CommListenerFactory factory = listenerFactories.get( name );
if ( factory == null ) {
factory = interpreter.getClassLoader().createCommListenerFactory( name, this );
if ( factory != null ) {
listenerFactories.put( name, factory );
}
}
return factory;
}
public LocalListener localListener()
{
return localListener;
}
public void addLocalInputPort( InputPort inputPort )
throws IOException
{
localListener.mergeInterface( inputPort.getInterface() );
localListener.addAggregations( inputPort.aggregationMap() );
localListener.addRedirections( inputPort.redirectionMap() );
listenersMap.put( inputPort.name(), localListener );
}
/**
* Adds an input port to this <code>CommCore</code>.
* This method is not thread-safe.
* @param inputPort the {@link InputPort} to add
* @param protocolFactory the <code>CommProtocolFactory</code> to use for the input port
* @param protocolConfigurationProcess the protocol configuration process to execute for configuring the created protocols
* @throws java.io.IOException in case of some underlying implementation error
* @see URI
* @see CommProtocolFactory
*/
public void addInputPort(
InputPort inputPort,
CommProtocolFactory protocolFactory,
Process protocolConfigurationProcess
)
throws IOException
{
protocolConfigurations.add( protocolConfigurationProcess );
String medium = inputPort.location().getScheme();
CommListenerFactory factory = getCommListenerFactory( medium );
if ( factory == null ) {
throw new UnsupportedCommMediumException( medium );
}
CommListener listener = factory.createListener(
interpreter,
protocolFactory,
inputPort
);
listenersMap.put( inputPort.name(), listener );
}
private final ExecutorService executorService;
private class CommThreadFactory implements ThreadFactory {
public Thread newThread( Runnable r )
{
return new CommChannelHandler( interpreter, r );
}
}
private final static Pattern pathSplitPattern = Pattern.compile( "/" );
private class CommChannelHandlerRunnable implements Runnable {
private final CommChannel channel;
private final InputPort port;
public CommChannelHandlerRunnable( CommChannel channel, InputPort port )
{
this.channel = channel;
this.port = port;
}
private void forwardResponse( CommMessage message )
throws IOException
{
message = new CommMessage(
channel.redirectionMessageId(),
message.operationName(),
message.resourcePath(),
message.value(),
message.fault()
);
try {
try {
channel.redirectionChannel().send( message );
} finally {
try {
if ( channel.redirectionChannel().toBeClosed() ) {
channel.redirectionChannel().close();
} else {
channel.redirectionChannel().disposeForInput();
}
} finally {
channel.setRedirectionChannel( null );
}
}
} finally {
channel.closeImpl();
}
}
private void handleRedirectionInput( CommMessage message, String[] ss )
throws IOException, URISyntaxException
{
// Redirection
String rPath;
if ( ss.length <= 2 ) {
rPath = "/";
} else {
StringBuilder builder = new StringBuilder();
for( int i = 2; i < ss.length; i++ ) {
builder.append( '/' );
builder.append( ss[ i ] );
}
rPath = builder.toString();
}
OutputPort oPort = port.redirectionMap().get( ss[1] );
if ( oPort == null ) {
String error = "Discarded a message for resource " + ss[1] +
", not specified in the appropriate redirection table.";
interpreter.logWarning( error );
throw new IOException( error );
}
try {
CommChannel oChannel = oPort.getNewCommChannel();
CommMessage rMessage =
new CommMessage(
message.id(),
message.operationName(),
rPath,
message.value(),
message.fault()
);
oChannel.setRedirectionChannel( channel );
oChannel.setRedirectionMessageId( rMessage.id() );
oChannel.send( rMessage );
oChannel.setToBeClosed( false );
oChannel.disposeForInput();
} catch( IOException e ) {
channel.send( CommMessage.createFaultResponse( message, new FaultException( Constants.IO_EXCEPTION_FAULT_NAME, e ) ) );
channel.disposeForInput();
throw e;
}
}
private void handleAggregatedInput( CommMessage message, AggregatedOperation operation )
throws IOException, URISyntaxException
{
operation.runAggregationBehaviour( message, channel );
}
private void handleDirectMessage( CommMessage message )
throws IOException
{
try {
InputOperation operation =
interpreter.getInputOperation( message.operationName() );
try {
operation.requestType().check( message.value() );
interpreter.correlationEngine().onMessageReceive( message, channel );
if ( operation instanceof OneWayOperation ) {
// We need to send the acknowledgement
channel.send( CommMessage.createEmptyResponse( message ) );
//channel.release();
}
} catch( TypeCheckingException e ) {
interpreter.logWarning( "Received message TypeMismatch (input operation " + operation.id() + "): " + e.getMessage() );
try {
channel.send( CommMessage.createFaultResponse( message, new FaultException( jolie.lang.Constants.TYPE_MISMATCH_FAULT_NAME, e.getMessage() ) ) );
} catch( IOException ioe ) {
Interpreter.getInstance().logSevere( ioe );
}
} catch( CorrelationError e ) {
interpreter.logWarning( "Received a non correlating message for operation " + message.operationName() + ". Sending CorrelationError to the caller." );
channel.send( CommMessage.createFaultResponse( message, new FaultException( "CorrelationError", "The message you sent can not be correlated with any session and can not be used to start a new session." ) ) );
}
} catch( InvalidIdException e ) {
interpreter.logWarning( "Received a message for undefined operation " + message.operationName() + ". Sending IOException to the caller." );
channel.send( CommMessage.createFaultResponse( message, new FaultException( "IOException", "Invalid operation: " + message.operationName() ) ) );
} finally {
channel.disposeForInput();
}
}
private void handleMessage( CommMessage message )
throws IOException
{
try {
String[] ss = pathSplitPattern.split( message.resourcePath() );
if ( ss.length > 1 ) {
handleRedirectionInput( message, ss );
} else {
if ( port.canHandleInputOperationDirectly( message.operationName() ) ) {
handleDirectMessage( message );
} else {
AggregatedOperation operation = port.getAggregatedOperation( message.operationName() );
if ( operation == null ) {
interpreter.logWarning(
"Received a message for operation " + message.operationName() +
", not specified in the input port at the receiving service. Sending IOException to the caller."
);
channel.send( CommMessage.createFaultResponse( message, new FaultException( "IOException", "Invalid operation: " + message.operationName() ) ) );
channel.disposeForInput();
} else {
handleAggregatedInput( message, operation );
}
}
}
} catch( URISyntaxException e ) {
interpreter.logSevere( e );
}
}
public void run()
{
CommChannelHandler thread = CommChannelHandler.currentThread();
thread.setExecutionThread( interpreter().initThread() );
channel.lock.lock();
channelHandlersLock.readLock().lock();
try {
if ( channel.redirectionChannel() == null ) {
assert( port != null );
CommMessage message = channel.recv();
if ( message != null ) {
handleMessage( message );
} else {
channel.disposeForInput();
}
} else {
channel.lock.unlock();
CommMessage response = channel.recvResponseFor( new CommMessage( channel.redirectionMessageId(), "", "/", Value.UNDEFINED_VALUE, null ) );
if ( response != null ) {
forwardResponse( response );
}
}
} catch( ChannelClosingException e ) {
interpreter.logFine( e );
} catch( IOException e ) {
interpreter.logSevere( e );
try {
channel.closeImpl();
} catch( IOException e2 ) {
interpreter.logSevere( e2 );
}
} finally {
channelHandlersLock.readLock().unlock();
if ( channel.lock.isHeldByCurrentThread() ) {
channel.lock.unlock();
}
thread.setExecutionThread( null );
}
}
}
/**
* Schedules the receiving of a message on this <code>CommCore</code> instance.
* @param channel the <code>CommChannel</code> to use for receiving the message
* @param port the <code>Port</code> responsible for the message receiving
*/
public void scheduleReceive( CommChannel channel, InputPort port )
{
executorService.execute( new CommChannelHandlerRunnable( channel, port ) );
}
/**
* Runs an asynchronous task in this CommCore internal thread pool.
* @param r the Runnable object to execute
*/
public void execute( Runnable r )
{
executorService.execute( r );
}
protected void startCommChannelHandler( Runnable r )
{
executorService.execute( r );
}
/**
* Initializes the communication core, starting its communication listeners.
* This method is asynchronous. When it returns, every communication listener has
* been issued to start, but they are not guaranteed to be ready to receive messages.
* This method throws an exception if some listener can not be issued to start;
* other errors will be logged by the listener through the interpreter logger.
*
* @throws IOException in case of some underlying <code>CommListener</code> initialization error
* @see CommListener
*/
public void init()
throws IOException
{
for( Entry< String, CommListener > entry : listenersMap.entrySet() ) {
entry.getValue().start();
}
active = true;
}
private PollingThread pollingThread = null;
private PollingThread pollingThread()
{
synchronized( this ) {
if ( pollingThread == null ) {
pollingThread = new PollingThread();
pollingThread.start();
}
}
return pollingThread;
}
private class PollingThread extends Thread {
private final Set< CommChannel > channels = new HashSet< CommChannel >();
private PollingThread()
{
super( threadGroup, interpreter.programFilename() + "-PollingThread" );
}
@Override
public void run()
{
Iterator< CommChannel > it;
CommChannel channel;
while( active ) {
synchronized( this ) {
if ( channels.isEmpty() ) {
// Do not busy-wait for no reason
try {
this.wait();
} catch( InterruptedException e ) {}
}
it = channels.iterator();
while( it.hasNext() ) {
channel = it.next();
try {
if ( ((PollableCommChannel)channel).isReady() ) {
it.remove();
scheduleReceive( channel, channel.parentInputPort() );
}
} catch( IOException e ) {
e.printStackTrace();
}
}
}
try {
Thread.sleep( 50 ); // msecs
} catch( InterruptedException e ) {}
}
for( CommChannel c : channels ) {
try {
c.closeImpl();
} catch( IOException e ) {
interpreter.logWarning( e );
}
}
}
public void register( CommChannel channel )
throws IOException
{
if ( !(channel instanceof PollableCommChannel) ) {
throw new IOException( "Channels registering for polling must implement PollableCommChannel interface");
}
synchronized( this ) {
channels.add( channel );
if ( channels.size() == 1 ) { // set was empty
this.notify();
}
}
}
}
/**
* Registers a <code>CommChannel</code> for input polling.
* The registered channel must implement the {@link PollableCommChannel <code>PollableCommChannel</code>} interface.
* @param channel the channel to register for polling
* @throws java.io.IOException in case the channel could not be registered for polling
* @see CommChannel
* @see PollableCommChannel
*/
public void registerForPolling( CommChannel channel )
throws IOException
{
pollingThread().register( channel );
}
private SelectorThread selectorThread = null;
private final Object selectorThreadMonitor = new Object();
private SelectorThread selectorThread()
throws IOException
{
synchronized( selectorThreadMonitor ) {
if ( selectorThread == null ) {
selectorThread = new SelectorThread( interpreter );
selectorThread.start();
}
}
return selectorThread;
}
private class SelectorThread extends JolieThread {
private final Selector selector;
private final Object selectingMutex = new Object();
public SelectorThread( Interpreter interpreter )
throws IOException
{
super( interpreter, threadGroup, interpreter.programFilename() + "-SelectorThread" );
this.selector = Selector.open();
}
@Override
public void run()
{
SelectableStreamingCommChannel channel;
while( active ) {
try {
synchronized( selectingMutex ) {
selector.select();
}
synchronized( this ) {
for( SelectionKey key : selector.selectedKeys() ) {
if ( key.isValid() ) {
channel = (SelectableStreamingCommChannel)key.attachment();
try {
if ( channel.lock.tryLock() ) {
try {
key.cancel();
key.channel().configureBlocking( true );
if ( channel.isOpen() ) {
/*if ( channel.selectionTimeoutHandler() != null ) {
interpreter.removeTimeoutHandler( channel.selectionTimeoutHandler() );
}*/
scheduleReceive( channel, channel.parentInputPort() );
} else {
channel.closeImpl();
}
} catch( IOException e ) {
throw e;
} finally {
channel.lock.unlock();
}
} else {
/*
* Make the selector give us this channel
* again at the next iteration.
*/
selector.wakeup();
}
} catch( IOException e ) {
if ( channel.lock.isHeldByCurrentThread() ) {
channel.lock.unlock();
}
interpreter.logWarning( e );
}
}
}
synchronized( selectingMutex ) {
selector.selectNow(); // Clean up the cancelled keys
}
}
} catch( IOException e ) {
interpreter.logSevere( e );
}
}
for( SelectionKey key : selector.keys() ) {
try {
((SelectableStreamingCommChannel)key.attachment()).closeImpl();
} catch( IOException e ) {
interpreter.logWarning( e );
}
}
}
public boolean register( SelectableStreamingCommChannel channel )
{
try {
if ( channel.inputStream().available() > 0 ) {
scheduleReceive( channel, channel.parentInputPort() );
return false;
}
synchronized( this ) {
if ( isSelecting( channel ) == false ) {
SelectableChannel c = channel.selectableChannel();
c.configureBlocking( false );
selector.wakeup();
synchronized( selectingMutex ) {
c.register( selector, SelectionKey.OP_READ, channel );
selector.wakeup();
}
}
}
return true;
} catch( ClosedChannelException e ) {
interpreter.logWarning( e );
return false;
} catch( IOException e ) {
interpreter.logSevere( e );
return false;
}
}
public void unregister( SelectableStreamingCommChannel channel )
throws IOException
{
synchronized( this ) {
if ( isSelecting( channel ) ) {
selector.wakeup();
synchronized( selectingMutex ) {
SelectionKey key = channel.selectableChannel().keyFor( selector );
if ( key != null ) {
key.cancel();
}
selector.selectNow();
}
channel.selectableChannel().configureBlocking( true );
}
}
}
private boolean isSelecting( SelectableStreamingCommChannel channel )
{
SelectableChannel c = channel.selectableChannel();
if ( c == null ) {
return false;
}
return c.keyFor( selector ) != null;
}
}
protected boolean isSelecting( SelectableStreamingCommChannel channel )
{
synchronized( this ) {
if ( selectorThread == null ) {
return false;
}
}
final SelectorThread t = selectorThread;
synchronized( t ) {
return t.isSelecting( channel );
}
}
protected void unregisterForSelection( SelectableStreamingCommChannel channel )
throws IOException
{
selectorThread().unregister( channel );
}
protected void registerForSelection( final SelectableStreamingCommChannel channel )
throws IOException
{
selectorThread().register( channel );
/*final TimeoutHandler handler = new TimeoutHandler( interpreter.persistentConnectionTimeout() ) {
@Override
public void onTimeout()
{
try {
if ( isSelecting( channel ) ) {
selectorThread().unregister( channel );
channel.setToBeClosed( true );
channel.close();
}
} catch( IOException e ) {
interpreter.logSevere( e );
}
}
};
channel.setSelectionTimeoutHandler( handler );
if ( selectorThread().register( channel ) ) {
interpreter.addTimeoutHandler( handler );
} else {
channel.setSelectionTimeoutHandler( null );
}*/
}
/** Shutdowns the communication core, interrupting every communication-related thread. */
public synchronized void shutdown()
{
if ( active ) {
active = false;
for( Entry< String, CommListener > entry : listenersMap.entrySet() ) {
entry.getValue().shutdown();
}
if ( selectorThread != null ) {
selectorThread.selector.wakeup();
try {
selectorThread.join();
} catch( InterruptedException e ) {}
}
try {
channelHandlersLock.writeLock().tryLock( CHANNEL_HANDLER_TIMEOUT, TimeUnit.SECONDS );
} catch( InterruptedException e ) {}
executorService.shutdown();
try {
executorService.awaitTermination( interpreter.persistentConnectionTimeout(), TimeUnit.MILLISECONDS );
} catch( InterruptedException e ) {}
threadGroup.interrupt();
}
}
private boolean active = false;
} |
/**
* Package for calculate task.
*
* @author Danila Barkov (mailto:danila.barkov@gmail.com)
* @version $Id$
* @since 0.1
*/
package ru.job4j;
/**
* Class.
* @throws Calculate
*/
public class Calculate {
/**
* Main.
* @param args - args
*/
public static void main(String[] args) {
System.out.println("Hello World");
}
} |
package ru.job4j;
/**
* Class +, -, /, *, ^ .
* @author akulikov
* @since 24.04.2017
* @version 1
*/
public class Calculate {
/**
* , ,
* "Hello world!"
* @param args - .
*/
public static void main(String[] args) {
System.out.println("Hello world!");
}
} |
// This file is part of OpenTSDB.
// This program is free software: you can redistribute it and/or modify it
// option) any later version. This program is distributed in the hope that it
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
package net.opentsdb.utils;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableMap;
/**
* OpenTSDB Configuration Class
*
* This handles all of the user configurable variables for a TSD. On
* initialization default values are configured for all variables. Then
* implementations should call the {@link #loadConfig()} methods to search for a
* default configuration or try to load one provided by the user.
*
* To add a configuration, simply set a default value in {@link #setDefaults()}.
* Wherever you need to access the config value, use the proper helper to fetch
* the value, accounting for exceptions that may be thrown if necessary.
*
* The get<type> number helpers will return NumberFormatExceptions if the
* requested property is null or unparseable. The {@link #getString(String)}
* helper will return a NullPointerException if the property isn't found.
* <p>
* Plugins can extend this class and copy the properties from the main
* TSDB.config instance. Plugins should never change the main TSD's config
* properties, rather a plugin should use the Config(final Config parent)
* constructor to get a copy of the parent's properties and then work with the
* values locally.
* @since 2.0
*/
public class Config {
private static final Logger LOG = LoggerFactory.getLogger(Config.class);
/** Flag to determine if we're running under Windows or not */
public static final boolean IS_WINDOWS =
System.getProperty("os.name", "").contains("Windows");
// These are accessed often so need a set address for fast access (faster
// than accessing the map. Their value will be changed when the config is
// loaded
// NOTE: edit the setDefaults() method if you add a public field
/** tsd.core.auto_create_metrics */
private boolean auto_metric = false;
/** tsd.core.auto_create_tagk */
private boolean auto_tagk = true;
/** tsd.core.auto_create_tagv */
private boolean auto_tagv = true;
/** tsd.storage.enable_compaction */
private boolean enable_compactions = true;
/** tsd.core.meta.enable_realtime_ts */
private boolean enable_realtime_ts = false;
/** tsd.core.meta.enable_realtime_uid */
private boolean enable_realtime_uid = false;
/** tsd.core.meta.enable_tsuid_incrementing */
private boolean enable_tsuid_incrementing = false;
/** tsd.core.meta.enable_tsuid_tracking */
private boolean enable_tsuid_tracking = false;
/** tsd.http.request.enable_chunked */
private boolean enable_chunked_requests = false;
/** tsd.storage.fix_duplicates */
private boolean fix_duplicates = false;
/** tsd.http.request.max_chunk */
private int max_chunked_requests = 4096;
/** tsd.core.tree.enable_processing */
private boolean enable_tree_processing = false;
protected final HashMap<String, String> properties =
new HashMap<String, String>();
/** Holds default values for the config */
protected static final HashMap<String, String> default_map =
new HashMap<String, String>();
/** Tracks the location of the file that was actually loaded */
private String config_location;
/**
* Constructor that initializes default configuration values. May attempt to
* search for a config file if configured.
* @param auto_load_config When set to true, attempts to search for a config
* file in the default locations
* @throws IOException Thrown if unable to read or parse one of the default
* config files
*/
public Config(final boolean auto_load_config) throws IOException {
if (auto_load_config)
this.loadConfig();
this.setDefaults();
}
/**
* Constructor that initializes default values and attempts to load the given
* properties file
* @param file Path to the file to load
* @throws IOException Thrown if unable to read or parse the file
*/
public Config(final String file) throws IOException {
this.loadConfig(file);
this.setDefaults();
}
/**
* Constructor for plugins or overloaders who want a copy of the parent
* properties but without the ability to modify them
*
* This constructor will not re-read the file, but it will copy the location
* so if a child wants to reload the properties periodically, they may do so
* @param parent Parent configuration object to load from
*/
public Config(final Config parent) {
// copy so changes to the local props by the plugin don't affect the master
this.properties.putAll(parent.properties);
this.config_location = parent.config_location;
this.setDefaults();
}
/** @return the auto_metric value */
public boolean auto_metric() {
return this.auto_metric;
}
/** @return the auto_tagk value */
public boolean auto_tagk() {
return auto_tagk;
}
/** @return the auto_tagv value */
public boolean auto_tagv() {
return auto_tagv;
}
/** @param auto_metric whether or not to auto create metrics */
public void setAutoMetric(boolean auto_metric) {
this.auto_metric = auto_metric;
properties.put("tsd.core.auto_create_metrics",
Boolean.toString(auto_metric));
}
/** @return the enable_compaction value */
public boolean enable_compactions() {
return this.enable_compactions;
}
/** @return whether or not to record new TSMeta objects in real time */
public boolean enable_realtime_ts() {
return enable_realtime_ts;
}
/** @return whether or not record new UIDMeta objects in real time */
public boolean enable_realtime_uid() {
return enable_realtime_uid;
}
/** @return whether or not to increment TSUID counters */
public boolean enable_tsuid_incrementing() {
return enable_tsuid_incrementing;
}
/** @return whether or not to record a 1 for every TSUID */
public boolean enable_tsuid_tracking() {
return enable_tsuid_tracking;
}
/** @return whether or not chunked requests are supported */
public boolean enable_chunked_requests() {
return this.enable_chunked_requests;
}
/** @return max incoming chunk size in bytes */
public int max_chunked_requests() {
return this.max_chunked_requests;
}
/** @return true if duplicate values should be fixed */
public boolean fix_duplicates() {
return fix_duplicates;
}
/** @param fix_duplicates true if duplicate values should be fixed */
public void setFixDuplicates(final boolean fix_duplicates) {
this.fix_duplicates = fix_duplicates;
}
/** @return whether or not to process new or updated TSMetas through trees */
public boolean enable_tree_processing() {
return enable_tree_processing;
}
/**
* Allows for modifying properties after creation or loading.
*
* WARNING: This should only be used on initialization and is meant for
* command line overrides. Also note that it will reset all static config
* variables when called.
*
* @param property The name of the property to override
* @param value The value to store
*/
public void overrideConfig(final String property, final String value) {
this.properties.put(property, value);
loadStaticVariables();
}
/**
* Returns the given property as a String
* @param property The property to load
* @return The property value as a string
* @throws NullPointerException if the property did not exist
*/
public final String getString(final String property) {
return this.properties.get(property);
}
/**
* Returns the given property as an integer
* @param property The property to load
* @return A parsed integer or an exception if the value could not be parsed
* @throws NumberFormatException if the property could not be parsed
* @throws NullPointerException if the property did not exist
*/
public final int getInt(final String property) {
return Integer.parseInt(this.properties.get(property));
}
/**
* Returns the given property as a short
* @param property The property to load
* @return A parsed short or an exception if the value could not be parsed
* @throws NumberFormatException if the property could not be parsed
* @throws NullPointerException if the property did not exist
*/
public final short getShort(final String property) {
return Short.parseShort(this.properties.get(property));
}
/**
* Returns the given property as a long
* @param property The property to load
* @return A parsed long or an exception if the value could not be parsed
* @throws NumberFormatException if the property could not be parsed
* @throws NullPointerException if the property did not exist
*/
public final long getLong(final String property) {
return Long.parseLong(this.properties.get(property));
}
/**
* Returns the given property as a float
* @param property The property to load
* @return A parsed float or an exception if the value could not be parsed
* @throws NumberFormatException if the property could not be parsed
* @throws NullPointerException if the property did not exist
*/
public final float getFloat(final String property) {
return Float.parseFloat(this.properties.get(property));
}
/**
* Returns the given property as a double
* @param property The property to load
* @return A parsed double or an exception if the value could not be parsed
* @throws NumberFormatException if the property could not be parsed
* @throws NullPointerException if the property did not exist
*/
public final double getDouble(final String property) {
return Double.parseDouble(this.properties.get(property));
}
/**
* Returns the given property as a boolean
*
* Property values are case insensitive and the following values will result
* in a True return value: - 1 - True - Yes
*
* Any other values, including an empty string, will result in a False
*
* @param property The property to load
* @return A parsed boolean
* @throws NullPointerException if the property was not found
*/
public final boolean getBoolean(final String property) {
final String val = this.properties.get(property).toUpperCase();
if (val.equals("1"))
return true;
if (val.equals("TRUE"))
return true;
if (val.equals("YES"))
return true;
return false;
}
/**
* Returns the directory name, making sure the end is an OS dependent slash
* @param property The property to load
* @return The property value with a forward or back slash appended
* @throws NullPointerException if the property was not found
*/
public final String getDirectoryName(final String property) {
String directory = properties.get(property);
if (IS_WINDOWS) {
// Windows swings both ways. If a forward slash was already used, we'll
// add one at the end if missing. Otherwise use the windows default of \
if (directory.charAt(directory.length() - 1) == '\\' ||
directory.charAt(directory.length() - 1) == '/') {
return directory;
}
if (directory.contains("/")) {
return directory + "/";
}
return directory + "\\";
}
if (directory.contains("\\")) {
throw new IllegalArgumentException(
"Unix path names cannot contain a back slash");
}
if (directory.charAt(directory.length() - 1) == '/') {
return directory;
}
return directory + "/";
}
/**
* Determines if the given propery is in the map
* @param property The property to search for
* @return True if the property exists and has a value, not an empty string
*/
public final boolean hasProperty(final String property) {
final String val = this.properties.get(property);
if (val == null)
return false;
if (val.isEmpty())
return false;
return true;
}
/**
* Returns a simple string with the configured properties for debugging
* @return A string with information about the config
*/
public final String dumpConfiguration() {
if (this.properties.isEmpty())
return "No configuration settings stored";
StringBuilder response = new StringBuilder("TSD Configuration:\n");
response.append("File [" + this.config_location + "]\n");
int line = 0;
for (Map.Entry<String, String> entry : this.properties.entrySet()) {
if (line > 0) {
response.append("\n");
}
response.append("Key [" + entry.getKey() + "] Value [");
if (entry.getKey().toUpperCase().contains("PASS")) {
response.append("********");
} else {
response.append(entry.getValue());
}
response.append("]");
line++;
}
return response.toString();
}
/** @return An immutable copy of the configuration map */
public final Map<String, String> getMap() {
return ImmutableMap.copyOf(properties);
}
/**
* Loads default entries that were not provided by a file or command line
*
* This should be called in the constructor
*/
protected void setDefaults() {
// map.put("tsd.network.port", ""); // does not have a default, required
// map.put("tsd.http.cachedir", ""); // does not have a default, required
// map.put("tsd.http.staticroot", ""); // does not have a default, required
default_map.put("tsd.network.bind", "0.0.0.0");
default_map.put("tsd.network.worker_threads", "");
default_map.put("tsd.network.async_io", "true");
default_map.put("tsd.network.tcp_no_delay", "true");
default_map.put("tsd.network.keep_alive", "true");
default_map.put("tsd.network.reuse_address", "true");
default_map.put("tsd.core.auto_create_metrics", "false");
default_map.put("tsd.core.auto_create_tagks", "true");
default_map.put("tsd.core.auto_create_tagvs", "true");
default_map.put("tsd.core.meta.enable_realtime_ts", "false");
default_map.put("tsd.core.meta.enable_realtime_uid", "false");
default_map.put("tsd.core.meta.enable_tsuid_incrementing", "false");
default_map.put("tsd.core.meta.enable_tsuid_tracking", "false");
default_map.put("tsd.core.plugin_path", "");
default_map.put("tsd.core.tree.enable_processing", "false");
default_map.put("tsd.rtpublisher.enable", "false");
default_map.put("tsd.rtpublisher.plugin", "");
default_map.put("tsd.search.enable", "false");
default_map.put("tsd.search.plugin", "");
default_map.put("tsd.stats.canonical", "false");
default_map.put("tsd.storage.fix_duplicates", "false");
default_map.put("tsd.storage.flush_interval", "1000");
default_map.put("tsd.storage.hbase.data_table", "tsdb");
default_map.put("tsd.storage.hbase.uid_table", "tsdb-uid");
default_map.put("tsd.storage.hbase.tree_table", "tsdb-tree");
default_map.put("tsd.storage.hbase.meta_table", "tsdb-meta");
default_map.put("tsd.storage.hbase.zk_quorum", "localhost");
default_map.put("tsd.storage.hbase.zk_basedir", "/hbase");
default_map.put("tsd.storage.enable_compaction", "true");
default_map.put("tsd.http.show_stack_trace", "true");
default_map.put("tsd.http.request.enable_chunked", "false");
default_map.put("tsd.http.request.max_chunk", "4096");
default_map.put("tsd.http.request.cors_domains", "");
default_map.put("tsd.http.request.cors_headers", "Authorization, "
+ "Content-Type, Accept, Origin, User-Agent, DNT, Cache-Control, "
+ "X-Mx-ReqToken, Keep-Alive, X-Requested-With, If-Modified-Since");
for (Map.Entry<String, String> entry : default_map.entrySet()) {
if (!properties.containsKey(entry.getKey()))
properties.put(entry.getKey(), entry.getValue());
}
loadStaticVariables();
}
/**
* Searches a list of locations for a valid opentsdb.conf file
*
* The config file must be a standard JAVA properties formatted file. If none
* of the locations have a config file, then the defaults or command line
* arguments will be used for the configuration
*
* Defaults for Linux based systems are: ./opentsdb.conf /etc/opentsdb.conf
* /etc/opentsdb/opentdsb.conf /opt/opentsdb/opentsdb.conf
*
* @throws IOException Thrown if there was an issue reading a file
*/
protected void loadConfig() throws IOException {
if (this.config_location != null && !this.config_location.isEmpty()) {
this.loadConfig(this.config_location);
return;
}
final ArrayList<String> file_locations = new ArrayList<String>();
// search locally first
file_locations.add("opentsdb.conf");
// add default locations based on OS
if (System.getProperty("os.name").toUpperCase().contains("WINDOWS")) {
file_locations.add("C:\\Program Files\\opentsdb\\opentsdb.conf");
file_locations.add("C:\\Program Files (x86)\\opentsdb\\opentsdb.conf");
} else {
file_locations.add("/etc/opentsdb.conf");
file_locations.add("/etc/opentsdb/opentsdb.conf");
file_locations.add("/opt/opentsdb/opentsdb.conf");
}
for (String file : file_locations) {
try {
FileInputStream file_stream = new FileInputStream(file);
Properties props = new Properties();
props.load(file_stream);
// load the hash map
this.loadHashMap(props);
} catch (Exception e) {
// don't do anything, the file may be missing and that's fine
LOG.debug("Unable to find or load " + file, e);
continue;
}
// no exceptions thrown, so save the valid path and exit
LOG.info("Successfully loaded configuration file: " + file);
this.config_location = file;
return;
}
LOG.info("No configuration found, will use defaults");
}
/**
* Attempts to load the configuration from the given location
* @param file Path to the file to load
* @throws IOException Thrown if there was an issue reading the file
* @throws FileNotFoundException Thrown if the config file was not found
*/
protected void loadConfig(final String file) throws FileNotFoundException,
IOException {
FileInputStream file_stream;
file_stream = new FileInputStream(file);
Properties props = new Properties();
props.load(file_stream);
// load the hash map
this.loadHashMap(props);
// no exceptions thrown, so save the valid path and exit
LOG.info("Successfully loaded configuration file: " + file);
this.config_location = file;
}
/**
* Loads the static class variables for values that are called often. This
* should be called any time the configuration changes.
*/
protected void loadStaticVariables() {
auto_metric = this.getBoolean("tsd.core.auto_create_metrics");
auto_tagk = this.getBoolean("tsd.core.auto_create_tagks");
auto_tagv = this.getBoolean("tsd.core.auto_create_tagvs");
enable_compactions = this.getBoolean("tsd.storage.enable_compaction");
enable_chunked_requests = this.getBoolean("tsd.http.request.enable_chunked");
enable_realtime_ts = this.getBoolean("tsd.core.meta.enable_realtime_ts");
enable_realtime_uid = this.getBoolean("tsd.core.meta.enable_realtime_uid");
enable_tsuid_incrementing =
this.getBoolean("tsd.core.meta.enable_tsuid_incrementing");
enable_tsuid_tracking =
this.getBoolean("tsd.core.meta.enable_tsuid_tracking");
if (this.hasProperty("tsd.http.request.max_chunk")) {
max_chunked_requests = this.getInt("tsd.http.request.max_chunk");
}
enable_tree_processing = this.getBoolean("tsd.core.tree.enable_processing");
fix_duplicates = this.getBoolean("tsd.storage.fix_duplicates");
}
/**
* Called from {@link #loadConfig} to copy the properties into the hash map
* Tsuna points out that the Properties class is much slower than a hash
* map so if we'll be looking up config values more than once, a hash map
* is the way to go
* @param props The loaded Properties object to copy
*/
private void loadHashMap(final Properties props) {
this.properties.clear();
@SuppressWarnings("rawtypes")
Enumeration e = props.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
this.properties.put(key, props.getProperty(key));
}
}
} |
package net.squanchy;
import android.app.Activity;
import android.app.Notification;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.Button;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import net.squanchy.eventdetails.domain.view.ExperienceLevel;
import net.squanchy.notification.NotificationCreator;
import net.squanchy.notification.NotificationsIntentService;
import net.squanchy.notification.Notifier;
import net.squanchy.schedule.domain.view.Event;
import net.squanchy.schedule.domain.view.Place;
import net.squanchy.schedule.domain.view.Track;
import net.squanchy.speaker.domain.view.Speaker;
import net.squanchy.support.lang.Optional;
import org.joda.time.LocalDateTime;
@SuppressWarnings("checkstyle:magicnumber")
public class DebugActivity extends Activity {
private NotificationCreator notificationCreator;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_debug);
Button buttonSingleNotification = (Button) findViewById(R.id.button_test_single_notification);
buttonSingleNotification.setOnClickListener(view -> testSingleNotification());
Button buttonMultipleNotifications = (Button) findViewById(R.id.button_test_multiple_notifications);
buttonMultipleNotifications.setOnClickListener(view -> testMultipleNotifications());
Button buttonService = (Button) findViewById(R.id.button_test_service);
buttonService.setOnClickListener(view -> testService());
notificationCreator = new NotificationCreator(this);
}
private void testSingleNotification() {
createAndNotifyTalksCount(1);
}
private void testMultipleNotifications() {
createAndNotifyTalksCount(3);
}
private void createAndNotifyTalksCount(int count) {
List<Event> events = new ArrayList<>();
for (int i = 0; i < count; i++) {
events.add(createTestEvent(i));
}
List<Notification> notifications = notificationCreator.createFrom(events);
Notifier notifier = Notifier.from(this);
notifier.showNotifications(notifications);
}
private Event createTestEvent(int id) {
LocalDateTime start = new LocalDateTime().plusMinutes(5);
LocalDateTime end = new LocalDateTime().plusMinutes(45);
return Event.create(
String.valueOf(id),
id,
"1",
start,
end,
"A very interesting talk",
createPlace(),
Optional.of(ExperienceLevel.ADVANCED),
createTalkSpeakers(),
Event.Type.TALK,
true,
Optional.absent(),
Optional.of(createTrack())
);
}
private Optional<Place> createPlace() {
Place place = Place.create("1", "That room over there", Optional.absent());
return Optional.of(place);
}
private List<Speaker> createTalkSpeakers() {
List<Speaker> speakers = new ArrayList<>(2);
speakers.add(Speaker.create(
"1",
101L,
"Ajeje Brazorf",
"https://yt3.ggpht.com/-d35Rq8vqvmE/AAAAAAAAAAI/AAAAAAAAAAA/zy1VyiRTNec/s900-c-k-no-mo-rj-c0xffffff/photo.jpg"
)
);
return speakers;
}
private Track createTrack() {
return Track.create(
"0",
"UI",
Optional.of(generateColor()),
Optional.of(generateColor()),
Optional.of("gs://droidcon-italy-2017.appspot.com/tracks/0.webp")
);
}
public int getRandomColor() {
Random rnd = new Random();
return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
}
private String generateColor() {
Random r = new Random();
final char[] hex = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
char[] s = new char[7];
int n = r.nextInt(0x1000000);
s[0] = '
for (int i = 1; i < 7; i++) {
s[i] = hex[n & 0xf];
n >>= 4;
}
return new String(s);
}
private void testService() {
Intent serviceIntent = new Intent(this, NotificationsIntentService.class);
startService(serviceIntent);
}
} |
package com.gh4a.widget;
import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Parcelable;
import android.support.annotation.ColorInt;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v7.view.menu.MenuBuilder;
import android.support.v7.view.menu.MenuPopupHelper;
import android.support.v7.widget.ListPopupWindow;
import android.support.v7.widget.PopupMenu;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.gh4a.Gh4Application;
import com.gh4a.R;
import com.gh4a.activities.UserActivity;
import com.gh4a.utils.ApiHelpers;
import com.gh4a.utils.AvatarHandler;
import com.gh4a.utils.Optional;
import com.gh4a.utils.RxUtils;
import com.gh4a.utils.UiUtils;
import com.meisolsson.githubsdk.model.Reaction;
import com.meisolsson.githubsdk.model.Reactions;
import com.meisolsson.githubsdk.model.User;
import com.meisolsson.githubsdk.service.reactions.ReactionService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import io.reactivex.Single;
public class ReactionBar extends LinearLayout implements View.OnClickListener {
public interface Item {
Object getCacheKey();
}
public interface Callback {
Single<List<Reaction>> loadReactionDetailsInBackground(Item item);
Single<Reaction> addReactionInBackground(Item item, String content);
}
private static final @IdRes int[] VIEW_IDS = {
R.id.plus_one, R.id.minus_one, R.id.laugh,
R.id.hooray, R.id.heart, R.id.confused
};
private static final String[] CONTENTS = {
Reaction.CONTENT_PLUS_ONE, Reaction.CONTENT_MINUS_ONE,
Reaction.CONTENT_LAUGH, Reaction.CONTENT_HOORAY,
Reaction.CONTENT_HEART, Reaction.CONTENT_CONFUSED
};
private final TextView mPlusOneView;
private final TextView mMinusOneView;
private final TextView mLaughView;
private final TextView mHoorayView;
private final TextView mConfusedView;
private final TextView mHeartView;
private final View mReactButton;
private Callback mCallback;
private Item mReferenceItem;
private ReactionUserPopup mPopup;
private ReactionDetailsCache mDetailsCache;
private MenuPopupHelper mAddReactionPopup;
private AddReactionMenuHelper mAddHelper;
private final PopupMenu.OnMenuItemClickListener mAddReactionClickListener =
new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
return mAddHelper.onItemClick(item);
}
};
public ReactionBar(Context context) {
this(context, null);
}
public ReactionBar(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public ReactionBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setOrientation(HORIZONTAL);
inflate(context, R.layout.reaction_bar, this);
mPlusOneView = findViewById(R.id.plus_one);
mMinusOneView = findViewById(R.id.minus_one);
mLaughView = findViewById(R.id.laugh);
mHoorayView = findViewById(R.id.hooray);
mConfusedView = findViewById(R.id.confused);
mHeartView = findViewById(R.id.heart);
mReactButton = findViewById(R.id.react);
setReactions(null);
}
public void setReactions(Reactions reactions) {
if (mPopup != null) {
mPopup.update();
}
if (mAddHelper != null) {
mAddHelper.update();
}
if (reactions != null && reactions.totalCount() > 0) {
updateView(mPlusOneView, reactions.plusOne());
updateView(mMinusOneView, reactions.minusOne());
updateView(mLaughView, reactions.laugh());
updateView(mHoorayView, reactions.hooray());
updateView(mConfusedView, reactions.confused());
updateView(mHeartView, reactions.heart());
setVisibility(View.VISIBLE);
} else {
setVisibility(View.GONE);
}
}
public void setDetailsCache(ReactionDetailsCache cache) {
mDetailsCache = cache;
}
public void setCallback(Callback callback, Item item) {
mCallback = callback;
mReferenceItem = item;
for (int id : VIEW_IDS) {
findViewById(id).setOnClickListener(callback != null ? this : null);
}
mReactButton.setVisibility(callback != null ? View.VISIBLE : View.GONE);
mReactButton.setOnClickListener(callback != null ? this : null);
}
@Override
protected void onDetachedFromWindow() {
if (mPopup != null) {
mPopup.dismiss();
}
super.onDetachedFromWindow();
}
@Override
protected Parcelable onSaveInstanceState() {
if (mPopup != null) {
mPopup.dismiss();
}
return super.onSaveInstanceState();
}
@Override
public void onClick(View view) {
if (mPopup != null && mPopup.isShowing()) {
mPopup.dismiss();
return;
}
if (view == mReactButton) {
if (mAddReactionPopup == null) {
PopupMenu popup = new PopupMenu(getContext(), mReactButton);
popup.inflate(R.menu.reaction_menu);
popup.setOnMenuItemClickListener(mAddReactionClickListener);
mAddHelper = new AddReactionMenuHelper(getContext(), popup.getMenu(),
mCallback, mReferenceItem, mDetailsCache);
mAddReactionPopup = new MenuPopupHelper(getContext(), (MenuBuilder) popup.getMenu(),
mReactButton);
mAddReactionPopup.setForceShowIcon(true);
}
mAddHelper.startLoadingIfNeeded();
mAddReactionPopup.show();
return;
}
for (int i = 0; i < VIEW_IDS.length; i++) {
if (view.getId() == VIEW_IDS[i]) {
if (mPopup == null) {
mPopup = new ReactionUserPopup(getContext(),
mCallback, mReferenceItem, mDetailsCache);
}
mPopup.setAnchorView(view);
mPopup.show(CONTENTS[i]);
}
}
}
private void updateView(TextView view, int count) {
if (count > 0) {
view.setText(String.valueOf(count));
view.setVisibility(View.VISIBLE);
} else {
view.setVisibility(View.GONE);
}
}
private static class ReactionUserPopup extends ListPopupWindow {
private final Callback mCallback;
private final Item mItem;
private List<Reaction> mLastKnownDetails;
private final ReactionDetailsCache mDetailsCache;
private final ReactionUserAdapter mAdapter;
private String mContent;
public ReactionUserPopup(@NonNull Context context, Callback callback,
Item item, ReactionDetailsCache detailsCache) {
super(context);
mCallback = callback;
mItem = item;
mDetailsCache = detailsCache;
mAdapter = new ReactionUserAdapter(context, this);
setContentWidth(
context.getResources()
.getDimensionPixelSize(R.dimen.reaction_details_popup_width));
setAdapter(mAdapter);
}
public void update() {
List<Reaction> details = mDetailsCache.getEntry(mItem);
if (details != null) {
populateAdapter(details);
}
}
public void show(String content) {
if (!TextUtils.equals(content, mContent)) {
mAdapter.setReactions(null);
mContent = content;
}
show();
List<Reaction> details = mDetailsCache.getEntry(mItem);
if (details != null) {
populateAdapter(details);
} else {
fetchReactions(mCallback, mItem, mDetailsCache)
.subscribe(reactions -> populateAdapter(reactions), error -> dismiss());
}
}
public void toggleOwnReaction(Reaction currentReaction) {
final long id = currentReaction != null ? currentReaction.id() : 0;
toggleReaction(mContent, id, mLastKnownDetails, mCallback, mItem, mDetailsCache)
.subscribe(result -> dismiss(), error -> dismiss());
}
private void populateAdapter(List<Reaction> details) {
List<Reaction> reactions = new ArrayList<>();
for (Reaction reaction : details) {
if (TextUtils.equals(mContent, reaction.content())) {
reactions.add(reaction);
}
}
mLastKnownDetails = details;
mAdapter.setReactions(reactions);
}
}
private static class ReactionUserAdapter extends BaseAdapter implements View.OnClickListener {
private final Context mContext;
private final ReactionUserPopup mParent;
private final LayoutInflater mInflater;
private List<User> mUsers;
private Reaction mOwnReaction;
public ReactionUserAdapter(Context context, ReactionUserPopup popup) {
mContext = context;
mParent = popup;
mInflater = LayoutInflater.from(context);
}
public void setReactions(List<Reaction> reactions) {
mOwnReaction = null;
if (reactions != null) {
User ownUser = Gh4Application.get().getCurrentAccountInfoForAvatar();
String ownLogin = ownUser != null ? ownUser.login() : null;
mUsers = new ArrayList<>();
for (Reaction reaction : reactions) {
if (ApiHelpers.loginEquals(reaction.user(), ownLogin)) {
mOwnReaction = reaction;
} else {
mUsers.add(reaction.user());
}
}
if (ownUser != null) {
mUsers.add(null);
mUsers.add(ownUser);
}
} else {
mUsers = null;
}
notifyDataSetChanged();
}
@Override
public int getCount() {
return mUsers != null ? mUsers.size() : 1;
}
@Override
public int getItemViewType(int position) {
if (mUsers == null) {
return 1;
}
return getItem(position) == null ? 2 : 0;
}
@Override
public int getViewTypeCount() {
return 3;
}
@Override
public Object getItem(int position) {
return mUsers != null ? mUsers.get(position) : null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
int viewType = getItemViewType(position);
@LayoutRes int layoutResId =
viewType == 0 ? R.layout.row_reaction_details :
viewType == 1 ? R.layout.reaction_details_progress :
R.layout.reaction_details_divider;
if (convertView == null) {
convertView = mInflater.inflate(layoutResId, parent, false);
}
if (viewType == 0) {
ImageView avatar = convertView.findViewById(R.id.avatar);
TextView name = convertView.findViewById(R.id.name);
String ownLogin = Gh4Application.get().getAuthLogin();
User user = mUsers.get(position);
AvatarHandler.assignAvatar(avatar, user);
convertView.setOnClickListener(this);
if (ApiHelpers.loginEquals(user, ownLogin)) {
avatar.setAlpha(mOwnReaction != null ? 1.0f : 0.4f);
name.setText(mOwnReaction != null
? R.string.remove_reaction : R.string.add_reaction);
convertView.setTag(mOwnReaction);
} else {
avatar.setAlpha(1.0f);
name.setText(ApiHelpers.getUserLogin(mContext, user));
convertView.setTag(user);
}
}
return convertView;
}
@Override
public void onClick(View view) {
if (view.getTag() instanceof User) {
User user = (User) view.getTag();
mParent.dismiss();
mContext.startActivity(UserActivity.makeIntent(mContext, user));
} else {
// own entry
mParent.toggleOwnReaction(mOwnReaction);
}
}
}
private static Single<List<Reaction>> fetchReactions(Callback callback, Item item,
ReactionDetailsCache cache) {
return callback.loadReactionDetailsInBackground(item)
.compose(RxUtils::doInBackground)
.compose(RxUtils.sortList((lhs, rhs) -> {
int result = lhs.content().compareTo(rhs.content());
if (result == 0) {
result = rhs.createdAt().compareTo(lhs.createdAt());
}
return result;
}))
.doOnSuccess(result -> cache.putEntry(item, result));
}
private static Single<Optional<Reaction>> toggleReaction(String content, long id,
List<Reaction> existingDetails, Callback callback, Item item,
ReactionDetailsCache cache) {
final Single<Optional<Reaction>> resultSingle;
if (id == 0) {
resultSingle = callback.addReactionInBackground(item, content)
.map(reaction -> Optional.of(reaction));
} else {
ReactionService service = Gh4Application.get().getGitHubService(ReactionService.class);
resultSingle = service.deleteReaction(id)
.map(response -> Optional.absent());
}
return resultSingle
.compose(RxUtils::doInBackground)
.doOnSuccess(reactionOpt -> {
if (reactionOpt.isPresent()) {
existingDetails.add(reactionOpt.get());
} else {
for (int i = 0; i < existingDetails.size(); i++) {
Reaction reaction = existingDetails.get(i);
if (reaction.id() == id) {
existingDetails.remove(i);
break;
}
}
}
cache.putEntry(item, existingDetails);
});
}
public static class AddReactionMenuHelper {
private final Context mContext;
private MenuItem mLoadingItem;
private final MenuItem[] mItems = new MenuItem[CONTENTS.length];
private final ReactionDetailsCache mDetailsCache;
private List<Reaction> mLastKnownDetails;
private long[] mOldReactionIds;
private final Callback mCallback;
private final Item mItem;
public AddReactionMenuHelper(@NonNull Context context, Menu menu,
Callback callback, Item item, ReactionDetailsCache detailsCache) {
mContext = context;
mCallback = callback;
mItem = item;
mDetailsCache = detailsCache;
updateFromMenu(menu);
}
public void updateFromMenu(Menu menu) {
mLoadingItem = menu.findItem(R.id.loading);
for (int i = 0; i < VIEW_IDS.length; i++) {
mItems[i] = menu.findItem(VIEW_IDS[i]);
Drawable icon = DrawableCompat.wrap(mItems[i].getIcon().mutate());
DrawableCompat.setTintMode(icon, PorterDuff.Mode.SRC_ATOP);
mItems[i].setIcon(icon);
}
if (mOldReactionIds != null) {
setDataItemsVisible(true);
}
}
public boolean onItemClick(MenuItem item) {
for (int i = 0; i < mItems.length; i++) {
if (item == mItems[i]) {
item.setChecked(mOldReactionIds[i] == 0);
addOrRemoveReaction(CONTENTS[i], mOldReactionIds[i]);
updateDrawableState();
return true;
}
}
return false;
}
public void update() {
List<Reaction> reactions = mDetailsCache.getEntry(mItem);
if (reactions != null) {
mOldReactionIds = new long[mItems.length];
mLastKnownDetails = new ArrayList<>(reactions);
String ownLogin = Gh4Application.get().getAuthLogin();
for (Reaction reaction : reactions) {
if (!ApiHelpers.loginEquals(reaction.user(), ownLogin)) {
continue;
}
for (int i = 0; i < CONTENTS.length; i++) {
if (TextUtils.equals(CONTENTS[i], reaction.content())) {
mOldReactionIds[i] = reaction.id();
break;
}
}
}
} else {
mOldReactionIds = null;
mLastKnownDetails = null;
}
setDataItemsVisible(mOldReactionIds != null);
}
public void startLoadingIfNeeded() {
if (mOldReactionIds != null) {
syncCheckStates();
} else if (mDetailsCache.hasEntryFor(mItem)) {
update();
} else {
fetchReactions(mCallback, mItem, mDetailsCache)
.subscribe(reactions -> update(), error -> update());
}
}
private void setDataItemsVisible(boolean visible) {
mLoadingItem.setVisible(!visible);
for (MenuItem item : mItems) {
item.setVisible(visible);
}
syncCheckStates();
}
private void syncCheckStates() {
for (int i = 0; i < mItems.length; i++) {
mItems[i].setChecked(mOldReactionIds != null && mOldReactionIds[i] != 0);
}
updateDrawableState();
}
private void updateDrawableState() {
@ColorInt int accentColor = UiUtils.resolveColor(mContext, R.attr.colorAccent);
@ColorInt int secondaryColor = UiUtils.resolveColor(mContext,
android.R.attr.textColorSecondary);
for (MenuItem item : mItems) {
DrawableCompat.setTint(item.getIcon(),
item.isChecked() ? accentColor : secondaryColor);
}
}
private void addOrRemoveReaction(final String content, final long id) {
toggleReaction(content, id, mLastKnownDetails, mCallback, mItem, mDetailsCache)
.subscribe(result -> {
for (int i = 0; i < CONTENTS.length; i++) {
if (TextUtils.equals(CONTENTS[i], content)) {
mOldReactionIds[i] = result.isPresent() ? result.get().id() : 0;
break;
}
}
}, error -> {});
}
}
public static class ReactionDetailsCache {
public interface Listener {
void onReactionsUpdated(Item item, Reactions reactions);
}
private final Listener mListener;
private boolean mDestroyed;
private final HashMap<Object, List<Reaction>> mMap = new HashMap<>();
public ReactionDetailsCache(Listener listener) {
super();
mListener = listener;
}
public void destroy() {
mDestroyed = true;
}
public void clear() {
mMap.clear();
}
public boolean hasEntryFor(Item item) {
return mMap.containsKey(item.getCacheKey());
}
public List<Reaction> getEntry(Item item) {
return mMap.get(item.getCacheKey());
}
public List<Reaction> putEntry(Item item, List<Reaction> value) {
Object key = item.getCacheKey();
List<Reaction> result = mMap.put(key, new ArrayList<>(value));
if (result != null && !mDestroyed) {
mListener.onReactionsUpdated(item, buildReactions(value));
}
return result;
}
private Reactions buildReactions(List<Reaction> reactions) {
int plusOne = 0, minusOne = 0, confused = 0, heart = 0, hooray = 0, laugh = 0;
for (Reaction reaction : reactions) {
switch (reaction.content()) {
case Reaction.CONTENT_PLUS_ONE: ++plusOne; break;
case Reaction.CONTENT_MINUS_ONE: ++minusOne; break;
case Reaction.CONTENT_CONFUSED: ++confused; break;
case Reaction.CONTENT_HEART: ++heart; break;
case Reaction.CONTENT_HOORAY: ++hooray; break;
case Reaction.CONTENT_LAUGH: ++laugh; break;
}
}
return Reactions.builder()
.plusOne(plusOne)
.minusOne(minusOne)
.confused(confused)
.heart(heart)
.hooray(hooray)
.laugh(laugh)
.build();
}
}
} |
package net.maxbraun.mirror;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import net.maxbraun.mirror.Commute.CommuteSummary;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
/**
* A helper class to regularly retrieve commute time estimates.
*/
public class Commute extends DataUpdater<CommuteSummary> {
private static final String TAG = Commute.class.getSimpleName();
/**
* The time in milliseconds between API calls to update the commute time.
*/
private static final long UPDATE_INTERVAL_MILLIS = TimeUnit.MINUTES.toMillis(15);
/**
* The time in milliseconds from now which is used as the future traffic reference point.
*/
private static final long FUTURE_DELTA_MILLIS = TimeUnit.MINUTES.toMillis(15);
/**
* The time delta in seconds below which the traffic trend is considered flat.
*/
private static final long TREND_THRESHOLD_SECONDS = TimeUnit.MINUTES.toSeconds(2);
/**
* The travel mode using standard driving directions using the road network.
*/
private static final String MODE_DRIVING = "driving";
/**
* The travel mode using walking directions via pedestrian paths and sidewalks.
*/
private static final String MODE_WALKING = "walking";
/**
* The travel mode using bicycling directions via bicycle paths and preferred streets.
*/
private static final String MODE_BICYCLING = "bicycling";
/**
* The travel mode using directions via public transit routes.
*/
private static final String MODE_TRANSIT = "transit";
/**
* The encoding used for request URLs.
*/
private static final String URL_ENCODE_FORMAT = "UTF-8";
/**
* The context used to load string resources.
*/
private final Context context;
/**
* A summary of current commute data.
*/
public static class CommuteSummary {
/**
* A human-readable text summary.
*/
public final String text;
/**
* The icon representing the travel mode.
*/
public final Drawable travelModeIcon;
/**
* The icon representing the traffic trend or {@code null} if it is flat.
*/
public final Drawable trafficTrendIcon;
public CommuteSummary(String text, Drawable travelModeIcon, Drawable trafficTrendIcon) {
this.text = text;
this.travelModeIcon = travelModeIcon;
this.trafficTrendIcon = trafficTrendIcon;
}
}
public Commute(Context context, UpdateListener<CommuteSummary> updateListener) {
super(updateListener, UPDATE_INTERVAL_MILLIS);
this.context = context;
}
@Override
protected CommuteSummary getData() {
// Get the latest data from the Google Maps Directions API for one departure now and one in the
// future, to compare traffic.
long nowMillis = System.currentTimeMillis();
long futureMillis = nowMillis + FUTURE_DELTA_MILLIS;
String nowRequestUrl = getRequestUrl(nowMillis);
String futureRequestUrl = getRequestUrl(futureMillis);
// Parse the data we are interested in from the response JSON.
try {
JSONObject nowResponse = Network.getJson(nowRequestUrl);
JSONObject futureResponse = Network.getJson(futureRequestUrl);
if ((nowResponse != null) && (futureResponse != null)) {
return parseCommuteSummary(nowResponse, futureResponse);
} else {
return null;
}
} catch (JSONException e) {
Log.e(TAG, "Failed to parse directions JSON.", e);
return null;
}
}
/**
* Creates the URL for a Google Maps Directions API request based on origin and destination
* addresses from resources.
*/
private String getRequestUrl(long departureTimeMillis) {
try {
return String.format(Locale.US, "https://maps.googleapis.com/maps/api/directions/json" +
"?origin=%s" +
"&destination=%s" +
"&mode=%s" +
"&departure_time=%d" +
"&key=%s",
URLEncoder.encode(context.getString(R.string.home), URL_ENCODE_FORMAT),
URLEncoder.encode(context.getString(R.string.work), URL_ENCODE_FORMAT),
context.getString(R.string.travel_mode),
departureTimeMillis / 1000,
context.getString(R.string.google_maps_directions_api_key));
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "Failed to create request URL.", e);
return null;
}
}
private CommuteSummary parseCommuteSummary(JSONObject nowResponse, JSONObject futureResponse)
throws JSONException {
String nowStatus = nowResponse.getString("status");
String futureStatus = futureResponse.getString("status");
if (!"OK".equals(nowStatus) || !"OK".equals(futureStatus)) {
Log.e(TAG, String.format("Error status in response: %s %s", nowStatus, futureStatus));
return null;
}
// Expect exactly one route.
JSONArray nowRoutes = nowResponse.getJSONArray("routes");
JSONObject nowRoute = nowRoutes.getJSONObject(0);
JSONArray futureRoutes = futureResponse.getJSONArray("routes");
JSONObject futureRoute = futureRoutes.getJSONObject(0);
// Expect exactly one leg.
JSONArray nowLegs = nowRoute.getJSONArray("legs");
JSONObject nowLeg = nowLegs.getJSONObject(0);
JSONArray futureLegs = futureRoute.getJSONArray("legs");
JSONObject futureLeg = futureLegs.getJSONObject(0);
// Get the duration now, with traffic if available.
JSONObject nowDuration;
boolean nowHasTraffic = nowLeg.has("duration_in_traffic");
if (nowHasTraffic) {
nowDuration = nowLeg.getJSONObject("duration_in_traffic");
} else {
nowDuration = nowLeg.getJSONObject("duration");
}
String nowDurationText = nowDuration.getString("text");
long nowDurationSeconds = nowDuration.getLong("value");
Log.d(TAG, String.format("Duration now: %s (%s secs) %b", nowDurationText,
nowDurationSeconds, nowHasTraffic));
// Get the duration in the future, with traffic if available.
JSONObject futureDuration;
boolean futureHasTraffic = futureLeg.has("duration_in_traffic");
if (futureHasTraffic) {
futureDuration = futureLeg.getJSONObject("duration_in_traffic");
} else {
futureDuration = futureLeg.getJSONObject("duration");
}
String futureDurationText = futureDuration.getString("text");
long futureDurationSeconds = futureDuration.getLong("value");
Log.d(TAG, String.format("Duration future: %s (%d secs) %b", futureDurationText,
futureDurationSeconds, futureHasTraffic));
// Create the text summary.
String nowSummaryText = nowRoute.getString("summary");
Log.d(TAG, "Summary text: " + nowSummaryText);
String text;
if (!TextUtils.isEmpty(nowSummaryText)) {
text = String.format("%s via %s", nowDurationText, nowSummaryText);
} else {
text = nowDurationText;
}
// Pick the icon for the travel mode.
String travelMode = context.getString(R.string.travel_mode);
int travelModeIconResource;
if (MODE_DRIVING.equals(travelMode)) {
travelModeIconResource = R.drawable.driving;
} else if (MODE_TRANSIT.equals(travelMode)) {
travelModeIconResource = R.drawable.transit;
} else if (MODE_WALKING.equals(travelMode)) {
travelModeIconResource = R.drawable.walking;
} else if (MODE_BICYCLING.equals(travelMode)) {
travelModeIconResource = R.drawable.bicycling;
} else {
Log.e(TAG, "Unknown travel mode: " + travelMode);
return null;
}
Log.d(TAG, "Using travel mode: " + travelMode);
Drawable travelModeIcon = context.getDrawable(travelModeIconResource);
// Check if there is a significant trend and use the corresponding icon.
Drawable trafficTrendIcon;
long trendSeconds = futureDurationSeconds - nowDurationSeconds;
Log.d(TAG, String.format("Traffic trend: %d secs", trendSeconds));
if (Math.abs(trendSeconds) >= TREND_THRESHOLD_SECONDS) {
int trendIconResource = trendSeconds > 0 ? R.drawable.trend_up : R.drawable.trend_down;
trafficTrendIcon = context.getDrawable(trendIconResource);
} else {
trafficTrendIcon = null;
}
return new CommuteSummary(text, travelModeIcon, trafficTrendIcon);
}
@Override
protected String getTag() {
return TAG;
}
} |
package net.maxbraun.mirror;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import net.maxbraun.mirror.Commute.CommuteSummary;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
/**
* A helper class to regularly retrieve commute time estimates.
*/
public class Commute extends DataUpdater<CommuteSummary> {
private static final String TAG = Commute.class.getSimpleName();
/**
* The time in milliseconds between API calls to update the commute time.
*/
private static final long UPDATE_INTERVAL_MILLIS = TimeUnit.MINUTES.toMillis(1);
/**
* The time in milliseconds from now which is used as the future traffic reference point.
*/
private static final long FUTURE_DELTA_MILLIS = TimeUnit.MINUTES.toMillis(15);
/**
* The time delta in seconds below which the traffic trend is considered flat.
*/
private static final long TREND_THRESHOLD_SECONDS = TimeUnit.MINUTES.toSeconds(2);
/**
* The travel mode using standard driving directions using the road network.
*/
private static final String MODE_DRIVING = "driving";
/**
* The travel mode using walking directions via pedestrian paths and sidewalks.
*/
private static final String MODE_WALKING = "walking";
/**
* The travel mode using bicycling directions via bicycle paths and preferred streets.
*/
private static final String MODE_BICYCLING = "bicycling";
/**
* The travel mode using directions via public transit routes.
*/
private static final String MODE_TRANSIT = "transit";
/**
* The encoding used for request URLs.
*/
private static final String URL_ENCODE_FORMAT = "UTF-8";
/**
* The context used to load string resources.
*/
private final Context context;
/**
* A summary of current commute data.
*/
public static class CommuteSummary {
/**
* A human-readable text summary.
*/
public final String text;
/**
* The icon representing the travel mode.
*/
public final Drawable travelModeIcon;
/**
* The icon representing the traffic trend or {@code null} if it is flat.
*/
public final Drawable trafficTrendIcon;
public CommuteSummary(String text, Drawable travelModeIcon, Drawable trafficTrendIcon) {
this.text = text;
this.travelModeIcon = travelModeIcon;
this.trafficTrendIcon = trafficTrendIcon;
}
}
public Commute(Context context, UpdateListener<CommuteSummary> updateListener) {
super(updateListener, UPDATE_INTERVAL_MILLIS);
this.context = context;
}
@Override
protected CommuteSummary getData() {
// Get the latest data from the Google Maps Directions API for one departure now and one in the
// future, to compare traffic.
long nowMillis = System.currentTimeMillis();
long futureMillis = nowMillis + FUTURE_DELTA_MILLIS;
String nowRequestUrl = getRequestUrl(nowMillis);
String futureRequestUrl = getRequestUrl(futureMillis);
// Parse the data we are interested in from the response JSON.
try {
JSONObject nowResponse = Network.getJson(nowRequestUrl);
JSONObject futureResponse = Network.getJson(futureRequestUrl);
if ((nowResponse != null) && (futureResponse != null)) {
return parseCommuteSummary(nowResponse, futureResponse);
} else {
return null;
}
} catch (JSONException e) {
Log.e(TAG, "Failed to parse directions JSON.", e);
return null;
}
}
/**
* Creates the URL for a Google Maps Directions API request based on origin and destination
* addresses from resources.
*/
private String getRequestUrl(long departureTimeMillis) {
try {
return String.format(Locale.US, "https://maps.googleapis.com/maps/api/directions/json" +
"?origin=%s" +
"&destination=%s" +
"&mode=%s" +
"&departure_time=%d" +
"&key=%s",
URLEncoder.encode(context.getString(R.string.home), URL_ENCODE_FORMAT),
URLEncoder.encode(context.getString(R.string.work), URL_ENCODE_FORMAT),
context.getString(R.string.travel_mode),
departureTimeMillis / 1000,
context.getString(R.string.google_maps_directions_api_key));
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "Failed to create request URL.", e);
return null;
}
}
private CommuteSummary parseCommuteSummary(JSONObject nowResponse, JSONObject futureResponse)
throws JSONException {
String nowStatus = nowResponse.getString("status");
String futureStatus = futureResponse.getString("status");
if (!"OK".equals(nowStatus) || !"OK".equals(futureStatus)) {
Log.e(TAG, String.format("Error status in response: %s %s", nowStatus, futureStatus));
return null;
}
// Expect exactly one route.
JSONArray nowRoutes = nowResponse.getJSONArray("routes");
JSONObject nowRoute = nowRoutes.getJSONObject(0);
JSONArray futureRoutes = futureResponse.getJSONArray("routes");
JSONObject futureRoute = futureRoutes.getJSONObject(0);
// Expect exactly one leg.
JSONArray nowLegs = nowRoute.getJSONArray("legs");
JSONObject nowLeg = nowLegs.getJSONObject(0);
JSONArray futureLegs = futureRoute.getJSONArray("legs");
JSONObject futureLeg = futureLegs.getJSONObject(0);
// Get the duration now, with traffic if available.
JSONObject nowDuration;
boolean nowHasTraffic = nowLeg.has("duration_in_traffic");
if (nowHasTraffic) {
nowDuration = nowLeg.getJSONObject("duration_in_traffic");
} else {
nowDuration = nowLeg.getJSONObject("duration");
}
String nowDurationText = nowDuration.getString("text");
long nowDurationSeconds = nowDuration.getLong("value");
Log.d(TAG, String.format("Duration now: %s (%s s) %b", nowDurationText,
nowDurationSeconds, nowHasTraffic));
// Get the duration in the future, with traffic if available.
JSONObject futureDuration;
boolean futureHasTraffic = futureLeg.has("duration_in_traffic");
if (futureHasTraffic) {
futureDuration = futureLeg.getJSONObject("duration_in_traffic");
} else {
futureDuration = futureLeg.getJSONObject("duration");
}
String futureDurationText = futureDuration.getString("text");
long futureDurationSeconds = futureDuration.getLong("value");
Log.d(TAG, String.format("Duration future: %s (%d secs) %b", futureDurationText,
futureDurationSeconds, futureHasTraffic));
// Create the text summary.
String nowSummaryText = nowRoute.getString("summary");
Log.d(TAG, "Summary text: " + nowSummaryText);
String text;
if (!TextUtils.isEmpty(nowSummaryText)) {
text = String.format("%s via %s", nowDurationText, nowSummaryText);
} else {
text = nowDurationText;
}
// Pick the icon for the travel mode.
String travelMode = context.getString(R.string.travel_mode);
int travelModeIconResource;
if (MODE_DRIVING.equals(travelMode)) {
travelModeIconResource = R.drawable.driving;
} else if (MODE_TRANSIT.equals(travelMode)) {
travelModeIconResource = R.drawable.transit;
} else if (MODE_WALKING.equals(travelMode)) {
travelModeIconResource = R.drawable.walking;
} else if (MODE_BICYCLING.equals(travelMode)) {
travelModeIconResource = R.drawable.bicycling;
} else {
Log.e(TAG, "Unknown travel mode: " + travelMode);
return null;
}
Log.d(TAG, "Using travel mode: " + travelMode);
Drawable travelModeIcon = context.getDrawable(travelModeIconResource);
// Check if there is a significant trend and use the corresponding icon.
Drawable trafficTrendIcon;
long trendSeconds = futureDurationSeconds - nowDurationSeconds;
Log.d(TAG, String.format("Traffic trend: %d secs", trendSeconds));
if (Math.abs(trendSeconds) >= TREND_THRESHOLD_SECONDS) {
int trendIconResource = trendSeconds > 0 ? R.drawable.trend_up : R.drawable.trend_down;
trafficTrendIcon = context.getDrawable(trendIconResource);
} else {
trafficTrendIcon = null;
}
return new CommuteSummary(text, travelModeIcon, trafficTrendIcon);
}
@Override
protected String getTag() {
return TAG;
}
} |
package jcavern;
import java.awt.event.*;
import java.awt.*;
import java.util.Enumeration;
public class KeyboardCommandListener extends KeyAdapter
{
/** * A model of the game world */
private World mWorld;
/** * The representation of the player */
private Player mPlayer;
private int mCurrentMode;
/** * In normal command mode (movement, etc) */
private static final int NORMAL_MODE = 1;
/** * In normal command mode (movement, etc) */
private static final int SWORD_MODE = 2;
/** * In normal command mode (movement, etc) */
private static final int RANGED_ATTACK_MODE = 3;
/** * In normal command mode (movement, etc) */
private static final int CASTLE_MODE = 4;
public KeyboardCommandListener(World aWorld, Player aPlayer)
{
mWorld = aWorld;
mPlayer = aPlayer;
mCurrentMode = NORMAL_MODE;
}
private int parseDirectionKey(KeyEvent e)
{
switch (e.getKeyChar())
{
case 'q' : return Location.NORTHWEST;
case 'w' : return Location.NORTH;
case 'e' : return Location.NORTHEAST;
case 'a' : return Location.WEST;
case 'd' : return Location.EAST;
case 'z' : return Location.SOUTHWEST;
case 'x' : return Location.SOUTH;
case 'c' : return Location.SOUTHEAST;
}
throw new IllegalArgumentException("not a movement key!");
}
/**
* Handles keyboard commands.
*/
public void keyTyped(KeyEvent e)
{
try
{
switch (mCurrentMode)
{
case NORMAL_MODE: switch (e.getKeyChar())
{
// movement commands
case 'q' :
case 'w' :
case 'e' :
case 'a' :
case 'd' :
case 'z' :
case 'x' :
case 'c' : mWorld.move(mPlayer, parseDirectionKey(e)); break;
case 's' : mCurrentMode = SWORD_MODE; JCavernApplet.log("Sword attack, direction?"); break;
case 'b' : mCurrentMode = RANGED_ATTACK_MODE; JCavernApplet.log("Ranged attack, direction?"); break;
} break;
case SWORD_MODE: switch (e.getKeyChar())
{
// movement commands
case 'q' :
case 'w' :
case 'e' :
case 'a' :
case 'd' :
case 'z' :
case 'x' :
case 'c' : mWorld.attack(mPlayer, parseDirectionKey(e)); mCurrentMode = NORMAL_MODE; break;
} break;
case RANGED_ATTACK_MODE: switch (e.getKeyChar())
{
// movement commands
case 'q' :
case 'w' :
case 'e' :
case 'a' :
case 'd' :
case 'z' :
case 'x' :
case 'c' : mWorld.rangedAttack(mPlayer, parseDirectionKey(e)); mCurrentMode = NORMAL_MODE; break;
} break;
}
}
catch(ThingCollisionException tce)
{
JCavernApplet.log("Collided with " + tce.getMovee());
mPlayer.collideWithTree();
}
catch(IllegalLocationException ile)
{
JCavernApplet.log("Tried to move off the edge of the world");
}
catch(NoSuchThingException nste)
{
JCavernApplet.log("Nothing to attack!");
mCurrentMode = NORMAL_MODE;
}
// and now, the monsters get a turn
if (mCurrentMode == NORMAL_MODE)
{
mWorld.doTurn();
}
}
} |
package encoder;
import java.io.File;
import checker.SemanticException;
import util.Arquivo;
import util.AST.*;
import util.AST.Number;
public class Encoder implements Visitor {
int contadorIf = 1, contadorElse = 1, contadorTest = 1, contadorWhile = 1;
int contadorDesvioCondicional = 1;
int nextInstr = 0;
File arquivo = new File("/Users/juvenalbisneto/Desktop/Output/output.asm");
Arquivo out = new Arquivo(arquivo.toString(), arquivo.toString());
public void encode(AST code) throws SemanticException {
this.out.println("extern _printf\n");
code.visit(this, null);
this.out.close();
}
public Object visitCode(Code code, Object args) throws SemanticException {
this.out.println("SECTION .data");
this.out.println("intFormat: db \"%d\", 10, 0");
if (code.getGlobalDataDiv() != null) {
code.getGlobalDataDiv().visit(this, null);
}
this.out.println();
code.getProgramDiv().visit(this, null);
return null;
}
public Object visitGlobalDataDiv(GlobalDataDiv gdd, Object args)
throws SemanticException {
if(gdd.getVarDeclaration() != null){
for (VarDeclaration varDecl : gdd.getVarDeclaration()) {
varDecl.visit(this, gdd);
}
}
return null;
}
public Object visitProgramDiv(ProgramDiv pdiv, Object args)
throws SemanticException {
this.out.println("SECTION .text");
this.out.println("global _WinMain@16\n");
if(pdiv.getArrayFunction() != null){
for (Function func : pdiv.getArrayFunction()) {
func.visit(this, null);
}
}
pdiv.getMainProc().visit(this, null);
return null;
}
public Object visitMainProc(MainProc main, Object args)
throws SemanticException {
this.out.println("_WinMain@16:");
this.out.println("push ebp");
this.out.println("mov ebp, esp");
this.out.println();
if (main.getVarDeclarations() != null) {
for (VarDeclaration varDecl : main.getVarDeclarations()) {
varDecl.visit(this, null);
}
}
if (main.getCommands() != null) {
for (Command cmd : main.getCommands()) {
cmd.visit(this, null);
}
}
this.out.println("mov esp, ebp");
this.out.println("pop ebp");
this.out.println("mov eax, 0");
this.out.println("ret");
return null;
}
public Object visitAccept(Accept accept, Object args)
throws SemanticException {
// TODO Auto-generated method stub
return null;
}
public Object visitArithmeticExpression(ArithmeticExpression expression,
Object args) throws SemanticException {
// TODO Auto-generated method stub
return null;
}
public Object visitArithmeticParcel(ArithmeticParcel parcel, Object args)
throws SemanticException {
// TODO Auto-generated method stub
return null;
}
public Object visitArithmeticTerm(ArithmeticTerm term, Object args)
throws SemanticException {
// TODO Auto-generated method stub
return null;
}
public Object visitArithmeticFactor(ArithmeticFactor factor, Object args)
throws SemanticException {
// TODO Auto-generated method stub
return null;
}
public Object visitBooleanExpression(BooleanExpression expression,
Object args) throws SemanticException {
// TODO Auto-generated method stub
return null;
}
public Object visitBoolValue(BoolValue bool, Object args)
throws SemanticException {
// TODO Auto-generated method stub
return null;
}
public Object visitBreak(Break brk, Object args) throws SemanticException {
// TODO Auto-generated method stub
return null;
}
public Object visitContinue(Continue cont, Object args)
throws SemanticException {
// TODO Auto-generated method stub
return null;
}
public Object visitDisplay(Display display, Object args)
throws SemanticException {
// TODO Auto-generated method stub
return null;
}
public Object visitFunction(Function function, Object args)
throws SemanticException {
// TODO Auto-generated method stub
return null;
}
public Object visitFunctionCall(FunctionCall fcall, Object args)
throws SemanticException {
// TODO Auto-generated method stub
return null;
}
public Object visitIdentifier(Identifier id, Object args)
throws SemanticException {
// TODO Auto-generated method stub
return null;
}
public Object visitIfStatement(IfStatement ifStatement, Object args)
throws SemanticException {
// TODO Auto-generated method stub
return null;
}
public Object visitNumber(Number number, Object args)
throws SemanticException {
// TODO Auto-generated method stub
return null;
}
public Object visitOpAdd(OpAdd opAdd, Object args) throws SemanticException {
// TODO Auto-generated method stub
return null;
}
public Object visitOpMult(OpMult opMult, Object args)
throws SemanticException {
// TODO Auto-generated method stub
return null;
}
public Object visitOpRelational(OpRelational opRel, Object args)
throws SemanticException {
// TODO Auto-generated method stub
return null;
}
public Object visitReturn(Return rtn, Object args) throws SemanticException {
// TODO Auto-generated method stub
return null;
}
public Object visitUntil(Until until, Object args) throws SemanticException {
// TODO Auto-generated method stub
return null;
}
public Object visitVarPIC9Declaration(VarPIC9Declaration var9, Object args)
throws SemanticException {
if(args instanceof GlobalDataDiv) {
var9.getIdentifier().memoryPosition = this.nextInstr;
System.out.println(var9.getIdentifier().spelling+" "+var9.getNumber().spelling);
this.out.println(var9.getIdentifier().spelling + ": dd 0");
this.nextInstr += 4;
} else if (args == null) {
var9.getIdentifier().memoryPosition = this.nextInstr;
this.nextInstr += 4;
} else {
throw new SemanticException("Entrada invalida para a declaracao de variaveis.");
}
return null;
}
public Object visitVarPICBOOLDeclaration(VarPICBOOLDeclaration varBool,
Object args) throws SemanticException {
// TODO Auto-generated method stub
return null;
}
} |
// $OldId: ExpandMixins.java,v 1.24 2002/11/11 16:08:50 schinz Exp $
package scalac.transformer;
import java.util.Arrays;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Iterator;
import scalac.Global;
import scalac.ast.Tree;
import scalac.ast.Tree.Template;
import scalac.ast.TreeList;
import scalac.ast.TreeGen;
import scalac.ast.TreeCloner;
import scalac.ast.TreeSymbolCloner;
import scalac.ast.Transformer;
import scalac.symtab.Modifiers;
import scalac.symtab.Scope;
import scalac.symtab.Scope.SymbolIterator;
import scalac.symtab.Symbol;
import scalac.symtab.SymbolCloner;
import scalac.symtab.SymbolSubstTypeMap;
import scalac.symtab.Type;
import scalac.util.Name;
import scalac.util.Debug;
public class ClassExpander {
//
// Private Fields
/** The global environment */
private final Global global;
/** A tree generator */
private final TreeGen gen;
/** The expanding class */
private final Symbol clasz;
/** The parents of the expanding class */
private final Type[] parents;
/** The members of the expanding class */
private final Scope members;
/** The template of the expanding class */
private final Template template;
/** The body of the expanding class */
private final LinkedList/*<Tree>*/ body;
/** The type map to apply to inlined symbols and trees */
private final SymbolSubstTypeMap map;
/** The symbol cloner to clone inlined symbols */
private final SymbolCloner cloner;
/** The state of this class (used to prevent misuses) */
private int state;
//
// Public Constructors
public ClassExpander(Global global, Symbol clasz, Template template) {
this.global = global;
this.gen = global.treeGen;
this.clasz = clasz;
this.parents = Type.cloneArray(clasz.parents());
this.members = clasz.members().cloneScope();
this.template = gen.Template(template.pos, template.symbol(),
Tree.cloneArray(template.parents), template.body);
this.body = new LinkedList();
this.map = new SymbolSubstTypeMap();
this.cloner = new SymbolCloner(
global.freshNameCreator, new HashMap(), map.getSymbols());
this.state = parents.length;
}
//
// Public Methods
public void inlineMixin(int i, Type type, Symbol iface, Template impl) {
assert 0 < i && i < state : "state = " + state + ", i = " + i;
switch (parents[i]) {
case TypeRef(Type prefix, Symbol mixin, Type[] args):
map.insertSymbol(mixin, clasz);
cloner.owners.put(mixin.primaryConstructor(), clasz);
inlineMixinTParams(type);
Tree.Apply constr = (Tree.Apply)template.parents[i];
Symbol[] vparams = mixin.valueParams();
inlineMixinVParams(vparams, constr.args, 0);
handleMixinInterfaceMembers(mixin);
inlineMixinMembers(mixin.nextInfo().members(), impl, vparams.length);
parents[i] = Type.TypeRef(prefix, iface, args);
template.parents[i] = gen.mkPrimaryConstr(constr.pos, parents[i]);
state = i;
return;
default:
throw Debug.abort("invalid base class type", parents[i]);
}
}
public Template getTemplate() {
assert 0 < state : "state = " + state;
Transformer superFixer = new Transformer(global) {
public Tree transform(Tree tree) {
switch (tree) {
case Select(Super(_, _), _):
Symbol symbol = map.lookupSymbol(tree.symbol());
if (symbol != null)
return gen.Select(gen.This(tree.pos, clasz), symbol);
}
return super.transform(tree);
}
};
body.addAll(Arrays.asList(superFixer.transform(template.body)));
template.body = (Tree[])body.toArray(new Tree[body.size()]);
// !!! *1 fix ExpandMixinsPhase.transformInfo and remove next line
clasz.updateInfo(Type.compoundType(parents, members, clasz));
state = 0;
return template;
}
//
// Private Methods
private void inlineMixinTParams(Type type) {
switch (type) {
case TypeRef(Type prefix, Symbol symbol, Type[] args):
map.insertType(symbol.typeParams(), args);
// !!! symbols could be equal but args different? need to rebind ?
if (prefix.symbol() != symbol.owner())
inlineMixinTParams(prefix.baseType(symbol.owner()));
return;
default:
throw Debug.abort("illegal case", type);
}
}
private void inlineMixinVParams(Symbol[] params, Tree[] args, int fstPos) {
for (int i = 0; i < params.length; i++) {
Symbol member = cloner.cloneSymbol(params[i], true);
member.flags &= ~Modifiers.PARAM;
member.flags |= Modifiers.PRIVATE;
members.enter(member);
}
// We need two loops because parameters may appear in their types.
for (int i = 0; i < params.length; i++) {
Symbol member = map.lookupSymbol(params[i]);
member.setType(map.apply(member.type()));
body.add(fstPos + i, gen.ValDef(member, args[i]));
}
}
// !!! This is just rapid fix. Needs to be reviewed.
private void handleMixinInterfaceMembers(Symbol mixin) {
Type[] parents = mixin.info().parents();
//assert parents.length == 2: Debug.show(mixin) +" -- "+ mixin.info();
for (int i = 1; i < parents.length; i++)
handleMixinInterfaceMembersRec(parents[i].symbol());
}
private void handleMixinInterfaceMembersRec(Symbol interfase) {
handleMixinInterfaceMembersAux(interfase.nextInfo().members());
Type[] parents = interfase.parents();
for (int i = 0; i < parents.length; i++) {
Symbol clasz = parents[i].symbol();
if (clasz.isInterface()) handleMixinInterfaceMembersRec(clasz);
}
}
private void handleMixinInterfaceMembersAux(Scope symbols) {
for (SymbolIterator i = symbols.iterator(true); i.hasNext();) {
Symbol member = i.next();
if (member.kind != scalac.symtab.Kinds.TYPE) continue;
Symbol subst = clasz.thisType().memberType(member).symbol();
if (subst == member) continue;
Symbol subst1 = map.lookupSymbol(member);
assert subst1 == null || subst1 == subst:
Debug.show(member," -> ",subst," + ",subst1);
if (subst1 == null) map.insertSymbol(member, subst);
}
}
private void inlineMixinMembers(Scope symbols, Template mixin, int fstPos) {
// The map names is used to implement an all or nothing
// strategy for overloaded symbols.
Map/*<Name,Name>*/ names = new HashMap();
for (SymbolIterator i = symbols.iterator(true); i.hasNext();) {
Symbol member = i.next();
Name name = (Name)names.get(member.name);
boolean shadowed = name == null &&
members.lookup(member.name) != Symbol.NONE;
Symbol clone = cloner.cloneSymbol(member, shadowed);
if (name != null)
clone.name = name;
else
names.put(member.name, clone.name);
if (clone.name != member.name) clone.flags &= ~Modifiers.OVERRIDE;
clone.setType(clone.type().cloneTypeNoSubst(cloner));
members.enterOrOverload(clone);
}
// We need two loops because members may appear in their types.
for (SymbolIterator i = symbols.iterator(true); i.hasNext();) {
Symbol member = map.lookupSymbol(i.next());
if (member == null) continue;
member.setType(map.applyParams(member.type()));
}
cloner.owners.put(mixin.symbol(), template.symbol());
final Set clones = new HashSet();
TreeSymbolCloner mixinSymbolCloner = new TreeSymbolCloner(cloner) {
public Symbol cloneSymbol(Symbol symbol) {
Symbol clone = super.cloneSymbol(symbol);
clones.add(clone);
return clone;
}
};
TreeCloner mixinTreeCloner = new TreeCloner(global, map) {
public Tree transform(Tree tree) {
switch (tree) {
case New(Template template):
assert template.parents.length == 1 : tree;
assert template.body.length == 0 : tree;
Tree apply = template.parents[0];
switch (apply) {
case Apply(Tree clasz, Tree[] args):
args = transform(args);
apply = gen.Apply(apply.pos, clasz, args);
return gen.New(tree.pos, apply);
default:
throw Debug.abort("illegal case", tree);
}
case Select(Super(_, _), _):
Symbol sym = tree.symbol();
Symbol newSym = sym.overridingSymbol(parents[0]);
if (newSym != Symbol.NONE)
return gen.Select(tree.pos,
gen.Super(tree.pos, newSym.owner()),
newSym);
else
return super.transform(tree);
default:
return super.transform(tree);
}
}
};
int pos = 0;
for (int i = 0; i < mixin.body.length; i++) {
Tree tree = mixin.body[i];
// Inline local code and members whose symbol has been cloned.
if (!tree.definesSymbol() ||
map.lookupSymbol(tree.symbol()) != null) {
mixinSymbolCloner.traverse(tree);
for (Iterator j = clones.iterator(); j.hasNext();) {
Symbol clone = (Symbol)j.next();
clone.setType(map.apply(clone.type()));
}
clones.clear();
body.add(fstPos + pos, mixinTreeCloner.transform(tree));
++pos;
}
}
}
//
} |
package me.openphoto.android.app;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import me.openphoto.android.app.model.Photo;
import me.openphoto.android.app.net.IOpenPhotoApi;
import me.openphoto.android.app.net.Paging;
import me.openphoto.android.app.net.PhotosResponse;
import me.openphoto.android.app.ui.adapter.EndlessAdapter;
import me.openphoto.android.app.ui.widget.ActionBar;
import me.openphoto.android.app.util.ImageWorker;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.bugsense.trace.BugSenseHandler;
/**
* The home activity - screen
*
* @author Patrick Boos
*/
public class HomeActivity extends Activity implements Refreshable {
public static final String TAG = HomeActivity.class.getSimpleName();
private ActionBar mActionBar;
private NewestPhotosAdapter mAdapter;
private LayoutInflater mInflater;
private ImageWorker iw;
/**
* Called when Home Activity is first loaded
*
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mInflater = LayoutInflater.from(this);
mActionBar = (ActionBar) getParent().findViewById(R.id.actionbar);
findViewById(R.id.actionbar).setVisibility(View.GONE);
// table with newest photos
refresh();
iw = new ImageWorker(this, mActionBar);
}
@Override
public void refresh() {
mAdapter = new NewestPhotosAdapter(this);
ListView list = (ListView) findViewById(R.id.list_newest_photos);
list.setAdapter(mAdapter);
}
private void alert(String msg)
{
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
private class NewestPhotosAdapter extends EndlessAdapter<Photo> {
private final IOpenPhotoApi mOpenPhotoApi;
private final Context mContext;
public NewestPhotosAdapter(Context context) {
super(Integer.MAX_VALUE);
mOpenPhotoApi = Preferences.getApi(HomeActivity.this);
mContext = context;
loadFirstPage();
}
@Override
public long getItemId(int position) {
return ((Photo) getItem(position)).getId().hashCode();
}
@Override
public View getView(Photo photo, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_newest_photos, parent, false);
}
// load the image in another thread
ImageView photoView =
(ImageView) convertView.findViewById(R.id.newest_image);
photoView.setTag(photo.getUrl("700x650xCR"));
Drawable dr =
iw.loadImage(this, photoView);
photoView.setImageDrawable(dr);
// set title or file's name
if (photo.getTitle() != null && photo.getTitle().trim().length()
> 0) {
((TextView) convertView.findViewById(R.id.newest_title)).setText
(photo.getTitle());
} else {
((TextView) convertView.findViewById(R.id.newest_title)).setText(photo
.getFilenameOriginal());
}
/*
* set the date
*/
Resources res = getResources();
String text = null;
long milliseconds = new Date().getTime() - photo.getDateTaken().getTime();
long days = milliseconds / (24 * 60 * 60 * 1000);
if (days >= 2) {
if (days > 365) {
// show in years
text = days / 365 == 1 ? String.format(
res.getString(R.string.newest_this_photo_was_taken), days / 365,
res.getString(R.string.year)) :
String.format(res.getString(R.string.newest_this_photo_was_taken),
days / 365, res.getString(R.string.years));
} else {
// lets show in days
text = String.format(res.getString(R.string.newest_this_photo_was_taken), days,
res.getString(R.string.days));
}
} else {
// lets show in hours
Long hours = days * 24;
if (hours < 1) {
text = String.format(res
.getString(R.string.newest_this_photo_was_taken_less_one_hour));
} else {
if (hours == 1) {
text = String.format(res.getString(R.string.newest_this_photo_was_taken),
1, res.getString(R.string.hour));
} else {
text = String.format(res.getString(R.string.newest_this_photo_was_taken),
hours, res.getString(R.string.hours));
}
}
}
// set the correct text in the textview
((TextView) convertView.findViewById(R.id.newest_date))
.setText(text);
// TODO: tags
return convertView;
}
@Override
public LoadResponse loadItems(int page) {
if (Preferences.isLoggedIn(mContext)) {
try {
PhotosResponse response = mOpenPhotoApi.getNewestPhotos(new Paging(page, 25));
return new LoadResponse(response.getPhotos(), false);
} catch (Exception e) {
Log.e(TAG, "Could not load next photos in list", e);
Map<String, String> extraData = new HashMap<String, String>();
extraData.put("message", "Could not load next photos in list for HomeActivity");
BugSenseHandler.log(TAG, extraData, e);
alert("Could not load next photos in list");
}
}
return new LoadResponse(null, false);
}
@Override
protected void onStartLoading() {
mActionBar.startLoading();
}
@Override
protected void onStoppedLoading() {
mActionBar.stopLoading();
}
}
} |
package com.android.utility;
import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.widget.Toast;
import com.google.gson.Gson;
import java.io.File;
import java.util.concurrent.ExecutionException;
public class Utils {
public static void savePreferenceData(Context context, String key, String value) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sp.edit();
editor.putString(key, value);
editor.commit();
}
public static void savePreferenceData(Context context, String key, Boolean value) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean(key, value);
editor.commit();
}
public static void savePreferenceData(Context context, String key, int value) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sp.edit();
editor.putInt(key, value);
editor.commit();
}
public static void savePreferenceData(Context context, String key, Object value) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sp.edit();
editor.putString(key, new Gson().toJson(value));
editor.commit();
}
public static void clearPreferences(Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sp.edit();
editor.clear();
editor.commit();
}
public static void removePreferenceData(Context context, String key) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.edit().remove(key).commit();
}
public static String readPreferenceData(Context context, String key, String defaultValue) {
if (context != null) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getString(key, defaultValue);
}
return null;
}
public static Boolean readPreferenceData(Context context, String key, boolean defaultValue) {
if (context != null) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getBoolean(key, defaultValue);
}
return false;
}
public static int readPreferenceData(Context context, String key, int defaultValue) {
if (context != null) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getInt(key, defaultValue);
}
return -1;
}
public static Object readPreferenceData(Context context, String key, String defaultValue, Class clazz) {
String result = readPreferenceData(context, key, defaultValue);
if (result != null) {
return new Gson().fromJson(result, clazz);
}
return result;
}
public static void createDirectory(Context context, String path) {
String tempPath = "";
File dirPath;
for (String dir : path.split("/")) {
dirPath = new File(context.getFilesDir(), tempPath + dir);
if (!dirPath.exists()) {
dirPath.mkdir();
tempPath = tempPath + dir + "/";
} else {
tempPath = tempPath + dir + "/";
}
}
}
public static void generateShortToast(Context context, String message) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
public static void generateLongToast(Context context, String message) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
public static void showProgressBar(ProgressDialog progressDialog) {
progressDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
progressDialog.show();
progressDialog.setContentView(R.layout.progress_dialog_layout);
progressDialog.setCancelable(true);
}
public static void showProgressBar(String title, String message, ProgressDialog progressDialog) {
progressDialog.setTitle(title);
progressDialog.setMessage(message);
progressDialog.show();
progressDialog.setCancelable(true);
}
public static void hideProgressBar(ProgressDialog progressDialog) {
try {
if (progressDialog != null)
progressDialog.cancel();
} catch(IllegalArgumentException e) {
e.printStackTrace();
}
}
public static void deleteDirectory(Context context, String directory) {
File dir = new File(context.getFilesDir() + directory);
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
new File(dir, children[i]).delete();
}
}
}
public static void downloadMusicFile(final String url, final String fileName, Activity activity) {
RunTimePermission permission = new RunTimePermission(activity, new RuntimePermissionInterface() {
@Override
public void doTaskAfterPermission() {
new Task.DownloadFileTask().execute(url, fileName + ".mp3", Environment.DIRECTORY_MUSIC);
}
});
permission.runtimePermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
public static void downloadVideoFile(final String url, final String fileName, Activity activity) {
RunTimePermission permission = new RunTimePermission(activity, new RuntimePermissionInterface() {
@Override
public void doTaskAfterPermission() {
new Task.DownloadFileTask().execute(url, fileName + ".mp4", Environment.DIRECTORY_MOVIES);
}
});
permission.runtimePermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
public static void downloadImageFile(final String url, final String fileName, Activity activity) {
RunTimePermission permission = new RunTimePermission(activity, new RuntimePermissionInterface() {
@Override
public void doTaskAfterPermission() {
new Task.DownloadFileTask().execute(url, fileName + ".jpg", Environment.DIRECTORY_PICTURES);
}
});
permission.runtimePermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
public static boolean hasInternetAccess() {
try {
return new Task.InternetCheckTask().execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return false;
}
public static boolean hasAppInForeground(Context context) {
try {
return new Task.ForegroundCheckTask().execute(context).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return false;
}
} |
package io.spacedog.rest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.Maps;
import com.google.common.io.Files;
import com.google.common.primitives.Ints;
import io.spacedog.model.Schema;
import io.spacedog.model.Settings;
import io.spacedog.sdk.SpaceDog;
import io.spacedog.utils.AuthorizationHeader;
import io.spacedog.utils.Check;
import io.spacedog.utils.Exceptions;
import io.spacedog.utils.Json;
import io.spacedog.utils.Optional7;
import io.spacedog.utils.SpaceHeaders;
import io.spacedog.utils.SpaceParams;
import io.spacedog.utils.Utils;
import io.spacedog.utils.WebPath;
import okhttp3.Credentials;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
public class SpaceRequest {
private static enum HttpVerb {
GET, POST, PUT, DELETE, HEAD, OPTIONS
}
private HttpVerb method;
private SpaceBackend backend;
private String path;
private JsonNode bodyJson;
private Object body;
private Request.Builder requestBuilder;
private Map<String, String> pathParams = Maps.newHashMap();
private Map<String, String> queryParams = Maps.newHashMap();
private Map<String, String> formFields = Maps.newHashMap();
private Boolean forTesting = null;
private MediaType contentType;
// static defaults
private static boolean forTestingDefault = false;
private static SpaceEnv env;
private SpaceRequest(String path, HttpVerb verb) {
this.path = path;
this.method = verb;
this.requestBuilder = new Request.Builder();
}
private HttpUrl computeHttpUrl() {
HttpUrl.Builder builder = path.startsWith("http")
? HttpUrl.parse(path).newBuilder()
: computeHttpUrlFromBackendAndPath();
for (Entry<String, String> queryParam : this.queryParams.entrySet())
builder.addQueryParameter(queryParam.getKey(), queryParam.getValue());
return builder.build();
}
private HttpUrl.Builder computeHttpUrlFromBackendAndPath() {
if (backend == null)
backend = env().target();
HttpUrl.Builder builder = new HttpUrl.Builder()
.scheme(backend.scheme())
.host(backend.host())
.port(backend.port());
path = applyPathParams(path);
for (String segment : WebPath.parse(path))
builder.addPathSegment(segment);
return builder;
}
private String applyPathParams(String uri) {
Check.notNull(uri, "uri");
for (Entry<String, String> pathParam : this.pathParams.entrySet()) {
if (uri.indexOf('{') == -1)
break;
uri = uri.replace(pathParam.getKey(), pathParam.getValue());
}
return uri;
}
public static SpaceRequest get(String path) {
return new SpaceRequest(path, HttpVerb.GET);
}
public static SpaceRequest post(String path) {
return new SpaceRequest(path, HttpVerb.POST);
}
public static SpaceRequest put(String path) {
return new SpaceRequest(path, HttpVerb.PUT);
}
public static SpaceRequest delete(String path) {
return new SpaceRequest(path, HttpVerb.DELETE);
}
public static SpaceRequest options(String path) {
return new SpaceRequest(path, HttpVerb.OPTIONS);
}
public static SpaceRequest head(String path) {
return new SpaceRequest(path, HttpVerb.HEAD);
}
public SpaceRequest www(SpaceDog backend) {
return www(backend.backendId());
}
private SpaceRequest www(String backendId) {
return backend(backendId + ".www");
}
public SpaceRequest backend(SpaceDog dog) {
return backend(dog.backend());
}
public SpaceRequest backend(SpaceBackend backend) {
this.backend = backend;
return this;
}
public SpaceRequest backend(String backend) {
this.backend = backend.startsWith("http")
? SpaceBackend.fromUrl(backend)
: env().target().instanciate(backend);
return this;
}
public SpaceRequest auth(SpaceDog dog) {
// TODO when all test are refactored like
// vince.get("/1/...")...
// this method should be removed
backend(dog);
Optional7<String> accessToken = dog.accessToken();
if (accessToken.isPresent())
return bearerAuth(accessToken.get());
Optional7<String> password = dog.password();
if (password.isPresent())
return basicAuth(dog.username(), password.get());
// if no password nor access token then no auth
return this;
}
public SpaceRequest basicAuth(SpaceDog user) {
// TODO when all tests are refactored like
// vince.delete("/1/...")...
// this method should not set the backend of the space request
// but only the basic authorization
return backend(user).basicAuth(user.username(), user.password().get());
}
public SpaceRequest basicAuth(String username, String password) {
Check.notNull(username, "username");
Check.notNull(password, "password");
return setHeader(SpaceHeaders.AUTHORIZATION,
Credentials.basic(username, password, Utils.UTF8));
}
public SpaceRequest bearerAuth(SpaceDog user) {
// TODO when all tests are refactored like
// vince.get("/1/...")...
// this method should not set the backend of the space request
// but only the basic authorization
return backend(user).bearerAuth(user.accessToken().get());
}
public SpaceRequest bearerAuth(String accessToken) {
Check.notNull(accessToken, "access token");
return setHeader(SpaceHeaders.AUTHORIZATION,
Utils.join(" ", SpaceHeaders.BEARER_SCHEME, accessToken));
}
public SpaceRequest contentType(MediaType contentType) {
this.contentType = contentType;
return this;
}
public SpaceRequest bodyBytes(byte[] bytes) {
this.contentType = OkHttp.OCTET_STREAM;
this.body = bytes;
return this;
}
public SpaceRequest bodyString(String body) {
this.contentType = OkHttp.TEXT_PLAIN;
this.body = body;
return this;
}
public SpaceRequest bodyMultipart(MultipartBody body) {
this.body = body;
return this;
}
public SpaceRequest bodyFile(File file) {
try {
return bodyBytes(Files.toByteArray(file));
} catch (IOException e) {
throw Exceptions.runtime(e);
}
}
public SpaceRequest bodySettings(Settings settings) {
return bodyJson(Json.mapper().valueToTree(settings));
}
public SpaceRequest bodyPojo(Object pojo) {
return bodyJson(Json.toNode(pojo));
}
public SpaceRequest bodySchema(Schema schema) {
return bodyJson(schema.node());
}
public SpaceRequest bodyJson(String body) {
this.contentType = OkHttp.JSON;
if (env().debug())
this.bodyJson = Json.readNode(body);
this.body = body;
return this;
}
public SpaceRequest bodyJson(Object... elements) {
return bodyJson(Json.object(elements));
}
public SpaceRequest bodyJson(JsonNode body) {
this.contentType = OkHttp.JSON;
this.bodyJson = body;
this.body = body.toString();
return this;
}
public SpaceRequest bodyResource(String path) {
return bodyBytes(Utils.readResource(path));
}
public SpaceRequest bodyResource(Class<?> contextClass, String resourceName) {
return bodyBytes(Utils.readResource(contextClass, resourceName));
}
public SpaceRequest routeParam(String name, String value) {
this.pathParams.put('{' + name + '}', value);
return this;
}
public SpaceRequest queryParam(String name, String value) {
this.queryParams.put(name, value);
return this;
}
public SpaceRequest size(int size) {
return this.queryParam("size", String.valueOf(size));
}
public SpaceRequest from(int from) {
return this.queryParam("from", String.valueOf(from));
}
public SpaceRequest refresh() {
return refresh(true);
}
public SpaceRequest refresh(boolean refresh) {
if (refresh)
this.queryParam(SpaceParams.REFRESH_PARAM, String.valueOf(refresh));
return this;
}
public SpaceRequest setHeader(String name, String value) {
this.requestBuilder.header(name, value);
return this;
}
public SpaceRequest addHeader(String name, String value) {
this.requestBuilder.addHeader(name, value);
return this;
}
public SpaceRequest removeHeader(String name) {
this.requestBuilder.removeHeader(name);
return this;
}
public SpaceResponse go(int... expectedStatus) {
SpaceResponse response = go();
if (!Ints.contains(expectedStatus, response.okResponse().code()))
throw new SpaceRequestException(response);
return response;
}
public SpaceResponse go() {
if ((forTesting == null && forTestingDefault)
|| (forTesting != null && forTesting))
this.setHeader(SpaceHeaders.SPACEDOG_TEST, "true");
requestBuilder.url(computeHttpUrl())
.method(method.name(), computeRequestBody());
return new SpaceResponse(this, requestBuilder.build());
}
private RequestBody computeRequestBody() {
if (!formFields.isEmpty()) {
FormBody.Builder builder = new FormBody.Builder();
for (Entry<String, String> formField : formFields.entrySet())
builder.add(formField.getKey(), formField.getValue());
return builder.build();
}
if (body instanceof byte[])
return RequestBody.create(contentType, (byte[]) body);
if (body instanceof String)
return RequestBody.create(contentType, (String) body);
// OkHttp doesn't accept null body for PUT and POST
if (method.equals(HttpVerb.PUT)
|| method.equals(HttpVerb.POST))
return RequestBody.create(OkHttp.TEXT_PLAIN, "");
return null;
}
public SpaceRequest formField(String name, String value) {
Check.notNull(value, "form field " + name);
this.formFields.put(name, value);
return this;
}
public SpaceRequest forTesting(boolean forTesting) {
this.forTesting = forTesting;
return this;
}
public static void setForTestingDefault(boolean value) {
forTestingDefault = value;
}
public static void env(SpaceEnv value) {
env = value;
}
public static SpaceEnv env() {
if (env == null)
env(SpaceEnv.defaultEnv());
return env;
}
public static String getBackendKey(JsonNode account) {
return new StringBuilder(account.get("backendId").asText())
.append(':')
.append(account.get("backendKey").get("name").asText())
.append(':')
.append(account.get("backendKey").get("secret").asText())
.toString();
}
public SpaceRequest debugServer() {
return setHeader(SpaceHeaders.SPACEDOG_DEBUG, "true");
}
public SpaceRequest cookies(String... cookies) {
removeHeader(SpaceHeaders.COOKIE);
for (String cookie : cookies)
addHeader(SpaceHeaders.COOKIE, cookie);
return this;
}
public SpaceRequest cookies(List<String> cookies) {
removeHeader(SpaceHeaders.COOKIE);
for (String cookie : cookies)
addHeader(SpaceHeaders.COOKIE, cookie);
return this;
}
public void printRequest(Request okRequest) {
Utils.info("%s %s", okRequest.method(), okRequest.url());
Utils.info("Request headers:");
Headers headers = okRequest.headers();
for (int i = 0; i < headers.size(); i++)
printRequestHeader(headers.name(i), headers.value(i));
if (okRequest.body() != null) {
Utils.info(" Content-Type: %s", okRequest.body().contentType());
try {
Utils.info(" Content-Length: %s", okRequest.body().contentLength());
} catch (IOException ignore) {
ignore.printStackTrace();
}
}
if (!formFields.isEmpty()) {
Utils.info("Request form body:");
for (Entry<String, String> entry : formFields.entrySet())
Utils.info(" %s = %s", entry.getKey(), entry.getValue());
}
if (bodyJson != null)
Utils.info("Request Json body: %s", Json.toPrettyString(bodyJson));
}
private void printRequestHeader(String key, String value) {
if (AuthorizationHeader.isKey(key)) {
AuthorizationHeader authHeader = new AuthorizationHeader(value, false);
if (authHeader.isBasic()) {
Utils.info(" Authorization: Basic %s:*******", authHeader.username());
return;
}
}
Utils.info(" %s: %s", key, value);
}
} |
package uk.ac.ebi.phis.service;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.json.JSONArray;
import org.json.JSONObject;
import org.neo4j.cypher.ParameterNotFoundException;
import org.springframework.stereotype.Service;
import uk.ac.ebi.phis.solrj.dto.ImageDTO;
import uk.ac.ebi.phis.solrj.dto.RoiDTO;
import uk.ac.ebi.phis.utils.web.JSONRestUtil;
@Service
public class ImageService {
private HttpSolrServer solr;
private static final Logger log = Logger.getLogger(ImageService.class);
public ImageService(String solrUrl) {
solr = new HttpSolrServer(solrUrl);
}
public String getAutosuggest(String term, String mutantGene, String expressedGeneOrAllele, String phenotype, Integer rows){
SolrQuery solrQuery = new SolrQuery();
ArrayList<String> suggestions = new ArrayList<>();
Integer suggestionNumber = 10;
Integer solrRows = 100;
if (term != null){
if (term.length() < 1){
return "";
}
solrQuery.setQuery(ImageDTO.TERM_AUTOSUGGEST + ":" + term);
solrQuery.setFields(ImageDTO.TERM_AUTOSUGGEST);
solrQuery.addHighlightField(ImageDTO.TERM_AUTOSUGGEST);
solrQuery.set("f.term_autosuggest_analysed.hl.preserveMulti", true);
}
else if (mutantGene != null){
if (mutantGene.length() < 1){
return "";
}
solrQuery.setQuery(ImageDTO.GENE_SYMBOL + ":" + mutantGene);
solrQuery.setFields(ImageDTO.GENE_SYMBOL);
solrQuery.addHighlightField(ImageDTO.GENE_SYMBOL);
solrQuery.set("f." + ImageDTO.GENE_SYMBOL + ".hl.preserveMulti", true);
}
else if (expressedGeneOrAllele != null){
if (expressedGeneOrAllele.length() < 1){
return "";
}
solrQuery.setQuery(ImageDTO.EXPRESSED_GF_SYMBOL_BAG + ":" + expressedGeneOrAllele);
solrQuery.setFields(ImageDTO.EXPRESSED_GF_SYMBOL_BAG);
solrQuery.addHighlightField(ImageDTO.EXPRESSED_GF_SYMBOL_BAG);
solrQuery.set("f." + ImageDTO.EXPRESSED_GF_SYMBOL_BAG + ".hl.preserveMulti", true);
}
else if (phenotype != null){
if (phenotype.length() < 1){
return "";
}
solrQuery.setQuery(ImageDTO.PHENOTYPE_LABEL_BAG + ":" + phenotype);
solrQuery.setFields(ImageDTO.PHENOTYPE_LABEL_BAG);
solrQuery.addHighlightField(ImageDTO.PHENOTYPE_LABEL_BAG);
solrQuery.set("f." + ImageDTO.PHENOTYPE_LABEL_BAG + ".hl.preserveMulti", true);
}
solrQuery.setHighlight(true);
solrQuery.setHighlightRequireFieldMatch(true);
if (rows != null){
solrRows = rows*10;
suggestionNumber = rows;
}
solrQuery.setRows(solrRows);
System.out.println("Solr URL : " + solr.getBaseURL() + "/select?" + solrQuery);
log.info("Solr URL in getImages : " + solr.getBaseURL() + "/select?" + solrQuery);
// Parse results to filter out un-highlighted entries and duplicates
try {
int i = 1;
while ((suggestions.size() < suggestionNumber && solr.query(solrQuery).getResults().getNumFound() > i*solrRows) || i == 1){
Map<String, Map<String, List<String>>> highlights = solr.query(solrQuery).getHighlighting();
OUTERMOST: for (Map<String, List<String>> suggests : highlights.values()){
for (List<String> suggestLists : suggests.values()){
for(String highlighted : suggestLists){
if (highlighted.contains("<b>") && !suggestions.contains(highlighted)){
suggestions.add(highlighted);
if (suggestions.size() == suggestionNumber){
break OUTERMOST;
}
}
}
}
}
solrQuery.setStart(i++*solrRows);
}
} catch (SolrServerException e) {
e.printStackTrace();
}
// Return in JSON format
JSONObject returnObj = new JSONObject();
returnObj.put("response", new JSONObject().put("suggestions", new JSONArray(suggestions)));
return returnObj.toString().replaceAll("<\\\\", "<");
}
public String getImage(String term, String phenotype, String geneParameterToBeDeleted, String mutantGene, String anatomy, String expressedGene, String sex, String taxon,
String image_type, String sample_type, String stage, String visualisationMethod, String samplePreparation, String imagingMethod, Integer rows, Integer start) throws SolrServerException{
SolrQuery solrQuery = new SolrQuery();
solrQuery.setQuery("*:*");
if ( geneParameterToBeDeleted != null){
mutantGene = geneParameterToBeDeleted;
}
if (term != null){
solrQuery.setQuery(ImageDTO.GENERIC_SEARCH + ":" + term);
if (term.contains(" ")){
String[] splittedQuery = term.split(" ");
String query = ImageDTO.GENERIC_SEARCH + ":" + org.apache.commons.lang3.StringUtils.join(splittedQuery, "^1 " + ImageDTO.GENERIC_SEARCH + ":");
solrQuery.set("defType", "edismax");
solrQuery.set("qf", ImageDTO.GENERIC_SEARCH);
solrQuery.set("bq", ImageDTO.GENERIC_SEARCH + ":\"" + term + "\"^10 " + query);
}else{
solrQuery.addFilterQuery(ImageDTO.GENERIC_SEARCH + ":"+ term);
}
/* solrQuery.addFilterQuery(ImageDTO.PHENOTYPE_ID_BAG + ":\""+ term + "\" OR " +
ImageDTO.PHENOTYPE_FREETEXT_BAG + ":\""+ term + "\" OR " +
ImageDTO.ANATOMY_COMPUTED_ID_BAG + ":\""+ term + "\" OR " +
ImageDTO.ANATOMY_COMPUTED_TERM_BAG + ":\""+ term + "\" OR " +
ImageDTO.ANATOMY_FREETEXT + ":\""+ term + "\" OR " +
ImageDTO.ANATOMY_ID + ":\""+ term + "\" OR " +
ImageDTO.ANATOMY_TERM + ":\""+ term + "\" OR " +
ImageDTO.GENE_ID + ":\""+ term + "\" OR " +
ImageDTO.GENE_SYMBOL + ":\""+ term + "\" OR " +
ImageDTO.EXPRESSED_GF_ID_BAG + ":\""+ term + "\" OR " +
ImageDTO.EXPRESSED_GF_SYMBOL_BAG + ":\""+ term + "\" OR " +
ImageDTO.EXPRESSION_IN_FREETEXT_BAG + ":\""+ term + "\" OR " +
ImageDTO.EXPRESSION_IN_ID_BAG + ":\""+ term + "\" OR " +
ImageDTO.EXPRESSION_IN_LABEL_BAG + ":\""+ term + "\" OR " +
ImageDTO.IMAGE_GENERATED_BY + ":\""+ term + "\" OR " +
ImageDTO.IMAGING_METHOD_ID + ":\""+ term + "\" OR " +
ImageDTO.IMAGING_METHOD_LABEL_ANALYSED + ":\""+ term + "\" OR " +
ImageDTO.VISUALISATION_METHOD_ID + ":\""+ term + "\" OR " +
ImageDTO.VISUALISATION_METHOD_LABEL + ":\""+ term + "\" OR " +
ImageDTO.SAMPLE_GENERATED_BY + ":\""+ term + "\" OR " +
ImageDTO.SAMPLE_PREPARATION_ID + ":\""+ term + "\" OR " +
ImageDTO.SAMPLE_PREPARATION_LABEL + ":\""+ term + "\" OR " +
ImageDTO.PHENOTYPE_LABEL_BAG + ":\""+ term + "\"");
*/ }
if (phenotype != null){
solrQuery.addFilterQuery(ImageDTO.PHENOTYPE_ID_BAG + ":\""+ phenotype + "\" OR " +
ImageDTO.PHENOTYPE_FREETEXT_BAG + ":\""+ phenotype + "\" OR " +
ImageDTO.PHENOTYPE_LABEL_BAG + ":\""+ phenotype + "\"");
}
if (mutantGene != null){
solrQuery.addFilterQuery(ImageDTO.GENE_ID + ":\""+ mutantGene + "\" OR " +
ImageDTO.GENE_SYMBOL + ":\""+ mutantGene + "\"");
}
if (anatomy != null){
solrQuery.addFilterQuery(ImageDTO.ANATOMY_ID + ":\""+ anatomy + "\" OR " +
ImageDTO.ANATOMY_TERM + ":\""+ anatomy + "\" OR " +
ImageDTO.ANATOMY_FREETEXT + ":\""+ anatomy + "\"" );
}
if (expressedGene != null){
solrQuery.addFilterQuery(ImageDTO.EXPRESSED_GF_ID_BAG + ":\"" + expressedGene + "\"");
}
if (taxon != null){
solrQuery.addFilterQuery(ImageDTO.TAXON + ":\"" + taxon + "\" OR " +
ImageDTO.NCBI_TAXON_ID + ":\"" + taxon + "\"");
}
if (image_type != null){
solrQuery.addFilterQuery(ImageDTO.IMAGE_TYPE + ":\"" + image_type + "\"");
}
if (sample_type != null){
solrQuery.addFilterQuery(ImageDTO.SAMPLE_TYPE + ":\"" + sample_type + "\"");
}
if (stage != null){
solrQuery.addFilterQuery(ImageDTO.STAGE + ":\"" + stage + "\" OR " +
ImageDTO.STAGE_ID + ":\"" + stage + "\"");
}
if (visualisationMethod != null){
solrQuery.addFilterQuery(ImageDTO.VISUALISATION_METHOD_ID + ":\"" + visualisationMethod + "\" OR " +
ImageDTO.VISUALISATION_METHOD_LABEL + ":\"" + visualisationMethod + "\"");
}
if (samplePreparation != null){
solrQuery.addFilterQuery(ImageDTO.SAMPLE_PREPARATION_ID + ":\"" + samplePreparation + "\" OR " +
ImageDTO.SAMPLE_PREPARATION_LABEL + ":\"" + samplePreparation + "\"");
}
if (samplePreparation != null){
solrQuery.addFilterQuery(ImageDTO.IMAGING_METHOD_LABEL_ANALYSED + ":\"" + imagingMethod + "\" OR " +
ImageDTO.IMAGING_METHOD_ID + ":\"" + imagingMethod + "\"");
}
if (sex != null){
solrQuery.addFilterQuery(ImageDTO.SEX + ":\"" + sex + "\"");
}
if (rows != null){
solrQuery.setRows(rows);
}
else solrQuery.setRows(100);
if (start != null){
solrQuery.set("start", start);
}
solrQuery.set("wt", "json");
solrQuery.setFacet(true);
solrQuery.addFacetField(ImageDTO.STAGE);
solrQuery.addFacetField(ImageDTO.IMAGING_METHOD_LABEL);
solrQuery.addFacetField(ImageDTO.TAXON);
solrQuery.addFacetField(ImageDTO.SAMPLE_TYPE);
solrQuery.setFacetMinCount(1);
// add pivot facets to get the number of image types per
solrQuery.set("facet.pivot", ImageDTO.SAMPLE_TYPE + "," + ImageDTO.IMAGE_TYPE);
System.out.println("\nSolr URL : " + solr.getBaseURL() + "/select?" + solrQuery);
log.info("Solr URL in getImages : " + solr.getBaseURL() + "/select?" + solrQuery);
try {
return JSONRestUtil.getResults(getQueryUrl(solrQuery)).toString();
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
return "Couldn't get anything back from solr.";
}
/**
*
* @param roiToReplace must exist
* @param roiToAdd must have teh same id as roiToReplace
*/
public void updateImageFromRoi(RoiDTO roiToReplace, RoiDTO roiToAdd){
if (imageIdExists(roiToAdd.getAssociatedImage()) && imageIdExists(roiToReplace.getAssociatedImage())){
deleteRoiRefferences(roiToReplace);
addToImageFromRoi(roiToAdd);
}
}
public boolean imageIdExists(String id){
return getImageById(id) != null;
}
/**
* Delete all refferences to this roi (roi id, annotations from annotations bags)
* @param roi
*/
public void deleteRoiRefferences(RoiDTO roi){
ImageDTO img = getImageById(roi.getAssociatedImage());
System.out.println("Roi list before " + img.getAssociatedRoi().size() + " " + img.getAssociatedRoi());
List<String> list = img.getAssociatedRoi();
list.remove(roi.getId());
img.setAssociatedRoi(list);
if (roi.getAbnormalityAnatomyId() != null){
img.setAbnormalAnatomyIdBag(removeOnce(img.getAbnormalAnatomyIdBag(), roi.getAbnormalityAnatomyId()));
}
if (roi.getAbnormalityAnatomyFreetext() != null){
img.setAbnormalAnatomyFreetextBag(removeOnce(img.getAbnormalAnatomyFreetextBag(), roi.getAbnormalityAnatomyFreetext()));
}
if (roi.getPhenotypeId() != null){
img.setPhenotypeIdBag(removeOnce(img.getPhenotypeIdBag(), roi.getPhenotypeId()));
}
if (roi.getPhenotypeFreetext() != null){
img.setPhenotypeFreetextBag(removeOnce(img.getPhenotypeFreetextBag(), roi.getPhenotypeFreetext()));
}
if (roi.getObservations() != null){
img.setObservationBag(removeOnce(img.getObservationBag(), roi.getObservations()));
}
if (roi.getDepictedAnatomyId() != null){
img.setDepictedAnatomyIdBag(removeOnce(img.getDepictedAnatomyIdBag(), roi.getDepictedAnatomyId()));
}
if (roi.getDepictedAnatomyFreetext() != null){
img.setDepictedAnatomyFreetextBag(removeOnce(img.getDepictedAnatomyFreetextBag(), roi.getDepictedAnatomyFreetext()));
}
if (roi.getExpressedAnatomyFreetext() != null){
img.setExpressionInFreetextBag(removeOnce(img.getExpressionInFreetextBag(), roi.getExpressedAnatomyFreetext()));
}
if (roi.getExpressedAnatomyId() != null){
img.setExpressionInIdBag(removeOnce(img.getExpressionInFreetextBag(), roi.getExpressedAnatomyId()));
}
img.setGenericSearch(new ArrayList<String>());
List<ImageDTO> update = new ArrayList<>();
update.add(img);
addBeans(update);
}
public ArrayList<String> removeOnce(ArrayList<String> from, List<String> whatToDelete){
ArrayList<String> res = from;
if ( res != null){
for(String toRemove : whatToDelete){
from.remove(toRemove);
}
}
return from;
}
/**
* To be used for atomic updates when a user adds a new annotation
* @param roi
* @throws Exception
*/
public void addToImageFromRoi(RoiDTO roi) throws ParameterNotFoundException{
ImageDTO img = getImageById(roi.getAssociatedImage());
if (img.getAssociatedRoi() == null){
throw new ParameterNotFoundException("Image id does not exist");
}else
if(!img.getAssociatedRoi().contains(roi.getId())){
img.addAssociatedRoi(roi.getId());
if (roi.getAbnormalityAnatomyId() != null){
System.out.println("Adding " + roi.getAbnormalityAnatomyId().get(0));
img.addAbnormalAnatomyIdBag(roi.getAbnormalityAnatomyId().get(0));
}
if (roi.getAbnormalityAnatomyFreetext() != null){
img.addAbnormalAnatomyFreetextBag(roi.getAbnormalityAnatomyFreetext().get(0));
}
if (roi.getPhenotypeId() != null){
img.addPhenotypeIdBag((ArrayList<String>) roi.getPhenotypeId());
}
if (roi.getPhenotypeFreetext() != null){
img.addPhenotypeFreetextBag((ArrayList<String>) roi.getPhenotypeFreetext());
}
if (roi.getObservations() != null){
img.addObservationBag((ArrayList<String>) roi.getObservations());
}
if (roi.getDepictedAnatomyId() != null){
img.addDepictedAnatomyIdBag(roi.getDepictedAnatomyId());
}
if (roi.getDepictedAnatomyFreetext() != null){
img.addDepictedAnatomyFreetextBag(roi.getDepictedAnatomyFreetext());
}
if (roi.getExpressedAnatomyFreetext() != null){
System.out.println("Expression added \n\n\n\n");
img.addExpressionInFreetextBag(roi.getExpressedAnatomyFreetext());
}
if (roi.getExpressedAnatomyId() != null){
img.addExpressionInIdBag(roi.getExpressedAnatomyId());
}
img.setGenericSearch(new ArrayList<String>());
List<ImageDTO> update = new ArrayList<>();
update.add(img);
addBeans(update);
}
}
public ImageDTO getImageById(String imageId){
ImageDTO img = null;
SolrQuery solrQuery = new SolrQuery();
solrQuery.setQuery(ImageDTO.ID + ":" + imageId);
try {
List<ImageDTO> images = solr.query(solrQuery).getBeans(ImageDTO.class);
img = images.get(0);
} catch (SolrServerException e) {
e.printStackTrace();
}
return img;
}
public String getSolrUrl () {
return solr.getBaseURL();
}
public void addBeans(List<ImageDTO> imageDocs){
try {
solr.addBeans(imageDocs);
solr.commit();
} catch (SolrServerException | IOException e) {
e.printStackTrace();
}
}
/**
* Removes all documents from the core
* @throws IOException
* @throws SolrServerException
*/
public void clear() throws SolrServerException, IOException{
solr.deleteByQuery("*:*");
}
public String getQueryUrl(SolrQuery q){
return solr.getBaseURL() + "/select?" + q.toString();
}
} |
package com.facebook.systrace;
import android.os.Build;
import android.os.Trace;
/**
* Systrace stub that mostly does nothing but delegates to Trace for beginning/ending sections.
* The internal version of this file has not been opensourced yet.
*/
public class Systrace {
public static final long TRACE_TAG_REACT_JAVA_BRIDGE = 0L;
public static final long TRACE_TAG_REACT_FRESCO = 0L;
public static final long TRACE_TAG_REACT_APPS = 0L;
public enum EventScope {
THREAD('t'),
PROCESS('p'),
GLOBAL('g');
private final char mCode;
private EventScope(char code) {
mCode = code;
}
public char getCode() {
return mCode;
}
}
public static void registerListener(TraceListener listener) {
}
public static void unregisterListener(TraceListener listener) {
}
public static boolean isTracing(long tag) {
return false;
}
public static void traceInstant(
long tag,
final String title,
EventScope scope) {
}
public static void beginSection(long tag, final String sectionName) {
if (Build.VERSION.SDK_INT >= 18) {
Trace.beginSection(sectionName);
}
}
public static void endSection(long tag) {
if (Build.VERSION.SDK_INT >= 18) {
Trace.endSection();
}
}
public static void beginAsyncSection(
long tag,
final String sectionName,
final int cookie) {
}
public static void endAsyncSection(
long tag,
final String sectionName,
final int cookie) {
}
public static void traceCounter(
long tag,
final String counterName,
final int counterValue) {
}
public static void startAsyncFlow(
long tag,
final String sectionName,
final int cookie){
}
public static void stepAsyncFlow(
long tag,
final String sectionName,
final int cookie){
}
public static void endAsyncFlow(
long tag,
final String sectionName,
final int cookie){
}
} |
package com.vondear.rxtools;
import android.content.Context;
import android.os.Handler;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class RxUtils {
private static Context context;
/**
*
*
* @param context
*/
public static void init(Context context) {
RxUtils.context = context.getApplicationContext();
RxCrashUtils.getInstance(context).init();
}
/**
* Context Context
* <p>
* ApplicationContext
*
* @return ApplicationContext
*/
public static Context getContext() {
if (context != null) return context;
throw new NullPointerException("init()");
}
public static void delayToDo(final DelayListener delayListener, long delayTime) {
new Handler().postDelayed(new Runnable() {
public void run() {
//execute the task
delayListener.doSomething();
}
}, delayTime);
}
/**
*
*
* @param textView
* @param waitTime
* @param interval
* @param hint
*/
public static void countDown(final TextView textView, long waitTime, long interval, final String hint) {
textView.setEnabled(false);
android.os.CountDownTimer timer = new android.os.CountDownTimer(waitTime, interval) {
@Override
public void onTick(long millisUntilFinished) {
textView.setText(" " + (millisUntilFinished / 1000) + " S");
}
@Override
public void onFinish() {
textView.setEnabled(true);
textView.setText(hint);
}
};
timer.start();
}
/**
* listView
*
* @param listView
*/
public static void fixListViewHeight(ListView listView) {
// ListView
ListAdapter listAdapter = listView.getAdapter();
int totalHeight = 0;
if (listAdapter == null) {
return;
}
for (int index = 0, len = listAdapter.getCount(); index < len; index++) {
View listViewItem = listAdapter.getView(index, null, listView);
// View
listViewItem.measure(0, 0);
totalHeight += listViewItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
// listView.getDividerHeight()
// params.heightListView
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
/**
* MD532
*
* @param MStr :
* @return
*/
public static String Md5(String MStr) {
try {
final MessageDigest mDigest = MessageDigest.getInstance("MD5");
mDigest.update(MStr.getBytes());
return bytesToHexString(mDigest.digest());
} catch (NoSuchAlgorithmException e) {
return String.valueOf(MStr.hashCode());
}
}
private static String bytesToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);
}
return sb.toString();
}
/**
* id
* <p>
* ,ID
* <p>
*
* getResources().getIdentifier("ic_launcher", "drawable", getPackageName());
*
* @param context
* @param name
* @param defType
* @return
*/
public static final int getResIdByName(Context context, String name, String defType) {
return context.getResources().getIdentifier("ic_launcher", "drawable", context.getPackageName());
}
public interface DelayListener {
void doSomething();
}
private static long lastClickTime;
public static boolean isFastClick(int millisecond) {
long curClickTime = System.currentTimeMillis();
long interval = (curClickTime - lastClickTime);
if (0 < interval && interval < millisecond) {
// lastClickTime
return true;
}
lastClickTime = curClickTime;
return false;
}
/**
* Edittext
*
* @param editText
*/
public static void setEdTwoDecimal(EditText editText) {
setEdDecimal(editText, 3);
}
public static void setEdDecimal(EditText editText, int count) {
if (count < 1) {
count = 1;
}
editText.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER);
final int finalCount = count;
editText.setFilters(new InputFilter[]{new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (source.equals(".") && dest.toString().length() == 0) {
return "0.";
}
if (dest.toString().contains(".")) {
int index = dest.toString().indexOf(".");
int mlength = dest.toString().substring(index).length();
if (mlength == finalCount) {
return "";
}
}
return null;
}
}});
}
public static void initEditNumberPrefix(final EditText edSerialNumber, final int number) {
edSerialNumber.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
String s = edSerialNumber.getText().toString();
String temp = "";
for (int i = s.length(); i < number; i++) {
s = "0" + s;
}
for (int i = 0; i < number; i++) {
temp += "0";
}
if (s.equals(temp)) {
s = temp.substring(1) + "1";
}
edSerialNumber.setText(s);
}
}
});
}
} |
import java.util.*;
public class RepairDroid
{
public static final String INITIAL_INPUT = Integer.toString(DroidMovement.NORTH);
private static final int EXPLORE_UNTIL_OXYGEN = 1;
private static final int EXPLORE_ENTIRE_MAZE = 2;
public RepairDroid (Vector<String> instructions, boolean debug)
{
_debug = debug;
_theComputer = new Intcode(instructions, INITIAL_INPUT, _debug);
_currentLocation = new Coordinate(0, 0); // starting location
_startingPoint = _currentLocation;
_theMap = new Maze();
_trackTaken = new Stack<Integer>();
_foundOxygenStation = false;
_exploreOption = EXPLORE_UNTIL_OXYGEN;
_theMap.updateTile(_currentLocation, TileId.STARTING_POINT);
}
public final int moveToOxygenStation ()
{
_exploreOption = EXPLORE_UNTIL_OXYGEN;
explore();
return _trackTaken.size();
}
public void printGrid ()
{
System.out.println(_theMap);
}
/*
* If we run into a wall then try a different direction.
* If we can't move other than backwards then do that.
* Don't move into areas we've already been.
*/
private int explore ()
{
int response = DroidStatus.ERROR;
while (!_theComputer.hasHalted() && !stopSearch())
{
boolean needToBackup = false;
//if (_debug)
System.out.println("\n"+_theMap);
/*
* We search N, E, S and then W.
*/
response = tryToMove(String.valueOf(DroidMovement.NORTH), DroidMovement.getNextPosition(_currentLocation, DroidMovement.NORTH));
if ((response != DroidStatus.ARRIVED) && (response != DroidStatus.MOVED))
{
//if (_debug)
System.out.println("\n"+_theMap);
response = tryToMove(String.valueOf(DroidMovement.EAST), DroidMovement.getNextPosition(_currentLocation, DroidMovement.EAST));
if ((response != DroidStatus.ARRIVED) && (response != DroidStatus.MOVED))
{
//if (_debug)
System.out.println("\n"+_theMap);
response = tryToMove(String.valueOf(DroidMovement.SOUTH), DroidMovement.getNextPosition(_currentLocation, DroidMovement.SOUTH));
if ((response != DroidStatus.ARRIVED) && (response != DroidStatus.MOVED))
{
//if (_debug)
System.out.println("\n"+_theMap);
response = tryToMove(String.valueOf(DroidMovement.WEST), DroidMovement.getNextPosition(_currentLocation, DroidMovement.WEST));
if ((response != DroidStatus.ARRIVED) && (response != DroidStatus.MOVED))
{
//if (_debug)
System.out.println("\n"+_theMap);
/*
* At this point we've exhausted all of the options for moving from
* the current location. Therefore, we need to backtrack.
*/
needToBackup = true;
}
}
}
}
if (_theComputer.status() == Status.HALTED)
response = DroidStatus.HALTED;
System.out.println("**DroidStatus "+DroidStatus.toString(response));
System.out.println("**search status "+stopSearch());
System.out.println("**and "+needToBackup);
System.out.println("**and "+Status.toString(_theComputer.status()));
System.out.println("**location "+_currentLocation);
if (needToBackup)
return backtrack();
}
if (_theComputer.status() == Status.HALTED)
response = DroidStatus.HALTED;
System.out.println("**DroidStatus "+DroidStatus.toString(response));
return response;
}
private int tryToMove (String direction, Coordinate to)
{
if (_debug)
System.out.println("Trying to move from: "+_currentLocation+" to "+to+" with direction "+DroidMovement.toString(direction));
// if we've already been there then don't move!
if (_theMap.isExplored(to))
return DroidStatus.VISITED;
_theComputer.setInput(direction);
_theComputer.executeUntilInput();
if (_theComputer.hasOutput())
{
int response = Integer.parseInt(_theComputer.getOutput());
if (_debug)
System.out.println("Response is "+DroidStatus.toString(response));
switch (response)
{
case DroidStatus.ARRIVED: // arrived at the station!!
{
_theMap.updateTile(_currentLocation, TileId.TRAVERSE);
_theMap.updateTile(to, TileId.OXYGEN_STATION);
_currentLocation = to;
recordJourney(Integer.parseInt(direction));
_foundOxygenStation = true;
if (_debug)
{
System.out.println("FOUND OXYGEN!");
System.out.println("\n"+_theMap);
}
return response;
}
case DroidStatus.COLLISION:
{
_theMap.updateTile(to, TileId.WALL); // didn't move as we hit a wall
return response;
}
case DroidStatus.MOVED:
{
/*
* Droid moved so let's try to move again.
*/
if (!_currentLocation.equals(_startingPoint))
_theMap.updateTile(_currentLocation, TileId.TRAVERSE);
_theMap.updateTile(to, TileId.DROID);
_currentLocation = to;
recordJourney(Integer.parseInt(direction));
return explore();
}
default:
System.out.println("Unknown response: "+response);
}
}
else
System.out.println("Error - no output after move instruction!");
return DroidStatus.ERROR; // error!!
}
private int backtrack ()
{
int status = DroidStatus.ERROR;
if (_trackTaken.size() > 0)
{
int backupDirection = DroidMovement.backupDirection(_trackTaken.pop());
if (_debug)
System.out.println("Trying to backup from: "+_currentLocation+" with direction "+DroidMovement.toString(backupDirection));
_theComputer.setInput(String.valueOf(backupDirection));
_theComputer.executeUntilInput();
if (_theComputer.hasOutput())
{
int response = Integer.parseInt(_theComputer.getOutput());
if (response == DroidStatus.MOVED)
{
_theMap.updateTile(_currentLocation, TileId.TRAVERSE);
_currentLocation = DroidMovement.getNextPosition(_currentLocation, backupDirection);
_theMap.updateTile(_currentLocation, TileId.DROID);
status = DroidStatus.BACKTRACKED; // different from normal move response
}
else
System.out.println("Unexpected backup response: "+response);
}
else
System.out.println("Error - no output after move instruction!");
}
else
System.out.println("Cannot backtrack!");
return status;
}
private void recordJourney (int direction)
{
if (!stopSearch())
_trackTaken.push(direction);
}
private final void printTrack ()
{
Enumeration<Integer> iter = _trackTaken.elements();
System.out.println("Path taken so far ...");
while (iter.hasMoreElements())
System.out.println("Moved "+DroidMovement.toString(iter.nextElement()));
}
private final boolean stopSearch ()
{
if ((_exploreOption == EXPLORE_UNTIL_OXYGEN) && (_foundOxygenStation))
return true;
else
return false;
}
private final boolean tryNextLocation (int response)
{
boolean result = false;
if (_exploreOption == EXPLORE_UNTIL_OXYGEN)
{
if ((response != DroidStatus.ARRIVED) && (response != DroidStatus.MOVED))
result = true;
}
else
{
if (response != DroidStatus.MOVED)
result = true;
}
return result;
}
private boolean _debug;
private Intcode _theComputer;
private Coordinate _currentLocation;
private Coordinate _startingPoint;
private Maze _theMap;
private Stack<Integer> _trackTaken;
private boolean _foundOxygenStation;
private int _exploreOption;
} |
import java.math.*;
public class SlamShuffle
{
public static final String DATA_FILE = "data.txt";
public static final BigInteger SIZE_OF_DECK = BigInteger.valueOf(119315717514047L);;
public static final BigInteger SHUFFLE_TIMES = BigInteger.valueOf(101741582076661L);
public static final int CARD = 2020;
public static void main (String[] args)
{
boolean debug = false;
for (int i = 0; i < args.length; i++)
{
if ("-help".equals(args[i]))
{
System.out.println("Usage: [-debug] [-help]");
System.exit(0);
}
if ("-debug".equals(args[i]))
debug = true;
if ("-verify".equals(args[i]))
verify = true;
}
}
} |
import java.util.*;
public class ReportRepair
{
public static final int TOTAL_TO_FIND = 2020;
public static final String DATA_FILE = "input.txt";
public static void main (String[] args)
{
int number = TOTAL_TO_FIND;
boolean verify = false;
boolean debug = false;
for (int i = 0; i < args.length; i++)
{
if ("-help".equals(args[i]))
{
System.out.println("Usage: [-verify] [-total <number>] [-help]");
System.exit(0);
}
if ("-total".equals(args[i]))
{
try
{
number = Integer.parseInt(args[i+1]);
}
catch (Exception ex)
{
System.err.println("Error parsing: "+args[i+1]);
System.exit(0);
}
}
if ("-debug".equals(args[i]))
debug = true;
if ("-verify".equals(args[i]))
verify = true;
}
if (verify)
{
Verifier v = new Verifier(debug);
if (v.verify())
System.out.println("Verified ok.");
else
System.out.println("Verify failed.");
System.exit(0);
}
Vector<Integer> values = Util.readValues(DATA_FILE);
Total finder = new Total(values, debug);
Integer[] figures = finder.sum(TOTAL_TO_FIND);
if (figures != null)
{
System.out.println("Entries are: "+figures[0]+" and "+figures[1]);
System.out.println("Multiplied together: "+(figures[0] * figures[1]));
}
else
System.out.println("No suitable entries found!");
}
} |
package jlibs.xml.sax.helpers;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.XMLFilterImpl;
import org.xml.sax.helpers.DefaultHandler;
import java.io.IOException;
import jlibs.xml.sax.SAXUtil;
import javax.xml.parsers.ParserConfigurationException;
/**
* @author Santhosh Kumar T
*/
public class NamespaceSupportReader extends XMLFilterImpl{
protected MyNamespaceSupport nsSupport = new MyNamespaceSupport();
public NamespaceSupportReader(boolean nsPrefixes) throws ParserConfigurationException, SAXException{
this(SAXUtil.newSAXParser(true, nsPrefixes).getXMLReader());
}
public NamespaceSupportReader(XMLReader parent){
super(parent);
}
public MyNamespaceSupport getNamespaceSupport(){
return nsSupport;
}
private boolean needNewContext;
@Override
public void startDocument() throws SAXException{
nsSupport.reset();
needNewContext = true;
super.startDocument();
}
public void startPrefixMapping(String prefix, String uri) throws SAXException{
if(needNewContext){
nsSupport.pushContext();
needNewContext = false;
}
nsSupport.declarePrefix(prefix, uri);
super.startPrefixMapping(prefix, uri);
}
public void startElement(String namespaceURI, String localName, String qualifiedName, Attributes atts) throws SAXException{
if(needNewContext)
nsSupport.pushContext();
needNewContext = true;
super.startElement(namespaceURI, localName, qualifiedName, atts);
}
public void endElement(String uri, String localName, String qName) throws SAXException{
nsSupport.popContext();
super.endElement(uri, localName, qName);
}
public void setDefaultHandler(DefaultHandler handler){
if(handler instanceof SAXHandler)
((SAXHandler)handler).nsSupport = nsSupport;
setContentHandler(handler);
setEntityResolver(handler);
setErrorHandler(handler);
setDTDHandler(handler);
}
public void parse(InputSource is, DefaultHandler handler) throws IOException, SAXException{
setDefaultHandler(handler);
parse(is);
}
public void parse(String systemId, DefaultHandler handler) throws IOException, SAXException{
setDefaultHandler(handler);
parse(systemId);
}
} |
import java.sql.Array;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* DatabaseHandler is the controller for managing the backend Postgres database.
* Please ensure the following is configured on the machine before running this.
* - Ensure that Postgres server is installed and running on machine
* - Ensure that there is a database named: ctfcrawler
* - Ensure that there is a postgres user/password: ctfcrawler/ctfcrawler
*
* Currently supported operations: Insert/Delete CtfCrawlEntry objects
*/
public class DatabaseHandler {
private static final int DOMAINSEARCH = 1;
private static final int CATEGORYSEARCH = 2;
private static final String dbUrl = "jdbc:postgresql://localhost:5432/ctfcrawler";
private static final String dbUser = "ctfcrawler";
private static final String dbPassword = "ctfcrawler";
private Connection dbCon = null;
public DatabaseHandler() {
connectDatabase();
createDatabaseStructureIfRequired();
verifyDatabaseStructure();
}
public static boolean isDatabaseAlive() {
boolean isAlive = false;
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
con = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
st = con.createStatement();
rs = st.executeQuery("SELECT VERSION()");
if (rs.next()) {
System.out.println("Database is up and alive.");
}
isAlive = true;
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(DatabaseHandler.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(DatabaseHandler.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
return isAlive;
}
private void connectDatabase() {
Statement st = null;
ResultSet rs = null;
try {
System.out.println("Connecting to Database...");
dbCon = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
st = dbCon.createStatement();
rs = st.executeQuery("SELECT VERSION()");
if (rs.next()) {
System.out.println("Database connected, version: " + rs.getString(1));
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(DatabaseHandler.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(DatabaseHandler.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
private void createDatabaseStructureIfRequired() {
try {
if (dbCon == null || dbCon.isClosed()) {
System.out.println("Database connection not found, or is closed");
connectDatabase();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
Statement stmt = dbCon.createStatement();
String sql = "CREATE TABLE IF NOT EXISTS CTFWRITEUPS " +
"(ID BIGSERIAL PRIMARY KEY NOT NULL," +
"URL TEXT NOT NULL," +
"RESPONSETIME TEXT NOT NULL," +
"CATEGORIES TEXT[] )";
int rowsUpdated = stmt.executeUpdate(sql);
stmt.close();
if (rowsUpdated > 0) {
System.out.println("Successfully created table CTFWRITEUPS.");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private boolean verifyDatabaseStructure() {
CtfCrawlEntry testEntry = generateTestCrawlEntry();
boolean isSuccess = insertToCTFCrawler(testEntry);
isSuccess = isSuccess && deleteFromCTFCrawler(testEntry);
if (isSuccess) {
System.out.println("Database Structure is verified.");
}
return isSuccess;
}
private CtfCrawlEntry generateTestCrawlEntry() {
String url = "TEST://ctftime.org";
String response = "999999999ms";
String[] tags = {"TEST","ENTRY","ONLY"};
CtfCrawlEntry testEntry = new CtfCrawlEntry(url, response, tags);
return testEntry;
}
public boolean insertToCTFCrawler(CtfCrawlEntry entry) {
boolean isInserted = false;
isInserted = insertToCTFCrawler(entry.getUrl(), entry.getResponse(), entry.getTags());
return isInserted;
}
private boolean insertToCTFCrawler(String url, String response, String[] tags) {
boolean isInserted = false;
try {
if (dbCon == null || dbCon.isClosed()) {
System.out.println("Database connection not found, or is closed");
connectDatabase();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
String sql = "INSERT INTO CTFWRITEUPS (URL,RESPONSETIME,CATEGORIES) " +
"VALUES (?,?,?)";
PreparedStatement statement = dbCon.prepareStatement(sql);
int index = 1;
statement.setString(index++, url);
statement.setString(index++, response);
statement.setArray(index++, dbCon.createArrayOf("text", tags));
int rowsUpdated = statement.executeUpdate();
System.out.println("Rows updated from INSERT statement: " + rowsUpdated);
isInserted = true;
} catch (SQLException e) {
isInserted = false;
e.printStackTrace();
}
return isInserted;
}
public boolean deleteFromCTFCrawler(CtfCrawlEntry entry) {
boolean isDeleted = false;
isDeleted = deleteFromCTFCrawler(entry.getUrl(), entry.getResponse(), entry.getTags());
return isDeleted;
}
private boolean deleteFromCTFCrawler(String url, String response, String[] tags) {
boolean isDeleted = false;
try {
if (dbCon == null || dbCon.isClosed()) {
System.out.println("Database connection not found, or is closed");
connectDatabase();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
String sql = "DELETE from CTFWRITEUPS " +
"WHERE URL=? AND RESPONSETIME=? AND CATEGORIES=?";
PreparedStatement statement = dbCon.prepareStatement(sql);
int index = 1;
statement.setString(index++, url);
statement.setString(index++, response);
statement.setArray(index++, dbCon.createArrayOf("text", tags));
int rowsUpdated = statement.executeUpdate();
System.out.println("Rows updated from DELETE statement: " + rowsUpdated);
isDeleted = true;
} catch (SQLException e) {
isDeleted = false;
e.printStackTrace();
}
return isDeleted;
}
public void showAllEntries() {
try {
String sql = "SELECT * from CTFWRITEUPS;";
PreparedStatement statement = dbCon.prepareStatement(sql);
ResultSet rs = statement.executeQuery();
while (rs.next()) {
int i = 1;
int id = rs.getInt(i++);
String url = rs.getString(i++);
String responsetime = rs.getString(i++);
Array arr = rs.getArray(i++);
String[] categories = (String[]) arr.getArray();
showTableEntry(id, url, responsetime, categories);
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void showAllCategories() {
try {
String sql = "SELECT * from CTFWRITEUPS;";
PreparedStatement statement = dbCon.prepareStatement(sql);
ResultSet rs = statement.executeQuery();
HashSet<String> allCategories = new HashSet<String>();
while (rs.next()) {
int i = 1;
int id = rs.getInt(i++);
String url = rs.getString(i++);
String responsetime = rs.getString(i++);
Array arr = rs.getArray(i++);
String[] categories = (String[]) arr.getArray();
for (String category : categories) {
allCategories.add(category);
}
}
rs.close();
Iterator<String> itr = allCategories.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void showEntriesWithDomainName(String domainUrl) {
int type = DOMAINSEARCH;
showEntriesFromCTFCrawlerDB(domainUrl, type);
}
public void showEntriesWithCategory(String category) {
int type = CATEGORYSEARCH;
showEntriesFromCTFCrawlerDB(category, type);
}
private void showEntriesFromCTFCrawlerDB(String searchterm, int type) {
try {
if (dbCon == null || dbCon.isClosed()) {
System.out.println("Database connection not found, or is closed");
connectDatabase();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
switch (type) {
case DOMAINSEARCH:
handleDomainSearch(searchterm);
break;
case CATEGORYSEARCH:
handleCategorySearch(searchterm);
break;
default:
System.out.println("Search type not implemented.");
break;
}
}
private void handleDomainSearch(String domainUrl) {
try {
String sql = "SELECT * from CTFWRITEUPS " +
"WHERE URL like ?";
PreparedStatement statement = dbCon.prepareStatement(sql);
int index = 1;
statement.setString(index++, "%" + domainUrl + "%");
ResultSet rs = statement.executeQuery();
while (rs.next()) {
int i = 1;
int id = rs.getInt(i++);
String url = rs.getString(i++);
String responsetime = rs.getString(i++);
Array arr = rs.getArray(i++);
String[] categories = (String[]) arr.getArray();
showTableEntry(id, url, responsetime, categories);
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private void handleCategorySearch(String category) {
if (category == null) {
System.out.println("Category should not be null");
return;
}
try {
String sql = "SELECT * from CTFWRITEUPS;";
PreparedStatement statement = dbCon.prepareStatement(sql);
ResultSet rs = statement.executeQuery();
while (rs.next()) {
int i = 1;
int id = rs.getInt(i++);
String url = rs.getString(i++);
String responsetime = rs.getString(i++);
Array arr = rs.getArray(i++);
String[] categories = (String[]) arr.getArray();
for (String cat: categories) {
if (category.equalsIgnoreCase(cat)) {
showTableEntry(id, url, responsetime, categories);
}
}
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private void showTableEntry(int id, String url, String response, String[] categories) {
if (url == null || response == null || categories == null) {
return;
}
System.out.println("\t\tEntry: " + id);
System.out.println("URL: " + url);
System.out.println("Categories: " + Arrays.toString(categories));
System.out.println("Response time: " + response);
System.out.println("
}
// Method to test database handler methods
public static void main(String[] args) {
DatabaseHandler.isDatabaseAlive();
DatabaseHandler dbHandler = new DatabaseHandler();
dbHandler.showEntriesWithDomainName("https://ctftime.org/writeups/");
dbHandler.showEntriesWithCategory("exploit");
dbHandler.showAllEntries();
}
} |
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* the project. */
package org.usfirst.frc4946;
import edu.wpi.first.wpilibj.DriverStationLCD;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.PWM;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.SimpleRobot;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the SimpleRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class BetaRobot extends SimpleRobot {
RobotDrive m_robotDrive = new RobotDrive(RobotConstants.PWM_MOTOR_LEFT_FRONT, RobotConstants.PWM_MOTOR_LEFT_REAR, RobotConstants.PWM_MOTOR_RIGHT_FRONT, RobotConstants.PWM_MOTOR_RIGHT_REAR);
Joystick m_driveJoystick = new Joystick(RobotConstants.JOYSTICK_LEFT);
Joystick m_taskJoystick = new Joystick(RobotConstants.JOYSTICK_RIGHT);
DriverStationLCD m_driverStation = DriverStationLCD.getInstance();
/**
* This function is called once each time the robot enters autonomous mode.
*/
public void autonomous() {
}
/**
* This function is called once each time the robot enters operator control.
*/
public void operatorControl() {
m_driverStation.println(DriverStationLCD.Line.kMain6, 1, "Entering operator control");
m_driverStation.updateLCD();
while (isOperatorControl() && isEnabled()){
buttonTest();
//Call the drive oriented code
operatorDriveSystem();
//Call the task oriented code
operatorTaskSystem();
}
m_driverStation.println(DriverStationLCD.Line.kMain6, 1, "Stopping operator control");
m_driverStation.updateLCD();
}
public void buttonTest() {
for(int i=0;i<20;i++)
{
if (m_driveJoystick.getRawButton(i)){
m_driverStation.println(DriverStationLCD.Line.kUser2, 1, "Button is "+i+" ");
m_driverStation.updateLCD();
}
}
}
private void operatorTaskSystem() {
//Code for the 'Task' joystick will go here
}
private void operatorDriveSystem() {
//m_robotDrive.arcadeDrive(m_driveJoystick);
//Same as above, but reduce either turning, or maximum speed depending on the trigger.
double outputMagnitude = m_driveJoystick.getY();
double curve = m_driveJoystick.getX();
m_driverStation.println(DriverStationLCD.Line.kUser3, 1, "Y value is "+outputMagnitude+" ");
m_driverStation.println(DriverStationLCD.Line.kUser4, 1, "X value is "+curve+" ");
m_driverStation.updateLCD();
//Check the joystick's deadzone
if(Math.abs(outputMagnitude) < RobotConstants.DRIVE_JOYSTICK_DEADZONE){
outputMagnitude = 0.0;
}
if(Math.abs(curve) < RobotConstants.DRIVE_JOYSTICK_DEADZONE){
curve = 0.0;
}
//Check the trigger
if( m_driveJoystick.getTrigger() ){
//allow fast speed, but reduce turning
curve *= 0.25;
}else{
//Drive slow if the trigger is not down
outputMagnitude *= 0.25;
}
m_robotDrive.arcadeDrive(outputMagnitude, curve, true);
}
} |
package tests;
import static org.junit.Assert.assertEquals;
import model.TurboIssue;
import org.junit.Test;
import stubs.ModelStub;
import filter.Parser;
import filter.expression.Qualifier;
public class EvalTests {
private final ModelStub model = new ModelStub();
@Test
public void id() {
TurboIssue issue = new TurboIssue("1", "desc", model);
issue.setId(1);
assertEquals(Qualifier.process(Parser.parse("id:1"), issue), true);
assertEquals(Qualifier.process(Parser.parse("id:a"), issue), false);
}
@Test
public void keyword() {
}
@Test
public void title() {
}
@Test
public void body() {
}
@Test
public void milestone() {
}
@Test
public void parent() {
}
@Test
public void label() {
}
@Test
public void assignee() {
}
@Test
public void author() {
}
@Test
public void involves() {
}
@Test
public void state() {
}
@Test
public void has() {
}
@Test
public void no() {
}
@Test
public void in() {
}
@Test
public void type() {
}
@Test
public void is() {
}
@Test
public void created() {
}
@Test
public void updated() {
}
} |
package util;
import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import javafx.application.Platform;
import org.eclipse.egit.github.core.Issue;
import model.Model;
public class ModelUpdater {
private Model model;
private IssueUpdateService issueUpdateService;
private long pollInterval = 60000; //time between polls in ms
private Timer pollTimer;
public ModelUpdater(GitHubClientExtended client, Model model){
this.model = model;
this.issueUpdateService = new IssueUpdateService(client);
}
private void updateModelIssues(){
List<Issue> updatedIssues = issueUpdateService.getUpdatedIssues(model.getRepoId());
WeakReference<Model> modelRef = new WeakReference<Model>(model);
Platform.runLater(new Runnable() {
@Override
public void run() {
Model model = modelRef.get();
if(model != null){
model.updateCachedIssues(updatedIssues);
}
}
});
}
public void startModelUpdate(){
if(pollTimer != null){
stopModelUpdate();
}
pollTimer = new Timer();
TimerTask pollTask = new TimerTask(){
@Override
public void run() {
updateModelIssues();
}
};
pollTimer.scheduleAtFixedRate(pollTask, 0, pollInterval);
}
public void stopModelUpdate(){
if(pollTimer != null){
pollTimer.cancel();
pollTimer = null;
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.